-
Notifications
You must be signed in to change notification settings - Fork 38
/
core.clj
165 lines (145 loc) · 4.89 KB
/
core.clj
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
(ns gniazdo.core
(:import (java.net HttpCookie URI)
java.nio.ByteBuffer
java.util.List
(org.eclipse.jetty.websocket.client ClientUpgradeRequest
WebSocketClient)
(org.eclipse.jetty.util.ssl SslContextFactory)
(org.eclipse.jetty.websocket.api WebSocketListener
RemoteEndpoint
Session)))
(set! *warn-on-reflection* 1)
;; ## Messages
(defprotocol Sendable
(send-to-endpoint [this ^RemoteEndpoint e]
"Sends an entity to a given WebSocket endpoint."))
(extend-protocol Sendable
java.lang.String
(send-to-endpoint [msg ^RemoteEndpoint e]
@(.sendStringByFuture e msg))
java.nio.ByteBuffer
(send-to-endpoint [buf ^RemoteEndpoint e]
@(.sendBytesByFuture e buf)))
(extend-type (class (byte-array 0))
Sendable
(send-to-endpoint [data ^RemoteEndpoint e]
@(.sendBytesByFuture e (ByteBuffer/wrap data))))
;; ## Client
(defprotocol ^:private Client
(send-msg [this msg]
"Sends a message (implementing `gniazdo.core/Sendable`) to the given WebSocket.")
(close [this]
"Closes the WebSocket.")
(session [this]
"Returns the underlying websocket session"))
;; ## WebSocket Helpers
(defn- add-headers!
[^ClientUpgradeRequest request headers]
{:pre [(every? string? (keys headers))]}
(doseq [[header value] headers]
(let [header-values (if (sequential? value)
value
[value])]
(assert (every? string? header-values))
(.setHeader
request
^String header
^java.util.List header-values))))
(defn- add-subprotocols!
[^ClientUpgradeRequest request subprotocols]
{:pre [(or (nil? subprotocols) (sequential? subprotocols))
(every? string? subprotocols)]}
(when (seq subprotocols)
(.setSubProtocols request ^List (into () subprotocols))))
(defn- add-cookies!
[^ClientUpgradeRequest request cookies]
(when (seq cookies)
(.setCookies request
(map (fn [{:keys [name value]}]
(HttpCookie. name value))
cookies))))
(defn- upgrade-request
^ClientUpgradeRequest
[{:keys [cookies headers subprotocols]}]
(doto (ClientUpgradeRequest.)
(add-cookies! cookies)
(add-headers! headers)
(add-subprotocols! subprotocols)))
(defn- listener
^WebSocketListener
[{:keys [on-connect on-receive on-binary on-error on-close]
:or {on-connect (constantly nil)
on-receive (constantly nil)
on-binary (constantly nil)
on-error (constantly nil)
on-close (constantly nil)}}
result-promise]
(reify WebSocketListener
(onWebSocketText [_ msg]
(on-receive msg))
(onWebSocketBinary [_ data offset length]
(on-binary data offset length))
(onWebSocketError [_ throwable]
(if (realized? result-promise)
(on-error throwable)
(deliver result-promise throwable)))
(onWebSocketConnect [_ session]
(deliver result-promise session)
(on-connect session))
(onWebSocketClose [_ x y]
(on-close x y))))
(defn- deref-session
^Session
[result-promise]
(let [result @result-promise]
(if (instance? Throwable result)
(throw result)
result)))
;; ## WebSocket Client + Connection (API)
(defn client
"Create a new instance of `WebSocketClient`. If the optionally supplied URI
is representing a secure WebSocket endpoint (\"wss://...\") an SSL-capable
instance will be returned."
(^WebSocketClient
[] (WebSocketClient.))
(^WebSocketClient
[^URI uri]
(if (= "wss" (.getScheme uri))
(WebSocketClient. (SslContextFactory.))
(WebSocketClient.))))
(defn- connect-with-client
"Connect to a WebSocket using the supplied `WebSocketClient` instance."
[^WebSocketClient client ^URI uri opts]
(let [request (upgrade-request opts)
cleanup (::cleanup opts)
result-promise (promise)
listener (listener opts result-promise)]
(.connect client listener uri request)
(let [session (deref-session result-promise)]
(reify Client
(send-msg [_ msg]
(send-to-endpoint msg (.getRemote session)))
(session [_]
session)
(close [_]
(when cleanup
(cleanup))
(.close session))))))
(defn- connect-helper
[^URI uri opts]
(let [client (client uri)]
(try
(.start client)
(->> (assoc opts ::cleanup #(.stop client))
(connect-with-client client uri))
(catch Throwable ex
(.stop client)
(throw ex)))))
(defn connect
"Connects to a WebSocket at a given URI (e.g. ws://example.org:1234/socket)."
[uri & {:keys [on-connect on-receive on-binary on-error on-close headers client subprotocols]
:as opts}]
(let [uri' (URI. uri)]
(if client
(connect-with-client client uri' opts)
(connect-helper uri' opts))))