Request more items beyond limit to work around LW weirdness.
[lw2-viewer.git] / src / backend.lisp
blobb38b0140becd2893646c12b97c2df5413da5bb1b
1 (uiop:define-package #:lw2.backend
2 (:use #:cl #:sb-thread #:flexi-streams #:alexandria #:iterate #:lw2-viewer.config #:lw2.sites #:lw2.context #:lw2.graphql #:lw2.lmdb
3 #:lw2.utils #:lw2.hash-utils #:lw2.backend-modules #:lw2.schema-type #:lw2.conditions #:lw2.web-push)
4 (:import-from #:alexandria-2 #:subseq*)
5 (:import-from #:collectors #:with-collector)
6 (:import-from #:lw2.user-context #:*current-auth-token*)
7 (:reexport #:lw2.backend-modules)
8 (:export #:*use-alignment-forum*
9 #:*graphql-debug-output*
10 #:*revalidate-default* #:*force-revalidate-default*
11 #:*messages-index-fields*
12 #:*notifications-base-terms*
13 #:*enable-rate-limit*
14 #:start-background-loader #:stop-background-loader #:background-loader-running-p
15 #:call-with-http-response
16 #:forwarded-header #:backend-request-headers
17 #:lw2-graphql-query #:lw2-query-string* #:lw2-query-string
18 #:lw2-graphql-query-map #:lw2-graphql-query-multi
19 #:signal-lw2-errors
20 #:earliest-post-time
21 #:flatten-shortform-comments #:get-shortform-votes
22 #:get-tag-posts
23 #:get-post-tag-votes #:get-tag-post-votes
24 #:get-slug-tagid
25 #:get-posts-index #:get-posts-json #:get-post-body #:get-post-vote #:get-post-comments #:get-post-answers #:get-post-debate-responses
26 #:get-post-comments-votes
27 #:get-tag-comments-votes
28 #:get-recent-comments #:get-recent-comments-json
29 #:get-collection
30 #:sequence-post-ids #:get-sequence #:get-post-sequence-ids #:get-sequence-post
31 #:get-conversation-messages
32 #:markdown-source
33 #:get-user
34 #:get-notifications #:check-notifications
35 #:mark-comment-replied #:check-comment-replied
36 #:lw2-search-query #:get-post-title #:get-post-slug #:get-slug-postid #:get-username #:get-user-full-name #:get-user-slug
37 #:do-wl-rest-mutate #:do-wl-rest-query #:do-wl-create-tag)
38 (:recycle #:lw2-viewer)
39 (:unintern #:get-posts #:make-posts-list-query #:define-backend-fields
40 #:*posts-index-fields* #:posts-index-fields #:post-body-fields
41 #:*comments-index-fields* #:comments-index-fields
42 #:*post-comments-fields* #:post-comments-fields
43 #:define-index-fields #:decode-graphql-json
44 #:lw2-graphql-query-noparse #:lw2-graphql-query-streamparse
45 #:*cookie-jar*
46 #:with-connection-pool #:call-with-connection-pool
47 #:cache-is-fresh))
49 (in-package #:lw2.backend)
51 ;; Dexador settings required for the system to work properly.
52 (setf dex:*default-connect-timeout* nil
53 dex:*default-read-timeout* nil
54 dex:*use-connection-pool* nil)
56 (defvar *use-alignment-forum* nil)
58 (defvar *graphql-debug-output* nil)
60 (defvar *revalidate-default* t)
61 (defvar *force-revalidate-default* nil)
63 (defparameter *messages-index-fields* '(:--id :user-id :created-at (:contents :html) (:conversation :--id :title) :----typename))
64 (defparameter *user-fields* '(:--id :slug :display-name :karma))
66 (defparameter *notifications-base-terms* (alist :view "userNotifications" :created-at :null :viewed :null))
68 (defun request-fields (query-type return-type context)
69 "Returns the desired fields for a given type of request."
70 (case return-type
71 (:total nil)
73 (with-collector (col)
74 (let ((backend *current-backend*)
75 (schema-type (find-schema-type query-type))
76 (added (make-hash-table :test 'eq)))
77 (dolist (field (cdr (assoc :fields schema-type)) (col))
78 (destructuring-bind (field-name field-type &key alias backend-type graphql-ignore subfields ((:context field-context)) context-not &allow-other-keys) field
79 (declare (ignore field-type))
80 (when (and (not (gethash field-name added))
81 (not graphql-ignore)
82 (or (not backend-type) (typep backend backend-type))
83 (or (not field-context) (eq context field-context))
84 (or (not context-not) (not (eq context context-not))))
85 (setf (gethash field-name added) t)
86 (col
87 (let ((result-name (or alias field-name)))
88 (if subfields
89 (list* result-name subfields)
90 result-name)))))))))))
92 (define-backend-function user-fields ()
93 (backend-lw2-legacy (load-time-value *user-fields*))
94 (backend-lw2-modernized (append (call-next-method) '(:groups :deleted :html-bio)))
95 (backend-alignment-forum (append (call-next-method) '(:af-karma :full-name))))
97 (define-cache-database 'backend-lw2-legacy
98 "index-json" "index-json-meta"
99 "post-comments-json" "post-comments-json-meta" "post-answers-json" "post-answers-json-meta"
100 "post-body-json" "post-body-json-meta"
101 "sequence-json" "sequence-json-meta" "post-sequence"
102 "user-json" "user-json-meta"
103 "user-page-items" "user-page-items-meta")
105 (define-cache-database 'backend-lw2-modernized
106 "user-deleted")
108 (define-backend-function comments-list-to-graphql-json (comments-list)
109 (backend-lw2-legacy
110 (json:encode-json-to-string
111 (plist-hash-table (list :data (plist-hash-table (list :*comments-list comments-list))))))
112 (backend-lw2-modernized
113 (json:encode-json-to-string
114 (plist-hash-table (list :data (plist-hash-table (list :*comments-list (plist-hash-table (list :results comments-list)))))))))
116 (defun do-graphql-debug (query)
117 (when *graphql-debug-output*
118 (format *graphql-debug-output* "~&GraphQL query: ~A~%" query)))
120 (defmacro with-retrying ((maybe-retry-fn-name &key retries before-maybe-retry before-retry) &body body)
121 (with-gensyms (remaining-retries retry)
122 `(let ((,remaining-retries ,retries))
123 (tagbody ,retry
124 (labels ((,maybe-retry-fn-name ()
125 ,before-maybe-retry
126 (when (> ,remaining-retries 0)
127 (decf ,remaining-retries)
128 ,before-retry
129 (go ,retry))))
130 ,@body)))))
132 (defun force-close (stream)
133 (ignore-errors (close stream :abort t)))
135 (sb-ext:defglobal *connection-pool* (make-hash-table :test 'equal))
136 (sb-ext:defglobal *connection-pool-lock* (sb-thread:make-mutex :name "*connection-pool-lock*"))
138 (defun connection-push (dest connection)
139 (let ((connection-pool *connection-pool*)
140 old-connection)
141 (sb-thread:with-mutex (*connection-pool-lock*)
142 (let ((vector (or (gethash dest connection-pool)
143 (setf (gethash dest connection-pool)
144 (make-array 4 :fill-pointer 0)))))
145 (unless (vector-push connection vector)
146 (setf old-connection (vector-pop vector))
147 (vector-push connection vector))))
148 (when old-connection
149 (force-close old-connection))))
151 (defun connection-pop (dest)
152 (let ((connection-pool *connection-pool*))
153 (sb-thread:with-mutex (*connection-pool-lock*)
154 (when-let (vector (gethash dest connection-pool))
155 (when (> (fill-pointer vector) 0)
156 (vector-pop vector))))))
158 (eval-when (:compile-toplevel :load-toplevel :execute)
159 (defstruct (token-bucket (:constructor %make-token-bucket))
160 (tokens internal-time-units-per-second :type fixnum)
161 (base-cost internal-time-units-per-second :type fixnum)
162 (last-update (get-internal-real-time) :type fixnum)
163 (tokens-per-unit 1 :type fixnum)
164 (token-limit internal-time-units-per-second :type fixnum))
166 (defun make-token-bucket (&key rate burst (fill-ratio 1.0))
167 (let* ((scaled-rate (rationalize (/ internal-time-units-per-second rate)))
168 (base-cost (numerator scaled-rate))
169 (tokens-per-unit (denominator scaled-rate))
170 (token-limit (* base-cost burst)))
171 (%make-token-bucket
172 :base-cost base-cost
173 :tokens-per-unit tokens-per-unit
174 :token-limit token-limit
175 :tokens (round (* token-limit fill-ratio))))))
177 (defun token-bucket-decrement (token-bucket n &optional with-punishment)
178 (let* ((time (get-internal-real-time))
179 (tpu (token-bucket-tokens-per-unit token-bucket))
180 (limit (token-bucket-token-limit token-bucket))
181 (cost (round (* n (token-bucket-base-cost token-bucket))))
182 (max-increment (+ limit cost))
183 (max-timediff (ceiling max-increment tpu))
184 (increment 0)
185 (result nil))
186 (declare (type (and fixnum (integer 0)) time)
187 (type (unsigned-byte 32) limit cost max-increment increment)
188 (type (integer 1 10000000) tpu))
189 (sb-ext:atomic-update (token-bucket-last-update token-bucket)
190 (lambda (previous)
191 (declare (type (and fixnum (integer 0)) previous))
192 (if (> (- time max-timediff) previous)
193 (setf increment max-increment)
194 (let ((timediff (- time (min previous time))))
195 (declare (type (unsigned-byte 32) timediff))
196 (setf increment (* timediff tpu))))
197 (max previous time)))
198 (sb-ext:atomic-update (token-bucket-tokens token-bucket)
199 (lambda (previous)
200 (declare (type (signed-byte 32) previous))
201 (let* ((new-refill (+ previous increment))
202 (new (- new-refill cost)))
203 (setf result (> new 0))
204 (if (or result with-punishment)
205 (min new limit)
206 (max (- limit) (min new-refill limit))))))
207 result))
209 (defun parse-ipv4 (string)
210 (let ((l (map 'list #'parse-integer
211 (split-sequence:split-sequence #\. string))))
212 (loop with res = 0
213 for n in l
214 do (setf res (+ n (ash res 8)))
215 finally (return res))))
217 (defvar *enable-rate-limit* t)
219 (defparameter *rate-limit-cost-factor* 1)
221 (sb-ext:defglobal *global-token-bucket* (make-token-bucket :rate 3 :burst 180))
223 (defun check-rate-limit ()
224 (or (token-bucket-decrement *global-token-bucket* *rate-limit-cost-factor*)
225 (error "Rate limit exceeded. Try again later.")))
227 (defun call-with-http-response (fn uri-string &rest args &key &allow-other-keys)
228 (when *enable-rate-limit*
229 (check-rate-limit))
230 (let* ((uri (quri:uri uri-string))
231 (uri-dest (concatenate 'string (quri:uri-host uri) ":" (format nil "~d" (quri:uri-port uri))))
232 (stream (connection-pop uri-dest)))
233 (let (response status-code headers response-uri new-stream success)
234 (with-retrying (maybe-retry :retries 3
235 :before-retry (sleep 0.2))
236 (unwind-protect
237 (handler-bind (((or dex:http-request-failed usocket:ns-condition usocket:socket-condition)
238 (lambda (condition)
239 (if-let ((r (find-restart 'dex:ignore-and-continue condition))
240 (ct (gethash "content-type" (dex:response-headers condition))))
241 (if (ppcre:scan "^application/json" ct)
242 (invoke-restart r)
243 (maybe-retry))))))
244 (setf (values response status-code headers response-uri new-stream)
245 (apply 'dex:request uri :use-connection-pool nil :keep-alive t :stream stream args))
246 (unless (eq stream new-stream)
247 (when stream (force-close stream))
248 (setf stream new-stream
249 new-stream nil))
250 (when (<= 500 status-code 599)
251 (maybe-retry)
252 (error 'lw2-connection-error :message (format nil "HTTP status ~A" status-code)))
253 (setf success t))
254 (when (not success)
255 (when (streamp response)
256 (force-close response))
257 (when stream
258 (force-close stream))
259 (setf stream nil))))
260 (unwind-protect
261 (funcall fn response)
262 (when (streamp response)
263 (close response))
264 (when stream ; the connection is reusable
265 (connection-push uri-dest stream))))))
267 (defun forwarded-header ()
268 (let ((addr (and (boundp 'hunchentoot:*request*) (hunchentoot:real-remote-addr))))
269 (list-cond (addr "X-Forwarded-For" addr))))
271 (defun signal-lw2-errors (errors)
272 (loop for error in errors
273 do (let ((message (cdr (assoc :message error)))
274 (path (cdr (assoc :path error))))
275 (unless (and path (> (length path) 1))
276 (cond
277 ((search "document_not_found" message) (error 'lw2-not-found-error))
278 ((search "app.missing_document" message) (error 'lw2-not-found-error))
279 ((search "only visible to logged-in users" message) (error 'lw2-login-required-error))
280 ((search "not_allowed" message) (error 'lw2-not-allowed-error))
281 (t (error 'lw2-unknown-error :message message)))))))
283 (define-backend-function earliest-post-time ()
284 (backend-lw2 (load-time-value (local-time:parse-timestring "2005-01-01")))
285 (backend-ea-forum (load-time-value (local-time:parse-timestring "2011-11-24")))
286 (backend-progress-forum (load-time-value (local-time:parse-timestring "2022-03-26"))))
288 (define-backend-function fixup-lw2-return-value (value)
289 (backend-base
290 (values value nil))
291 (backend-lw2-modernized
292 (values
293 (let ((x (first value)))
294 (if (member (car x) '(:result :results :total-count))
295 (cdr x)
297 (let ((x (second value)))
298 (if (eq (car x) :total-count)
299 (cdr x)))))
300 (backend-accordius
301 (values value nil)))
303 (define-backend-function deserialize-query-result (result-source)
304 (backend-base
305 (let ((string-source (typecase result-source
306 (string
307 result-source)
308 (vector
309 (flexi-streams:make-in-memory-input-stream result-source))
310 (stream
311 (ensure-character-stream result-source)))))
312 (json:decode-json-from-source string-source))))
314 (define-backend-function postprocess-query-result (result)
315 (backend-base
316 result)
317 (backend-lw2-legacy
318 (signal-lw2-errors (cdr (assoc :errors result)))
319 (fixup-lw2-return-value (cdadr (assoc :data result)))))
321 (define-backend-function decode-query-result (result-source)
322 (backend-base
323 (postprocess-query-result
324 (deserialize-query-result result-source))))
326 (defmethod graphql-uri ((backend backend-alignment-forum))
327 (if *use-alignment-forum*
328 "https://www.alignmentforum.org/graphql"
329 (call-next-method)))
331 (define-backend-function backend-request-headers (auth-token forwarded)
332 (backend-websocket-login
333 (list-cond* (auth-token :authorization auth-token)
334 (call-next-method)))
335 (backend-passport-js-login
336 (list-cond* (auth-token :cookie (concatenate 'string "loginToken=" auth-token))
337 (call-next-method)))
338 (backend-oauth2.0-login
339 (list-cond* (auth-token :cookie (concatenate 'string "clientId=" (oauth2.0-client-id backend) "; loginToken=" auth-token))
340 (call-next-method)))
341 (backend-graphql
342 (alist* :content-type "application/json"
343 (if forwarded (forwarded-header)))))
345 (define-backend-function call-with-backend-response (fn query &key return-type auth-token)
346 (backend-graphql
347 (call-with-http-response
349 (graphql-uri *current-backend*)
350 :method :post
351 :headers (backend-request-headers auth-token nil)
352 :content (dynamic-let ((q (alist :query query))) (json:encode-json-to-string q))
353 :want-stream (not return-type))))
355 (define-backend-function lw2-graphql-query (query &key auth-token return-type (decoder 'decode-query-result))
356 (backend-base
357 (do-graphql-debug query)
358 (call-with-backend-response
359 (ecase return-type
360 ((nil) decoder)
361 (:string #'identity)
362 (:both (lambda (string) (values (funcall decoder string) string))))
363 query
364 :return-type return-type
365 :auth-token auth-token)))
367 (defun lw2-graphql-query-map (fn data &key auth-token postprocess)
368 (multiple-value-bind (map-values queries)
369 (loop for d in data
370 as out-values = (multiple-value-list (funcall fn d))
371 as (out passthrough-p) = out-values
372 collect out-values into map-values
373 when (not passthrough-p) collect out into queries
374 finally (return (values map-values queries)))
375 (let* ((query-string
376 (with-output-to-string (stream)
377 (format stream "{")
378 (loop for n from 0
379 for q in queries
380 do (format stream "g~6,'0D:~A " n q))
381 (format stream "}")))
382 (query-result-data (when queries (lw2-graphql-query query-string :decoder 'deserialize-query-result :auth-token auth-token)))
383 (errors (cdr (assoc :errors query-result-data))))
384 (signal-lw2-errors errors)
385 (values
386 (loop as results = (sort (cdr (assoc :data query-result-data)) #'string< :key #'car) then (if passthrough-p results (rest results))
387 for (out passthrough-p) in map-values
388 as result-data-cell = (first results)
389 as result-data = (if passthrough-p out (fixup-lw2-return-value (cdr result-data-cell)))
390 for input-data in data
391 collect (if postprocess (funcall postprocess input-data result-data) result-data))
392 errors))))
394 (defun lw2-graphql-query-multi (query-list &key auth-token)
395 (values-list (lw2-graphql-query-map #'identity query-list :auth-token auth-token)))
397 (defvar *background-cache-update-threads* (make-hash-table :test 'equal
398 :weakness :value
399 :synchronized t))
401 (defvar *parsed-results-cache* (make-hash-table :test 'equal
402 :weakness :value
403 :synchronized t))
405 (defun cache-update (cache-db key data)
406 (let ((meta-db (format nil "~A-meta" cache-db))
407 (new-hash (hash-string data))
408 (current-time (get-unix-time)))
409 (with-cache-transaction
410 (let* ((metadata (cache-get meta-db key :value-type :lisp))
411 (same-data (equalp new-hash (cdr (assoc :city-128-hash metadata))))
412 (last-mod (if same-data
413 (or (cdr (assoc :last-modified metadata)) current-time)
414 current-time)))
415 (cache-put meta-db key (alist :last-checked current-time :last-modified last-mod :city-128-hash new-hash) :value-type :lisp)
416 (unless same-data
417 (remhash (list *current-backend* cache-db key) *parsed-results-cache*)
418 (cache-put cache-db key data))
419 (values data (unix-to-universal-time last-mod))))))
421 (defun cache-mark-stale (cache-db key)
422 (let ((meta-db (format nil "~A-meta" cache-db))
423 (current-time (get-unix-time)))
424 (with-cache-transaction
425 (let* ((metadata (cache-get meta-db key :value-type :lisp))
426 (metadata (alist* :last-modified current-time (delete :last-modified metadata :key #'car))))
427 (cache-put meta-db key metadata :value-type :lisp)))))
429 (declaim (type (and fixnum (integer 1)) *cache-stale-factor* *cache-skip-factor*))
430 (defparameter *cache-stale-factor* 100)
431 (defparameter *cache-skip-factor* 5000)
433 (defun cache-freshness-status (cache-db key)
434 (with-cache-readonly-transaction
435 (when (cache-exists cache-db key)
436 (let ((metadata (cache-get (format nil "~A-meta" cache-db) key :value-type :lisp))
437 (current-time (get-unix-time)))
438 (if-let ((last-mod (cdr (assoc :last-modified metadata)))
439 (last-checked (cdr (assoc :last-checked metadata))))
440 (values
441 (let ((unmodified-time (- last-checked last-mod))
442 (last-checked-time (- current-time last-checked)))
443 (if (> unmodified-time (* *cache-skip-factor* last-checked-time))
444 :skip
445 (> unmodified-time (* *cache-stale-factor* last-checked-time))))
447 (unix-to-universal-time last-mod)))))))
449 (defgeneric run-query (query)
450 (:method ((query string))
451 (lw2-graphql-query query :return-type :string))
452 (:method ((query function))
453 (funcall query)))
455 (declaim (inline make-thread-with-current-backend))
457 (defun make-thread-with-current-backend (fn &rest args)
458 (let ((current-backend *current-backend*))
459 (apply #'sb-thread:make-thread
460 (lambda ()
461 (let ((*current-backend* current-backend))
462 (funcall fn)))
463 args)))
465 (defun ensure-cache-update-thread (query cache-db cache-key)
466 (let ((key (format nil "~A-~A" cache-db cache-key)))
467 (labels ((background-fn ()
468 (unwind-protect
469 (block nil
470 (multiple-value-bind (value error)
471 (log-and-ignore-errors
472 (sb-sys:with-deadline (:seconds 60)
473 (return (cache-update cache-db cache-key (run-query query)))))
474 (declare (ignore value))
475 (return error)))
476 (remhash key *background-cache-update-threads*))))
477 (sb-ext:with-locked-hash-table (*background-cache-update-threads*)
478 (let ((thread (gethash key *background-cache-update-threads*)))
479 (if thread thread
480 (setf (gethash key *background-cache-update-threads*)
481 (make-thread-with-current-backend #'background-fn :name "background cache update"))))))))
483 (define-backend-function lw2-graphql-query-timeout-cached (query cache-db cache-key &key (decoder 'decode-query-result)
484 (revalidate *revalidate-default*) (force-revalidate *force-revalidate-default*))
485 (backend-base
486 (multiple-value-bind (is-fresh cached-result last-modified)
487 (cache-freshness-status cache-db cache-key)
488 (labels ((get-cached-result ()
489 (if-let ((parsed-result (gethash (list *current-backend* cache-db cache-key) *parsed-results-cache*)))
490 (multiple-value-call #'values (values-list parsed-result) last-modified)
491 (multiple-value-bind (result count)
492 (with-cache-readonly-transaction (funcall decoder (cache-get cache-db cache-key :return-type 'binary-stream)))
493 (setf (gethash (list *current-backend* cache-db cache-key) *parsed-results-cache*) (list result count))
494 (values result count last-modified)))))
495 (if (and cached-result (or (not revalidate)
496 (and (not force-revalidate) (eq is-fresh :skip))))
497 (get-cached-result)
498 (let ((timeout (if cached-result
499 (if force-revalidate nil 3)
500 nil))
501 (thread (ensure-cache-update-thread query cache-db cache-key)))
502 (block retrieve-result
503 (if (and cached-result (if force-revalidate (not revalidate) (or is-fresh (not revalidate))))
504 (get-cached-result)
505 (handler-bind
506 ((fatal-error (lambda (c)
507 (declare (ignore c))
508 (if cached-result
509 (return-from retrieve-result (get-cached-result))))))
510 (multiple-value-bind (new-result last-modified)
511 (sb-thread:join-thread thread :timeout timeout)
512 (typecase new-result
513 (condition (error new-result))
514 (t (multiple-value-bind (result count)
515 (funcall decoder new-result)
516 (setf (gethash (list *current-backend* cache-db cache-key) *parsed-results-cache*) (list result count))
517 (values result count last-modified))))))))))))))
519 (define-backend-function lw2-query-string* (query-type return-type args &key context fields with-total))
521 (define-backend-operation lw2-query-string* backend-lw2-legacy (query-type return-type args &key context (fields (request-fields query-type return-type context)) with-total)
522 (declare (ignore with-total))
523 (labels ((lisp-to-lw2-case (x) (json:lisp-to-camel-case (format nil "*~A" x))))
524 (graphql-query-string*
525 (concatenate 'string
526 (lisp-to-lw2-case query-type)
528 (lisp-to-lw2-case return-type))
529 (if (eq return-type :single)
530 args
531 (alist :terms args))
532 fields)))
534 (define-backend-operation lw2-query-string* backend-lw2-modernized (query-type return-type args &key context (fields (request-fields query-type return-type context)) with-total)
535 (graphql-query-string*
536 (if (eq return-type :single)
537 (json:lisp-to-camel-case (string query-type))
538 (concatenate 'string (json:lisp-to-camel-case (string query-type)) "s"))
539 (alist :input (case return-type
540 (:single (alist :selector args))
541 (:list (alist :enable-total with-total :terms args))
542 (:total (alist :enable-total t :terms args))))
543 (case return-type
544 (:total '(:total-count))
545 (:list (list-cond (t :results fields)
546 (with-total :total-count)))
547 (:single (alist :result fields)))))
549 (define-backend-function lw2-query-string (query-type return-type args &key context fields with-total))
551 (define-backend-operation lw2-query-string backend-lw2-legacy (query-type return-type args &rest rest &key context fields with-total)
552 (declare (ignore context fields with-total))
553 (format nil "{~A}" (apply 'lw2-query-string* query-type return-type args rest)))
555 (define-backend-function lw2-query-list-limit-workaround (query-type terms &rest rest &key fields context auth-token)
556 (backend-graphql
557 (declare (ignore fields context))
558 (let (items-list)
559 (loop for offset from 0 by 500
560 as items-next = (lw2-graphql-query (apply 'lw2-query-string query-type :list (alist* :limit 500 :offset offset terms) (filter-plist rest :fields :context))
561 :auth-token auth-token)
562 as length = (length items-next)
563 do (setf items-list (nconc items-list items-next))
564 while (>= length 500))
565 items-list))
566 (backend-accordius
567 (declare (ignore fields context))
568 (lw2-graphql-query (apply 'lw2-query-string query-type :list terms (filter-plist rest :fields :context)) :auth-token auth-token)))
570 (defun get-cached-index-query (cache-id query)
571 (multiple-value-bind (is-fresh cached-result last-modified)
572 (cache-freshness-status "index-json" cache-id)
573 (declare (ignore is-fresh))
574 (labels ((query-and-put ()
575 (multiple-value-bind (encoded-result last-modified)
576 (cache-update "index-json" cache-id (lw2-graphql-query query :return-type :string))
577 (multiple-value-bind (result count)
578 (decode-query-result encoded-result)
579 (values result count last-modified))))
580 (get-cached-result ()
581 (with-cache-readonly-transaction
582 (multiple-value-bind (result count)
583 (decode-query-result (cache-get "index-json" cache-id :return-type 'binary-stream))
584 (values result count last-modified)))))
585 (if (and cached-result (background-loader-ready-p))
586 (get-cached-result)
587 (if cached-result
588 (handler-case
589 (query-and-put)
590 (t () (get-cached-result)))
591 (query-and-put))))))
593 (define-backend-function get-posts-index-query-terms (&key view (sort "new") (limit 40) offset before after karma-threshold &allow-other-keys)
594 (backend-lw2-legacy
595 (let ((sort-key (alexandria:switch (sort :test #'string=)
596 ("new" "new")
597 ("hot" "magic")
598 ("active" "recentComments")
599 ("top" "top")
600 ("old" "old"))))
601 (multiple-value-bind (view-terms cache-key)
602 (alexandria:switch (view :test #'string=)
603 ("featured" (alist :sorted-by sort-key :filter "curated"))
604 ("all" (alist :sorted-by sort-key :filter "all"))
605 ("alignment-forum" (alist :sorted-by sort-key :af t))
606 ("questions" (alist :sorted-by sort-key :filter "questions"))
607 ("events" (alist :sorted-by sort-key :filter "events"))
608 ("nominations" (alist :view "nominations2019"))
609 ("reviews" (alist :view "reviews2019"))
610 (t (values
611 (alist :sorted-by sort-key :filter "frontpage")
612 (if (not (or (string/= sort "new") (/= limit 40) offset before after karma-threshold))
613 "new-not-meta"))))
614 (let ((terms
615 (alist-without-null* :before before
616 :after after
617 ;; Workaround offsets not working as of 2024-02-02
618 :limit (if limit (+ limit (or offset 0)))
619 #| :offset offset |#
620 :karma-threshold karma-threshold
621 view-terms)))
622 (values terms cache-key))))))
624 (define-backend-operation get-posts-index-query-terms backend-lw2-tags :around (&key hide-tags &allow-other-keys)
625 (multiple-value-bind (query-terms cache-key) (call-next-method)
626 (if hide-tags
627 (values (acons :filter-settings (alist :tags (list* :list (map 'list (lambda (tagid) (alist :tag-id tagid :filter-mode "Hidden"))
628 hide-tags)))
629 query-terms)
630 nil)
631 (values query-terms cache-key))))
633 (define-backend-function get-posts-index-query-string (&rest args &key &allow-other-keys)
634 (backend-lw2-legacy
635 (declare (dynamic-extent args))
636 (multiple-value-bind (query-terms cache-key)
637 (apply #'%get-posts-index-query-terms backend args)
638 (values (lw2-query-string :post :list query-terms)
639 cache-key))))
641 (define-backend-function get-posts-index (&rest args &key (limit 40) offset &allow-other-keys)
642 (backend-lw2-legacy
643 (declare (dynamic-extent args))
644 (multiple-value-bind (query-string cache-key)
645 (apply #'%get-posts-index-query-string backend args)
646 (if cache-key
647 (get-cached-index-query cache-key query-string)
648 (let ((result (lw2-graphql-query query-string))
649 (offset (or offset 0)))
650 ;; Workaround offsets not working as of 2024-02-02
651 (if limit
652 (subseq* result offset (+ limit offset))
653 result))))))
655 (define-backend-operation get-posts-index backend-lw2-tags :around (&rest args &key hide-tags offset (limit 40) &allow-other-keys)
656 ;; Workaround for https://github.com/LessWrong2/Lesswrong2/issues/3099
657 (declare (dynamic-extent args))
658 (if hide-tags
659 (let ((offset (or offset 0)))
660 (subseq
661 (apply #'call-next-method backend :offset 0 :limit (+ limit offset) args)
662 offset))
663 (call-next-method)))
665 (defun get-posts-json ()
666 (lw2-graphql-query (get-posts-index-query-string) :return-type :string))
668 (defun get-recent-comments (&key with-total)
669 (get-cached-index-query "recent-comments" (lw2-query-string :comment :list '((:view . "allRecentComments") (:limit . 20)) :context :index :with-total with-total)))
671 (defun get-recent-comments-json ()
672 (lw2-graphql-query (lw2-query-string :comment :list '((:view . "allRecentComments") (:limit . 20)) :context :index) :return-type :string))
674 (defun process-vote-result (res)
675 (alist-bind ((id (or null simple-string) :--id)
676 current-user-votes
677 current-user-vote
678 current-user-extended-vote)
680 (let ((karma-vote (or (nonempty-string current-user-vote)
681 (cdr (assoc :vote-type (first current-user-votes))))))
682 (values (list-cond* (karma-vote :karma karma-vote)
683 current-user-extended-vote)
684 id))))
686 (defun process-votes-result (res)
687 (let ((hash (make-hash-table)))
688 (dolist (v res hash)
689 (multiple-value-bind (vote id) (process-vote-result v)
690 (when vote
691 (setf (gethash id hash) vote))))))
693 (defun flatten-shortform-comments (comments)
694 (let ((output comments))
695 (loop for comment in comments do
696 (setf output (append (cdr (assoc :latest-children comment)) output)))
697 output))
699 (defun get-shortform-votes (auth-token &key (offset 0) (limit 20))
700 (process-votes-result
701 (flatten-shortform-comments
702 (lw2-graphql-query (lw2-query-string :comment :list (alist :view "shortform" :offset offset :limit limit)
703 :fields '(:--id :current-user-vote :current-user-extended-vote (:latest-children :--id :current-user-vote :current-user-extended-vote)))
704 :auth-token auth-token))))
706 (defun get-post-vote (post-id auth-token)
707 (process-vote-result (lw2-graphql-query (lw2-query-string :post :single (alist :document-id post-id) :fields '(:--id :current-user-vote :current-user-extended-vote)) :auth-token auth-token)))
709 (define-cache-database 'backend-lw2-tags "tag-posts" "tag-posts-meta" "post-tags" "post-tags-meta")
711 (define-backend-function get-tag-posts (slug &key (revalidate *revalidate-default*) (force-revalidate *force-revalidate-default*))
712 (backend-base (declare (ignore revalidate force-revalidate)) nil)
713 (backend-lw2-tags
714 (let* ((tagid (get-slug-tagid slug))
715 (query-fn (lambda ()
716 (comments-list-to-graphql-json
717 (lw2-query-list-limit-workaround
718 :tag-rel
719 (alist :view "postsWithTag" :tag-id tagid)
720 :fields (list (list* :post (request-fields :post :list :index))))))))
721 (iter
722 (for x in (lw2-graphql-query-timeout-cached query-fn "tag-posts" tagid :revalidate revalidate :force-revalidate force-revalidate))
723 (when-let (post (cdr (assoc :post x)))
724 (collect post))))))
726 (define-backend-function get-tag-post-votes (tag-id auth-token)
727 (backend-base (progn tag-id auth-token nil))
728 (backend-lw2-tags
729 (process-votes-result
730 (map 'list #'cdr
731 (lw2-query-list-limit-workaround
732 :tag-rel
733 (alist :view "postsWithTag" :tag-id tag-id)
734 :fields '(:--id :current-user-vote :current-user-extended-vote)
735 :auth-token auth-token)))))
737 (define-backend-function get-post-tags (post-id &key (revalidate *revalidate-default*) (force-revalidate *force-revalidate-default*))
738 (backend-base (declare (ignore revalidate force-revalidate)) nil)
739 (backend-lw2-tags
740 (let ((query-string (lw2-query-string :tag-rel :list (alist :view "tagsOnPost" :post-id post-id) :fields '((:tag :name :slug)))))
741 (lw2-graphql-query-timeout-cached query-string "post-tags" post-id :revalidate revalidate :force-revalidate force-revalidate))))
743 (define-backend-function get-post-tag-votes (post-id auth-token)
744 (backend-base (progn post-id auth-token nil))
745 (backend-lw2-tags
746 (process-votes-result
747 (lw2-graphql-query (lw2-query-string :tag-rel :list (alist :view "tagsOnPost" :post-id post-id) :fields '(:--id :current-user-vote :current-user-extended-vote))
748 :auth-token auth-token))))
750 (define-backend-function get-post-body (post-id &key (revalidate *revalidate-default*) (force-revalidate *force-revalidate-default*) auth-token)
751 (backend-graphql
752 (let ((query-string (lw2-query-string :post :single (alist :document-id post-id) :context :body)))
753 (block nil
754 (tagbody retry
755 (handler-bind ((lw2-login-required-error (lambda (&rest args)
756 (declare (ignore args))
757 (let ((current-auth-token *current-auth-token*))
758 (when (and (not auth-token) current-auth-token)
759 (setf auth-token current-auth-token)
760 (go retry))))))
761 (return
762 (if auth-token
763 (lw2-graphql-query query-string :auth-token auth-token)
764 (lw2-graphql-query-timeout-cached query-string "post-body-json" post-id :revalidate revalidate :force-revalidate force-revalidate))))))))
765 (backend-lw2-tags
766 (declare (ignore auth-token))
767 (acons :tags (get-post-tags post-id :revalidate revalidate :force-revalidate force-revalidate) (call-next-method)))
768 (backend-magnum-crossposts
769 (declare (ignore auth-token))
770 (let ((post (call-next-method)))
771 (alist-bind (is-crosspost hosted-here foreign-post-id) (cdr (assoc :fm-crosspost post))
772 (cond ((not (and (backend-magnum-crosspost-site backend)
773 (not (boundp '*retrieve-crosspost*))
774 is-crosspost foreign-post-id))
775 post)
776 (:otherwise
777 (block nil
778 (handler-bind ((error (lambda (condition)
779 (declare (ignore condition))
780 (when hosted-here
781 (return (remove :fm-crosspost post :key #'car))))))
782 (let* ((*current-site* (find-site (backend-magnum-crosspost-site backend)))
783 (*current-backend* (site-backend *current-site*))
784 (*retrieve-crosspost* nil)
785 (foreign-post (get-post-body foreign-post-id :revalidate revalidate :force-revalidate force-revalidate))
786 (foreign-post-body (cdr (assoc :html-body foreign-post))))
787 (declare (special *retrieve-crosspost*))
788 (if foreign-post-body
789 (list-cond*
790 ((not hosted-here) :html-body foreign-post-body)
791 (t :foreign-post foreign-post)
792 post)
793 post))))))))))
795 (defun get-post-comments-list (post-id view &rest rest &key auth-token parent-answer-id fields context)
796 (declare (ignore fields context auth-token))
797 (let ((terms (alist :view view :post-id post-id)))
798 (when parent-answer-id
799 (setf terms (acons :parent-answer-id parent-answer-id terms)))
800 (apply 'lw2-query-list-limit-workaround :comment terms (filter-plist rest :fields :context :auth-token))))
802 (defun get-post-answer-replies (post-id answers &rest rest &key auth-token fields context)
803 ;; todo: support more than 500 answers per question
804 (declare (ignore fields context))
805 (let* ((terms (alist :view "repliesToAnswer" :post-id post-id :limit 500))
806 (result (lw2-graphql-query-map
807 #'identity
808 (mapcar (lambda (answer) (apply 'lw2-query-string* :comment :list
809 (acons :parent-answer-id (cdr (assoc :--id answer)) terms)
810 (filter-plist rest :fields :context)))
811 answers)
812 :auth-token auth-token)))
813 (apply #'nconc result)))
815 (define-backend-function get-post-comments-votes (post-id auth-token)
816 (backend-graphql
817 (let ((fields '(:--id :current-user-vote :current-user-extended-vote)))
818 (process-votes-result
819 (get-post-comments-list post-id "postCommentsTop" :auth-token auth-token :fields fields))))
820 (backend-q-and-a
821 (let* ((fields '(:--id :current-user-vote :current-user-extended-vote))
822 (answers (get-post-comments-list post-id "questionAnswers" :auth-token auth-token :fields fields)))
823 (process-votes-result
824 (nconc
825 (get-post-comments-list post-id "postCommentsTop" :auth-token auth-token :fields fields)
826 (get-post-answer-replies post-id answers :auth-token auth-token :fields fields)
827 answers)))))
829 (define-backend-function get-tag-comments-votes (tag-id auth-token)
830 (backend-lw2-tags-comments
831 (process-votes-result (lw2-graphql-query (lw2-query-string :comment :list (alist :tag-id tag-id :view "tagDiscussionComments") :fields '(:--id :current-user-vote :current-user-extended-vote))
832 :auth-token auth-token))))
834 (define-backend-function get-post-comments (post-id &key (revalidate *revalidate-default*) (force-revalidate *force-revalidate-default*))
835 (backend-graphql
836 (let ((fn (lambda ()
837 (comments-list-to-graphql-json
838 (get-post-comments-list post-id "postCommentsTop")))))
839 (lw2-graphql-query-timeout-cached fn "post-comments-json" post-id :revalidate revalidate :force-revalidate force-revalidate)))
840 (backend-ea-forum
841 ;; Work around bizarre parent comment bug in EA forum
842 (declare (ignore revalidate force-revalidate))
843 (let ((comments (call-next-method)))
844 (dolist (c comments)
845 (if-let (parent-id-cons (assoc :parent-comment-id c))
846 (if (and (string= (cdr parent-id-cons) "rjgZaK8uzHG3jAu2p")
847 (not (string= post-id "h26Kx7uGfQfNewi7d")))
848 (setf (cdr parent-id-cons) nil))))
849 comments)))
851 (defun get-post-answers (post-id &key (revalidate *revalidate-default*) (force-revalidate *force-revalidate-default*))
852 (let ((fn (lambda ()
853 (let ((answers (get-post-comments-list post-id "questionAnswers")))
854 (comments-list-to-graphql-json
855 (nconc
856 answers
857 (get-post-answer-replies post-id answers)))))))
858 (lw2-graphql-query-timeout-cached fn "post-answers-json" post-id :revalidate revalidate :force-revalidate force-revalidate)))
860 (define-cache-database 'backend-debates
861 "post-debate-responses-json" "post-debate-responses-json-meta")
863 (define-backend-function get-post-debate-responses (post-id &key (revalidate *revalidate-default*) (force-revalidate *force-revalidate-default*))
864 (backend-base
865 (declare (ignore post-id revalidate force-revalidate))
866 nil)
867 (backend-debates
868 (let ((fn (lambda ()
869 (comments-list-to-graphql-json
870 (get-post-comments-list post-id "debateResponses")))))
871 (lw2-graphql-query-timeout-cached fn "post-debate-responses-json" post-id :revalidate revalidate :force-revalidate force-revalidate))))
873 (define-backend-function get-collection (collection-id)
874 (backend-graphql
875 (lw2-graphql-query
876 (lw2-query-string :collection :single
877 (alist :document-id collection-id)
878 :fields `(:--id :title (:contents :html) :grid-image-id :----typename
879 (:books :title :subtitle (:contents :html) :----typename
880 (:sequences :title (:contents :html) :grid-image-id :----typename
881 (:chapters :title :subtitle :number (:contents :html) (:posts ,@(request-fields :post :list nil))))))))))
883 (defun sequence-iterate (sequence fn)
884 (dolist (chapter (cdr (assoc :chapters sequence)))
885 (dolist (post (cdr (assoc :posts chapter)))
886 (funcall fn post))))
888 (defun sequence-post-ids (sequence)
889 (with-collector (col)
890 (sequence-iterate sequence
891 (lambda (post)
892 (col (cdr (assoc :--id post)))))
893 (col)))
895 (defun get-sequence-post (sequence post-id)
896 (sequence-iterate sequence
897 (lambda (post)
898 (when (string= (cdr (assoc :--id post)) post-id)
899 (return-from get-sequence-post post))))
900 nil)
902 (define-backend-function get-sequence (sequence-id)
903 (backend-graphql
904 (let ((fn (lambda ()
905 (multiple-value-bind (sequence sequence-json)
906 (lw2-graphql-query
907 (lw2-query-string :sequence :single
908 (alist :document-id sequence-id)
909 :fields `(:--id :title :created-at :user-id
910 (:contents :html)
911 (:chapters :title :subtitle :number (:contents :html) (:posts ,@(request-fields :post :list nil)))
912 :grid-image-id :----typename))
913 :return-type :both)
914 (let ((posts (sequence-post-ids sequence)))
915 (with-cache-transaction
916 (dolist (post-id posts)
917 (let ((old-seqs (cache-get "post-sequence" post-id :value-type :json)))
918 (unless (member sequence-id old-seqs :test #'string=)
919 (cache-put "post-sequence" post-id (cons sequence-id old-seqs) :value-type :json)))))
920 sequence-json)))))
921 (lw2-graphql-query-timeout-cached fn "sequence-json" sequence-id))))
923 (define-backend-function get-post-sequence-ids (post-id)
924 (backend-graphql
925 (cache-get "post-sequence" post-id :value-type :json)))
927 (defun preload-sequences-cache ()
928 (declare (optimize space (compilation-speed 2) (speed 0)))
929 (let ((sequences (apply #'append
930 (loop for view in '("curatedSequences" "communitySequences")
931 collect (lw2-graphql-query (lw2-query-string :sequence :list (alist :view view) :fields '(:--id)))))))
932 (dolist (sequence sequences)
933 (get-sequence (cdr (assoc :--id sequence))))
934 (format t "Retrieved ~A sequences." (length sequences)))
935 (values))
937 (define-backend-function user-deleted (user-id &optional (status nil set))
938 (backend-base
939 (declare (ignore user-id status set))
940 nil)
941 (backend-lw2-modernized
942 (when user-id
943 (if set
944 (if status
945 (cache-put "user-deleted" user-id "1")
946 (cache-del "user-deleted" user-id))
947 (cache-get "user-deleted" user-id :return-type 'existence)))))
949 (define-backend-function get-user (user-identifier-type user-identifier &key (revalidate *revalidate-default*) (force-revalidate *force-revalidate-default*) auth-token)
950 (backend-graphql
951 (let* ((user-id (ccase user-identifier-type
952 (:user-id user-identifier)
953 (:user-slug (get-slug-userid user-identifier))))
954 (query-string (lw2-query-string :user :single (alist :document-id user-id) :fields (list-cond* (auth-token :last-notifications-check) (user-fields))))
955 (result (if auth-token
956 (lw2-graphql-query query-string :auth-token auth-token)
957 (lw2-graphql-query-timeout-cached query-string "user-json" user-id :revalidate revalidate :force-revalidate force-revalidate))))
958 (alist-bind ((user-id (or simple-string null) :--id)
959 (display-name (or simple-string null))
960 (full-name (or simple-string null))
961 (slug (or simple-string null))
962 (deleted boolean))
963 result
964 (when user-id
965 (with-cache-transaction
966 (when display-name
967 (cache-username user-id display-name))
968 (when full-name
969 (cache-user-full-name user-id full-name))
970 (when slug
971 (cache-user-slug user-id slug)
972 (cache-slug-userid slug user-id))
973 (user-deleted user-id deleted))))
974 result)))
976 (define-backend-function get-notifications (&key user-id (offset 0) (limit 40) auth-token)
977 (backend-lw2-legacy
978 (lw2-graphql-query (lw2-query-string :notification :list
979 (alist* :user-id user-id :limit limit :offset offset *notifications-base-terms*)
980 :fields '(:--id :document-type :document-id :link :title :message :type :viewed))
981 :auth-token auth-token))
982 (backend-lw2-modernized
983 (declare (ignore user-id offset limit auth-token))
984 (let ((*notifications-base-terms* (remove :null *notifications-base-terms* :key #'cdr)))
985 (call-next-method))))
987 (define-backend-function check-notifications (user-id auth-token &key full since)
988 (backend-lw2-legacy
989 (multiple-value-bind (notifications user-info)
990 (lw2-graphql-query-multi (list
991 (lw2-query-string* :notification :list (alist* :user-id user-id :limit (if full 3 1) *notifications-base-terms*)
992 :fields (if full '(:--id :message :created-at) '(:created-at)))
993 (lw2-query-string* :user :single (alist :document-id user-id) :fields '(:last-notifications-check)))
994 :auth-token auth-token)
995 (let ((last-check (or since
996 (let ((last-check-string (cdr (assoc :last-notifications-check user-info))))
997 (when (and (stringp last-check-string) (not (equal last-check-string "")))
998 (local-time:parse-timestring last-check-string))))))
999 (when notifications
1000 (labels ((unread-p (notification)
1001 (if last-check
1002 (local-time:timestamp>
1003 (local-time:parse-timestring (cdr (assoc :created-at notification)))
1004 last-check)
1005 ;; User has never checked notifications before -- all are unread
1006 t)))
1007 (if full
1008 (remove-if-not #'unread-p notifications)
1009 (unread-p (first notifications))))))))
1010 (backend-lw2-modernized
1011 (declare (ignore user-id auth-token full since))
1012 (let ((*notifications-base-terms* (remove :null *notifications-base-terms* :key #'cdr)))
1013 (call-next-method))))
1015 (define-cache-database 'backend-lw2-legacy "comment-reply-by-user")
1017 (define-backend-function mark-comment-replied (reply)
1018 (backend-lw2-legacy
1019 (alexandria:when-let* ((parent-comment-id (cdr (assoc :parent-comment-id reply)))
1020 (reply-id (cdr (assoc :--id reply)))
1021 (user-id (cdr (assoc :user-id reply))))
1022 (cache-put "comment-reply-by-user" (concatenate 'string parent-comment-id " " user-id) reply-id))))
1024 (define-backend-function check-comment-replied (comment-id user-id)
1025 (backend-lw2-legacy
1026 (cache-get "comment-reply-by-user" (concatenate 'string comment-id " " user-id))))
1028 (define-backend-function get-user-page-items (user-id request-type &key (offset 0) (limit 40) (sort-type :date) drafts
1029 (revalidate *revalidate-default*) (force-revalidate *force-revalidate-default*) auth-token)
1030 (backend-lw2-legacy
1031 (multiple-value-bind (real-offset real-limit) (if (eq request-type :both)
1032 (values 0 (+ offset limit))
1033 (values offset limit))
1034 (let* ((cache-database (when (and (eq request-type :both)
1035 (or (not offset) (= offset 0))
1036 (= limit 40)
1037 (eq sort-type :date)
1038 (not drafts)
1039 (not auth-token))
1040 "user-page-items"))
1041 (return-type (if cache-database :string nil))
1042 (fn (lambda ()
1043 (labels ((posts-query-string ()
1044 (let* ((base-terms
1045 (cond
1046 (drafts (alist :view "drafts"))
1047 ((eq sort-type :score) (alist :view "top"))
1048 ((eq sort-type :date-reverse) (alist :view "old"))
1049 (t (alist :view "userPosts"))))
1050 (terms (alist* :offset real-offset :limit real-limit :user-id user-id base-terms)))
1051 (declare (dynamic-extent base-terms terms))
1052 (lw2-query-string* :post :list terms)))
1053 (comments-query-string ()
1054 (let* ((view (ecase sort-type
1055 (:score "postCommentsTop")
1056 (:date "allRecentComments")
1057 (:date-reverse "postCommentsOld")))
1058 (terms (alist :offset real-offset
1059 :limit real-limit
1060 :user-id user-id
1061 :view view)))
1062 (declare (dynamic-extent view terms))
1063 (lw2-query-string* :comment :list terms
1064 :context :index))))
1065 (declare (dynamic-extent #'posts-query-string #'comments-query-string))
1066 (case request-type
1067 (:both (let ((result (multiple-value-call #'concatenate 'list
1068 (lw2-graphql-query-multi (list (posts-query-string) (comments-query-string))))))
1069 (ecase return-type
1070 (:string (json:encode-json-to-string result))
1071 ((nil) result))))
1072 (:posts (lw2-graphql-query (format nil "{~A}" (posts-query-string)) :auth-token auth-token :return-type return-type))
1073 (:comments (lw2-graphql-query (format nil "{~A}" (comments-query-string)) :auth-token auth-token :return-type return-type)))))))
1074 (if cache-database
1075 (lw2-graphql-query-timeout-cached fn cache-database user-id :decoder 'deserialize-query-result :revalidate revalidate :force-revalidate force-revalidate)
1076 (funcall fn))))))
1078 (define-backend-function get-conversation-messages (conversation-id auth-token)
1079 (backend-lw2-legacy
1080 (lw2-graphql-query-multi
1081 (list
1082 (lw2-query-string* :conversation :single (alist :document-id conversation-id) :fields '(:title (:participants :display-name :slug)))
1083 (lw2-query-string* :message :list (alist :view "messagesConversation" :conversation-id conversation-id) :fields *messages-index-fields*))
1084 :auth-token auth-token)))
1086 (defun search-result-markdown-to-html (item)
1087 (alist* :html-body
1088 (handler-case (nth-value 1 (cl-markdown:markdown (cdr (assoc :body item)) :stream nil))
1089 (serious-condition () "[Error while processing search result]"))
1090 item))
1092 (define-backend-function algolia-search-index-name (index)
1093 (backend-lw2
1094 (format nil "test_~(~A~)" index))
1095 (backend-ea-forum
1096 (format nil "test_~(~A~)" index))
1097 (backend-progress-forum
1098 (format nil "pf-prod-~(~A~)" index)))
1100 (define-backend-function encode-algolia-search-query (query indexes)
1101 (backend-algolia-search
1102 (json:encode-json-alist-to-string
1103 (alist
1104 "requests"
1105 (loop for index in indexes
1106 collect (alist "indexName" (algolia-search-index-name index)
1107 "params" (format nil "query=~A&hitsPerPage=200&page=0"
1108 (url-rewrite:url-encode query)))))))
1109 (backend-lw2
1110 (json:encode-json-to-string
1111 (loop for index in indexes
1112 collect (alist "indexName" (algolia-search-index-name index)
1113 "params" (alist "query" query
1114 "hitsPerPage" 200
1115 "page" 0))))))
1117 (define-backend-function decode-algolia-search-results (data)
1118 (backend-algolia-search
1119 (cdr (assoc :results data)))
1120 (backend-lw2
1121 data))
1123 (define-backend-function lw2-search-query (query &key (indexes '(:tags :posts :comments)))
1124 (backend-algolia-search
1125 (call-with-http-response
1126 (lambda (req-stream)
1127 (let* ((tags nil)
1128 (result-groups (loop
1129 for results in (decode-algolia-search-results
1130 (json:decode-json req-stream))
1131 for index in indexes
1132 for hits = (cdr (assoc :hits results))
1133 do (setf hits (case index
1134 (:posts (map 'list (lambda (post) (if (cdr (assoc :comment-count post)) post (alist* :comment-count 0 post))) hits))
1135 (:comments (map 'list #'search-result-markdown-to-html hits))
1136 (:tags (progn (setf tags (map 'list (lambda (tag) (alist* :----typename "Tag" tag)) hits))
1137 nil))
1138 (t hits)))
1139 collect hits)))
1140 (values
1141 (with-collector (col)
1142 (let ((remaining-result-groups result-groups))
1143 (loop while (some #'identity result-groups)
1144 do (multiple-value-bind (firstn rest)
1145 (firstn (car remaining-result-groups) 10)
1146 (map nil #'col firstn)
1147 (setf (car remaining-result-groups) rest
1148 remaining-result-groups (or (rest remaining-result-groups)
1149 result-groups)))))
1150 (col))
1151 tags)))
1152 (algolia-search-uri *current-backend*)
1153 :method :post
1154 :headers '(("Origin" . "https://www.greaterwrong.com")
1155 ("Referer" . "https://www.greaterwrong.com/")
1156 ("Content-Type" . "application/json"))
1157 :content (encode-algolia-search-query query indexes)
1158 :want-stream t)))
1160 (define-backend-function get-username-wrapper (user-id fn)
1161 (backend-base
1162 (funcall fn user-id))
1163 (backend-lw2-modernized
1164 (if (user-deleted user-id)
1165 "[deleted]"
1166 (funcall fn user-id))))
1168 (define-backend-function get-user-full-name-wrapper (user-id fn)
1169 (backend-base
1170 (funcall fn user-id))
1171 (backend-ea-forum
1172 ""))
1174 (define-cache-database 'backend-lw2-legacy "comment-markdown-source" "post-markdown-source")
1176 (defun markdown-source-db-name (target-type)
1177 (ecase target-type (:comment "comment-markdown-source") (:post "post-markdown-source")))
1179 (define-backend-function markdown-source (target-type id version)
1180 (backend-lw2-modernized
1181 (let ((db-name (markdown-source-db-name target-type))
1182 (version (base64:usb8-array-to-base64-string (hash-string version))))
1184 (if-let ((cache-data (cache-get db-name id :value-type :lisp)))
1185 (alist-bind ((cached-version simple-string :version)
1186 (markdown simple-string))
1187 cache-data
1188 (when (string= version cached-version)
1189 markdown)))
1190 (trivia:ematch (lw2-graphql-query (lw2-query-string target-type :single
1191 (alist :document-id id)
1192 :fields '(:html-body (:contents :markdown)))
1193 :auth-token *current-auth-token*)
1194 ((trivia:alist (:html-body . html-body)
1195 (:contents . (assoc :markdown markdown)))
1196 (cache-put db-name id (alist :version (base64:usb8-array-to-base64-string (hash-string html-body)) :markdown markdown) :value-type :lisp)
1197 markdown))))))
1199 (define-backend-function (setf markdown-source) (markdown target-type id version)
1200 (backend-lw2-modernized
1201 (let ((version (base64:usb8-array-to-base64-string (hash-string version))))
1202 (cache-put (markdown-source-db-name target-type)
1204 (alist :version version :markdown markdown)
1205 :value-type :lisp))))
1207 (defun get-elicit-question-title (question-id)
1208 (cdr
1209 (lw2-graphql-query (graphql-query-string "ElicitBlockData" (alist :question-id question-id) '(:title)))))
1211 (defun make-rate-limiter (delay)
1212 (let ((rl-hash (make-hash-table :test 'equal :synchronized t)))
1213 (lambda (datum fn)
1214 (let ((unix-time (get-unix-time)))
1215 (if (sb-ext:with-locked-hash-table (rl-hash)
1216 (maphash (lambda (k v)
1217 (if (> (- unix-time v) delay)
1218 (remhash k rl-hash)))
1219 rl-hash)
1220 (not (gethash datum rl-hash)))
1221 (progn
1222 (setf (gethash datum rl-hash) unix-time)
1223 (funcall fn))
1224 (error "Request aborted due to rate limit."))))))
1226 (defmacro with-rate-limit (&body outer-body)
1227 `(let ((rate-limiter (make-rate-limiter 30)))
1228 (macrolet ((rate-limit ((key) &body inner-body)
1229 `(funcall rate-limiter ,key (lambda () ,@inner-body))))
1230 ,@outer-body)))
1232 (with-rate-limit
1233 (simple-cacheable ("post-title" 'backend-lw2-legacy "postid-to-title" post-id)
1234 (rate-limit (post-id) (cdr (first (lw2-graphql-query (lw2-query-string :post :single (alist :document-id post-id) :fields '(:title))))))))
1236 (with-rate-limit
1237 (simple-cacheable ("post-slug" 'backend-lw2-legacy "postid-to-slug" post-id)
1238 (rate-limit (post-id) (cdr (first (lw2-graphql-query (lw2-query-string :post :single (alist :document-id post-id) :fields '(:slug))))))))
1240 (with-rate-limit
1241 (simple-cacheable ("slug-postid" 'backend-lw2-legacy "slug-to-postid" slug)
1242 (rate-limit (slug) (cdr (first (lw2-graphql-query (lw2-query-string :post :single (alist :slug slug) :fields '(:--id))))))))
1244 (with-rate-limit
1245 (simple-cacheable ("username" 'backend-lw2-legacy "userid-to-displayname" user-id :get-wrapper #'get-username-wrapper)
1246 (rate-limit (user-id) (cdr (first (lw2-graphql-query (lw2-query-string :user :single (alist :document-id user-id) :fields '(:display-name))))))))
1248 (with-rate-limit
1249 (simple-cacheable ("user-slug" 'backend-lw2-legacy "userid-to-slug" user-id)
1250 (rate-limit (user-id) (cdr (first (lw2-graphql-query (lw2-query-string :user :single (alist :document-id user-id) :fields '(:slug))))))))
1252 (with-rate-limit
1253 (simple-cacheable ("user-full-name" 'backend-lw2-legacy "userid-to-full-name" user-id :get-wrapper #'get-user-full-name-wrapper)
1254 (rate-limit (user-id) (or (cdr (first (lw2-graphql-query (lw2-query-string :user :single (alist :document-id user-id) :fields '(:full-name)))))
1255 ""))))
1257 (with-rate-limit
1258 (simple-cacheable ("slug-userid" 'backend-lw2-legacy "slug-to-userid" slug)
1259 (rate-limit (slug) (cdr (first (lw2-graphql-query (lw2-query-string :user :single (alist :slug slug) :fields '(:--id))))))))
1261 (with-rate-limit
1262 (simple-cacheable ("slug-tagid" 'backend-lw2-tags "slug-to-tagid" slug :catch-errors nil)
1263 (rate-limit (slug) (cdr (first (first (lw2-graphql-query (lw2-query-string :tag :list (alist :view "tagBySlug" :slug slug) :fields '(:--id)))))))))
1265 (defun preload-username-cache ()
1266 (declare (optimize space (compilation-speed 2) (speed 0)))
1267 (let ((user-list (lw2-graphql-query (lw2-query-string :user :list '() :fields '(:--id :slug :display-name)))))
1268 (with-cache-transaction
1269 (loop for user in user-list
1270 do (alist-bind ((user-id (or simple-string null) :--id)
1271 (slug (or simple-string null))
1272 (display-name (or simple-string null)))
1273 user
1274 (when user-id
1275 (when display-name
1276 (cache-username user-id display-name))
1277 (when slug
1278 (cache-user-slug user-id slug)
1279 (cache-slug-userid slug user-id))))))))