-
-
Notifications
You must be signed in to change notification settings - Fork 194
/
Copy pathsente.cljc
1577 lines (1341 loc) · 64.9 KB
/
sente.cljc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(ns taoensso.sente
"Channel sockets for Clojure/Script.
Protocol | client>server | client>server ?+ ack/reply | server>user push
* WebSockets: ✓ [1] ✓
* Ajax: [2] ✓ [3]
[1] Emulate with cb-uuid wrapping
[2] Emulate with dummy-cb wrapping
[3] Emulate with long-polling
Abbreviations:
* chsk - Channel socket (Sente's own pseudo \"socket\")
* server-ch - Underlying web server's async channel that implement
Sente's server channel interface
* sch - server-ch alias
* uid - User-id. An application-level user identifier used for async
push. May have semantic meaning (e.g. username, email address),
may not (e.g. client/random id) - app's discretion.
* cb - Callback
* tout - Timeout
* ws - WebSocket/s
* pstr - Packed string. Arbitrary Clojure data serialized as a
string (e.g. edn) for client<->server comms
* udt - Unix timestamp (datetime long)
Special messages:
* Callback wrapping: [<clj> <?cb-uuid>] for [1], [2]
* Callback replies: :chsk/closed, :chsk/timeout, :chsk/error
* Client-side events:
[:chsk/handshake [<?uid> <?csrf-token> <?handshake-data> <first-handshake?>]]
[:chsk/state [<old-state-map> <new-state-map>]]
[:chsk/recv <ev-as-pushed-from-server>] ; Server>user push
* Server-side events:
[:chsk/bad-package <packed-str>]
[:chsk/bad-event <event>]
[:chsk/uidport-open <uid>]
[:chsk/uidport-close <uid>]
Channel socket state map:
:type - e/o #{:auto :ws :ajax}
:open? - Truthy iff chsk appears to be open (connected) now
:ever-opened? - Truthy iff chsk handshake has ever completed successfully
:first-open? - Truthy iff chsk just completed first successful handshake
:uid - User id provided by server on handshake, or nil
:csrf-token - CSRF token provided by server on handshake, or nil
:handshake-data - Arb user data provided by server on handshake
:last-ws-error - ?{:udt _ :ev <WebSocket-on-error-event>}
:last-ws-close - ?{:udt _ :ev <WebSocket-on-close-event>
:clean? _ :code _ :reason _}
:last-close - ?{:udt _ :reason _}, with reason e/o
#{nil :requested-disconnect :requested-reconnect
:downgrading-ws-to-ajax :unexpected}
Notable implementation details:
* core.async is used liberally where brute-force core.async allows for
significant implementation simplifications. We lean on core.async's
efficiency here.
* For WebSocket fallback we use long-polling rather than HTTP 1.1 streaming
(chunked transfer encoding). Http-kit _does_ support chunked transfer
encoding but a small minority of browsers &/or proxies do not. Instead of
implementing all 3 modes (WebSockets, streaming, long-polling) - it seemed
reasonable to focus on the two extremes (performance + compatibility).
In any case client support for WebSockets is growing rapidly so fallback
modes will become increasingly irrelevant while the extra simplicity will
continue to pay dividends.
General-use notes:
* Single HTTP req+session persists over entire chsk session but cannot
modify sessions! Use standard a/sync HTTP Ring req/resp for logins, etc.
* Easy to wrap standard HTTP Ring resps for transport over chsks. Prefer
this approach to modifying handlers (better portability)."
{:author "Peter Taoussanis (@ptaoussanis)"}
#?(:clj
(:require
[clojure.string :as str]
[clojure.core.async :as async :refer (<! <!! >! >!! put! chan go go-loop)]
[taoensso.encore :as enc :refer (swap-in! reset-in! swapped have have! have?)]
[taoensso.timbre :as timbre :refer (tracef debugf infof warnf errorf)]
[taoensso.sente.interfaces :as interfaces]))
#?(:cljs
(:require
[clojure.string :as str]
[cljs.core.async :as async :refer (<! >! put! chan)]
[taoensso.encore :as enc :refer (format swap-in! reset-in! swapped)
:refer-macros (have have! have?)]
[taoensso.timbre :as timbre :refer-macros (tracef debugf infof warnf errorf)]
[taoensso.sente.interfaces :as interfaces]))
#?(:cljs
(:require-macros
[cljs.core.async.macros :as asyncm :refer (go go-loop)]
[taoensso.sente :as sente-macros :refer (elide-require)])))
(if (vector? taoensso.encore/encore-version)
(enc/assert-min-encore-version [2 67 1])
(enc/assert-min-encore-version 2.67))
#?(:cljs (def ^:private node-target? (= *target* "nodejs")))
;; (timbre/set-level! :trace) ; Uncomment for debugging
(defonce debug-mode?_ (atom false))
;;;; Events
;; Clients & server both send `event`s and receive (i.e. route) `event-msg`s:
;; - `event`s have the same form client+server side,
;; - `event-msg`s have a similar but not identical form
(defn- validate-event [x]
(cond
(not (vector? x)) :wrong-type
(not (#{1 2} (count x))) :wrong-length
:else (let [[ev-id _] x]
(cond (not (keyword? ev-id)) :wrong-id-type
(not (namespace ev-id)) :unnamespaced-id
:else nil))))
(defn event? "Valid [ev-id ?ev-data] form?" [x] (nil? (validate-event x)))
(defn as-event [x] (if (event? x) x [:chsk/bad-event x]))
(defn assert-event [x]
(when-let [?err (validate-event x)]
(let [err-msg
(str
(case ?err
:wrong-type "Malformed event (wrong type)."
:wrong-length "Malformed event (wrong length)."
(:wrong-id-type :unnamespaced-id)
"Malformed event (`ev-id` should be a namespaced keyword)."
:else "Malformed event (unknown error).")
" Event should be of `[ev-id ?ev-data]` form: " x)]
(throw (ex-info err-msg {:malformed-event x})))))
(defn client-event-msg? [x]
(and
(map? x)
(enc/ks= #{:ch-recv :send-fn :state :event :id :?data} x)
(let [{:keys [ch-recv send-fn state event]} x]
(and
(enc/chan? ch-recv)
(ifn? send-fn)
(enc/atom? state)
(event? event)))))
(defn server-event-msg? [x]
(and
(map? x)
(enc/ks= #{:ch-recv :send-fn :connected-uids
:ring-req :client-id
:event :id :?data :?reply-fn :uid} x)
(let [{:keys [ch-recv send-fn connected-uids
ring-req client-id event ?reply-fn]} x]
(and
(enc/chan? ch-recv)
(ifn? send-fn)
(enc/atom? connected-uids)
(map? ring-req)
(enc/nblank-str? client-id)
(event? event)
(or (nil? ?reply-fn)
(ifn? ?reply-fn))))))
(defn- put-server-event-msg>ch-recv!
"All server `event-msg`s go through this"
[ch-recv {:as ev-msg :keys [event ?reply-fn]}]
(let [[ev-id ev-?data :as valid-event] (as-event event)
ev-msg* (merge ev-msg {:event valid-event
:?reply-fn ?reply-fn
:id ev-id
:?data ev-?data})]
(if-not (server-event-msg? ev-msg*)
(warnf "Bad ev-msg: %s" ev-msg) ; Log 'n drop
(put! ch-recv ev-msg*))))
;;; Note that cb replys need _not_ be `event` form!
#?(:cljs (defn cb-error? [cb-reply-clj] (#{:chsk/closed :chsk/timeout :chsk/error} cb-reply-clj)))
#?(:cljs (defn cb-success? [cb-reply-clj] (not (cb-error? cb-reply-clj))))
;;;; Packing
;; * Client<->server payloads are arbitrary Clojure vals (cb replies or events).
;; * Payloads are packed for client<->server transit.
;; * Packing includes ->str encoding, and may incl. wrapping to carry cb info.
(defn- unpack "prefixed-pstr->[clj ?cb-uuid]"
[packer prefixed-pstr]
(have? string? prefixed-pstr)
(let [wrapped? (enc/str-starts-with? prefixed-pstr "+")
pstr (subs prefixed-pstr 1)
clj
(try
(interfaces/unpack packer pstr)
(catch #?(:clj Throwable :cljs :default) t
(debugf "Bad package: %s (%s)" pstr t)
[:chsk/bad-package pstr]))
[clj ?cb-uuid] (if wrapped? clj [clj nil])
?cb-uuid (if (= 0 ?cb-uuid) :ajax-cb ?cb-uuid)]
(tracef "Unpacking: %s -> %s" prefixed-pstr [clj ?cb-uuid])
[clj ?cb-uuid]))
(defn- with-?meta [x ?m] (if (seq ?m) (with-meta x ?m) x))
(defn- pack "clj->prefixed-pstr"
([packer ?packer-meta clj]
(let [pstr
(str "-" ; => Unwrapped (no cb metadata)
(interfaces/pack packer (with-?meta clj ?packer-meta)))]
(tracef "Packing (unwrapped): %s -> %s" [?packer-meta clj] pstr)
pstr))
([packer ?packer-meta clj ?cb-uuid]
(let [;;; Keep wrapping as light as possible:
?cb-uuid (if (= ?cb-uuid :ajax-cb) 0 ?cb-uuid)
wrapped-clj (if ?cb-uuid [clj ?cb-uuid] [clj])
pstr
(str "+" ; => Wrapped (cb metadata)
(interfaces/pack packer (with-?meta wrapped-clj ?packer-meta)))]
(tracef "Packing (wrapped): %s -> %s" [?packer-meta clj ?cb-uuid] pstr)
pstr)))
(deftype EdnPacker []
interfaces/IPacker
(pack [_ x] (enc/pr-edn x))
(unpack [_ s] (enc/read-edn s)))
(def ^:private default-edn-packer (EdnPacker.))
(defn- coerce-packer [x]
(if (= x :edn)
default-edn-packer
(have #(satisfies? interfaces/IPacker %) x)))
(comment
(do
(require '[taoensso.sente.packers.transit :as transit])
(def ^:private default-transit-json-packer (transit/get-transit-packer)))
(let [pack interfaces/pack
unpack interfaces/unpack
data {:a :A :b :B :c "hello world"}]
(enc/qb 10000
(let [pk default-edn-packer] (unpack pk (pack pk data)))
(let [pk default-transit-json-packer] (unpack pk (pack pk data))))))
;;;; Server API
(declare
^:private send-buffered-server-evs>ws-clients!
^:private send-buffered-server-evs>ajax-clients!
^:private default-client-side-ajax-timeout-ms)
(defn make-channel-socket-server!
"Takes a web server adapter[1] and returns a map with keys:
:ch-recv ; core.async channel to receive `event-msg`s (internal or from clients).
:send-fn ; (fn [user-id ev] for server>user push.
:ajax-post-fn ; (fn [ring-req]) for Ring CSRF-POST + chsk URL.
:ajax-get-or-ws-handshake-fn ; (fn [ring-req]) for Ring GET + chsk URL.
:connected-uids ; Watchable, read-only (atom {:ws #{_} :ajax #{_} :any #{_}}).
Common options:
:user-id-fn ; (fn [ring-req]) -> unique user-id for server>user push.
:csrf-token-fn ; (fn [ring-req]) -> CSRF token for Ajax POSTs.
:handshake-data-fn ; (fn [ring-req]) -> arb user data to append to handshake evs.
:ws-kalive-ms ; Ping to keep a WebSocket conn alive if no activity
; w/in given msecs.
:lp-timeout-ms ; Timeout (repoll) long-polling Ajax conns after given msecs.
:send-buf-ms-ajax ; [2]
:send-buf-ms-ws ; [2]
:packer ; :edn (default), or an IPacker implementation.
[1] e.g. `(taoensso.sente.server-adapters.http-kit/get-sch-adapter)` or
`(taoensso.sente.server-adapters.immutant/get-sch-adapter)`.
You must have the necessary web-server dependency in your project.clj and
the necessary entry in your namespace's `ns` form.
[2] Optimization to allow transparent batching of rapidly-triggered
server>user pushes. This is esp. important for Ajax clients which use a
(slow) reconnecting poller. Actual event dispatch may occur <= given ms
after send call (larger values => larger batch windows)."
[web-server-ch-adapter
& [{:keys [recv-buf-or-n ws-kalive-ms lp-timeout-ms
send-buf-ms-ajax send-buf-ms-ws
user-id-fn csrf-token-fn handshake-data-fn packer]
:or {recv-buf-or-n (async/sliding-buffer 1000)
ws-kalive-ms (enc/ms :secs 25) ; < Heroku 55s timeout
lp-timeout-ms (enc/ms :secs 20) ; < Heroku 30s timeout
send-buf-ms-ajax 100
send-buf-ms-ws 30
user-id-fn (fn [ring-req] (get-in ring-req [:session :uid]))
csrf-token-fn (fn [ring-req]
(or (get-in ring-req [:session :csrf-token])
(get-in ring-req [:session :ring.middleware.anti-forgery/anti-forgery-token])
(get-in ring-req [:session "__anti-forgery-token"])))
handshake-data-fn (fn [ring-req] nil)
packer :edn}}]]
(have? enc/pos-int? send-buf-ms-ajax send-buf-ms-ws)
(have? #(satisfies? interfaces/IServerChanAdapter %) web-server-ch-adapter)
(let [max-ms default-client-side-ajax-timeout-ms]
(when (>= lp-timeout-ms max-ms)
(throw
(ex-info (str ":lp-timeout-ms must be < " max-ms)
{:lp-timeout-ms lp-timeout-ms
:default-client-side-ajax-timeout-ms max-ms}))))
(let [packer (coerce-packer packer)
ch-recv (chan recv-buf-or-n)
user-id-fn
(fn [ring-req client-id]
;; Allow uid to depend (in part or whole) on client-id. Be cautious
;; of security implications.
(or (user-id-fn (assoc ring-req :client-id client-id)) ::nil-uid))
;; :ws udts used for ws-kalive (to check for activity in window period)
;; :ajax udts used for lp-timeout (as a way to check active conn identity)
conns_ (atom {:ws {} :ajax {}}) ; {<uid> {<client-id> [<?sch> <udt>]}}
send-buffers_ (atom {:ws {} :ajax {}}) ; {<uid> [<buffered-evs> <#{ev-uuids}>]}
connected-uids_ (atom {:ws #{} :ajax #{} :any #{}}) ; Public
upd-conn!
(fn
([conn-type uid client-id] ; Update udt
(swap-in! conns_ [conn-type uid client-id]
(fn [?v]
(let [[?sch _udt] ?v
new-udt (enc/now-udt)]
(enc/swapped
[?sch new-udt]
{:init? (nil? ?v) :udt new-udt :?sch ?sch})))))
([conn-type uid client-id new-?sch] ; Update sch + udt
(swap-in! conns_ [conn-type uid client-id]
(fn [?v]
(let [new-udt (enc/now-udt)]
(enc/swapped
[new-?sch new-udt]
{:init? (nil? ?v) :udt new-udt :?sch new-?sch}))))))
connect-uid!
(fn [conn-type uid] {:pre [(have? uid)]}
(let [newly-connected?
(swap-in! connected-uids_ []
(fn [{:keys [ws ajax any] :as old-m}]
(let [new-m
(case conn-type
:ws {:ws (conj ws uid) :ajax ajax :any (conj any uid)}
:ajax {:ws ws :ajax (conj ajax uid) :any (conj any uid)})]
(swapped new-m
(let [old-any (:any old-m)
new-any (:any new-m)]
(when (and (not (contains? old-any uid))
(contains? new-any uid))
:newly-connected))))))]
newly-connected?))
upd-connected-uid!
(fn [uid] {:pre [(have? uid)]}
(let [newly-disconnected?
(swap-in! connected-uids_ []
(fn [{:keys [ws ajax any] :as old-m}]
(let [conns' @conns_
any-ws-clients? (contains? (:ws conns') uid)
any-ajax-clients? (contains? (:ajax conns') uid)
any-clients? (or any-ws-clients?
any-ajax-clients?)
new-m
{:ws (if any-ws-clients? (conj ws uid) (disj ws uid))
:ajax (if any-ajax-clients? (conj ajax uid) (disj ajax uid))
:any (if any-clients? (conj any uid) (disj any uid))}]
(swapped new-m
(let [old-any (:any old-m)
new-any (:any new-m)]
(when (and (contains? old-any uid)
(not (contains? new-any uid)))
:newly-disconnected))))))]
newly-disconnected?))
send-fn ; server>user (by uid) push
(fn [user-id ev & [{:as opts :keys [flush?]}]]
(let [uid (if (= user-id :sente/all-users-without-uid) ::nil-uid user-id)
_ (tracef "Chsk send: (->uid %s) %s" uid ev)
_ (assert uid
(str "Support for sending to `nil` user-ids has been REMOVED. "
"Please send to `:sente/all-users-without-uid` instead."))
_ (assert-event ev)
ev-uuid (enc/uuid-str)
flush-buffer!
(fn [conn-type]
(when-let
[pulled
(swap-in! send-buffers_ [conn-type]
(fn [m]
;; Don't actually flush unless the event buffered
;; with _this_ send call is still buffered (awaiting
;; flush). This means that we'll have many (go
;; block) buffer flush calls that'll noop. They're
;; cheap, and this approach is preferable to
;; alternatives like flush workers.
(let [[_ ev-uuids] (get m uid)]
(if (contains? ev-uuids ev-uuid)
(swapped (dissoc m uid)
(get m uid))
(swapped m nil)))))]
(let [[buffered-evs ev-uuids] pulled]
(have? vector? buffered-evs)
(have? set? ev-uuids)
(let [packer-metas (mapv meta buffered-evs)
combined-packer-meta (reduce merge {} packer-metas)
buffered-evs-ppstr (pack packer
combined-packer-meta
buffered-evs)]
(tracef "buffered-evs-ppstr: %s (with meta %s)"
buffered-evs-ppstr combined-packer-meta)
(case conn-type
:ws (send-buffered-server-evs>ws-clients! conns_
uid buffered-evs-ppstr upd-conn!)
:ajax (send-buffered-server-evs>ajax-clients! conns_
uid buffered-evs-ppstr))))))]
(if (= ev [:chsk/close]) ; Currently undocumented
(do
(debugf "Chsk closing (client may reconnect): %s" uid)
(when flush?
(flush-buffer! :ws)
(flush-buffer! :ajax))
(doseq [[?sch _udt] (vals (get-in @conns_ [:ws uid]))]
(when-let [sch ?sch] (interfaces/sch-close! sch)))
(doseq [[?sch _udt] (vals (get-in @conns_ [:ajax uid]))]
(when-let [sch ?sch] (interfaces/sch-close! sch))))
(do
;; Buffer event
(doseq [conn-type [:ws :ajax]]
(swap-in! send-buffers_ [conn-type uid]
(fn [?v]
(if-not ?v
[[ev] #{ev-uuid}]
(let [[buffered-evs ev-uuids] ?v]
[(conj buffered-evs ev)
(conj ev-uuids ev-uuid)])))))
;;; Flush event buffers after relevant timeouts:
;; * May actually flush earlier due to another timeout.
;; * We send to _all_ of a uid's connections.
;; * Broadcasting is possible but I'd suggest doing it rarely,
;; and only to users we know/expect are actually online.
;;
(if flush?
(do
(flush-buffer! :ws)
(flush-buffer! :ajax))
(let [ws-timeout (async/timeout send-buf-ms-ws)
ajax-timeout (async/timeout send-buf-ms-ajax)]
(go
(<! ws-timeout)
(flush-buffer! :ws))
(go
(<! ajax-timeout)
(flush-buffer! :ajax)))))))
;; Server-side send is async so nothing useful to return (currently
;; undefined):
nil)
ev-msg-const
{:ch-recv ch-recv
:send-fn send-fn
:connected-uids connected-uids_}]
{:ch-recv ch-recv
:send-fn send-fn
:connected-uids connected-uids_
;; Does not participate in `conns_` (has specific req->resp)
:ajax-post-fn
(fn [ring-req]
(interfaces/ring-req->server-ch-resp web-server-ch-adapter ring-req
{:on-open
(fn [server-ch websocket?]
(assert (not websocket?))
(let [params (get ring-req :params)
ppstr (get params :ppstr)
client-id (get params :client-id)
[clj has-cb?] (unpack packer ppstr)
reply-fn
(let [replied?_ (atom false)]
(fn [resp-clj] ; Any clj form
(when (compare-and-set! replied?_ false true)
(tracef "Chsk send (ajax post reply): %s" resp-clj)
(interfaces/sch-send! server-ch websocket?
(pack packer (meta resp-clj) resp-clj)))))]
(put-server-event-msg>ch-recv! ch-recv
(merge ev-msg-const
{;; Note that the client-id is provided here just for the
;; user's convenience. non-lp-POSTs don't actually need a
;; client-id for Sente's own implementation:
:client-id client-id #_"unnecessary-for-non-lp-POSTs"
:ring-req ring-req
:event clj
:uid (user-id-fn ring-req client-id)
:?reply-fn (when has-cb? reply-fn)}))
(if has-cb?
(when-let [ms lp-timeout-ms]
(go
(<! (async/timeout ms))
(reply-fn :chsk/timeout)))
(reply-fn :chsk/dummy-cb-200))))}))
;; Ajax handshake/poll, or WebSocket handshake
:ajax-get-or-ws-handshake-fn
(fn [ring-req]
(let [sch-uuid (enc/uuid-str 6)
params (get ring-req :params)
client-id (get params :client-id)
csrf-token (csrf-token-fn ring-req)
uid (user-id-fn ring-req client-id)
receive-event-msg! ; Partial
(fn self
([event ] (self event nil))
([event ?reply-fn]
(put-server-event-msg>ch-recv! ch-recv
(merge ev-msg-const
{:client-id client-id
:ring-req ring-req
:event event
:?reply-fn ?reply-fn
:uid uid}))))
send-handshake!
(fn [server-ch websocket?]
(tracef "send-handshake!")
(let [?handshake-data (handshake-data-fn ring-req)
handshake-ev
(if (nil? ?handshake-data) ; Micro optimization
[:chsk/handshake [uid csrf-token]]
[:chsk/handshake [uid csrf-token ?handshake-data]])]
(interfaces/sch-send! server-ch websocket?
(pack packer nil handshake-ev))))]
(if (str/blank? client-id)
(let [err-msg "Client's Ring request doesn't have a client id. Does your server have the necessary keyword Ring middleware (`wrap-params` & `wrap-keyword-params`)?"]
(errorf (str err-msg ": %s") ring-req) ; Careful re: % in req
(throw (ex-info err-msg {:ring-req ring-req})))
(interfaces/ring-req->server-ch-resp web-server-ch-adapter ring-req
{:on-open
(fn [server-ch websocket?]
(if websocket?
;; WebSocket handshake
(let [_ (tracef "New WebSocket channel: %s (%s)" uid sch-uuid)
updated-conn (upd-conn! :ws uid client-id server-ch)
udt-open (:udt updated-conn)]
(when (connect-uid! :ws uid)
(receive-event-msg! [:chsk/uidport-open uid]))
(send-handshake! server-ch websocket?)
;; Start ws-kalive loop
;; This also works to gc ws conns that were suddenly
;; terminated (e.g. by turning on airplane mode)
(when-let [ms ws-kalive-ms]
(go-loop [udt-t0 udt-open]
(<! (async/timeout ms))
(when-let [[_sch udt-t1] (get-in @conns_ [:ws uid client-id])]
(when (interfaces/sch-open? server-ch)
;; (assert (= _sch server-ch))
(when (= udt-t1 udt-t0)
;; We've seen no send/recv activity on this
;; conn w/in our kalive window so send a ping
;; ->client (should auto-close conn if it's
;; gone dead)
(interfaces/sch-send! server-ch websocket?
(pack packer nil :chsk/ws-ping)))
(recur udt-t1))))))
;; Ajax handshake/poll
(let [_ (tracef "New Ajax handshake/poll: %s (%s)" uid sch-uuid)
updated-conn (upd-conn! :ajax uid client-id server-ch)
udt-open (:udt updated-conn)
handshake? (or (:init? updated-conn) (:handshake? params))]
(when (connect-uid! :ajax uid)
(receive-event-msg! [:chsk/uidport-open uid]))
(if handshake?
; Client will immediately repoll
(send-handshake! server-ch websocket?)
(when-let [ms lp-timeout-ms]
(go
(<! (async/timeout ms))
(when-let [[_sch udt-t1] (get-in @conns_ [:ajax uid client-id])]
(when (= udt-t1 udt-open)
;; (assert (= _sch server-ch))
;; Appears to still be the active sch
(interfaces/sch-send! server-ch websocket?
(pack packer nil :chsk/timeout))))))))))
:on-msg
(fn [server-ch websocket? req-ppstr]
(assert websocket?)
(upd-conn! :ws uid client-id)
(let [[clj ?cb-uuid] (unpack packer req-ppstr)]
(receive-event-msg! clj ; Should be ev
(when ?cb-uuid
(fn reply-fn [resp-clj] ; Any clj form
(tracef "Chsk send (ws reply): %s" resp-clj)
;; true iff apparent success:
(interfaces/sch-send! server-ch websocket?
(pack packer (meta resp-clj) resp-clj ?cb-uuid)))))))
:on-close ; We rely on `on-close` to trigger for _every_ conn!
(fn [server-ch websocket? _status]
;; Note that `status` type varies with underlying web server
(let [conn-type (if websocket? :ws :ajax)
_ (tracef "%s channel closed: %s (%s)"
(if websocket? "WebSocket" "Ajax")
uid sch-uuid)
updated-conn (upd-conn! conn-type uid client-id nil)
udt-close (:udt updated-conn)]
;; Allow some time for possible reconnects (repoll,
;; sole window refresh, etc.):
(go
(<! (async/timeout 5000))
(let [[_?sch udt-t1] (get-in @conns_ [conn-type uid client-id])]
(when @debug-mode?_
(debugf "close-timeout: %s %s %s %s" conn-type uid
sch-uuid [(= udt-t1 udt-close) udt-t1 udt-close]))
(when (= udt-t1 udt-close)
(let [disconnect? ; Removed entry for client-id?
(swap-in! conns_ [conn-type uid client-id]
(fn [[_sch udt-t1]]
(if (= udt-t1 udt-close)
(swapped :swap/dissoc true)
(swapped udt-t1 false))))]
(when disconnect?
;; Potentially remove entry for uid
(swap-in! conns_ [conn-type uid]
(fn [?m] (if (empty? ?m) :swap/dissoc ?m)))
(when (upd-connected-uid! uid)
(receive-event-msg! [:chsk/uidport-close uid])))))))))
:on-error
(fn [server-ch websocket? error]
(errorf "ring-req->server-ch-resp error: %s (%s)"
error uid sch-uuid))}))))}))
(defn- send-buffered-server-evs>ws-clients!
"Actually pushes buffered events (as packed-str) to all uid's WebSocket conns."
[conns_ uid buffered-evs-pstr upd-conn!]
(tracef "send-buffered-server-evs>ws-clients!: %s" buffered-evs-pstr)
(doseq [[client-id [?sch _udt]] (get-in @conns_ [:ws uid])]
(when-let [sch ?sch]
(upd-conn! :ws uid client-id)
(interfaces/sch-send! sch :websocket buffered-evs-pstr))))
(defn- send-buffered-server-evs>ajax-clients!
"Actually pushes buffered events (as packed-str) to all uid's Ajax conns.
Allows some time for possible Ajax poller reconnects."
[conns_ uid buffered-evs-pstr]
(tracef "send-buffered-server-evs>ajax-clients!: %s" buffered-evs-pstr)
(let [nmax-attempts 7
ms-base 90
ms-rand 90
;; (* 7 (+ 90 (/ 90 2.0))) ~= 945ms
;; All connected/possibly-reconnecting client uuids:
client-ids-unsatisfied (keys (get-in @conns_ [:ajax uid]))]
(when-not (empty? client-ids-unsatisfied)
;; (tracef "client-ids-unsatisfied: %s" client-ids-unsatisfied)
(go-loop [n 0 client-ids-satisfied #{}]
(let [?pulled ; nil or {<client-id> [<?sch> <udt>]}
(swap-in! conns_ [:ajax uid]
(fn [m] ; {<client-id> [<?sch> <udt>]}
(let [ks-to-pull (remove client-ids-satisfied (keys m))]
;; (tracef "ks-to-pull: %s" ks-to-pull)
(if (empty? ks-to-pull)
(swapped m nil)
(swapped
(reduce
(fn [m k]
(let [[?sch udt] (get m k)]
;; Nb don't change udt; for Ajax conns_ we only
;; want udt updated on poll or close, not on
;; activity (as with ws conns_)
(assoc m k [nil udt #_(enc/now-udt)])))
m ks-to-pull)
(select-keys m ks-to-pull))))))]
(have? [:or nil? map?] ?pulled)
(let [?newly-satisfied
(when ?pulled
(reduce-kv
(fn [s client-id [?sch _udt]]
(let [sent?
(when-let [sch ?sch]
;; Will noop + return false if sch already closed:
(interfaces/sch-send! ?sch (not :websocket)
buffered-evs-pstr))]
(if sent? (conj s client-id) s)))
#{} ?pulled))
now-satisfied (into client-ids-satisfied ?newly-satisfied)]
;; (tracef "now-satisfied: %s" now-satisfied)
(when (and (< n nmax-attempts)
(some (complement now-satisfied) client-ids-unsatisfied))
;; Allow some time for possible poller reconnects:
(<! (async/timeout (+ ms-base (rand-int ms-rand))))
(recur (inc n) now-satisfied))))))))
;;;; Client API
#?(:cljs (def ajax-lite "Alias of `taoensso.encore/ajax-lite`" enc/ajax-lite))
#?(:cljs
(defprotocol IChSocket
(-chsk-connect! [chsk])
(-chsk-disconnect! [chsk reason])
(-chsk-reconnect! [chsk])
(-chsk-send! [chsk ev opts])))
#?(:cljs
(do
(defn chsk-connect! [chsk] (-chsk-connect! chsk))
(defn chsk-disconnect! [chsk] (-chsk-disconnect! chsk :requested-disconnect))
(defn chsk-reconnect! "Useful for reauthenticating after login/logout, etc."
[chsk] (-chsk-reconnect! chsk))
(def chsk-destroy! "Deprecated" chsk-disconnect!)))
#?(:cljs
(defn chsk-send!
"Sends `[ev-id ev-?data :as event]`, returns true on apparent success."
([chsk ev] (chsk-send! chsk ev {}))
([chsk ev ?timeout-ms ?cb] (chsk-send! chsk ev {:timeout-ms ?timeout-ms
:cb ?cb}))
([chsk ev opts]
(tracef "Chsk send: (%s) %s" (assoc opts :cb (boolean (:cb opts))) ev)
(-chsk-send! chsk ev opts))))
#?(:cljs
(defn- chsk-send->closed! [?cb-fn]
(warnf "Chsk send against closed chsk.")
(when ?cb-fn (?cb-fn :chsk/closed))
false))
#?(:cljs
(defn- assert-send-args [x ?timeout-ms ?cb]
(assert-event x)
(assert (or (and (nil? ?timeout-ms) (nil? ?cb))
(and (enc/nat-int? ?timeout-ms)))
(str "cb requires a timeout; timeout-ms should be a +ive integer: " ?timeout-ms))
(assert (or (nil? ?cb) (ifn? ?cb) (enc/chan? ?cb))
(str "cb should be nil, an ifn, or a channel: " (type ?cb)))))
#?(:cljs
(defn- pull-unused-cb-fn! [cbs-waiting_ ?cb-uuid]
(when-let [cb-uuid ?cb-uuid]
(swap-in! cbs-waiting_ [cb-uuid]
(fn [?f] (swapped :swap/dissoc ?f))))))
#?(:cljs
(defn- swap-chsk-state!
"Atomically swaps the value of chk's :state_ atom."
[chsk f]
(let [[old-state new-state]
(swap-in! (:state_ chsk)
(fn [old-state]
(let [new-state (f old-state)
new-state
(if (:first-open? old-state)
(assoc new-state :first-open? false)
new-state)]
(swapped new-state [old-state new-state]))))]
(when (not= old-state new-state)
(let [output [old-state new-state]]
;; (debugf "Chsk state change: %s" output)
(put! (get-in chsk [:chs :state]) [:chsk/state output])
output)))))
#?(:cljs
(defn- chsk-state->closed [state reason]
(have? map? state)
(have? [:el #{:requested-disconnect
:requested-reconnect
:downgrading-ws-to-ajax
:unexpected}] reason)
(if (or (:open? state) (not= reason :unexpected))
(assoc state
:open? false
:last-close {:udt (enc/now-udt) :reason reason})
state)))
#?(:cljs
(defn- cb-chan-as-fn
"Experimental, undocumented. Allows a core.async channel to be provided
instead of a cb-fn. The channel will receive values of form
[<event-id>.cb <reply>]."
[?cb ev]
(if (or (nil? ?cb) (ifn? ?cb))
?cb
(do
(have? enc/chan? ?cb)
(assert-event ev)
(let [[ev-id _] ev
cb-ch ?cb]
(fn [reply]
(put! cb-ch
[(keyword (str (enc/as-qname ev-id) ".cb"))
reply])))))))
#?(:cljs
(defn- receive-buffered-evs! [chs clj]
(tracef "receive-buffered-evs!: %s" clj)
(let [buffered-evs (have vector? clj)]
(doseq [ev buffered-evs]
(assert-event ev)
;; Should never receive :chsk/* events from server here:
(let [[id] ev] (assert (not= (namespace id) "chsk")))
(put! (:<server chs) ev)))))
#?(:cljs
(defn- handshake? [x]
(and (vector? x) ; Nb support arb input (e.g. cb replies)
(let [[x1] x] (= x1 :chsk/handshake)))))
#?(:cljs
(defn- receive-handshake! [chsk-type chsk clj]
(have? [:el #{:ws :ajax}] chsk-type)
(have? handshake? clj)
(tracef "receive-handshake! (%s): %s" chsk-type clj)
(let [[_ [?uid ?csrf-token ?handshake-data]] clj
{:keys [chs ever-opened?_]} chsk
first-handshake? (compare-and-set! ever-opened?_ false true)
new-state
{:type chsk-type ; :auto -> e/o #{:ws :ajax}, etc.
:open? true
:ever-opened? true
:uid ?uid
:csrf-token ?csrf-token
:handshake-data ?handshake-data
:first-open? first-handshake?}
handshake-ev
[:chsk/handshake
[?uid ?csrf-token ?handshake-data first-handshake?]]]
(assert-event handshake-ev)
(when (str/blank? ?csrf-token)
(warnf "SECURITY WARNING: no CSRF token available for use by Sente"))
(swap-chsk-state! chsk #(merge % new-state))
(put! (:internal chs) handshake-ev)
:handled)))
#?(:clj
(defmacro ^:private elide-require
"Experimental. The presence of `js/require` calls can cause issues with
React Native, even if they never execute. Currently no other known
workarounds. Ref. https://github.com/ptaoussanis/sente/issues/247."
[& body]
(when-not (enc/get-sys-val "SENTE_ELIDE_JS_REQUIRE")
`(do ~@body))))
#?(:cljs
(def ^:private ?node-npm-websocket_
"nnil iff the websocket npm library[1] is available.
Easiest way to install:
1. Add the lein-npm[2] plugin to your `project.clj`,
2. Add: `:npm {:dependencies [[websocket \"1.0.23\"]]}`
[1] Ref. https://www.npmjs.com/package/websocket
[2] Ref. https://github.com/RyanMcG/lein-npm"
(delay ; Eager eval causes issues with React Native, Ref. #247,
(elide-require
(when (and node-target? (exists? js/require))
(try
(js/require "websocket")
;; In particular, catch 'UnableToResolveError'
(catch :default e
;; (errorf e "Unable to load npm websocket lib")
nil)))))))
#?(:cljs
(defrecord ChWebSocket
;; WebSocket-only IChSocket implementation
;; Handles (re)connections, cbs, etc.
[client-id chs params packer url
state_ ; {:type _ :open? _ :uid _ :csrf-token _ ...}
retry-handle_ retry-count_ ever-opened?_
backoff-ms-fn ; (fn [nattempt]) -> msecs
cbs-waiting_ ; {<cb-uuid> <fn> ...}
socket_]
IChSocket
(-chsk-disconnect! [chsk reason]
(reset! retry-handle_ "_disable-auto-retry")
(swap-chsk-state! chsk #(chsk-state->closed % reason))
(when-let [s @socket_] (.close s 1000 "CLOSE_NORMAL")))
(-chsk-reconnect! [chsk]
(-chsk-disconnect! chsk :requested-reconnect)
(-chsk-connect! chsk))
(-chsk-send! [chsk ev opts]
(let [{?timeout-ms :timeout-ms ?cb :cb :keys [flush?]} opts
_ (assert-send-args ev ?timeout-ms ?cb)
?cb-fn (cb-chan-as-fn ?cb ev)]
(if-not (:open? @state_) ; Definitely closed
(chsk-send->closed! ?cb-fn)
;; TODO Buffer before sending (but honor `:flush?`)
(let [?cb-uuid (when ?cb-fn (enc/uuid-str 6))
ppstr (pack packer (meta ev) ev ?cb-uuid)]
(when-let [cb-uuid ?cb-uuid]
(reset-in! cbs-waiting_ [cb-uuid] (have ?cb-fn))
(when-let [timeout-ms ?timeout-ms]
(go (<! (async/timeout timeout-ms))
(when-let [cb-fn* (pull-unused-cb-fn! cbs-waiting_ ?cb-uuid)]
(cb-fn* :chsk/timeout)))))
(try
(.send @socket_ ppstr)
:apparent-success
(catch :default e
(errorf e "Chsk send error")
(when-let [cb-uuid ?cb-uuid]
(let [cb-fn* (or (pull-unused-cb-fn! cbs-waiting_ cb-uuid)
(have ?cb-fn))]
(cb-fn* :chsk/error)))
false))))))
(-chsk-connect! [chsk]
(when-let [WebSocket
(or
(enc/oget goog/global "WebSocket")
(enc/oget goog/global "MozWebSocket")
(enc/oget @?node-npm-websocket_ "w3cwebsocket"))]
(let [retry-handle (enc/uuid-str)
have-handle? (fn [] (= @retry-handle_ retry-handle))
connect-fn
(fn connect-fn []
(when (have-handle?)
(let [retry-fn
(fn [] ; Backoff then recur
(when (have-handle?)
(let [retry-count* (swap! retry-count_ inc)
backoff-ms (backoff-ms-fn retry-count*)]
(warnf "Chsk is closed: will try reconnect attempt (%s) in %s ms"
retry-count* backoff-ms)
(.setTimeout goog/global connect-fn backoff-ms))))
?socket
(try
(WebSocket.
(enc/merge-url-with-query-string url
(merge params ; 1st (don't clobber impl.):
{:client-id client-id})))