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