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