-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
repl.cljc
1534 lines (1352 loc) · 57.8 KB
/
repl.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 figwheel.repl
(:require
[clojure.string :as string]
#?@(:cljs [[goog.object :as gobj]
[goog.storage.mechanism.mechanismfactory :as storage-factory]
[goog.Uri :as guri]
[goog.string :as gstring]
[goog.net.jsloader :as loader]
[goog.net.XhrIo :as xhrio]
[goog.log :as glog]
[goog.array :as garray]
[goog.json :as gjson]
[goog.html.legacyconversions :as conv]
[goog.userAgent.product :as product]]
:clj [[clojure.data.json :as json]
[clojure.set :as set]
[clojure.edn :as edn]
[clojure.java.browse :as browse]
[cljs.repl]
[cljs.stacktrace]
[clojure.java.io :as io]
[clojure.string :as string]
[figwheel.server.ring]
[figwheel.server.jetty-websocket]]))
(:import
#?@(:cljs [goog.net.WebSocket
goog.debug.Console
[goog.Uri QueryData]
[goog Promise]
[goog.storage.mechanism HTML5SessionStorage]]
:clj [java.util.concurrent.ArrayBlockingQueue
java.net.URLDecoder
[java.lang ProcessBuilder Process]])))
(def default-port 9500)
#?(:cljs (do
;; TODO dev only
;; --------------------------------------------------
;; Logging
;; --------------------------------------------------
;;
;; Levels
;; goog.debug.Logger.Level.(SEVERE WARNING INFO CONFIG FINE FINER FINEST)
;;
;; set level (.setLevel logger goog.debug.Logger.Level.INFO)
;; disable (.setCapturing log-console false)
(defonce logger (glog/getLogger "Figwheel REPL"))
(defn ^:export console-logging []
(when-not (gobj/get goog.debug.Console "instance")
(let [c (goog.debug.Console.)]
;; don't display time
(doto (.getFormatter c)
(gobj/set "showAbsoluteTime" false)
(gobj/set "showRelativeTime" false))
(gobj/set goog.debug.Console "instance" c)
c))
(when-let [console-instance (gobj/get goog.debug.Console "instance")]
(.setCapturing console-instance true)
true))
(defonce log-console (console-logging))
(defn debug [msg]
(glog/log logger goog.debug.Logger.Level.FINEST msg))
;; TODO dev
#_(.setLevel logger goog.debug.Logger.Level.FINEST)
;; --------------------------------------------------------------
;; Bootstrap goog require reloading
;; --------------------------------------------------------------
(declare queued-file-reload)
(defn unprovide! [ns]
(if (some? goog/debugLoader_)
(let [path (.getPathFromDeps_ goog/debugLoader_ ns)]
(gobj/remove (.-written_ goog/debugLoader_) path)
(gobj/remove (.-written_ goog/debugLoader_) (str js/goog.basePath path)))
(let [path (gobj/get js/goog.dependencies_.nameToPath ns)]
(gobj/remove js/goog.dependencies_.visited path)
(gobj/remove js/goog.dependencies_.written path)
(gobj/remove js/goog.dependencies_.written (str js/goog.basePath path)))))
;; this will not work unless bootstrap has been called
(defn figwheel-require [src reload]
;; require is going to be called
(set! (.-require js/goog) figwheel-require)
(when (= reload "reload-all")
(set! (.-cljsReloadAll_ js/goog) true))
(when (or reload (.-cljsReloadAll_ js/goog))
(unprovide! src))
(let [res (.require_figwheel_backup_ js/goog src)]
(when (= reload "reload-all")
(set! (.-cljsReloadAll_ js/goog) false))
res))
(defn bootstrap-goog-base
"Reusable browser REPL bootstrapping. Patches the essential functions
in goog.base to support re-loading of namespaces after page load."
[]
;; The biggest problem here is that clojure.browser.repl might have
;; patched this or might patch this afterward
(when-not js/COMPILED
(when-not (.-require_figwheel_backup_ js/goog)
(set! (.-require_figwheel_backup_ js/goog) (or js/goog.require__ js/goog.require)))
(set! (.-isProvided_ js/goog) (fn [name] false))
(when-not (and (exists? js/cljs)
(exists? js/cljs.user))
(goog/constructNamespace_ "cljs.user"))
(set! (.-CLOSURE_IMPORT_SCRIPT goog/global) queued-file-reload)
(set! (.-require js/goog) figwheel-require)))
(defn patch-goog-base []
(defonce bootstrapped-cljs (do (bootstrap-goog-base) true)))
;; --------------------------------------------------------------
;; File reloading on different platforms
;; --------------------------------------------------------------
;; this assumes no query string on url
(defn add-cache-buster [url]
(.makeUnique (guri/parse url)))
(def gloader
(cond
(exists? loader/safeLoad)
#(loader/safeLoad (conv/trustedResourceUrlFromString (str %1)) %2)
(exists? loader/load) #(loader/load (str %1) %2)
:else (throw (ex-info "No remote script loading function found." {}))))
(defn reload-file-in-html-env
[request-url callback]
{:pre [(string? request-url) (not (nil? callback))]}
(doto (gloader (add-cache-buster request-url) #js {:cleanupWhenDone true})
(.addCallback #(apply callback [true]))
(.addErrback #(apply callback [false]))))
(def ^:export write-script-tag-import reload-file-in-html-env)
(defn ^:export worker-import-script [request-url callback]
{:pre [(string? request-url) (not (nil? callback))]}
(callback (try
(do (.importScripts js/self (add-cache-buster request-url))
true)
(catch js/Error e
(glog/error logger (str "Figwheel: Error loading file " request-url))
(glog/error logger e)
false))))
(defn ^:export create-node-script-import-fn []
(let [node-path-lib (js/require "path")
;; just finding a file that is in the cache so we can
;; figure out where we are
util-pattern (str (.-sep node-path-lib)
(.join node-path-lib "goog" "bootstrap" "nodejs.js"))
util-path (gobj/findKey js/require.cache (fn [v k o] (gstring/endsWith k util-pattern)))
parts (-> (string/split util-path #"[/\\]") pop pop)
root-path (string/join (.-sep node-path-lib) parts)]
(fn [request-url callback]
(assert (string? request-url) (not (nil? callback)))
(let [cache-path (.resolve node-path-lib root-path request-url)]
(gobj/remove (.-cache js/require) cache-path)
(callback (try
(js/require cache-path)
(catch js/Error e
(glog/error logger (str "Figwheel: Error loading file " cache-path))
(glog/error logger e)
false)))))))
(def host-env
(cond
(not (nil? goog/nodeGlobalRequire)) :node
(not (nil? goog/global.document)) :html
(and (exists? goog/global.navigator)
(= goog/global.navigator.product "ReactNative"))
:react-native
(and
(nil? goog/global.document)
(exists? js/self)
(exists? (.-importScripts js/self)))
:worker))
(def reload-file*
(condp = host-env
:node (create-node-script-import-fn)
:html write-script-tag-import
:worker worker-import-script
(fn [a b] (throw "Reload not defined for this platform"))))
;; TODO Should just leverage the import script here somehow
(defn reload-file [{:keys [request-url] :as file-msg} callback]
{:pre [(string? request-url) (not (nil? callback))]}
(glog/fine logger (str "Attempting to load " request-url))
((or (gobj/get goog.global "FIGWHEEL_IMPORT_SCRIPT") reload-file*)
request-url
(fn [success?]
(if success?
(do
(glog/fine logger (str "Successfully loaded " request-url))
(apply callback [(assoc file-msg :loaded-file true)]))
(do
(glog/error logger (str "Error loading file " request-url))
(apply callback [file-msg]))))))
;; for goog.require consumption
(defonce reload-promise-chain (atom (Promise. #(%1 true))))
(defn queued-file-reload
([url] (queued-file-reload url nil))
([url opt-source-text]
;; guard against reloading goog/base.js
;; as it will blow away import figwheel reloading hooks
(if (string/ends-with? url "goog/base.js")
true
(when-let [next-promise-fn
(cond opt-source-text
#(.then %
(fn [_]
(Promise.
(fn [r _]
(try (js/eval opt-source-text)
(catch js/Error e
(glog/error logger e)))
(r true)))))
url
#(.then %
(fn [_]
(Promise.
(fn [r _]
(reload-file {:request-url url}
(fn [file-msg]
(r true))))))))]
(swap! reload-promise-chain next-promise-fn)))))
(defn ^:export after-reloads [f]
(swap! reload-promise-chain #(.then % f)))
;; --------------------------------------------------------------
;; REPL print forwarding
;; --------------------------------------------------------------
(goog-define print-output "console,repl")
(defn print-receivers [outputs]
(->> (string/split outputs #",")
(map string/trim)
(filter (complement string/blank?))
(map keyword)
set))
(defmulti out-print (fn [k args] k))
(defmethod out-print :console [_ args]
(.apply (.-log js/console) js/console (garray/clone (to-array args))))
(defmulti err-print (fn [k args] k))
(defmethod err-print :console [_ args]
(.apply (.-error js/console) js/console (garray/clone (to-array args))))
(defn setup-printing! []
(let [printers (print-receivers print-output)]
(set-print-fn! (fn [& args] (doseq [p printers] (out-print p args))))
(set-print-err-fn! (fn [& args] (doseq [p printers] (err-print p args))))))
#_ (printing-receivers "console,repl")
;; --------------------------------------------------------------
;; Websocket REPL
;; --------------------------------------------------------------
(goog-define connect-url "ws://[[client-hostname]]:[[client-port]]/figwheel-connect")
(def state (atom {}))
;; returns nil if not available
(def storage (storage-factory/createHTML5SessionStorage "figwheel.repl"))
(defn set-state [k v]
(swap! state assoc k v)
(when storage (.set storage (str k) v)))
(defn get-state [k]
(if storage (.get storage (str k)) (get @state k)))
(defn ^:export session-name [] (get-state ::session-name))
(defn ^:export session-id [] (get-state ::session-id))
(defn response-for [{:keys [uuid]} response-body]
(cond->
{:session-id (session-id)
:session-name (session-name)
:response response-body}
uuid (assoc :uuid uuid)))
;; this is a fire and forget POST
(def http-post
(condp = host-env
:node
(let [http (js/require "http")]
(fn [url post-data]
(let [data (volatile! "")
uri (guri/parse (str url))]
(-> (.request http
#js {:host (.getDomain uri)
:port (.getPort uri)
:path (str (.getPath uri) (when-let [q (.getQuery uri)]
(str "?" q)))
:method "POST"
:headers #js {"Content-Length" (js/Buffer.byteLength post-data)}}
(fn [x]))
(.on "error" #(js/console.error %))
(doto
(.write post-data)
(.end))))))
(fn [url response]
(js/goog.net.Xhrio.send
url
(fn [e] (debug "Response Posted"))
"POST"
response))))
(defn respond-to [{:keys [websocket http-url] :as old-msg} response-body]
(let [response (response-for old-msg response-body)]
(cond
websocket
(.send websocket (pr-str response))
http-url
(http-post http-url (pr-str response)))))
(defn respond-to-connection [response-body]
(respond-to (:connection @state) response-body))
(defmulti message :op)
(defmethod message "naming" [msg]
(when-let [sn (:session-name msg)] (set-state ::session-name sn))
(when-let [sid (:session-id msg)] (set-state ::session-id sid))
(glog/info logger (str "Session ID: " (session-id)))
(glog/info logger (str "Session Name: " (session-name))))
(defmethod message "ping" [msg] (respond-to msg {:pong true}))
(defn get-ua-product []
(cond
(not (nil? goog/nodeGlobalRequire)) :chrome
product/SAFARI :safari
product/CHROME :chrome
product/FIREFOX :firefox
product/IE :ie))
(let [print-to-console? ((print-receivers print-output) :console)]
(defn eval-javascript** [code]
(let [ua-product (get-ua-product)]
(try
(let [sb (js/goog.string.StringBuffer.)]
;; TODO capture err as well?
(binding [cljs.core/*print-newline* true
cljs.core/*print-fn* (fn [x] (.append sb x))]
(let [result-value (js/eval code)
;; the result needs to be readable
result-value (if-not (string? result-value)
(try
(pr-str result-value)
(catch js/Error e
nil))
result-value)
output-str (str sb)]
(when (and print-to-console? (not (zero? (.getLength sb))))
(js/setTimeout #(out-print :console [output-str]) 0))
{:status :success
:out output-str
:ua-product ua-product
:value result-value})))
(catch js/Error e
;; logging errors to console helpful
(when (and (exists? js/console) (exists? js/console.error))
(js/console.error "REPL eval error" e))
{:status :exception
:value (pr-str e)
:ua-product ua-product
:stacktrace (.-stack e)})
(catch :default e
{:status :exception
:ua-product ua-product
:value (pr-str e)
:stacktrace "No stacktrace available."})))))
(defmethod message "eval" [{:keys [code] :as msg}]
(let [result (eval-javascript** code)]
(respond-to msg result)))
(defmethod message "messages" [{:keys [messages http-url]}]
(doseq [msg messages]
(message (cond-> (js->clj msg :keywordize-keys true)
http-url (assoc :http-url http-url)))))
(defn fill-url-template [connect-url']
(if (= host-env :html)
(-> connect-url'
(string/replace "[[client-hostname]]" js/location.hostname)
(string/replace "[[client-port]]" js/location.port))
connect-url'))
(defn make-url [connect-url']
(let [uri (guri/parse (fill-url-template (or connect-url' connect-url)))
domain (.getDomain uri)]
(when (string/ends-with? domain ":")
(.setDomain uri (subs domain 0 (dec (count domain)))))
(cond-> (.add (.getQueryData uri) "fwsid" (or (session-id) (random-uuid)))
(session-name) (.add "fwsname" (session-name)))
uri))
(defn exponential-backoff [attempt]
(* 1000 (min (js/Math.pow 2 attempt) 20)))
(defn hook-repl-printing-output! [respond-msg]
(defmethod out-print :repl [_ args]
(respond-to respond-msg
{:output true
:stream :out
:args (mapv #(if (string? %) % (gjson/serialize %)) args)}))
(defmethod err-print :repl [_ args]
(respond-to respond-msg
{:output true
:stream :err
:args (mapv #(if (string? %) % (gjson/serialize %)) args)}))
(setup-printing!))
(defn connection-established! [url]
(when (= host-env :html)
(let [target (.. goog.global -document -body)]
(.dispatchEvent
target
(doto (js/Event. "figwheel.repl.connected" target)
(gobj/add "data" {:url url}))))))
(defn connection-closed! [url]
(when (= host-env :html)
(let [target (.. goog.global -document -body)]
(.dispatchEvent
target
(doto (js/Event. "figwheel.repl.disconnected" target)
(gobj/add "data" {:url url}))))))
(defn get-websocket-class []
(or
(gobj/get goog.global "WebSocket")
(gobj/get goog.global "FIGWHEEL_WEBSOCKET_CLASS")
(and (= host-env :node)
(try (js/require "ws")
(catch js/Error e
nil)))
(and (= host-env :worker)
(gobj/get js/self "WebSocket"))))
(defn ensure-websocket [thunk]
(if (gobj/get goog.global "WebSocket")
(thunk)
(if-let [websocket-class (get-websocket-class)]
(do
(gobj/set goog.global "WebSocket" websocket-class)
(thunk)
(gobj/set goog.global "WebSocket" nil))
(do
(glog/error
logger
(if (= host-env :node)
"Can't connect!! Please make sure ws is installed\n do -> 'npm install ws'"
"Can't connect!! This client doesn't support WebSockets"))))))
(defn ws-connect [& [websocket-url']]
(ensure-websocket
#(let [websocket (goog.net.WebSocket.)
url (str (make-url websocket-url'))]
(try
(doto websocket
(.addEventListener goog.net.WebSocket.EventType.MESSAGE
(fn [e]
(when-let [msg (gobj/get e "message")]
(try
(debug msg)
(message (assoc
(js->clj (js/JSON.parse msg) :keywordize-keys true)
:websocket websocket))
(catch js/Error e
(glog/error logger e))))))
(.addEventListener goog.net.WebSocket.EventType.OPENED
(fn [e]
(connection-established! url)
(swap! state assoc :connection {:websocket websocket})
(hook-repl-printing-output! {:websocket websocket})))
(.addEventListener goog.net.WebSocket.EventType.CLOSED
(fn [e] (connection-closed! url)))
(.open url))))))
;; -----------------------------------------------------------
;; HTTP simple and long polling
;; -----------------------------------------------------------
(def http-get
(condp = host-env
:node
(let [http (js/require "http")]
(fn [url]
(Promise.
(fn [succ err]
(let [data (volatile! "")]
(-> (.get http (str url)
(fn [response]
(.on response "data"
(fn [chunk] (vswap! data str chunk)))
(.on response "end" #(succ
(try (js/JSON.parse @data)
(catch js/Error e
(js/console.error e)
(err e)))))))
(.on "error" err)))))))
(fn [url]
(Promise.
(fn [succ err]
(js/goog.net.Xhrio.send
url
(fn [e]
(let [xhr (gobj/get e "target")]
(if (.isSuccess xhr)
(succ (.getResponseJson xhr))
(err xhr))))))))))
(declare http-connect http-connect*)
(defn poll [msg-fn connect-url']
(.then (http-get (make-url connect-url'))
(fn [msg]
(msg-fn msg)
(js/setTimeout #(poll msg-fn connect-url') 500))
(fn [e] ;; lost connection
(connection-closed! connect-url')
(http-connect connect-url'))))
(defn long-poll [msg-fn connect-url']
(.then (http-get (make-url connect-url'))
(fn [msg]
(msg-fn msg)
(long-poll msg-fn connect-url'))
(fn [e] ;; lost connection
(connection-closed! connect-url')
(http-connect connect-url'))))
(defn http-connect* [attempt connect-url']
(let [url (make-url connect-url')
surl (str url)
msg-fn (fn [msg]
(try
(debug (pr-str msg))
(message (assoc (js->clj msg :keywordize-keys true)
:http-url surl))
(catch js/Error e
(glog/error logger e))))]
(doto (.getQueryData url)
(.add "fwinit" "true"))
(.then (http-get url)
(fn [msg]
(let [typ (gobj/get msg "connection-type")]
(glog/info logger (str "Connected: " typ))
(msg-fn msg)
(connection-established! url)
;; after connecting setup printing redirects
(swap! state assoc :connection {:http-url surl})
(hook-repl-printing-output! {:http-url surl})
(if (= typ "http-long-polling")
(long-poll msg-fn connect-url')
(poll msg-fn connect-url'))))
(fn [e];; didn't connect
(when (instance? js/Error e)
(glog/error logger e))
(when (and (instance? goog.net.XhrIo e) (.getResponseBody e))
(debug (.getResponseBody e)))
(let [wait-time (exponential-backoff attempt)]
(glog/info logger (str "HTTP Connection Error: next connection attempt in " (/ wait-time 1000) " seconds"))
(js/setTimeout #(http-connect* (inc attempt) connect-url')
wait-time))))))
(defn http-connect [& [connect-url']]
(http-connect* 0 connect-url'))
(defn switch-to-http? [url]
(if (or (gstring/startsWith url "http")
(get-websocket-class))
url
(do
(glog/warning
logger
(str
"No WebSocket implementation found! Falling back to http-long-polling"
(when (= host-env :node)
":\n For a more efficient connection ensure that \"ws\" is installed :: do -> 'npm install ws'")))
(-> (guri/parse url)
(.setScheme "http")
str))))
(goog-define client-log-level "info")
(def log-levels
(into {}
(map (juxt
string/lower-case
#(gobj/get goog.debug.Logger.Level %))
(map str '(SEVERE WARNING INFO CONFIG FINE FINER FINEST)))))
(defn set-log-level [logger' level]
(if-let [lvl (get log-levels level)]
(do
(.setLevel logger' lvl)
(debug (str "setting log level to " level)))
(glog/warning logger'
(str "Log level " (pr-str level) " doesn't exist must be one of "
(pr-str '("severe" "warning" "info" "config" "fine" "finer" "finest"))))))
(defn init-log-level! []
(doseq [logger' (cond-> [logger]
(exists? js/figwheel.core)
(conj js/figwheel.core.logger))]
(set-log-level logger' client-log-level)))
(defn connect* [connect-url']
(init-log-level!)
(patch-goog-base)
(let [url (switch-to-http? (string/trim (or connect-url' connect-url)))]
(cond
(gstring/startsWith url "ws") (ws-connect url)
(gstring/startsWith url "http") (http-connect url))))
(defn connect [& [connect-url']]
(defonce connected
(do (connect* connect-url') true))))
)
;; end :cljs
#?(:clj (do
(defonce ^:private listener-set (atom {}))
(defn add-listener
([f] (add-listener f f))
([k f] (swap! listener-set assoc k f) nil))
(defn remove-listener [k] (swap! listener-set dissoc k) nil)
(defn clear-listeners []
(reset! listener-set {}))
(declare name-list)
(defn log [& args]
(spit "server.log" (apply prn-str args) :append true))
(defonce scratch (atom {}))
(def ^:dynamic *server* nil)
(defn parse-query-string [qs]
(when (string? qs)
(into {} (for [[_ k v] (re-seq #"([^&=]+)=([^&]+)" qs)]
[(keyword k) (java.net.URLDecoder/decode v)]))))
;; ------------------------------------------------------------------
;; Connection management
;; ------------------------------------------------------------------
(defonce ^:dynamic *connections* (atom {}))
(defn taken-names [connections]
(set (mapv :session-name (vals connections))))
(defn available-names [connections]
(set/difference name-list (taken-names connections)))
(defn negotiate-id [ring-request connections]
(let [query (parse-query-string (:query-string ring-request))
sid (:fwsid query (str (java.util.UUID/randomUUID)))
sname (or (some-> connections (get sid) :session-name)
(when-let [chosen-name (:fwsname query)]
(when-not ((taken-names connections) chosen-name)
chosen-name))
(rand-nth (seq (available-names connections))))]
[sid sname]))
(defn create-connection! [ring-request options]
(let [[sess-id sess-name] (negotiate-id ring-request @*connections*)
conn (merge (select-keys ring-request [:server-port :scheme :uri :server-name :query-string :request-method])
(cond-> {:session-name sess-name
:session-id sess-id
::alive-at (System/currentTimeMillis)
:created-at (System/currentTimeMillis)}
(:query-string ring-request)
(assoc :query (parse-query-string (:query-string ring-request))))
options)]
(swap! *connections* assoc sess-id conn)
conn))
(defn remove-connection! [{:keys [session-id] :as conn}]
(swap! *connections* dissoc session-id))
(defn receive-message! [data]
(when-let [data
(try
(edn/read-string data)
(catch Throwable t
(binding [*out* *err*] (clojure.pprint/pprint (Throwable->map t)))))]
(doseq [[_ f] @listener-set]
(try (f data) (catch Throwable ex)))))
(defn naming-response [{:keys [session-name session-id type] :as conn}]
(json/write-str {:op :naming
:session-name session-name
:session-id session-id
:connection-type type}))
;; ------------------------------------------------------------------
;; Websocket behavior
;; ------------------------------------------------------------------
(defn abstract-websocket-connection [connections]
(let [conn (volatile! nil)]
{:on-connect (fn [{:keys [request send-fn close-fn is-open-fn]
:as connect-data}]
;; TODO remove dev only
(swap! scratch assoc :ring-request request)
(binding [*connections* connections]
(let [conn' (create-connection!
request
{:type :websocket
:is-open-fn is-open-fn
:close-fn close-fn
:send-fn (fn [_ data]
(send-fn data))})]
(vreset! conn conn')
(send-fn (naming-response conn')))))
:on-close (fn [status] (binding [*connections* connections]
(remove-connection! @conn)))
:on-receive (fn [data] (binding [*connections* connections]
(receive-message! data)))}))
;; ------------------------------------------------------------------
;; http polling
;; ------------------------------------------------------------------
(defn json-response [json-body]
{:status 200
:headers {"Content-Type" "application/json"}
:body json-body})
(defn http-polling-send [conn data]
(swap! (::comm-atom conn) update :messages (fnil conj []) data))
(defn http-polling-connect [ring-request]
(let [{:keys [fwsid fwinit]} (-> ring-request :query-string parse-query-string)]
;; new connection create the connection
(cond
(not (get @*connections* fwsid))
(let [conn (create-connection! ring-request
{:type :http-polling
::comm-atom (atom {})
:is-open-fn (fn [conn]
(< (- (System/currentTimeMillis)
(::alive-at conn))
3000))
:send-fn http-polling-send})]
(json-response (naming-response conn)))
fwinit
(let [conn (get @*connections* fwsid)]
(swap! *connections* assoc-in [fwsid :created-at] (System/currentTimeMillis))
(json-response (naming-response conn)))
:else
;; otherwise we are polling
(let [messages (volatile! [])
comm-atom (get-in @*connections* [fwsid ::comm-atom])]
(swap! *connections* assoc-in [fwsid ::alive-at] (System/currentTimeMillis))
(swap! comm-atom update :messages (fn [msgs] (vreset! messages (or msgs [])) []))
(json-response
(json/write-str {:op :messages
:messages (mapv json/read-json @messages)
:connection-type :http-polling}))))))
(defn http-polling-endpoint [ring-request]
(condp = (:request-method ring-request)
:get (http-polling-connect ring-request)
:post (do (receive-message! (slurp (:body ring-request)))
{:status 200
:headers {"Content-Type" "text/html"}
:body "Received"})))
;; simple http polling can be included in any ring middleware stack
(defn http-polling-middleware [handler path connections]
(fn [ring-request]
(if-not (.startsWith (:uri ring-request) path)
(handler ring-request)
(binding [*connections* connections]
(http-polling-endpoint ring-request)))))
;; ------------------------------------------------------------------
;; http async polling - long polling
;; ------------------------------------------------------------------
;; long polling is a bit complex - but this currently appears to work
;; as well as websockets in terms of connectivity, it is slower and heavier
;; overall and much harder to determine when it is closed
(declare send-for-response)
(defn ping [conn] (send-for-response [conn] {:op :ping}))
;; could make no-response behavior configurable
(defn ping-thread [connections fwsid {:keys [interval
ping-timeout]
:or {interval 15000
ping-timeout 2000}}]
(doto (Thread.
(fn []
(loop []
(Thread/sleep interval)
(when-let [conn (get @connections fwsid)]
(if-not (try
;; TODO consider re-trying a couple times on failure
(deref (ping conn) ping-timeout false)
(catch Throwable e
false))
(swap! connections dissoc fwsid)
(recur))))))
(.setDaemon true)
(.start)))
;; agents would be easier but heavier and agent clean up is harder
(defn long-poll-send [comm-atom msg]
(let [data (volatile! nil)
add-message #(if-not msg % (update % :messages (fnil conj []) msg))]
(swap! comm-atom
(fn [{:keys [respond messages] :as comm}]
(if (and respond (or (not-empty messages) msg))
(do (vreset! data (add-message comm)) {})
(add-message comm))))
(when-let [{:keys [respond messages]} @data]
;; when this fails?
(respond
(json-response
(json/write-str {:op :messages
:messages (mapv json/read-json messages)
:connection-type :http-long-polling}))))))
(defn long-poll-capture-respond [comm-atom respond]
(let [has-messages (volatile! false)]
(swap! comm-atom (fn [{:keys [messages] :as comm}]
(vreset! has-messages (not (empty? messages)))
(assoc comm :respond respond)))
(when @has-messages (long-poll-send comm-atom nil))))
;; may turn this into a multi method
(defn connection-send [{:keys [send-fn] :as conn} data]
(send-fn conn data))
(defn send-for-response* [prom conn msg]
(let [uuid (str (java.util.UUID/randomUUID))
listener (fn listen [msg]
(when (= uuid (:uuid msg))
(when-let [result (:response msg)]
(deliver prom
(if (instance? clojure.lang.IMeta result)
(vary-meta result assoc ::message msg)
result)))
(remove-listener listen)))]
(add-listener listener)
(try
(connection-send
conn
(json/write-str
(-> (select-keys conn [:session-id :session-name])
(merge msg)
(assoc :uuid uuid))))
(catch Throwable t
(remove-listener listener)
(throw t)))))
(def no-connection-result
(vary-meta
{:status :exception
:value "Expected REPL Connections Evaporated!"
:stacktrace "No stacktrace available."}
assoc ::no-connection-made true))
(defn broadcast-for-response [connections msg]
(let [prom (promise)
cnt (->> connections
(mapv #(try
(send-for-response* prom % msg)
true
(catch Throwable t
nil)))
(filter some?)
count)]
(when (zero? cnt)
(deliver prom no-connection-result))
prom))
(defn send-for-response [connections msg]
(let [prom (promise)
sent (loop [[conn & xc] connections]
(when conn
(if-not (try
(send-for-response* prom conn msg)
true
(catch Throwable t
false))
(recur xc)
true)))]
(when-not sent
(deliver prom no-connection-result))
prom))
(defn http-long-polling-connect [ring-request respond raise]
(let [{:keys [fwsid fwinit]} (-> ring-request :query-string parse-query-string)]
(if (not (get @*connections* fwsid))
(let [conn (create-connection!
ring-request
{:type :http-long-polling
::comm-atom (atom {:messages []})
:is-open-fn (fn [conn]
(not (> (- (System/currentTimeMillis)
(::alive-at conn))
20000)))
:send-fn (fn [conn msg]
(long-poll-send (::comm-atom conn) msg))})]
(respond (json-response (naming-response conn)))
;; keep alive with ping thread
;; This behavior is much more subtle that it appears, it is far better
;; than webserver triggered async timeout because it doesn't
;; leave behind an orphaned respond-fn
;; also it helps us remove lost connections, as I haven't found
;; a way to discover if an HTTPChannel is closed on the remote endpoint
;; TODO a short ping-timeout could be a problem if an
;; env has a long running eval
;; this could reuse the eval timeout
(ping-thread *connections* fwsid {:interval 15000 :ping-timeout 2000}))
(let [conn (get @*connections* fwsid)]
(if fwinit
(do
(respond (json-response (naming-response conn)))
(swap! *connections* assoc-in [fwsid :created-at] (System/currentTimeMillis)))
(do
(long-poll-capture-respond (::comm-atom conn) respond)
(swap! *connections* assoc-in [fwsid ::alive-at] (System/currentTimeMillis))))))))
(defn http-long-polling-endpoint [ring-request send raise]
(condp = (:request-method ring-request)
:get (http-long-polling-connect ring-request send raise)
:post (do (receive-message! (slurp (:body ring-request)))
(send {:status 200
:headers {"Content-Type" "text/html"}
:body "Received"}))))
(defn asyc-http-polling-middleware [handler path connections]
(fn [ring-request send raise]
(swap! scratch assoc :async-request ring-request)
(if-not (.startsWith (:uri ring-request) path)
(handler ring-request send raise)
(binding [*connections* connections]
(try
(http-long-polling-endpoint ring-request send raise)
(catch Throwable e
(raise e)))))))
;; ---------------------------------------------------
;; ReplEnv implmentation
;; ---------------------------------------------------
(defn open-connections []
(filter (fn [{:keys [is-open-fn] :as conn}]
(try (or (nil? is-open-fn) (is-open-fn conn))
(catch Throwable t
false)))
(vals @*connections*)))
(defn connections-available [repl-env]
(sort-by
:created-at >
(filter (or (some-> repl-env :connection-filter)
identity)
(open-connections))))
(defn wait-for-connection [repl-env]
(loop []
(when (empty? (connections-available repl-env))
(Thread/sleep 500)
(recur))))
(defn send-for-eval [{:keys [focus-session-name ;; just here for consideration
broadcast] :as repl-env} connections js]