-
-
Notifications
You must be signed in to change notification settings - Fork 192
/
sente.cljc
2185 lines (1819 loc) · 91.6 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/ws-ping] ; ws-ping from server
[:chsk/handshake [<?uid> nil[4] <?handshake-data> <first-handshake?>]]
[:chsk/state [<old-state-map> <new-state-map> <open-change?>]]
[:chsk/recv <ev-as-pushed-from-server>] ; Server>user push
* Server-side events:
[:chsk/ws-ping] ; ws-ping from client
[:chsk/ws-pong] ; ws-pong from client
[:chsk/uidport-open <uid>]
[:chsk/uidport-close <uid>]
[:chsk/bad-package <packed-str>]
[:chsk/bad-event <event>]
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
: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 :clean :unexpected :requested-disconnect
:requested-reconnect :downgrading-ws-to-ajax
:ws-ping-timeout :ws-error}
:udt-next-reconnect - Approximate udt of next scheduled auto-reconnect attempt
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).
[4] Used to be a csrf-token. Was removed in v1.14 for security reasons.
A `nil` remains for limited backwards-compatibility with pre-v1.14 clients."
{:author "Peter Taoussanis (@ptaoussanis)"}
(:require
[clojure.string :as str]
[clojure.core.async :as async :refer [<! >! put! chan go go-loop]]
[taoensso.encore :as enc :refer [have have! have? swap-in! reset-in! swapped]]
[taoensso.timbre :as timbre]
[taoensso.sente.interfaces :as interfaces])
#?(:cljs (:require-macros [taoensso.sente :as sente-macros :refer [elide-require]]))
#?(:clj (:import [org.java_websocket.client WebSocketClient])))
(enc/assert-min-encore-version [3 62 1])
(def sente-version "Useful for identifying client/server mismatch" [1 19 2])
#?(:cljs (def ^:private node-target? (= *target* "nodejs")))
;;;; Logging config
(defn set-min-log-level!
"Sets Timbre's minimum log level for internal Sente namespaces.
Possible levels: #{:trace :debug :info :warn :error :fatal :report}.
Default level: `:warn`."
[level]
(timbre/set-ns-min-level! "taoensso.sente.*" level)
(timbre/set-ns-min-level! "taoensso.sente" level)
nil)
(defonce ^:private __set-default-log-level (set-min-log-level! :warn))
(defn- strim [^long max-len s]
(if (> (count s) max-len)
(str (enc/get-substr-by-len s 0 max-len) #_"+")
(do s)))
(defn- lid "Log id"
([uid ] (if (= uid :sente/nil-uid) "u_nil" (str "u_" (strim 6 (str uid)))))
([uid client-id ] (str (lid uid) "/c_" (strim 6 (str client-id))))
([uid client-id conn-id] (str (lid uid client-id) "/n_" (strim 6 conn-id))))
(comment (lid (enc/uuid-str) (enc/uuid-str) (enc/uuid-str)))
;;;; 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- expected [expected x] {:expected expected :actual {:type (type x) :value x}})
(defn validate-event
"Returns nil if given argument is a valid [ev-id ?ev-data] form. Otherwise
returns a map of validation errors like `{:wrong-type {:expected _ :actual _}}`."
[x]
(cond
(not (vector? x)) {:wrong-type (expected :vector x)}
(not (#{1 2} (count x))) {:wrong-length (expected #{1 2} x)}
:else
(let [[ev-id _] x]
(cond
(not (keyword? ev-id)) {:wrong-id-type (expected :keyword ev-id)}
(not (namespace ev-id)) {:unnamespaced-id (expected :namespaced-keyword ev-id)}
:else nil))))
(defn assert-event
"Returns given argument if it is a valid [ev-id ?ev-data] form. Otherwise
throws a validation exception."
[x]
(when-let [errs (validate-event x)]
(throw (ex-info "Invalid event" {:given x :errors errs}))))
(defn event? "Valid [ev-id ?ev-data] form?" [x] (nil? (validate-event x)))
(defn as-event [x]
(if-let [errs (validate-event x)]
;; [:chsk/bad-event {:given x :errors errs}] ; Breaking change
[:chsk/bad-event x]
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 :send-buffers
:ring-req :client-id
:event :id :?data :?reply-fn :uid} x)
(let [{:keys [ch-recv send-fn connected-uids send-buffers
ring-req client-id event ?reply-fn]} x]
(and
(enc/chan? ch-recv)
(ifn? send-fn)
(enc/atom? connected-uids)
(enc/atom? send-buffers)
(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 (server-event-msg? ev-msg*)
(put! ch-recv ev-msg*)
(timbre/warnf "Bad `event-msg` from server: %s" ev-msg) ; Log and drop
)))
;;; 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.
(defn- parse-packed
"Returns [<packed> <?format>]. Used to support some minimal backwards
compatibility between v2 `pack` and v1 `unpack`."
;; TODO Remove this in a future ~breaking release
[packed]
(if (string? packed)
(cond
(enc/str-starts-with? packed "+") [(subs packed 1) :v1/wrapped]
(enc/str-starts-with? packed "-") [(subs packed 1) :v1/unwrapped]
:else [ packed :v2/unwrapped])
[packed :v2/unwrapped]))
(comment (parse-packed "+[[\"foo\"] \"uuid\"]"))
(defn- unpack "packed->[clj ?cb-uuid]"
[packer packed]
(let [[packed ?format] (parse-packed packed)
unpacked ; [clj ?cb-uuid]
(try
(interfaces/unpack packer packed)
(catch #?(:clj Throwable :cljs :default) t
(timbre/errorf t "Failed to unpack: %s" packed)
[[:chsk/bad-package packed] nil]))
[clj ?cb-uuid]
(case ?format
:v1/wrapped unpacked
:v1/unwrapped [unpacked nil]
:v2/unwrapped unpacked)
?cb-uuid (if (= 0 ?cb-uuid) :ajax-cb ?cb-uuid)]
[clj ?cb-uuid]))
(def ^:dynamic *write-legacy-pack-format?*
"Advanced option, most users can ignore this var. Only necessary
for those that want to use Sente < v1.18 with a non-standard
IPacker that deals with non-string payloads.
Details:
Sente uses a private message format as an implementation detail
for client<->server comms.
As part of [#398], this format is being updated to support
non-string (e.g. binary) payloads.
Unfortunately updating the format is non-trivial because:
1. Both the client & server need to support the same format.
2. Clients are often served as cached cl/js.
To help ease migration, the new pack format is being rolled out
in stages:
Sente <= v1.16: reads v1 format only
writes v1 format only
Sente v1.17: reads v1 and v2 formats
writes v1 and v2 formats (v1 default)
Sente v1.18: reads v1 and v2 formats
writes v1 and v2 formats (v2 default) <- Currently here
Sente >= v1.19: reads v2 format only
writes v2 format only
This var controls which format to use for writing.
Override default with `alter-var-root` or `binding`."
false)
(defn- pack "[clj ?cb-uuid]->packed"
([packer clj ] (pack packer clj nil))
([packer clj ?cb-uuid]
(let [?cb-uuid (if (= ?cb-uuid :ajax-cb) 0 ?cb-uuid)
packed
(interfaces/pack packer
(if-some [cb-uuid ?cb-uuid]
[clj cb-uuid]
[clj ]))]
(if *write-legacy-pack-format?*
(str "+" (have string? packed))
(do packed)))))
(comment
(unpack default-edn-packer
(binding [*write-legacy-pack-format?* true]
(pack default-edn-packer [:foo]))))
(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 1e4 ; [111.96 67.26]
(let [pk default-edn-packer] (unpack pk (pack pk data)))
(let [pk default-transit-json-packer] (unpack pk (pack pk data))))))
;;;; Server API
(def ^:private next-idx! (enc/counter))
(declare
^:private send-buffered-server-evs>clients!
^:private default-client-side-ajax-timeout-ms)
(defn allow-origin?
"Alpha, subject to change.
Returns true iff given Ring request is allowed by `allowed-origins`.
`allowed-origins` may be `:all` or #{<origin> ...}."
[allowed-origins ring-req]
(enc/cond
(= allowed-origins :all) true
:let
[headers (get ring-req :headers)
origin (get headers "origin" :nx)
have-origin? (not= origin :nx)]
(and
have-origin?
(contains? (set allowed-origins) origin))
true
;; As per OWASP CSRF Prevention Cheat Sheet
:let [referer (get headers "referer" "")]
(and
(not have-origin?)
(enc/rsome #(str/starts-with? referer (str % "/")) allowed-origins))
true
:else false))
(comment
;; good (pass)
(allow-origin? :all {:headers {"origin" "http://site.com"}})
(allow-origin? #{"http://site.com"} {:headers {"origin" "http://site.com"}})
(allow-origin? #{"http://site.com"} {:headers {"referer" "http://site.com/"}})
;; bad (fail)
(allow-origin? #{"http://site.com"} {:headers nil})
(allow-origin? #{"http://site.com"} {:headers {"origin" "http://attacker.com"}})
(allow-origin? #{"http://site.com"} {:headers {"referer" "http://attacker.com/"}})
(allow-origin? #{"http://site.com"} {:headers {"referer" "http://site.com.attacker.com/"}}))
(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 ; Ring handler for CSRF-POST + chsk URL.
:ajax-get-or-ws-handshake-fn ; Ring handler for Ring GET + chsk URL.
:connected-uids ; Watchable, read-only (atom {:ws #{_} :ajax #{_} :any #{_}}).
Security options:
:allowed-origins ; e.g. #{\"http://site.com\" ...}, defaults to :all. ; Alpha
:csrf-token-fn ; ?(fn [ring-req]) -> CSRF-token for Ajax POSTs and WS handshake.
; nil => CSRF check will be DISABLED (can pose a *CSRF SECURITY RISK*
; for website use cases, so please ONLY disable this check if you're
; very sure you understand the implications!).
:authorized?-fn ; ?(fn [ring-req]) -> When non-nil, (authorized?-fn <ring-req>)
; must return truthy, otherwise connection requests will be
; rejected with (unauthorized-fn <ring-req>) response.
;
; May check Authroization HTTP header, etc.
:?unauthorized-fn ; An alternative API to `authorized?-fn`+`unauthorized-fn` pair.
; ?(fn [ring-req)) -> <?rejection-resp>. I.e. when return value
; is non-nil, connection requests will be rejected with that
; non-nil value.
Other common options:
:user-id-fn ; (fn [ring-req]) -> unique user-id for server>user push.
: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. Should be different to client's :ws-kalive-ms.
: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.
:ws-ping-timeout-ms ; When pinging to test WebSocket connections, msecs to
; await reply before regarding the connection as broken
;; When a connection is closed, Sente waits a little for possible reconnection before
;; actually marking the connection as closed. This facilitates Ajax long-polling,
;; server->client buffering, and helps to reduce event noise from spotty connections.
:ms-allow-reconnect-before-close-ws ; Msecs to wait for WebSocket conns (default: 2500)
:ms-allow-reconnect-before-close-ajax ; Msecs to wait for Ajax conns (default: 5000)
[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 ws-ping-timeout-ms
send-buf-ms-ajax send-buf-ms-ws
user-id-fn bad-csrf-fn bad-origin-fn csrf-token-fn
handshake-data-fn packer allowed-origins
authorized?-fn unauthorized-fn ?unauthorized-fn
ms-allow-reconnect-before-close-ws
ms-allow-reconnect-before-close-ajax]
: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
;; TODO Default initially disabled since it can take some time
;; for clients to update in the wild. We want to ensure that all
;; clients DO respond to pings before enabling the server to close
;; unresponsive connections.
;;
;; So we're rolling this new feature out in 2 steps:
;; 1. Update clients to respond to pings (with pongs)
;; 2. Update servers to regard lack of pong as broken conn
;;
;; The feature can be enabled early by manually providing a
;; `ws-ping-timeout-ms` val in opts.
;;
ws-ping-timeout-ms nil #_(enc/ms :secs 5) ; TODO Enable default val
send-buf-ms-ajax 100
send-buf-ms-ws 30
user-id-fn (fn [ ring-req] (get-in ring-req [:session :uid]))
bad-csrf-fn (fn [_ring-req] {:status 403 :body "Bad CSRF token"})
bad-origin-fn (fn [_ring-req] {:status 403 :body "Unauthorized origin"})
unauthorized-fn (fn [_ring-req] {:status 401 :body "Unauthorized request"})
ms-allow-reconnect-before-close-ws 2500
ms-allow-reconnect-before-close-ajax 5000
csrf-token-fn
(fn [ring-req]
(or (:anti-forgery-token ring-req)
(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"])
#_:sente/no-reference-csrf-token
))
handshake-data-fn (fn [ring-req] nil)
packer :edn
allowed-origins :all}}]]
(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 [allowed-origins (have [:or set? #{:all}] allowed-origins)
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)) :sente/nil-uid))
conns_ (atom {:ws {} :ajax {}}) ; {<uid> {<client-id> [<?sch> <udt-last-activity> <conn-id>]}}
send-buffers_ (atom {:ws {} :ajax {}}) ; {<uid> [<buffered-evs> <#{ev-uuids}>]}
connected-uids_ (atom {:ws #{} :ajax #{} :any #{}}) ; Public
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?))
maybe-disconnect-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) :sente/nil-uid user-id)
_ (timbre/tracef "Server asked to send event to %s: %s" (lid 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 [buffered-evs-ppstr (pack packer buffered-evs)]
(send-buffered-server-evs>clients! conn-type
conns_ uid buffered-evs-ppstr (count buffered-evs))))))]
(if (= ev [:chsk/close]) ; Currently undocumented
(do
(timbre/infof "Server asked to close chsk for %s" (lid 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)
bad-csrf?
(fn [ring-req]
(if (nil? csrf-token-fn) ; Provides a way to disable CSRF check
false
(if-let [reference-csrf-token (csrf-token-fn ring-req)]
(let [csrf-token-from-client
(or
(get-in ring-req [:params :csrf-token])
(get-in ring-req [:headers "x-csrf-token"])
(get-in ring-req [:headers "x-xsrf-token"]))]
(not
(enc/const-str=
reference-csrf-token
csrf-token-from-client)))
true ; By default fail if no CSRF token
)))
unauthorized?
(fn [ring-req]
(if (nil? authorized?-fn)
false
(not (authorized?-fn ring-req))))
;; nnil if connection attempt should be rejected
possible-rejection-resp
(fn [ring-req]
(enc/cond
(bad-csrf? ring-req)
(bad-csrf-fn ring-req)
(not (allow-origin? allowed-origins ring-req))
(bad-origin-fn ring-req)
(unauthorized? ring-req)
(unauthorized-fn ring-req)
:if-some [unauthorized-resp (when-let [uf ?unauthorized-fn]
(uf ring-req))]
unauthorized-resp
:else nil))
ev-msg-const
{:ch-recv ch-recv
:send-fn send-fn
:connected-uids connected-uids_
:send-buffers send-buffers_}]
{:ch-recv ch-recv
:send-fn send-fn
:connected-uids_ connected-uids_
:connected-uids connected-uids_ ; For back compatibility
:private {:conns_ conns_
:send-buffers_ send-buffers_}
;; Does not participate in `conns_` (has specific req->resp)
:ajax-post-fn
(fn ring-handler
([ring-req] (ring-handler ring-req nil nil))
([ring-req ?ring-async-resp-fn ?ring-async-raise-fn]
(enc/cond
:if-let [resp (possible-rejection-resp ring-req)] resp
:else
(interfaces/ring-req->server-ch-resp web-server-ch-adapter ring-req
{:ring-async-resp-fn ?ring-async-resp-fn
:ring-async-raise-fn ?ring-async-raise-fn
: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)
(timbre/debugf "[ajax/on-open] Server will reply to message from %s: %s"
(lid (user-id-fn ring-req client-id) client-id)
resp-clj)
(interfaces/sch-send! server-ch websocket?
(pack packer 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-handler
([ring-req] (ring-handler ring-req nil nil))
([ring-req ?ring-async-resp-fn ?ring-async-raise-fn]
(let [;; ?ws-key (get-in ring-req [:headers "sec-websocket-key"])
conn-id (enc/uuid-str 6) ; 1 per ws/ajax rreq, equiv to server-ch identity
params (get ring-req :params)
client-id (get params :client-id)
uid (user-id-fn ring-req client-id)
lid* (lid uid client-id conn-id)]
(enc/cond
(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`)?"]
(timbre/error (str err-msg ": " lid*))
(throw (ex-info err-msg {:ring-req ring-req, :lid lid*})))
:if-let [resp (possible-rejection-resp ring-req)] resp
:else
(let [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?]
(timbre/infof "Server will send %s handshake to %s" (if websocket? :ws :ajax) lid*)
(let [?handshake-data (handshake-data-fn ring-req)
handshake-ev
(if (nil? ?handshake-data) ; Micro optimization
[:chsk/handshake [uid nil]]
[:chsk/handshake [uid nil ?handshake-data]])]
;; Returns true iff server-ch open during call
(interfaces/sch-send! server-ch websocket?
(pack packer handshake-ev))))
on-error
(fn [server-ch websocket? error]
(timbre/errorf "%s Server sch error for %s: %s"
(if websocket? "[ws/on-error]" "[ajax/on-error]")
lid* error))
on-msg
(fn [server-ch websocket? req-ppstr]
(assert websocket?)
(swap-in! conns_ [:ws uid client-id]
(fn [[?sch _udt conn-id]]
(when conn-id [?sch (enc/now-udt) conn-id])))
(let [[clj ?cb-uuid] (unpack packer req-ppstr)]
;; clj should be ev
(cond
(= clj [:chsk/ws-pong]) (receive-event-msg! clj nil)
(= clj [:chsk/ws-ping])
(do
;; Auto reply to ping
(when-let [cb-uuid ?cb-uuid]
(timbre/debugf "[ws/on-msg] Server will auto-reply to ping from %s" lid*)
(interfaces/sch-send! server-ch websocket?
(pack packer "pong" cb-uuid)))
(receive-event-msg! clj nil))
:else
(receive-event-msg! clj
(when ?cb-uuid
(fn reply-fn [resp-clj] ; Any clj form
(timbre/debugf "[ws/on-msg] Server will reply to message from %s: %s" lid* resp-clj)
;; true iff apparent success:
(interfaces/sch-send! server-ch websocket?
(pack packer resp-clj ?cb-uuid))))))))
on-close
(fn [server-ch websocket? _status]
;; - We rely on `on-close` to trigger for *every* sch.
;; - May be called *more* than once for a given sch.
;; - `status` type varies with underlying web server.
(let [conn-type (if websocket? :ws :ajax)
log-prefix (if websocket? "[ws/on-close]" "[ajax/on-close]")
active-conn-closed?
(swap-in! conns_ [conn-type uid client-id]
(fn [[?sch _udt conn-id*]]
(if (= conn-id conn-id*)
(swapped [nil (enc/now-udt) conn-id] true)
(swapped :swap/abort false))))]
;; Inactive => a connection closed that's not currently in conns_
(timbre/debugf "%s %s server sch closed for %s"
log-prefix (if active-conn-closed? "Active" "Inactive") lid*)
(when active-conn-closed?
;; Allow some time for possible reconnects (repoll,
;; sole window refresh, etc.) before regarding close
;; as non-transient "disconnect"
(go
(let [ms-timeout
(if websocket?
ms-allow-reconnect-before-close-ws
ms-allow-reconnect-before-close-ajax)]
(<! (async/timeout ms-timeout)))
(let [[active-conn-disconnected? ?conn-entry]
(swap-in! conns_ [conn-type uid client-id]
(fn [[_?sch _udt conn-id* :as ?conn-entry]]
(if (= conn-id conn-id*)
(swapped :swap/dissoc [true ?conn-entry])
(swapped :swap/abort [false ?conn-entry]))))]
(let [level (if active-conn-disconnected? :info (if websocket? :debug :trace))]
(timbre/logf level "%s Server sch on-close timeout for %s: %s"
log-prefix lid*
(if active-conn-disconnected?
{:disconnected? true}
{:disconnected? false, :?conn-entry ?conn-entry})))
(when active-conn-disconnected?
;; Potentially remove uid's entire entry
(swap-in! conns_ [conn-type uid]
(fn [m-clients]
(if (empty? m-clients)
:swap/dissoc
:swap/abort)))
(when (maybe-disconnect-uid!? uid)
(timbre/infof "%s uid port close for %s" log-prefix lid*)
(receive-event-msg! [:chsk/uidport-close uid]))))))))
on-open
(fn [server-ch websocket?]
(if websocket?
;; WebSocket handshake
(do
(timbre/infof "[ws/on-open] New server WebSocket sch for %s" lid*)
(when (send-handshake!? server-ch websocket?)
(let [[_ udt-open]
(swap-in! conns_ [:ws uid client-id]
(fn [_] [server-ch (enc/now-udt) conn-id]))]
;; Server-side loop to detect broken conns, Ref. #230
(when ws-kalive-ms
(go-loop [udt-t0 udt-open
ms-timeout ws-kalive-ms
expecting-pong? false]
(<! (async/timeout ms-timeout))
(let [?conn-entry (get-in @conns_ [:ws uid client-id])
[?sch udt-t1 conn-id*] ?conn-entry
{:keys [recur? udt ms-timeout expecting-pong? force-close?]}
(enc/cond
(nil? ?conn-entry) {:recur? false}
(not= conn-id conn-id*) {:recur? false}
(when-let [sch ?sch] (not (interfaces/sch-open? sch))) {:recur? false, :force-close? true}
(not= udt-t0 udt-t1) ; Activity in last kalive window
{:recur? true, :udt udt-t1, :ms-timeout ws-kalive-ms, :expecting-pong? false}
:do (timbre/debugf "[ws/on-open] kalive loop inactivity for %s" lid*)
expecting-pong?
(do
;; Was expecting pong (=> activity) in last kalive window
(interfaces/sch-close! server-ch)
{:recur? false})
:else
(if-let [;; If a conn has gone bad but is still marked as open,
;; attempting to send a ping will usually trigger the
;; conn's :on-close immediately, i.e. no need to wait
;; for a missed pong.
ping-apparently-sent?
(interfaces/sch-send! server-ch websocket?
(pack packer :chsk/ws-ping))]
(if ws-ping-timeout-ms
{:recur? true, :udt udt-t1, :ms-timeout ws-ping-timeout-ms, :expecting-pong? true}
{:recur? true, :udt udt-t1, :ms-timeout ws-kalive-ms, :expecting-pong? false})
{:recur? false, :force-close? true}))]
(if recur?
(recur udt ms-timeout expecting-pong?)
(do
(timbre/debugf "[ws/on-open] Ending kalive loop for %s" lid*)
(when force-close?
;; It's rare but possible for a conn's :on-close to fire
;; *before* a handshake, leaving a closed sch in conns_
(timbre/debugf "[ws/on-open] Force close connection for %s" lid*)
(on-close server-ch websocket? nil)))))))
(when (connect-uid!? :ws uid)
(timbre/infof "[ws/on-open] uid port open for %s" lid*)
(receive-event-msg! [:chsk/uidport-open uid])))))
;; Ajax handshake/poll
(let [send-handshake?
(or
(:handshake? params)
(nil? (get-in @conns_ [:ajax uid client-id])))]
(timbre/logf (if send-handshake? :info :trace)
"[ajax/on-open] New server Ajax sch (poll/handshake) for %s: %s"
lid* {:send-handshake? send-handshake?})
(if send-handshake?
(do
(swap-in! conns_ [:ajax uid client-id] (fn [_] [nil (enc/now-udt) conn-id]))
(send-handshake!? server-ch websocket?)
;; `server-ch` will close, and client will immediately repoll
)
(let [[_ udt-open]
(swap-in! conns_ [:ajax uid client-id]
(fn [_] [server-ch (enc/now-udt) conn-id]))]
(when-let [ms lp-timeout-ms]
(go
(<! (async/timeout ms))
(when-let [[_?sch _udt conn-id*] (get-in @conns_ [:ajax uid client-id])]
(when (= conn-id conn-id*)
(timbre/debugf "[ajax/on-open] Polling timeout for %s" lid*)
(interfaces/sch-send! server-ch websocket?
(pack packer :chsk/timeout))))))
(when (connect-uid!? :ajax uid)
(timbre/infof "[ajax/on-open] uid port open for %s" lid*)
(receive-event-msg! [:chsk/uidport-open uid])))))))]
(interfaces/ring-req->server-ch-resp web-server-ch-adapter ring-req
{:ring-async-resp-fn ?ring-async-resp-fn
:ring-async-raise-fn ?ring-async-raise-fn
:on-open on-open
:on-msg on-msg
:on-close on-close
:on-error on-error}))))))}))
(def ^:dynamic *simulated-bad-conn-rate*
"Debugging tool. Proportion ∈ℝ[0,1] of connection activities to sabotage."
nil)
(defn- simulated-bad-conn? []
(when-let [sbcr *simulated-bad-conn-rate*]
(enc/chance sbcr)))
(comment (binding [*simulated-bad-conn-rate* 0.5] (simulated-bad-conn?)))
(defn- send-buffered-server-evs>clients!
"Actually pushes buffered events (as packed-str) to all uid's conns.
Allows some time for possible reconnects."
[conn-type conns_ uid buffered-evs-pstr n-buffered-evs]