Add support for debates.
[lw2-viewer.git] / src / backend.lisp
blob08236111868efc4ce8264aac14cdc34a33e94fec
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"))))
286 (define-backend-function fixup-lw2-return-value (value)
287 (backend-base
288 (values value nil))
289 (backend-lw2-modernized
290 (values
291 (let ((x (first value)))
292 (if (member (car x) '(:result :results :total-count))
293 (cdr x)
295 (let ((x (second value)))
296 (if (eq (car x) :total-count)
297 (cdr x)))))
298 (backend-accordius
299 (values value nil)))
301 (define-backend-function deserialize-query-result (result-source)
302 (backend-base
303 (let ((string-source (typecase result-source
304 (string
305 result-source)
306 (vector
307 (flexi-streams:make-in-memory-input-stream result-source))
308 (stream
309 (ensure-character-stream result-source)))))
310 (json:decode-json-from-source string-source))))
312 (define-backend-function postprocess-query-result (result)
313 (backend-base
314 result)
315 (backend-lw2-legacy
316 (signal-lw2-errors (cdr (assoc :errors result)))
317 (fixup-lw2-return-value (cdadr (assoc :data result)))))
319 (define-backend-function decode-query-result (result-source)
320 (backend-base
321 (postprocess-query-result
322 (deserialize-query-result result-source))))
324 (defmethod graphql-uri ((backend backend-alignment-forum))
325 (if *use-alignment-forum*
326 "https://www.alignmentforum.org/graphql"
327 (call-next-method)))
329 (define-backend-function backend-request-headers (auth-token forwarded)
330 (backend-websocket-login
331 (list-cond* (auth-token :authorization auth-token)
332 (call-next-method)))
333 (backend-passport-js-login
334 (list-cond* (auth-token :cookie (concatenate 'string "loginToken=" auth-token))
335 (call-next-method)))
336 (backend-oauth2.0-login
337 (list-cond* (auth-token :cookie (concatenate 'string "clientId=" (oauth2.0-client-id backend) "; loginToken=" auth-token))
338 (call-next-method)))
339 (backend-graphql
340 (alist* :content-type "application/json"
341 (if forwarded (forwarded-header)))))
343 (define-backend-function call-with-backend-response (fn query &key return-type auth-token)
344 (backend-graphql
345 (call-with-http-response
347 (graphql-uri *current-backend*)
348 :method :post
349 :headers (backend-request-headers auth-token nil)
350 :content (dynamic-let ((q (alist :query query))) (json:encode-json-to-string q))
351 :want-stream (not return-type))))
353 (define-backend-function lw2-graphql-query (query &key auth-token return-type (decoder 'decode-query-result))
354 (backend-base
355 (do-graphql-debug query)
356 (call-with-backend-response
357 (ecase return-type
358 ((nil) decoder)
359 (:string #'identity)
360 (:both (lambda (string) (values (funcall decoder string) string))))
361 query
362 :return-type return-type
363 :auth-token auth-token)))
365 (defun lw2-graphql-query-map (fn data &key auth-token postprocess)
366 (multiple-value-bind (map-values queries)
367 (loop for d in data
368 as out-values = (multiple-value-list (funcall fn d))
369 as (out passthrough-p) = out-values
370 collect out-values into map-values
371 when (not passthrough-p) collect out into queries
372 finally (return (values map-values queries)))
373 (let* ((query-string
374 (with-output-to-string (stream)
375 (format stream "{")
376 (loop for n from 0
377 for q in queries
378 do (format stream "g~6,'0D:~A " n q))
379 (format stream "}")))
380 (query-result-data (when queries (lw2-graphql-query query-string :decoder 'deserialize-query-result :auth-token auth-token)))
381 (errors (cdr (assoc :errors query-result-data))))
382 (signal-lw2-errors errors)
383 (values
384 (loop as results = (sort (cdr (assoc :data query-result-data)) #'string< :key #'car) then (if passthrough-p results (rest results))
385 for (out passthrough-p) in map-values
386 as result-data-cell = (first results)
387 as result-data = (if passthrough-p out (fixup-lw2-return-value (cdr result-data-cell)))
388 for input-data in data
389 collect (if postprocess (funcall postprocess input-data result-data) result-data))
390 errors))))
392 (defun lw2-graphql-query-multi (query-list &key auth-token)
393 (values-list (lw2-graphql-query-map #'identity query-list :auth-token auth-token)))
395 (defvar *background-cache-update-threads* (make-hash-table :test 'equal
396 :weakness :value
397 :synchronized t))
399 (defvar *parsed-results-cache* (make-hash-table :test 'equal
400 :weakness :value
401 :synchronized t))
403 (defun cache-update (cache-db key data)
404 (let ((meta-db (format nil "~A-meta" cache-db))
405 (new-hash (hash-string data))
406 (current-time (get-unix-time)))
407 (with-cache-transaction
408 (let* ((metadata (cache-get meta-db key :value-type :lisp))
409 (same-data (equalp new-hash (cdr (assoc :city-128-hash metadata))))
410 (last-mod (if same-data
411 (or (cdr (assoc :last-modified metadata)) current-time)
412 current-time)))
413 (cache-put meta-db key (alist :last-checked current-time :last-modified last-mod :city-128-hash new-hash) :value-type :lisp)
414 (unless same-data
415 (remhash (list *current-backend* cache-db key) *parsed-results-cache*)
416 (cache-put cache-db key data))
417 (values data (unix-to-universal-time last-mod))))))
419 (defun cache-mark-stale (cache-db key)
420 (let ((meta-db (format nil "~A-meta" cache-db))
421 (current-time (get-unix-time)))
422 (with-cache-transaction
423 (let* ((metadata (cache-get meta-db key :value-type :lisp))
424 (metadata (alist* :last-modified current-time (delete :last-modified metadata :key #'car))))
425 (cache-put meta-db key metadata :value-type :lisp)))))
427 (declaim (type (and fixnum (integer 1)) *cache-stale-factor* *cache-skip-factor*))
428 (defparameter *cache-stale-factor* 100)
429 (defparameter *cache-skip-factor* 5000)
431 (defun cache-freshness-status (cache-db key)
432 (with-cache-readonly-transaction
433 (when (cache-exists cache-db key)
434 (let ((metadata (cache-get (format nil "~A-meta" cache-db) key :value-type :lisp))
435 (current-time (get-unix-time)))
436 (if-let ((last-mod (cdr (assoc :last-modified metadata)))
437 (last-checked (cdr (assoc :last-checked metadata))))
438 (values
439 (let ((unmodified-time (- last-checked last-mod))
440 (last-checked-time (- current-time last-checked)))
441 (if (> unmodified-time (* *cache-skip-factor* last-checked-time))
442 :skip
443 (> unmodified-time (* *cache-stale-factor* last-checked-time))))
445 (unix-to-universal-time last-mod)))))))
447 (defgeneric run-query (query)
448 (:method ((query string))
449 (lw2-graphql-query query :return-type :string))
450 (:method ((query function))
451 (funcall query)))
453 (declaim (inline make-thread-with-current-backend))
455 (defun make-thread-with-current-backend (fn &rest args)
456 (let ((current-backend *current-backend*))
457 (apply #'sb-thread:make-thread
458 (lambda ()
459 (let ((*current-backend* current-backend))
460 (funcall fn)))
461 args)))
463 (defun ensure-cache-update-thread (query cache-db cache-key)
464 (let ((key (format nil "~A-~A" cache-db cache-key)))
465 (labels ((background-fn ()
466 (unwind-protect
467 (block nil
468 (multiple-value-bind (value error)
469 (log-and-ignore-errors
470 (sb-sys:with-deadline (:seconds 60)
471 (return (cache-update cache-db cache-key (run-query query)))))
472 (declare (ignore value))
473 (return error)))
474 (remhash key *background-cache-update-threads*))))
475 (sb-ext:with-locked-hash-table (*background-cache-update-threads*)
476 (let ((thread (gethash key *background-cache-update-threads*)))
477 (if thread thread
478 (setf (gethash key *background-cache-update-threads*)
479 (make-thread-with-current-backend #'background-fn :name "background cache update"))))))))
481 (define-backend-function lw2-graphql-query-timeout-cached (query cache-db cache-key &key (decoder 'decode-query-result)
482 (revalidate *revalidate-default*) (force-revalidate *force-revalidate-default*))
483 (backend-base
484 (multiple-value-bind (is-fresh cached-result last-modified)
485 (cache-freshness-status cache-db cache-key)
486 (labels ((get-cached-result ()
487 (if-let ((parsed-result (gethash (list *current-backend* cache-db cache-key) *parsed-results-cache*)))
488 (multiple-value-call #'values (values-list parsed-result) last-modified)
489 (multiple-value-bind (result count)
490 (with-cache-readonly-transaction (funcall decoder (cache-get cache-db cache-key :return-type 'binary-stream)))
491 (setf (gethash (list *current-backend* cache-db cache-key) *parsed-results-cache*) (list result count))
492 (values result count last-modified)))))
493 (if (and cached-result (or (not revalidate)
494 (and (not force-revalidate) (eq is-fresh :skip))))
495 (get-cached-result)
496 (let ((timeout (if cached-result
497 (if force-revalidate nil 3)
498 nil))
499 (thread (ensure-cache-update-thread query cache-db cache-key)))
500 (block retrieve-result
501 (if (and cached-result (if force-revalidate (not revalidate) (or is-fresh (not revalidate))))
502 (get-cached-result)
503 (handler-bind
504 ((fatal-error (lambda (c)
505 (declare (ignore c))
506 (if cached-result
507 (return-from retrieve-result (get-cached-result))))))
508 (multiple-value-bind (new-result last-modified)
509 (sb-thread:join-thread thread :timeout timeout)
510 (typecase new-result
511 (condition (error new-result))
512 (t (multiple-value-bind (result count)
513 (funcall decoder new-result)
514 (setf (gethash (list *current-backend* cache-db cache-key) *parsed-results-cache*) (list result count))
515 (values result count last-modified))))))))))))))
517 (define-backend-function lw2-query-string* (query-type return-type args &key context fields with-total))
519 (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)
520 (declare (ignore with-total))
521 (labels ((lisp-to-lw2-case (x) (json:lisp-to-camel-case (format nil "*~A" x))))
522 (graphql-query-string*
523 (concatenate 'string
524 (lisp-to-lw2-case query-type)
526 (lisp-to-lw2-case return-type))
527 (if (eq return-type :single)
528 args
529 (alist :terms args))
530 fields)))
532 (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)
533 (graphql-query-string*
534 (if (eq return-type :single)
535 (json:lisp-to-camel-case (string query-type))
536 (concatenate 'string (json:lisp-to-camel-case (string query-type)) "s"))
537 (alist :input (case return-type
538 (:single (alist :selector args))
539 (:list (alist :enable-total with-total :terms args))
540 (:total (alist :enable-total t :terms args))))
541 (case return-type
542 (:total '(:total-count))
543 (:list (list-cond (t :results fields)
544 (with-total :total-count)))
545 (:single (alist :result fields)))))
547 (define-backend-function lw2-query-string (query-type return-type args &key context fields with-total))
549 (define-backend-operation lw2-query-string backend-lw2-legacy (query-type return-type args &rest rest &key context fields with-total)
550 (declare (ignore context fields with-total))
551 (format nil "{~A}" (apply 'lw2-query-string* query-type return-type args rest)))
553 (define-backend-function lw2-query-list-limit-workaround (query-type terms &rest rest &key fields context auth-token)
554 (backend-graphql
555 (declare (ignore fields context))
556 (let (items-list)
557 (loop for offset from 0 by 500
558 as items-next = (lw2-graphql-query (apply 'lw2-query-string query-type :list (alist* :limit 500 :offset offset terms) (filter-plist rest :fields :context))
559 :auth-token auth-token)
560 as length = (length items-next)
561 do (setf items-list (nconc items-list items-next))
562 while (>= length 500))
563 items-list))
564 (backend-accordius
565 (declare (ignore fields context))
566 (lw2-graphql-query (apply 'lw2-query-string query-type :list terms (filter-plist rest :fields :context)) :auth-token auth-token)))
568 (defun get-cached-index-query (cache-id query)
569 (multiple-value-bind (is-fresh cached-result last-modified)
570 (cache-freshness-status "index-json" cache-id)
571 (declare (ignore is-fresh))
572 (labels ((query-and-put ()
573 (multiple-value-bind (encoded-result last-modified)
574 (cache-update "index-json" cache-id (lw2-graphql-query query :return-type :string))
575 (multiple-value-bind (result count)
576 (decode-query-result encoded-result)
577 (values result count last-modified))))
578 (get-cached-result ()
579 (with-cache-readonly-transaction
580 (multiple-value-bind (result count)
581 (decode-query-result (cache-get "index-json" cache-id :return-type 'binary-stream))
582 (values result count last-modified)))))
583 (if (and cached-result (background-loader-ready-p))
584 (get-cached-result)
585 (if cached-result
586 (handler-case
587 (query-and-put)
588 (t () (get-cached-result)))
589 (query-and-put))))))
591 (define-backend-function get-posts-index-query-terms (&key view (sort "new") (limit 21) offset before after karma-threshold &allow-other-keys)
592 (backend-lw2-legacy
593 (let ((sort-key (alexandria:switch (sort :test #'string=)
594 ("new" "new")
595 ("hot" "magic")
596 ("active" "recentComments")
597 ("top" "top")
598 ("old" "old"))))
599 (multiple-value-bind (view-terms cache-key)
600 (alexandria:switch (view :test #'string=)
601 ("featured" (alist :sorted-by sort-key :filter "curated"))
602 ("all" (alist :sorted-by sort-key :filter "all"))
603 ("alignment-forum" (alist :sorted-by sort-key :af t))
604 ("questions" (alist :sorted-by sort-key :filter "questions"))
605 ("events" (alist :sorted-by sort-key :filter "events"))
606 ("nominations" (alist :view "nominations2019"))
607 ("reviews" (alist :view "reviews2019"))
608 (t (values
609 (alist :sorted-by sort-key :filter "frontpage")
610 (if (not (or (string/= sort "new") (/= limit 21) offset before after karma-threshold)) "new-not-meta"))))
611 (let ((terms
612 (alist-without-null* :before before
613 :after after
614 :limit limit
615 :offset offset
616 :karma-threshold karma-threshold
617 view-terms)))
618 (values terms cache-key))))))
620 (define-backend-operation get-posts-index-query-terms backend-lw2-tags :around (&key hide-tags &allow-other-keys)
621 (multiple-value-bind (query-terms cache-key) (call-next-method)
622 (if hide-tags
623 (values (acons :filter-settings (alist :tags (list* :list (map 'list (lambda (tagid) (alist :tag-id tagid :filter-mode "Hidden"))
624 hide-tags)))
625 query-terms)
626 nil)
627 (values query-terms cache-key))))
629 (define-backend-function get-posts-index-query-string (&rest args &key &allow-other-keys)
630 (backend-lw2-legacy
631 (declare (dynamic-extent args))
632 (multiple-value-bind (query-terms cache-key)
633 (apply #'%get-posts-index-query-terms backend args)
634 (values (lw2-query-string :post :list query-terms)
635 cache-key))))
637 (define-backend-function get-posts-index (&rest args &key &allow-other-keys)
638 (backend-lw2-legacy
639 (declare (dynamic-extent args))
640 (multiple-value-bind (query-string cache-key)
641 (apply #'%get-posts-index-query-string backend args)
642 (if cache-key
643 (get-cached-index-query cache-key query-string)
644 (lw2-graphql-query query-string)))))
646 (define-backend-operation get-posts-index backend-lw2-tags :around (&rest args &key hide-tags offset (limit 21) &allow-other-keys)
647 ;; Workaround for https://github.com/LessWrong2/Lesswrong2/issues/3099
648 (declare (dynamic-extent args))
649 (if hide-tags
650 (let ((offset (or offset 0)))
651 (subseq
652 (apply #'call-next-method backend :offset 0 :limit (+ limit offset) args)
653 offset))
654 (call-next-method)))
656 (defun get-posts-json ()
657 (lw2-graphql-query (get-posts-index-query-string) :return-type :string))
659 (defun get-recent-comments (&key with-total)
660 (get-cached-index-query "recent-comments" (lw2-query-string :comment :list '((:view . "allRecentComments") (:limit . 20)) :context :index :with-total with-total)))
662 (defun get-recent-comments-json ()
663 (lw2-graphql-query (lw2-query-string :comment :list '((:view . "allRecentComments") (:limit . 20)) :context :index) :return-type :string))
665 (defun process-vote-result (res)
666 (alist-bind ((id (or null simple-string) :--id)
667 current-user-votes
668 current-user-vote
669 current-user-extended-vote)
671 (let ((karma-vote (or (nonempty-string current-user-vote)
672 (cdr (assoc :vote-type (first current-user-votes))))))
673 (values (list-cond* (karma-vote :karma karma-vote)
674 current-user-extended-vote)
675 id))))
677 (defun process-votes-result (res)
678 (let ((hash (make-hash-table)))
679 (dolist (v res hash)
680 (multiple-value-bind (vote id) (process-vote-result v)
681 (when vote
682 (setf (gethash id hash) vote))))))
684 (defun flatten-shortform-comments (comments)
685 (let ((output comments))
686 (loop for comment in comments do
687 (setf output (append (cdr (assoc :latest-children comment)) output)))
688 output))
690 (defun get-shortform-votes (auth-token &key (offset 0) (limit 20))
691 (process-votes-result
692 (flatten-shortform-comments
693 (lw2-graphql-query (lw2-query-string :comment :list (alist :view "shortform" :offset offset :limit limit)
694 :fields '(:--id :current-user-vote :current-user-extended-vote (:latest-children :--id :current-user-vote :current-user-extended-vote)))
695 :auth-token auth-token))))
697 (defun get-post-vote (post-id auth-token)
698 (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)))
700 (define-cache-database 'backend-lw2-tags "tag-posts" "tag-posts-meta" "post-tags" "post-tags-meta")
702 (define-backend-function get-tag-posts (slug &key (revalidate *revalidate-default*) (force-revalidate *force-revalidate-default*))
703 (backend-base (declare (ignore revalidate force-revalidate)) nil)
704 (backend-lw2-tags
705 (let* ((tagid (get-slug-tagid slug))
706 (query-fn (lambda ()
707 (comments-list-to-graphql-json
708 (lw2-query-list-limit-workaround
709 :tag-rel
710 (alist :view "postsWithTag" :tag-id tagid)
711 :fields (list (list* :post (request-fields :post :list :index))))))))
712 (iter
713 (for x in (lw2-graphql-query-timeout-cached query-fn "tag-posts" tagid :revalidate revalidate :force-revalidate force-revalidate))
714 (when-let (post (cdr (assoc :post x)))
715 (collect post))))))
717 (define-backend-function get-tag-post-votes (tag-id auth-token)
718 (backend-base (progn tag-id auth-token nil))
719 (backend-lw2-tags
720 (process-votes-result
721 (map 'list #'cdr
722 (lw2-query-list-limit-workaround
723 :tag-rel
724 (alist :view "postsWithTag" :tag-id tag-id)
725 :fields '(:--id :current-user-vote :current-user-extended-vote)
726 :auth-token auth-token)))))
728 (define-backend-function get-post-tags (post-id &key (revalidate *revalidate-default*) (force-revalidate *force-revalidate-default*))
729 (backend-base (declare (ignore revalidate force-revalidate)) nil)
730 (backend-lw2-tags
731 (let ((query-string (lw2-query-string :tag-rel :list (alist :view "tagsOnPost" :post-id post-id) :fields '((:tag :name :slug)))))
732 (lw2-graphql-query-timeout-cached query-string "post-tags" post-id :revalidate revalidate :force-revalidate force-revalidate))))
734 (define-backend-function get-post-tag-votes (post-id auth-token)
735 (backend-base (progn post-id auth-token nil))
736 (backend-lw2-tags
737 (process-votes-result
738 (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))
739 :auth-token auth-token))))
741 (define-backend-function get-post-body (post-id &key (revalidate *revalidate-default*) (force-revalidate *force-revalidate-default*) auth-token)
742 (backend-graphql
743 (let ((query-string (lw2-query-string :post :single (alist :document-id post-id) :context :body)))
744 (block nil
745 (tagbody retry
746 (handler-bind ((lw2-login-required-error (lambda (&rest args)
747 (declare (ignore args))
748 (let ((current-auth-token *current-auth-token*))
749 (when (and (not auth-token) current-auth-token)
750 (setf auth-token current-auth-token)
751 (go retry))))))
752 (return
753 (if auth-token
754 (lw2-graphql-query query-string :auth-token auth-token)
755 (lw2-graphql-query-timeout-cached query-string "post-body-json" post-id :revalidate revalidate :force-revalidate force-revalidate))))))))
756 (backend-lw2-tags
757 (declare (ignore auth-token))
758 (acons :tags (get-post-tags post-id :revalidate revalidate :force-revalidate force-revalidate) (call-next-method)))
759 (backend-magnum-crossposts
760 (declare (ignore auth-token))
761 (let ((post (call-next-method)))
762 (alist-bind (is-crosspost hosted-here foreign-post-id) (cdr (assoc :fm-crosspost post))
763 (cond ((not (and (backend-magnum-crosspost-site backend)
764 (not (boundp '*retrieve-crosspost*))
765 is-crosspost foreign-post-id))
766 post)
767 (:otherwise
768 (let* ((*current-site* (find-site (backend-magnum-crosspost-site backend)))
769 (*current-backend* (site-backend *current-site*))
770 (*retrieve-crosspost* nil)
771 (foreign-post (get-post-body foreign-post-id :revalidate revalidate :force-revalidate force-revalidate))
772 (foreign-post-body (cdr (assoc :html-body foreign-post))))
773 (declare (special *retrieve-crosspost*))
774 (if foreign-post-body
775 (list-cond*
776 ((not hosted-here) :html-body foreign-post-body)
777 (t :foreign-post foreign-post)
778 post)
779 post))))))))
781 (defun get-post-comments-list (post-id view &rest rest &key auth-token parent-answer-id fields context)
782 (declare (ignore fields context auth-token))
783 (let ((terms (alist :view view :post-id post-id)))
784 (when parent-answer-id
785 (setf terms (acons :parent-answer-id parent-answer-id terms)))
786 (apply 'lw2-query-list-limit-workaround :comment terms (filter-plist rest :fields :context :auth-token))))
788 (defun get-post-answer-replies (post-id answers &rest rest &key auth-token fields context)
789 ;; todo: support more than 500 answers per question
790 (declare (ignore fields context))
791 (let* ((terms (alist :view "repliesToAnswer" :post-id post-id :limit 500))
792 (result (lw2-graphql-query-map
793 #'identity
794 (mapcar (lambda (answer) (apply 'lw2-query-string* :comment :list
795 (acons :parent-answer-id (cdr (assoc :--id answer)) terms)
796 (filter-plist rest :fields :context)))
797 answers)
798 :auth-token auth-token)))
799 (apply #'nconc result)))
801 (define-backend-function get-post-comments-votes (post-id auth-token)
802 (backend-graphql
803 (let ((fields '(:--id :current-user-vote :current-user-extended-vote)))
804 (process-votes-result
805 (get-post-comments-list post-id "postCommentsTop" :auth-token auth-token :fields fields))))
806 (backend-q-and-a
807 (let* ((fields '(:--id :current-user-vote :current-user-extended-vote))
808 (answers (get-post-comments-list post-id "questionAnswers" :auth-token auth-token :fields fields)))
809 (process-votes-result
810 (nconc
811 (get-post-comments-list post-id "postCommentsTop" :auth-token auth-token :fields fields)
812 (get-post-answer-replies post-id answers :auth-token auth-token :fields fields)
813 answers)))))
815 (define-backend-function get-tag-comments-votes (tag-id auth-token)
816 (backend-lw2-tags-comments
817 (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))
818 :auth-token auth-token))))
820 (define-backend-function get-post-comments (post-id &key (revalidate *revalidate-default*) (force-revalidate *force-revalidate-default*))
821 (backend-graphql
822 (let ((fn (lambda ()
823 (comments-list-to-graphql-json
824 (get-post-comments-list post-id "postCommentsTop")))))
825 (lw2-graphql-query-timeout-cached fn "post-comments-json" post-id :revalidate revalidate :force-revalidate force-revalidate)))
826 (backend-ea-forum
827 ;; Work around bizarre parent comment bug in EA forum
828 (declare (ignore revalidate force-revalidate))
829 (let ((comments (call-next-method)))
830 (dolist (c comments)
831 (if-let (parent-id-cons (assoc :parent-comment-id c))
832 (if (and (string= (cdr parent-id-cons) "rjgZaK8uzHG3jAu2p")
833 (not (string= post-id "h26Kx7uGfQfNewi7d")))
834 (setf (cdr parent-id-cons) nil))))
835 comments)))
837 (defun get-post-answers (post-id &key (revalidate *revalidate-default*) (force-revalidate *force-revalidate-default*))
838 (let ((fn (lambda ()
839 (let ((answers (get-post-comments-list post-id "questionAnswers")))
840 (comments-list-to-graphql-json
841 (nconc
842 answers
843 (get-post-answer-replies post-id answers)))))))
844 (lw2-graphql-query-timeout-cached fn "post-answers-json" post-id :revalidate revalidate :force-revalidate force-revalidate)))
846 (define-cache-database 'backend-debates
847 "post-debate-responses-json" "post-debate-responses-json-meta")
849 (define-backend-function get-post-debate-responses (post-id &key (revalidate *revalidate-default*) (force-revalidate *force-revalidate-default*))
850 (backend-base
851 (declare (ignore post-id revalidate force-revalidate))
852 nil)
853 (backend-debates
854 (let ((fn (lambda ()
855 (comments-list-to-graphql-json
856 (get-post-comments-list post-id "debateResponses")))))
857 (lw2-graphql-query-timeout-cached fn "post-debate-responses-json" post-id :revalidate revalidate :force-revalidate force-revalidate))))
859 (define-backend-function get-collection (collection-id)
860 (backend-graphql
861 (lw2-graphql-query
862 (lw2-query-string :collection :single
863 (alist :document-id collection-id)
864 :fields `(:--id :title (:contents :html) :grid-image-id :----typename
865 (:books :title :subtitle (:contents :html) :----typename
866 (:sequences :title (:contents :html) :grid-image-id :----typename
867 (:chapters :title :subtitle :number (:contents :html) (:posts ,@(request-fields :post :list nil))))))))))
869 (defun sequence-iterate (sequence fn)
870 (dolist (chapter (cdr (assoc :chapters sequence)))
871 (dolist (post (cdr (assoc :posts chapter)))
872 (funcall fn post))))
874 (defun sequence-post-ids (sequence)
875 (with-collector (col)
876 (sequence-iterate sequence
877 (lambda (post)
878 (col (cdr (assoc :--id post)))))
879 (col)))
881 (defun get-sequence-post (sequence post-id)
882 (sequence-iterate sequence
883 (lambda (post)
884 (when (string= (cdr (assoc :--id post)) post-id)
885 (return-from get-sequence-post post))))
886 nil)
888 (define-backend-function get-sequence (sequence-id)
889 (backend-graphql
890 (let ((fn (lambda ()
891 (multiple-value-bind (sequence sequence-json)
892 (lw2-graphql-query
893 (lw2-query-string :sequence :single
894 (alist :document-id sequence-id)
895 :fields `(:--id :title :created-at :user-id
896 (:contents :html)
897 (:chapters :title :subtitle :number (:contents :html) (:posts ,@(request-fields :post :list nil)))
898 :grid-image-id :----typename))
899 :return-type :both)
900 (let ((posts (sequence-post-ids sequence)))
901 (with-cache-transaction
902 (dolist (post-id posts)
903 (let ((old-seqs (cache-get "post-sequence" post-id :value-type :json)))
904 (unless (member sequence-id old-seqs :test #'string=)
905 (cache-put "post-sequence" post-id (cons sequence-id old-seqs) :value-type :json)))))
906 sequence-json)))))
907 (lw2-graphql-query-timeout-cached fn "sequence-json" sequence-id))))
909 (define-backend-function get-post-sequence-ids (post-id)
910 (backend-graphql
911 (cache-get "post-sequence" post-id :value-type :json)))
913 (defun preload-sequences-cache ()
914 (declare (optimize space (compilation-speed 2) (speed 0)))
915 (let ((sequences (apply #'append
916 (loop for view in '("curatedSequences" "communitySequences")
917 collect (lw2-graphql-query (lw2-query-string :sequence :list (alist :view view) :fields '(:--id)))))))
918 (dolist (sequence sequences)
919 (get-sequence (cdr (assoc :--id sequence))))
920 (format t "Retrieved ~A sequences." (length sequences)))
921 (values))
923 (define-backend-function user-deleted (user-id &optional (status nil set))
924 (backend-base
925 (declare (ignore user-id status set))
926 nil)
927 (backend-lw2-modernized
928 (if set
929 (if status
930 (cache-put "user-deleted" user-id "1")
931 (cache-del "user-deleted" user-id))
932 (cache-get "user-deleted" user-id :return-type 'existence))))
934 (define-backend-function get-user (user-identifier-type user-identifier &key (revalidate *revalidate-default*) (force-revalidate *force-revalidate-default*) auth-token)
935 (backend-graphql
936 (let* ((user-id (ccase user-identifier-type
937 (:user-id user-identifier)
938 (:user-slug (get-slug-userid user-identifier))))
939 (query-string (lw2-query-string :user :single (alist :document-id user-id) :fields (list-cond* (auth-token :last-notifications-check) (user-fields))))
940 (result (if auth-token
941 (lw2-graphql-query query-string :auth-token auth-token)
942 (lw2-graphql-query-timeout-cached query-string "user-json" user-id :revalidate revalidate :force-revalidate force-revalidate))))
943 (alist-bind ((user-id (or simple-string null) :--id)
944 (display-name (or simple-string null))
945 (full-name (or simple-string null))
946 (slug (or simple-string null))
947 (deleted boolean))
948 result
949 (when user-id
950 (with-cache-transaction
951 (when display-name
952 (cache-username user-id display-name))
953 (when full-name
954 (cache-user-full-name user-id full-name))
955 (when slug
956 (cache-user-slug user-id slug)
957 (cache-slug-userid slug user-id))
958 (user-deleted user-id deleted))))
959 result)))
961 (define-backend-function get-notifications (&key user-id (offset 0) (limit 21) auth-token)
962 (backend-lw2-legacy
963 (lw2-graphql-query (lw2-query-string :notification :list
964 (alist* :user-id user-id :limit limit :offset offset *notifications-base-terms*)
965 :fields '(:--id :document-type :document-id :link :title :message :type :viewed))
966 :auth-token auth-token))
967 (backend-lw2-modernized
968 (declare (ignore user-id offset limit auth-token))
969 (let ((*notifications-base-terms* (remove :null *notifications-base-terms* :key #'cdr)))
970 (call-next-method))))
972 (define-backend-function check-notifications (user-id auth-token &key full since)
973 (backend-lw2-legacy
974 (multiple-value-bind (notifications user-info)
975 (lw2-graphql-query-multi (list
976 (lw2-query-string* :notification :list (alist* :user-id user-id :limit (if full 3 1) *notifications-base-terms*)
977 :fields (if full '(:--id :message :created-at) '(:created-at)))
978 (lw2-query-string* :user :single (alist :document-id user-id) :fields '(:last-notifications-check)))
979 :auth-token auth-token)
980 (let ((last-check (or since
981 (let ((last-check-string (cdr (assoc :last-notifications-check user-info))))
982 (when (and (stringp last-check-string) (not (equal last-check-string "")))
983 (local-time:parse-timestring last-check-string))))))
984 (when notifications
985 (labels ((unread-p (notification)
986 (if last-check
987 (local-time:timestamp>
988 (local-time:parse-timestring (cdr (assoc :created-at notification)))
989 last-check)
990 ;; User has never checked notifications before -- all are unread
991 t)))
992 (if full
993 (remove-if-not #'unread-p notifications)
994 (unread-p (first notifications))))))))
995 (backend-lw2-modernized
996 (declare (ignore user-id auth-token full since))
997 (let ((*notifications-base-terms* (remove :null *notifications-base-terms* :key #'cdr)))
998 (call-next-method))))
1000 (define-cache-database 'backend-lw2-legacy "comment-reply-by-user")
1002 (define-backend-function mark-comment-replied (reply)
1003 (backend-lw2-legacy
1004 (alexandria:when-let* ((parent-comment-id (cdr (assoc :parent-comment-id reply)))
1005 (reply-id (cdr (assoc :--id reply)))
1006 (user-id (cdr (assoc :user-id reply))))
1007 (cache-put "comment-reply-by-user" (concatenate 'string parent-comment-id " " user-id) reply-id))))
1009 (define-backend-function check-comment-replied (comment-id user-id)
1010 (backend-lw2-legacy
1011 (cache-get "comment-reply-by-user" (concatenate 'string comment-id " " user-id))))
1013 (define-backend-function get-user-page-items (user-id request-type &key (offset 0) (limit 21) (sort-type :date) drafts
1014 (revalidate *revalidate-default*) (force-revalidate *force-revalidate-default*) auth-token)
1015 (backend-lw2-legacy
1016 (multiple-value-bind (real-offset real-limit) (if (eq request-type :both)
1017 (values 0 (+ offset limit))
1018 (values offset limit))
1019 (let* ((cache-database (when (and (eq request-type :both)
1020 (or (not offset) (= offset 0))
1021 (= limit 21)
1022 (eq sort-type :date)
1023 (not drafts)
1024 (not auth-token))
1025 "user-page-items"))
1026 (return-type (if cache-database :string nil))
1027 (fn (lambda ()
1028 (labels ((posts-query-string ()
1029 (let* ((base-terms
1030 (cond
1031 (drafts (alist :view "drafts"))
1032 ((eq sort-type :score) (alist :view "top"))
1033 ((eq sort-type :date-reverse) (alist :view "old"))
1034 (t (alist :view "userPosts"))))
1035 (terms (alist* :offset real-offset :limit real-limit :user-id user-id base-terms)))
1036 (declare (dynamic-extent base-terms terms))
1037 (lw2-query-string* :post :list terms)))
1038 (comments-query-string ()
1039 (let* ((view (ecase sort-type
1040 (:score "postCommentsTop")
1041 (:date "allRecentComments")
1042 (:date-reverse "postCommentsOld")))
1043 (terms (alist :offset real-offset
1044 :limit real-limit
1045 :user-id user-id
1046 :view view)))
1047 (declare (dynamic-extent view terms))
1048 (lw2-query-string* :comment :list terms
1049 :context :index))))
1050 (declare (dynamic-extent #'posts-query-string #'comments-query-string))
1051 (case request-type
1052 (:both (let ((result (multiple-value-call #'concatenate 'list
1053 (lw2-graphql-query-multi (list (posts-query-string) (comments-query-string))))))
1054 (ecase return-type
1055 (:string (json:encode-json-to-string result))
1056 ((nil) result))))
1057 (:posts (lw2-graphql-query (format nil "{~A}" (posts-query-string)) :auth-token auth-token :return-type return-type))
1058 (:comments (lw2-graphql-query (format nil "{~A}" (comments-query-string)) :auth-token auth-token :return-type return-type)))))))
1059 (if cache-database
1060 (lw2-graphql-query-timeout-cached fn cache-database user-id :decoder 'deserialize-query-result :revalidate revalidate :force-revalidate force-revalidate)
1061 (funcall fn))))))
1063 (define-backend-function get-conversation-messages (conversation-id auth-token)
1064 (backend-lw2-legacy
1065 (lw2-graphql-query-multi
1066 (list
1067 (lw2-query-string* :conversation :single (alist :document-id conversation-id) :fields '(:title (:participants :display-name :slug)))
1068 (lw2-query-string* :message :list (alist :view "messagesConversation" :conversation-id conversation-id) :fields *messages-index-fields*))
1069 :auth-token auth-token)))
1071 (define-backend-function lw2-search-query (query &key (indexes '("test_tags" "test_posts" "test_comments")))
1072 (backend-algolia-search
1073 (call-with-http-response
1074 (lambda (req-stream)
1075 (values-list (loop for r in (cdr (assoc :results (json:decode-json req-stream)))
1076 collect (cdr (assoc :hits r)))))
1077 (algolia-search-uri *current-backend*)
1078 :method :post
1079 :headers '(("Origin" . "https://www.greaterwrong.com")
1080 ("Referer" . "https://www.greaterwrong.com/")
1081 ("Content-Type" . "application/json"))
1082 :content (json:encode-json-alist-to-string
1083 (alist "requests" (loop for index in indexes
1084 collect (alist "indexName" index
1085 "params" (format nil "query=~A&hitsPerPage=20&page=0"
1086 (url-rewrite:url-encode query))))))
1087 :want-stream t)))
1089 (define-backend-function get-username-wrapper (user-id fn)
1090 (backend-base
1091 (funcall fn user-id))
1092 (backend-lw2-modernized
1093 (if (user-deleted user-id)
1094 "[deleted]"
1095 (funcall fn user-id))))
1097 (define-cache-database 'backend-lw2-legacy "comment-markdown-source" "post-markdown-source")
1099 (defun markdown-source-db-name (target-type)
1100 (ecase target-type (:comment "comment-markdown-source") (:post "post-markdown-source")))
1102 (define-backend-function markdown-source (target-type id version)
1103 (backend-lw2-modernized
1104 (let ((db-name (markdown-source-db-name target-type))
1105 (version (base64:usb8-array-to-base64-string (hash-string version))))
1107 (if-let ((cache-data (cache-get db-name id :value-type :lisp)))
1108 (alist-bind ((cached-version simple-string :version)
1109 (markdown simple-string))
1110 cache-data
1111 (when (string= version cached-version)
1112 markdown)))
1113 (trivia:ematch (lw2-graphql-query (lw2-query-string target-type :single
1114 (alist :document-id id)
1115 :fields '(:html-body (:contents :markdown)))
1116 :auth-token *current-auth-token*)
1117 ((trivia:alist (:html-body . html-body)
1118 (:contents . (assoc :markdown markdown)))
1119 (cache-put db-name id (alist :version (base64:usb8-array-to-base64-string (hash-string html-body)) :markdown markdown) :value-type :lisp)
1120 markdown))))))
1122 (define-backend-function (setf markdown-source) (markdown target-type id version)
1123 (backend-lw2-modernized
1124 (let ((version (base64:usb8-array-to-base64-string (hash-string version))))
1125 (cache-put (markdown-source-db-name target-type)
1127 (alist :version version :markdown markdown)
1128 :value-type :lisp))))
1130 (defun get-elicit-question-title (question-id)
1131 (cdr
1132 (lw2-graphql-query (graphql-query-string "ElicitBlockData" (alist :question-id question-id) '(:title)))))
1134 (defun make-rate-limiter (delay)
1135 (let ((rl-hash (make-hash-table :test 'equal :synchronized t)))
1136 (lambda (datum fn)
1137 (let ((unix-time (get-unix-time)))
1138 (if (sb-ext:with-locked-hash-table (rl-hash)
1139 (maphash (lambda (k v)
1140 (if (> (- unix-time v) delay)
1141 (remhash k rl-hash)))
1142 rl-hash)
1143 (not (gethash datum rl-hash)))
1144 (progn
1145 (setf (gethash datum rl-hash) unix-time)
1146 (funcall fn))
1147 (error "Request aborted due to rate limit."))))))
1149 (defmacro with-rate-limit (&body outer-body)
1150 `(let ((rate-limiter (make-rate-limiter 30)))
1151 (macrolet ((rate-limit ((key) &body inner-body)
1152 `(funcall rate-limiter ,key (lambda () ,@inner-body))))
1153 ,@outer-body)))
1155 (with-rate-limit
1156 (simple-cacheable ("post-title" 'backend-lw2-legacy "postid-to-title" post-id)
1157 (rate-limit (post-id) (cdr (first (lw2-graphql-query (lw2-query-string :post :single (alist :document-id post-id) :fields '(:title))))))))
1159 (with-rate-limit
1160 (simple-cacheable ("post-slug" 'backend-lw2-legacy "postid-to-slug" post-id)
1161 (rate-limit (post-id) (cdr (first (lw2-graphql-query (lw2-query-string :post :single (alist :document-id post-id) :fields '(:slug))))))))
1163 (with-rate-limit
1164 (simple-cacheable ("slug-postid" 'backend-lw2-legacy "slug-to-postid" slug)
1165 (rate-limit (slug) (cdr (first (lw2-graphql-query (lw2-query-string :post :single (alist :slug slug) :fields '(:--id))))))))
1167 (with-rate-limit
1168 (simple-cacheable ("username" 'backend-lw2-legacy "userid-to-displayname" user-id :get-wrapper #'get-username-wrapper)
1169 (rate-limit (user-id) (cdr (first (lw2-graphql-query (lw2-query-string :user :single (alist :document-id user-id) :fields '(:display-name))))))))
1171 (with-rate-limit
1172 (simple-cacheable ("user-slug" 'backend-lw2-legacy "userid-to-slug" user-id)
1173 (rate-limit (user-id) (cdr (first (lw2-graphql-query (lw2-query-string :user :single (alist :document-id user-id) :fields '(:slug))))))))
1175 (with-rate-limit
1176 (simple-cacheable ("user-full-name" 'backend-lw2-legacy "userid-to-full-name" user-id)
1177 (rate-limit (user-id) (or (cdr (first (lw2-graphql-query (lw2-query-string :user :single (alist :document-id user-id) :fields '(:full-name)))))
1178 ""))))
1180 (with-rate-limit
1181 (simple-cacheable ("slug-userid" 'backend-lw2-legacy "slug-to-userid" slug)
1182 (rate-limit (slug) (cdr (first (lw2-graphql-query (lw2-query-string :user :single (alist :slug slug) :fields '(:--id))))))))
1184 (with-rate-limit
1185 (simple-cacheable ("slug-tagid" 'backend-lw2-tags "slug-to-tagid" slug :catch-errors nil)
1186 (rate-limit (slug) (cdr (first (first (lw2-graphql-query (lw2-query-string :tag :list (alist :view "tagBySlug" :slug slug) :fields '(:--id)))))))))
1188 (defun preload-username-cache ()
1189 (declare (optimize space (compilation-speed 2) (speed 0)))
1190 (let ((user-list (lw2-graphql-query (lw2-query-string :user :list '() :fields '(:--id :slug :display-name)))))
1191 (with-cache-transaction
1192 (loop for user in user-list
1193 do (alist-bind ((user-id (or simple-string null) :--id)
1194 (slug (or simple-string null))
1195 (display-name (or simple-string null)))
1196 user
1197 (when user-id
1198 (when display-name
1199 (cache-username user-id display-name))
1200 (when slug
1201 (cache-user-slug user-id slug)
1202 (cache-slug-userid slug user-id))))))))