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