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
19 #:flatten-shortform-comments
#:get-shortform-votes
21 #:get-post-tag-votes
#:get-tag-post-votes
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
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
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."
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
))
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
)
83 (let ((result-name (or alias field-name
)))
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
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
104 (define-backend-function comments-list-to-graphql-json
(comments-list)
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
))
120 (labels ((,maybe-retry-fn-name
()
122 (when (> ,remaining-retries
0)
123 (decf ,remaining-retries
)
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
*)
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
))))
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 (defun call-with-http-response (fn uri-string
&rest args
&key
&allow-other-keys
)
155 (let* ((uri (quri:uri uri-string
))
156 (uri-dest (concatenate 'string
(quri:uri-host uri
) ":" (format nil
"~d" (quri:uri-port uri
))))
157 (stream (connection-pop uri-dest
)))
158 (let (response status-code headers response-uri new-stream success
)
159 (with-retrying (maybe-retry :retries
3
160 :before-retry
(sleep 0.2))
162 (handler-bind (((or dex
:http-request-failed usocket
:ns-condition usocket
:socket-condition
)
164 (if-let ((r (find-restart 'dex
:ignore-and-continue condition
)))
167 (setf (values response status-code headers response-uri new-stream
)
168 (apply 'dex
:request uri
:use-connection-pool nil
:keep-alive t
:stream stream args
))
169 (unless (eq stream new-stream
)
170 (when stream
(force-close stream
))
171 (setf stream new-stream
173 (when (<= 500 status-code
599)
175 (error 'lw2-connection-error
:message
(format nil
"HTTP status ~A" status-code
)))
178 (when (streamp response
)
179 (force-close response
))
181 (force-close stream
))
184 (funcall fn response
)
185 (when (streamp response
)
187 (when stream
; the connection is reusable
188 (connection-push uri-dest stream
))))))
190 (defun forwarded-header ()
191 (let ((addr (and (boundp 'hunchentoot
:*request
*) (hunchentoot:real-remote-addr
))))
192 (list-cond (addr "X-Forwarded-For" addr
))))
194 (defun signal-lw2-errors (errors)
195 (loop for error in errors
196 do
(let ((message (cdr (assoc :message error
)))
197 (path (cdr (assoc :path error
))))
198 (unless (and path
(> (length path
) 1))
200 ((search "document_not_found" message
) (error 'lw2-not-found-error
))
201 ((search "app.missing_document" message
) (error 'lw2-not-found-error
))
202 ((search "only visible to logged-in users" message
) (error 'lw2-login-required-error
))
203 ((search "not_allowed" message
) (error 'lw2-not-allowed-error
))
204 (t (error 'lw2-unknown-error
:message message
)))))))
206 (define-backend-function earliest-post-time
()
207 (backend-lw2 (load-time-value (local-time:parse-timestring
"2005-01-01")))
208 (backend-ea-forum (load-time-value (local-time:parse-timestring
"2011-11-24"))))
210 (define-backend-function fixup-lw2-return-value
(value)
213 (backend-lw2-modernized
217 (if (member (car x
) '(:result
:results
:total-count
))
224 (define-backend-function deserialize-query-result
(result-source)
226 (let ((string-source (typecase result-source
230 (flexi-streams:make-in-memory-input-stream result-source
))
232 (ensure-character-stream result-source
)))))
233 (json:decode-json-from-source string-source
))))
235 (define-backend-function postprocess-query-result
(result)
239 (signal-lw2-errors (cdr (assoc :errors result
)))
240 (fixup-lw2-return-value (cdadr (assoc :data result
)))))
242 (define-backend-function decode-query-result
(result-source)
244 (postprocess-query-result
245 (deserialize-query-result result-source
))))
247 (defmethod graphql-uri ((backend backend-alignment-forum
))
248 (if *use-alignment-forum
*
249 "https://www.alignmentforum.org/graphql"
252 (define-backend-function backend-request-headers
(auth-token forwarded
)
253 (backend-websocket-login
254 (list-cond* (auth-token :authorization auth-token
)
256 (backend-passport-js-login
257 (list-cond* (auth-token :cookie
(concatenate 'string
"loginToken=" auth-token
))
260 (alist* :content-type
"application/json"
261 (if forwarded
(forwarded-header)))))
263 (define-backend-function call-with-backend-response
(fn query
&key return-type auth-token
)
265 (call-with-http-response
267 (graphql-uri *current-backend
*)
269 :headers
(backend-request-headers auth-token nil
)
270 :content
(dynamic-let ((q (alist :query query
))) (json:encode-json-to-string q
))
271 :want-stream
(not return-type
))))
273 (define-backend-function lw2-graphql-query
(query &key auth-token return-type
(decoder 'decode-query-result
))
275 (do-graphql-debug query
)
276 (call-with-backend-response
280 (:both
(lambda (string) (values (funcall decoder string
) string
))))
282 :return-type return-type
283 :auth-token auth-token
)))
285 (defun lw2-graphql-query-map (fn data
&key auth-token postprocess
)
286 (multiple-value-bind (map-values queries
)
288 as out-values
= (multiple-value-list (funcall fn d
))
289 as
(out passthrough-p
) = out-values
290 collect out-values into map-values
291 when
(not passthrough-p
) collect out into queries
292 finally
(return (values map-values queries
)))
294 (with-output-to-string (stream)
298 do
(format stream
"g~6,'0D:~A " n q
))
299 (format stream
"}")))
300 (query-result-data (when queries
(lw2-graphql-query query-string
:decoder
'deserialize-query-result
:auth-token auth-token
)))
301 (errors (cdr (assoc :errors query-result-data
))))
302 (signal-lw2-errors errors
)
304 (loop as results
= (sort (cdr (assoc :data query-result-data
)) #'string
< :key
#'car
) then
(if passthrough-p results
(rest results
))
305 for
(out passthrough-p
) in map-values
306 as result-data-cell
= (first results
)
307 as result-data
= (if passthrough-p out
(fixup-lw2-return-value (cdr result-data-cell
)))
308 for input-data in data
309 collect
(if postprocess
(funcall postprocess input-data result-data
) result-data
))
312 (defun lw2-graphql-query-multi (query-list &key auth-token
)
313 (values-list (lw2-graphql-query-map #'identity query-list
:auth-token auth-token
)))
315 (defvar *background-cache-update-threads
* (make-hash-table :test
'equal
319 (defun cache-update (cache-db key data
)
320 (let ((meta-db (format nil
"~A-meta" cache-db
))
321 (new-hash (hash-string data
))
322 (current-time (get-unix-time)))
323 (with-cache-transaction
324 (let* ((metadata (cache-get meta-db key
:value-type
:lisp
))
325 (last-mod (if (equalp new-hash
(cdr (assoc :city-128-hash metadata
)))
326 (or (cdr (assoc :last-modified metadata
)) current-time
)
328 (cache-put meta-db key
(alist :last-checked current-time
:last-modified last-mod
:city-128-hash new-hash
) :value-type
:lisp
)
329 (cache-put cache-db key data
)))))
331 (defun cache-mark-stale (cache-db key
)
332 (let ((meta-db (format nil
"~A-meta" cache-db
))
333 (current-time (get-unix-time)))
334 (with-cache-transaction
335 (let* ((metadata (cache-get meta-db key
:value-type
:lisp
))
336 (metadata (alist* :last-modified current-time
(delete :last-modified metadata
:key
#'car
))))
337 (cache-put meta-db key metadata
:value-type
:lisp
)))))
339 (declaim (type (and fixnum
(integer 1)) *cache-stale-factor
* *cache-skip-factor
*))
340 (defparameter *cache-stale-factor
* 100)
341 (defparameter *cache-skip-factor
* 5000)
343 (defun cache-is-fresh (cache-db key
)
344 (let ((metadata (cache-get (format nil
"~A-meta" cache-db
) key
:value-type
:lisp
))
345 (current-time (get-unix-time)))
346 (if-let ((last-mod (cdr (assoc :last-modified metadata
)))
347 (last-checked (cdr (assoc :last-checked metadata
))))
348 (let ((unmodified-time (- last-checked last-mod
))
349 (last-checked-time (- current-time last-checked
)))
350 (if (> unmodified-time
(* *cache-skip-factor
* last-checked-time
))
352 (> unmodified-time
(* *cache-stale-factor
* last-checked-time
)))))))
354 (defgeneric run-query
(query)
355 (:method
((query string
))
356 (lw2-graphql-query query
:return-type
:string
))
357 (:method
((query function
))
360 (declaim (inline make-thread-with-current-backend
))
362 (defun make-thread-with-current-backend (fn &rest args
)
363 (let ((current-backend *current-backend
*))
364 (apply #'sb-thread
:make-thread
366 (let ((*current-backend
* current-backend
))
370 (defun ensure-cache-update-thread (query cache-db cache-key
)
371 (let ((key (format nil
"~A-~A" cache-db cache-key
)))
372 (labels ((background-fn ()
374 (multiple-value-bind (value error
)
375 (log-and-ignore-errors
376 (sb-sys:with-deadline
(:seconds
60)
378 (cache-update cache-db cache-key
(run-query query
)))))
380 (remhash key
*background-cache-update-threads
*))))
381 (sb-ext:with-locked-hash-table
(*background-cache-update-threads
*)
382 (let ((thread (gethash key
*background-cache-update-threads
*)))
384 (setf (gethash key
*background-cache-update-threads
*)
385 (make-thread-with-current-backend #'background-fn
:name
"background cache update"))))))))
387 (define-backend-function lw2-graphql-query-timeout-cached
(query cache-db cache-key
&key
(decoder 'decode-query-result
)
388 (revalidate *revalidate-default
*) (force-revalidate *force-revalidate-default
*))
390 (multiple-value-bind (cached-result is-fresh
) (with-cache-readonly-transaction
391 (values (cache-exists cache-db cache-key
)
392 (cache-is-fresh cache-db cache-key
)))
393 (labels ((get-cached-result ()
394 (with-cache-readonly-transaction (funcall decoder
(cache-get cache-db cache-key
:return-type
'binary-stream
)))))
395 (if (and cached-result
(or (not revalidate
)
396 (and (not force-revalidate
) (eq is-fresh
:skip
))))
398 (let ((timeout (if cached-result
399 (if force-revalidate nil
3)
401 (thread (ensure-cache-update-thread query cache-db cache-key
)))
402 (block retrieve-result
403 (if (and cached-result
(if force-revalidate
(not revalidate
) (or is-fresh
(not revalidate
))))
406 ((fatal-error (lambda (c)
409 (return-from retrieve-result
(get-cached-result))))))
410 (let ((new-result (sb-thread:join-thread thread
:timeout timeout
)))
412 (condition (error new-result
))
413 (t (funcall decoder new-result
)))))))))))))
415 (define-backend-function lw2-query-string
* (query-type return-type args
&key context fields with-total
))
417 (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
)
418 (declare (ignore with-total
))
419 (labels ((lisp-to-lw2-case (x) (json:lisp-to-camel-case
(format nil
"*~A" x
))))
420 (graphql-query-string*
422 (lisp-to-lw2-case query-type
)
424 (lisp-to-lw2-case return-type
))
425 (if (eq return-type
:single
)
430 (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
)
431 (graphql-query-string*
432 (if (eq return-type
:single
)
433 (json:lisp-to-camel-case
(string query-type
))
434 (concatenate 'string
(json:lisp-to-camel-case
(string query-type
)) "s"))
435 (alist :input
(case return-type
436 (:single
(alist :selector args
))
437 (:list
(alist :enable-total with-total
:terms args
))
438 (:total
(alist :enable-total t
:terms args
))))
440 (:total
'(:total-count
))
441 (:list
(list-cond (t :results fields
)
442 (with-total :total-count
)))
443 (:single
(alist :result fields
)))))
445 (define-backend-function lw2-query-string
(query-type return-type args
&key context fields with-total
))
447 (define-backend-operation lw2-query-string backend-lw2-legacy
(query-type return-type args
&rest rest
&key context fields with-total
)
448 (declare (ignore context fields with-total
))
449 (format nil
"{~A}" (apply 'lw2-query-string
* query-type return-type args rest
)))
451 (define-backend-function lw2-query-list-limit-workaround
(query-type terms
&rest rest
&key fields context auth-token
)
453 (declare (ignore fields context
))
455 (loop for offset from
0 by
500
456 as items-next
= (lw2-graphql-query (apply 'lw2-query-string query-type
:list
(alist* :limit
500 :offset offset terms
) (filter-plist rest
:fields
:context
))
457 :auth-token auth-token
)
458 as length
= (length items-next
)
459 do
(setf items-list
(nconc items-list items-next
))
460 while
(>= length
500))
463 (declare (ignore fields context
))
464 (lw2-graphql-query (apply 'lw2-query-string query-type
:list terms
(filter-plist rest
:fields
:context
)) :auth-token auth-token
)))
466 (defun get-cached-index-query (cache-id query
)
467 (labels ((query-and-put ()
468 (let* ((result (lw2-graphql-query query
:return-type
:string
))
469 (decoded-result (multiple-value-list (decode-query-result result
))))
470 (cache-put "index-json" cache-id result
)
471 (values-list decoded-result
)))
472 (get-cached-result ()
473 (with-cache-readonly-transaction (decode-query-result (cache-get "index-json" cache-id
:return-type
'binary-stream
)))))
474 (let ((cached-result (cache-get "index-json" cache-id
:return-type
'existence
)))
475 (if (and cached-result
(background-loader-ready-p))
480 (t () (get-cached-result)))
483 (define-backend-function get-posts-index-query-terms
(&key view
(sort "new") (limit 21) offset before after
&allow-other-keys
)
485 (let ((sort-key (alexandria:switch
(sort :test
#'string
=)
488 ("active" "recentComments")
491 (multiple-value-bind (view-terms cache-key
)
492 (alexandria:switch
(view :test
#'string
=)
493 ("featured" (alist :sorted-by sort-key
:filter
"curated"))
494 ("all" (alist :sorted-by sort-key
:filter
"all"))
495 ("alignment-forum" (alist :sorted-by sort-key
:af t
))
496 ("questions" (alist :sorted-by sort-key
:filter
"questions"))
497 ("events" (alist :sorted-by sort-key
:filter
"events"))
498 ("nominations" (alist :view
"nominations2019"))
499 ("reviews" (alist :view
"reviews2019"))
501 (alist :sorted-by sort-key
:filter
"frontpage")
502 (if (not (or (string/= sort
"new") (/= limit
21) offset before after
)) "new-not-meta"))))
504 (alist-without-null* :before before
509 (values terms cache-key
))))))
511 (define-backend-operation get-posts-index-query-terms backend-lw2-tags
:around
(&key hide-tags
&allow-other-keys
)
512 (multiple-value-bind (query-terms cache-key
) (call-next-method)
514 (values (acons :filter-settings
(alist :tags
(list* :list
(map 'list
(lambda (tagid) (alist :tag-id tagid
:filter-mode
"Hidden"))
518 (values query-terms cache-key
))))
520 (define-backend-function get-posts-index-query-string
(&rest args
&key
&allow-other-keys
)
522 (declare (dynamic-extent args
))
523 (multiple-value-bind (query-terms cache-key
)
524 (apply #'%get-posts-index-query-terms backend args
)
525 (values (lw2-query-string :post
:list query-terms
)
528 (define-backend-function get-posts-index
(&rest args
&key
&allow-other-keys
)
530 (declare (dynamic-extent args
))
531 (multiple-value-bind (query-string cache-key
)
532 (apply #'%get-posts-index-query-string backend args
)
534 (get-cached-index-query cache-key query-string
)
535 (lw2-graphql-query query-string
)))))
537 (define-backend-operation get-posts-index backend-lw2-tags
:around
(&rest args
&key hide-tags offset
(limit 21) &allow-other-keys
)
538 ;; Workaround for https://github.com/LessWrong2/Lesswrong2/issues/3099
539 (declare (dynamic-extent args
))
541 (let ((offset (or offset
0)))
543 (apply #'call-next-method backend
:offset
0 :limit
(+ limit offset
) args
)
547 (defun get-posts-json ()
548 (lw2-graphql-query (get-posts-index-query-string) :return-type
:string
))
550 (defun get-recent-comments (&key with-total
)
551 (get-cached-index-query "recent-comments" (lw2-query-string :comment
:list
'((:view .
"allRecentComments") (:limit .
20)) :context
:index
:with-total with-total
)))
553 (defun get-recent-comments-json ()
554 (lw2-graphql-query (lw2-query-string :comment
:list
'((:view .
"allRecentComments") (:limit .
20)) :context
:index
) :return-type
:string
))
556 (defun process-vote-result (res)
557 (alist-bind ((id (or null simple-string
) :--id
)
560 current-user-extended-vote
)
562 (let ((karma-vote (or (nonempty-string current-user-vote
)
563 (cdr (assoc :vote-type
(first current-user-votes
))))))
564 (values (list-cond* (karma-vote :karma karma-vote
)
565 current-user-extended-vote
)
568 (defun process-votes-result (res)
569 (let ((hash (make-hash-table)))
571 (multiple-value-bind (vote id
) (process-vote-result v
)
573 (setf (gethash id hash
) vote
))))))
575 (defun flatten-shortform-comments (comments)
576 (let ((output comments
))
577 (loop for comment in comments do
578 (setf output
(append (cdr (assoc :latest-children comment
)) output
)))
581 (defun get-shortform-votes (auth-token &key
(offset 0) (limit 20))
582 (process-votes-result
583 (flatten-shortform-comments
584 (lw2-graphql-query (lw2-query-string :comment
:list
(alist :view
"shortform" :offset offset
:limit limit
)
585 :fields
'(:--id
:current-user-vote
:current-user-extended-vote
(:latest-children
:--id
:current-user-vote
:current-user-extended-vote
)))
586 :auth-token auth-token
))))
588 (defun get-post-vote (post-id auth-token
)
589 (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
)))
591 (define-cache-database 'backend-lw2-tags
"tag-posts" "tag-posts-meta" "post-tags" "post-tags-meta")
593 (define-backend-function get-tag-posts
(slug &key
(revalidate *revalidate-default
*) (force-revalidate *force-revalidate-default
*))
594 (backend-base (declare (ignore revalidate force-revalidate
)) nil
)
596 (let* ((tagid (get-slug-tagid slug
))
598 (comments-list-to-graphql-json
599 (lw2-query-list-limit-workaround
601 (alist :view
"postsWithTag" :tag-id tagid
)
602 :fields
(list (list* :post
(request-fields :post
:list
:index
))))))))
604 (for x in
(lw2-graphql-query-timeout-cached query-fn
"tag-posts" tagid
:revalidate revalidate
:force-revalidate force-revalidate
))
605 (when-let (post (cdr (assoc :post x
)))
608 (define-backend-function get-tag-post-votes
(tag-id auth-token
)
609 (backend-base (progn tag-id auth-token nil
))
611 (process-votes-result
613 (lw2-query-list-limit-workaround
615 (alist :view
"postsWithTag" :tag-id tag-id
)
616 :fields
'(:--id
:current-user-vote
:current-user-extended-vote
)
617 :auth-token auth-token
)))))
619 (define-backend-function get-post-tags
(post-id &key
(revalidate *revalidate-default
*) (force-revalidate *force-revalidate-default
*))
620 (backend-base (declare (ignore revalidate force-revalidate
)) nil
)
622 (let ((query-string (lw2-query-string :tag-rel
:list
(alist :view
"tagsOnPost" :post-id post-id
) :fields
'((:tag
:name
:slug
)))))
623 (lw2-graphql-query-timeout-cached query-string
"post-tags" post-id
:revalidate revalidate
:force-revalidate force-revalidate
))))
625 (define-backend-function get-post-tag-votes
(post-id auth-token
)
626 (backend-base (progn post-id auth-token nil
))
628 (process-votes-result
629 (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
))
630 :auth-token auth-token
))))
632 (define-backend-function get-post-body
(post-id &key
(revalidate *revalidate-default
*) (force-revalidate *force-revalidate-default
*) auth-token
)
634 (let ((query-string (lw2-query-string :post
:single
(alist :document-id post-id
) :context
:body
)))
637 (handler-bind ((lw2-login-required-error (lambda (&rest args
)
638 (declare (ignore args
))
639 (let ((current-auth-token *current-auth-token
*))
640 (when (and (not auth-token
) current-auth-token
)
641 (setf auth-token current-auth-token
)
645 (lw2-graphql-query query-string
:auth-token auth-token
)
646 (lw2-graphql-query-timeout-cached query-string
"post-body-json" post-id
:revalidate revalidate
:force-revalidate force-revalidate
))))))))
648 (declare (ignore auth-token
))
649 (acons :tags
(get-post-tags post-id
:revalidate revalidate
:force-revalidate force-revalidate
) (call-next-method)))
650 (backend-magnum-crossposts
651 (declare (ignore auth-token
))
652 (let ((post (call-next-method)))
653 (alist-bind (is-crosspost hosted-here foreign-post-id
) (cdr (assoc :fm-crosspost post
))
654 (cond ((not (and (backend-magnum-crosspost-site backend
)
655 (not (boundp '*retrieve-crosspost
*))
656 is-crosspost foreign-post-id
))
659 (let* ((*current-site
* (find-site (backend-magnum-crosspost-site backend
)))
660 (*current-backend
* (site-backend *current-site
*))
661 (*retrieve-crosspost
* nil
)
662 (foreign-post (get-post-body foreign-post-id
:revalidate revalidate
:force-revalidate force-revalidate
))
663 (foreign-post-body (cdr (assoc :html-body foreign-post
))))
664 (declare (special *retrieve-crosspost
*))
665 (if foreign-post-body
667 ((not hosted-here
) :html-body foreign-post-body
)
668 (t :foreign-post foreign-post
)
672 (defun get-post-comments-list (post-id view
&rest rest
&key auth-token parent-answer-id fields context
)
673 (declare (ignore fields context auth-token
))
674 (let ((terms (alist :view view
:post-id post-id
)))
675 (when parent-answer-id
676 (setf terms
(acons :parent-answer-id parent-answer-id terms
)))
677 (apply 'lw2-query-list-limit-workaround
:comment terms
(filter-plist rest
:fields
:context
:auth-token
))))
679 (defun get-post-answer-replies (post-id answers
&rest rest
&key auth-token fields context
)
680 ;; todo: support more than 500 answers per question
681 (declare (ignore fields context
))
682 (let* ((terms (alist :view
"repliesToAnswer" :post-id post-id
:limit
500))
683 (result (lw2-graphql-query-map
685 (mapcar (lambda (answer) (apply 'lw2-query-string
* :comment
:list
686 (acons :parent-answer-id
(cdr (assoc :--id answer
)) terms
)
687 (filter-plist rest
:fields
:context
)))
689 :auth-token auth-token
)))
690 (apply #'nconc result
)))
692 (define-backend-function get-post-comments-votes
(post-id auth-token
)
694 (let ((fields '(:--id
:current-user-vote
:current-user-extended-vote
)))
695 (process-votes-result
696 (get-post-comments-list post-id
"postCommentsTop" :auth-token auth-token
:fields fields
))))
698 (let* ((fields '(:--id
:current-user-vote
:current-user-extended-vote
))
699 (answers (get-post-comments-list post-id
"questionAnswers" :auth-token auth-token
:fields fields
)))
700 (process-votes-result
702 (get-post-comments-list post-id
"postCommentsTop" :auth-token auth-token
:fields fields
)
703 (get-post-answer-replies post-id answers
:auth-token auth-token
:fields fields
)
706 (define-backend-function get-tag-comments-votes
(tag-id auth-token
)
707 (backend-lw2-tags-comments
708 (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
))
709 :auth-token auth-token
))))
711 (define-backend-function get-post-comments
(post-id &key
(revalidate *revalidate-default
*) (force-revalidate *force-revalidate-default
*))
714 (comments-list-to-graphql-json
715 (get-post-comments-list post-id
"postCommentsTop")))))
716 (lw2-graphql-query-timeout-cached fn
"post-comments-json" post-id
:revalidate revalidate
:force-revalidate force-revalidate
)))
718 ;; Work around bizarre parent comment bug in EA forum
719 (declare (ignore revalidate force-revalidate
))
720 (let ((comments (call-next-method)))
722 (if-let (parent-id-cons (assoc :parent-comment-id c
))
723 (if (and (string= (cdr parent-id-cons
) "rjgZaK8uzHG3jAu2p")
724 (not (string= post-id
"h26Kx7uGfQfNewi7d")))
725 (setf (cdr parent-id-cons
) nil
))))
728 (defun get-post-answers (post-id &key
(revalidate *revalidate-default
*) (force-revalidate *force-revalidate-default
*))
730 (let ((answers (get-post-comments-list post-id
"questionAnswers")))
731 (comments-list-to-graphql-json
734 (get-post-answer-replies post-id answers
)))))))
735 (lw2-graphql-query-timeout-cached fn
"post-answers-json" post-id
:revalidate revalidate
:force-revalidate force-revalidate
)))
737 (defun sequence-iterate (sequence fn
)
738 (dolist (chapter (cdr (assoc :chapters sequence
)))
739 (dolist (post (cdr (assoc :posts chapter
)))
742 (defun sequence-post-ids (sequence)
743 (with-collector (col)
744 (sequence-iterate sequence
746 (col (cdr (assoc :--id post
)))))
749 (defun get-sequence-post (sequence post-id
)
750 (sequence-iterate sequence
752 (when (string= (cdr (assoc :--id post
)) post-id
)
753 (return-from get-sequence-post post
))))
756 (define-backend-function get-sequence
(sequence-id)
759 (multiple-value-bind (sequence sequence-json
)
761 (lw2-query-string :sequence
:single
762 (alist :document-id sequence-id
)
763 :fields
`(:--id
:title
:created-at
:user-id
765 (:chapters
:title
:subtitle
:number
(:contents
:html
) (:posts
,@(request-fields :post
:list nil
)))
766 :grid-image-id
:----typename
))
768 (let ((posts (sequence-post-ids sequence
)))
769 (with-cache-transaction
770 (dolist (post-id posts
)
771 (let ((old-seqs (cache-get "post-sequence" post-id
:value-type
:json
)))
772 (unless (member sequence-id old-seqs
:test
#'string
=)
773 (cache-put "post-sequence" post-id
(cons sequence-id old-seqs
) :value-type
:json
)))))
775 (lw2-graphql-query-timeout-cached fn
"sequence-json" sequence-id
))))
777 (define-backend-function get-post-sequence-ids
(post-id)
779 (cache-get "post-sequence" post-id
:value-type
:json
)))
781 (defun preload-sequences-cache ()
782 (declare (optimize space
(compilation-speed 2) (speed 0)))
783 (let ((sequences (apply #'append
784 (loop for view in
'("curatedSequences" "communitySequences")
785 collect
(lw2-graphql-query (lw2-query-string :sequence
:list
(alist :view view
) :fields
'(:--id
)))))))
786 (dolist (sequence sequences
)
787 (get-sequence (cdr (assoc :--id sequence
))))
788 (format t
"Retrieved ~A sequences." (length sequences
)))
791 (define-backend-function user-deleted
(user-id &optional
(status nil set
))
793 (declare (ignore user-id status set
))
795 (backend-lw2-modernized
798 (cache-put "user-deleted" user-id
"1")
799 (cache-del "user-deleted" user-id
))
800 (cache-get "user-deleted" user-id
:return-type
'existence
))))
802 (define-backend-function get-user
(user-identifier-type user-identifier
&key
(revalidate *revalidate-default
*) (force-revalidate *force-revalidate-default
*) auth-token
)
804 (let* ((user-id (ccase user-identifier-type
805 (:user-id user-identifier
)
806 (:user-slug
(get-slug-userid user-identifier
))))
807 (query-string (lw2-query-string :user
:single
(alist :document-id user-id
) :fields
(list-cond* (auth-token :last-notifications-check
) (user-fields))))
808 (result (if auth-token
809 (lw2-graphql-query query-string
:auth-token auth-token
)
810 (lw2-graphql-query-timeout-cached query-string
"user-json" user-id
:revalidate revalidate
:force-revalidate force-revalidate
))))
811 (alist-bind ((user-id (or simple-string null
) :--id
)
812 (display-name (or simple-string null
))
813 (full-name (or simple-string null
))
814 (slug (or simple-string null
))
818 (with-cache-transaction
820 (cache-username user-id display-name
))
822 (cache-user-full-name user-id full-name
))
824 (cache-user-slug user-id slug
)
825 (cache-slug-userid slug user-id
))
826 (user-deleted user-id deleted
))))
829 (define-backend-function get-notifications
(&key user-id
(offset 0) (limit 21) auth-token
)
831 (lw2-graphql-query (lw2-query-string :notification
:list
832 (alist* :user-id user-id
:limit limit
:offset offset
*notifications-base-terms
*)
833 :fields
'(:--id
:document-type
:document-id
:link
:title
:message
:type
:viewed
))
834 :auth-token auth-token
))
835 (backend-lw2-modernized
836 (declare (ignore user-id offset limit auth-token
))
837 (let ((*notifications-base-terms
* (remove :null
*notifications-base-terms
* :key
#'cdr
)))
838 (call-next-method))))
840 (define-backend-function check-notifications
(user-id auth-token
&key full since
)
842 (multiple-value-bind (notifications user-info
)
843 (lw2-graphql-query-multi (list
844 (lw2-query-string* :notification
:list
(alist* :user-id user-id
:limit
(if full
3 1) *notifications-base-terms
*)
845 :fields
(if full
'(:--id
:message
:created-at
) '(:created-at
)))
846 (lw2-query-string* :user
:single
(alist :document-id user-id
) :fields
'(:last-notifications-check
)))
847 :auth-token auth-token
)
848 (let ((last-check (or since
849 (let ((last-check-string (cdr (assoc :last-notifications-check user-info
))))
850 (when (and (stringp last-check-string
) (not (equal last-check-string
"")))
851 (local-time:parse-timestring last-check-string
))))))
853 (labels ((unread-p (notification)
855 (local-time:timestamp
>
856 (local-time:parse-timestring
(cdr (assoc :created-at notification
)))
858 ;; User has never checked notifications before -- all are unread
861 (remove-if-not #'unread-p notifications
)
862 (unread-p (first notifications
))))))))
863 (backend-lw2-modernized
864 (declare (ignore user-id auth-token full since
))
865 (let ((*notifications-base-terms
* (remove :null
*notifications-base-terms
* :key
#'cdr
)))
866 (call-next-method))))
868 (define-cache-database 'backend-lw2-legacy
"comment-reply-by-user")
870 (define-backend-function mark-comment-replied
(reply)
872 (alexandria:when-let
* ((parent-comment-id (cdr (assoc :parent-comment-id reply
)))
873 (reply-id (cdr (assoc :--id reply
)))
874 (user-id (cdr (assoc :user-id reply
))))
875 (cache-put "comment-reply-by-user" (concatenate 'string parent-comment-id
" " user-id
) reply-id
))))
877 (define-backend-function check-comment-replied
(comment-id user-id
)
879 (cache-get "comment-reply-by-user" (concatenate 'string comment-id
" " user-id
))))
881 (define-backend-function get-user-page-items
(user-id request-type
&key
(offset 0) (limit 21) (sort-type :date
) drafts
882 (revalidate *revalidate-default
*) (force-revalidate *force-revalidate-default
*) auth-token
)
884 (multiple-value-bind (real-offset real-limit
) (if (eq request-type
:both
)
885 (values 0 (+ offset limit
))
886 (values offset limit
))
887 (let* ((cache-database (when (and (eq request-type
:both
)
888 (or (not offset
) (= offset
0))
894 (return-type (if cache-database
:string nil
))
896 (labels ((posts-query-string ()
899 (drafts (alist :view
"drafts"))
900 ((eq sort-type
:score
) (alist :view
"top"))
901 ((eq sort-type
:date-reverse
) (alist :view
"old"))
902 (t (alist :view
"userPosts"))))
903 (terms (alist* :offset real-offset
:limit real-limit
:user-id user-id base-terms
)))
904 (declare (dynamic-extent base-terms terms
))
905 (lw2-query-string* :post
:list terms
)))
906 (comments-query-string ()
907 (let* ((view (ecase sort-type
908 (:score
"postCommentsTop")
909 (:date
"allRecentComments")
910 (:date-reverse
"postCommentsOld")))
911 (terms (alist :offset real-offset
915 (declare (dynamic-extent view terms
))
916 (lw2-query-string* :comment
:list terms
918 (declare (dynamic-extent #'posts-query-string
#'comments-query-string
))
920 (:both
(let ((result (multiple-value-call #'concatenate
'list
921 (lw2-graphql-query-multi (list (posts-query-string) (comments-query-string))))))
923 (:string
(json:encode-json-to-string result
))
925 (:posts
(lw2-graphql-query (format nil
"{~A}" (posts-query-string)) :auth-token auth-token
:return-type return-type
))
926 (:comments
(lw2-graphql-query (format nil
"{~A}" (comments-query-string)) :auth-token auth-token
:return-type return-type
)))))))
928 (lw2-graphql-query-timeout-cached fn cache-database user-id
:decoder
'deserialize-query-result
:revalidate revalidate
:force-revalidate force-revalidate
)
931 (define-backend-function get-conversation-messages
(conversation-id auth-token
)
933 (lw2-graphql-query-multi
935 (lw2-query-string* :conversation
:single
(alist :document-id conversation-id
) :fields
'(:title
(:participants
:display-name
:slug
)))
936 (lw2-query-string* :message
:list
(alist :view
"messagesConversation" :conversation-id conversation-id
) :fields
*messages-index-fields
*))
937 :auth-token auth-token
)))
939 (define-backend-function lw2-search-query
(query)
940 (backend-algolia-search
941 (call-with-http-response
943 (values-list (loop for r in
(cdr (assoc :results
(json:decode-json req-stream
)))
944 collect
(cdr (assoc :hits r
)))))
945 (algolia-search-uri *current-backend
*)
947 :headers
'(("Origin" .
"https://www.greaterwrong.com")
948 ("Referer" .
"https://www.greaterwrong.com/")
949 ("Content-Type" .
"application/json"))
950 :content
(json:encode-json-alist-to-string
951 (alist "requests" (loop for index in
'("test_tags" "test_posts" "test_comments")
952 collect
(alist "indexName" index
953 "params" (format nil
"query=~A&hitsPerPage=20&page=0"
954 (url-rewrite:url-encode query
))))))
957 (define-backend-function get-username-wrapper
(user-id fn
)
959 (funcall fn user-id
))
960 (backend-lw2-modernized
961 (if (user-deleted user-id
)
963 (funcall fn user-id
))))
965 (define-cache-database 'backend-lw2-legacy
"comment-markdown-source" "post-markdown-source")
967 (defun markdown-source-db-name (target-type)
968 (ecase target-type
(:comment
"comment-markdown-source") (:post
"post-markdown-source")))
970 (define-backend-function markdown-source
(target-type id version
)
971 (backend-lw2-modernized
972 (let ((db-name (markdown-source-db-name target-type
))
973 (version (base64:usb8-array-to-base64-string
(hash-string version
))))
975 (if-let ((cache-data (cache-get db-name id
:value-type
:lisp
)))
976 (alist-bind ((cached-version simple-string
:version
)
977 (markdown simple-string
))
979 (when (string= version cached-version
)
981 (trivia:ematch
(lw2-graphql-query (lw2-query-string target-type
:single
982 (alist :document-id id
)
983 :fields
'(:html-body
(:contents
:markdown
)))
984 :auth-token
*current-auth-token
*)
985 ((trivia:alist
(:html-body . html-body
)
986 (:contents .
(assoc :markdown markdown
)))
987 (cache-put db-name id
(alist :version
(base64:usb8-array-to-base64-string
(hash-string html-body
)) :markdown markdown
) :value-type
:lisp
)
990 (define-backend-function (setf markdown-source
) (markdown target-type id version
)
991 (backend-lw2-modernized
992 (let ((version (base64:usb8-array-to-base64-string
(hash-string version
))))
993 (cache-put (markdown-source-db-name target-type
)
995 (alist :version version
:markdown markdown
)
996 :value-type
:lisp
))))
998 (defun get-elicit-question-title (question-id)
1000 (lw2-graphql-query (graphql-query-string "ElicitBlockData" (alist :question-id question-id
) '(:title
)))))
1002 (defun make-rate-limiter (delay)
1003 (let ((rl-hash (make-hash-table :test
'equal
:synchronized t
)))
1005 (let ((unix-time (get-unix-time)))
1006 (if (sb-ext:with-locked-hash-table
(rl-hash)
1007 (maphash (lambda (k v
)
1008 (if (> (- unix-time v
) delay
)
1009 (remhash k rl-hash
)))
1011 (not (gethash datum rl-hash
)))
1013 (setf (gethash datum rl-hash
) unix-time
)
1015 (error "Request aborted due to rate limit."))))))
1017 (defmacro with-rate-limit
(&body outer-body
)
1018 `(let ((rate-limiter (make-rate-limiter 30)))
1019 (macrolet ((rate-limit ((key) &body inner-body
)
1020 `(funcall rate-limiter
,key
(lambda () ,@inner-body
))))
1024 (simple-cacheable ("post-title" 'backend-lw2-legacy
"postid-to-title" post-id
)
1025 (rate-limit (post-id) (cdr (first (lw2-graphql-query (lw2-query-string :post
:single
(alist :document-id post-id
) :fields
'(:title
))))))))
1028 (simple-cacheable ("post-slug" 'backend-lw2-legacy
"postid-to-slug" post-id
)
1029 (rate-limit (post-id) (cdr (first (lw2-graphql-query (lw2-query-string :post
:single
(alist :document-id post-id
) :fields
'(:slug
))))))))
1032 (simple-cacheable ("slug-postid" 'backend-lw2-legacy
"slug-to-postid" slug
)
1033 (rate-limit (slug) (cdr (first (lw2-graphql-query (lw2-query-string :post
:single
(alist :slug slug
) :fields
'(:--id
))))))))
1036 (simple-cacheable ("username" 'backend-lw2-legacy
"userid-to-displayname" user-id
:get-wrapper
#'get-username-wrapper
)
1037 (rate-limit (user-id) (cdr (first (lw2-graphql-query (lw2-query-string :user
:single
(alist :document-id user-id
) :fields
'(:display-name
))))))))
1040 (simple-cacheable ("user-slug" 'backend-lw2-legacy
"userid-to-slug" user-id
)
1041 (rate-limit (user-id) (cdr (first (lw2-graphql-query (lw2-query-string :user
:single
(alist :document-id user-id
) :fields
'(:slug
))))))))
1044 (simple-cacheable ("user-full-name" 'backend-lw2-legacy
"userid-to-full-name" user-id
)
1045 (rate-limit (user-id) (or (cdr (first (lw2-graphql-query (lw2-query-string :user
:single
(alist :document-id user-id
) :fields
'(:full-name
)))))
1049 (simple-cacheable ("slug-userid" 'backend-lw2-legacy
"slug-to-userid" slug
)
1050 (rate-limit (slug) (cdr (first (lw2-graphql-query (lw2-query-string :user
:single
(alist :slug slug
) :fields
'(:--id
))))))))
1053 (simple-cacheable ("slug-tagid" 'backend-lw2-tags
"slug-to-tagid" slug
:catch-errors nil
)
1054 (rate-limit (slug) (cdr (first (first (lw2-graphql-query (lw2-query-string :tag
:list
(alist :view
"tagBySlug" :slug slug
) :fields
'(:--id
)))))))))
1056 (defun preload-username-cache ()
1057 (declare (optimize space
(compilation-speed 2) (speed 0)))
1058 (let ((user-list (lw2-graphql-query (lw2-query-string :user
:list
'() :fields
'(:--id
:slug
:display-name
)))))
1059 (with-cache-transaction
1060 (loop for user in user-list
1061 do
(alist-bind ((user-id (or simple-string null
) :--id
)
1062 (slug (or simple-string null
))
1063 (display-name (or simple-string null
)))
1067 (cache-username user-id display-name
))
1069 (cache-user-slug user-id slug
)
1070 (cache-slug-userid slug user-id
))))))))