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