-
-
Notifications
You must be signed in to change notification settings - Fork 203
Expand file tree
/
Copy pathWeb3WebSocketProvider.swift
More file actions
346 lines (280 loc) · 12.1 KB
/
Web3WebSocketProvider.swift
File metadata and controls
346 lines (280 loc) · 12.1 KB
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
import Foundation
import Dispatch
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
import WebSocketKit
import NIOPosix
public class Web3WebSocketProvider: Web3Provider, Web3BidirectionalProvider {
// MARK: - Properties
let encoder = JSONEncoder()
let decoder = JSONDecoder()
private let receiveQueue: DispatchQueue
private let reconnectQueue: DispatchQueue
public private(set) var closed: Bool = false
public let wsUrl: URL
public let timeoutNanoSeconds: UInt64
private let wsEventLoopGroup: EventLoopGroup
public private(set) var webSocket: WebSocket!
// Stores ids and notification groups
private let pendingRequests: SynchronizedDictionary<Int, (timeoutItem: DispatchWorkItem, responseCompletion: (_ response: String?) -> Void)> = [:]
// Stores subscription ids and semaphores
private let currentSubscriptions: SynchronizedDictionary<String, (onCancel: () -> Void, onNotification: (_ notification: String) -> Void)> = [:]
// Maintain sync current id
private let nextIdQueue = DispatchQueue(label: "Web3WebSocketProvider_nextIdQueue", attributes: .concurrent)
private var currentId = 1
private var nextId: Int {
get {
var retId: Int!
nextIdQueue.sync(flags: .barrier) {
retId = currentId
if currentId < UInt16.max {
currentId += 1
} else {
currentId = 1
}
}
return retId
}
}
public enum Error: Swift.Error {
case invalidUrl
case timeoutError
case unexpectedResponse
case webSocketClosedRetry
case subscriptionCancelled
}
// MARK: - Initialization
public init(wsUrl: String, timeout: DispatchTimeInterval = .seconds(120)) throws {
// Concurrent queue for faster concurrent requests
self.receiveQueue = DispatchQueue(label: "Web3WebSocketProvider_Receive", attributes: .concurrent)
self.reconnectQueue = DispatchQueue(label: "Web3WebSocketProvider_Reconnect", attributes: .concurrent)
guard let url = URL(string: wsUrl) else {
throw Error.invalidUrl
}
self.wsUrl = url
// Timeout in ns
switch timeout {
case .seconds(let int):
self.timeoutNanoSeconds = UInt64(int * 1_000_000_000)
case .milliseconds(let int):
self.timeoutNanoSeconds = UInt64(int * 1_000_000)
case .microseconds(let int):
self.timeoutNanoSeconds = UInt64(int * 1_000)
case .nanoseconds(let int):
self.timeoutNanoSeconds = UInt64(int)
default:
self.timeoutNanoSeconds = UInt64(120 * 1_000_000_000)
}
self.wsEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 4)
// Initial connect
try reconnect()
}
deinit {
closed = true
// Close connection if already initialized
if let webSocket {
_ = webSocket.close(code: .goingAway)
}
// As described in https://github.com/apple/swift-nio/issues/2371
try? wsEventLoopGroup.syncShutdownGracefully()
}
// MARK: - Web3Provider
public func send<Params, Result>(request: RPCRequest<Params>, response: @escaping Web3ResponseCompletion<Result>) {
let replacedIdRequest = RPCRequest(id: self.nextId, jsonrpc: request.jsonrpc, method: request.method, params: request.params)
let body: Data
do {
body = try self.encoder.encode(replacedIdRequest)
} catch {
let err = Web3Response<Result>(error: .requestFailed(error))
response(err)
return
}
// Generic failure sender
let failure: (_ error: Error) -> () = { error in
let err = Web3Response<Result>(error: .serverError(error))
response(err)
return
}
// The timeout
let timeoutItem = DispatchWorkItem {
self.pendingRequests[replacedIdRequest.id] = nil
// Respond to user
failure(Error.timeoutError)
}
self.receiveQueue.asyncAfter(deadline: DispatchTime(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + self.timeoutNanoSeconds), execute: timeoutItem)
// The response
let responseCompletion: (_ response: String?) -> Void = { responseString in
defer {
// Remove from pending requests
self.pendingRequests[replacedIdRequest.id] = nil
}
timeoutItem.cancel()
self.pendingRequests.getValueAsync(key: replacedIdRequest.id) { value in
guard value != nil else {
// Timeout happened already. Rare. Timeout sent the timeout error. Do nothing.
return
}
self.receiveQueue.async {
guard let responseString = responseString else {
failure(Error.webSocketClosedRetry)
return
}
// Parse response
guard let responseData = responseString.data(using: .utf8), let decoded = try? self.decoder.decode(RPCResponse<Result>.self, from: responseData) else {
failure(Error.unexpectedResponse)
return
}
// Put back original request id
let idReplacedDecoded = RPCResponse<Result>(id: request.id, jsonrpc: decoded.jsonrpc, result: decoded.result, error: decoded.error)
// Return result
let res = Web3Response(rpcResponse: idReplacedDecoded)
response(res)
}
}
}
// Set the pending request
self.pendingRequests[replacedIdRequest.id] = (timeoutItem: timeoutItem, responseCompletion: responseCompletion)
// Response result for sending the message over the WebSocket
let promise = self.wsEventLoopGroup.next().makePromise(of: Void.self)
promise.futureResult.whenComplete { result in
switch result {
case .success(_):
break
case .failure(let error):
let err = Web3Response<Result>(error: .requestFailed(error))
response(err)
return
}
}
// Send Request through WebSocket once the Promise was set
self.webSocket.send(String(data: body, encoding: .utf8) ?? "", promise: promise)
}
// MARK: - Web3BidirectionalProvider
public func subscribe<Params, Result>(request: RPCRequest<Params>, response: @escaping Web3ResponseCompletion<String>, onEvent: @escaping Web3ResponseCompletion<Result>) {
self.send(request: request) { (_ resp: Web3Response<String>) -> Void in
guard let subscriptionId = resp.result else {
let err = Web3Response<String>(error: .serverError(resp.error))
response(err)
return
}
// Return subscription id
let res = Web3Response(status: .success(subscriptionId))
response(res)
let queue = self.receiveQueue
// Subscription cancelled by us or the server, not the User.
let onCancel: () -> Void = {
queue.async {
// We are done, the subscription was cancelled. We don't care why
self.currentSubscriptions[subscriptionId] = nil
// Notify client
let err = Web3Response<Result>(error: .subscriptionCancelled(Error.subscriptionCancelled))
onEvent(err)
}
}
let notificationReceived: (_ notification: String) -> Void = { notification in
queue.async {
// Generic failure sender
let failure: (_ error: Error) -> () = { error in
let err = Web3Response<Result>(error: .serverError(error))
onEvent(err)
return
}
// Parse notification
guard let notificationData = notification.data(using: .utf8), let decoded = try? self.decoder.decode(RPCEventResponse<Result>.self, from: notificationData) else {
failure(Error.unexpectedResponse)
return
}
// Return result
let res = Web3Response(rpcEventResponse: decoded)
onEvent(res)
}
}
// Now we need to register the subscription id to our internal subscription id register
self.currentSubscriptions[subscriptionId] = (onCancel: onCancel, onNotification: notificationReceived)
}
}
public func unsubscribe(subscriptionId: String, completion: @escaping (_ success: Bool) -> Void) {
let unsubscribe = BasicRPCRequest(id: 1, jsonrpc: Web3.jsonrpc, method: "eth_unsubscribe", params: [subscriptionId])
self.send(request: unsubscribe) { (_ resp: Web3Response<Bool>) -> Void in
let success = resp.result ?? false
if success {
self.currentSubscriptions.getValueAsync(key: subscriptionId) { value in
self.receiveQueue.async {
value?.onCancel()
}
}
}
completion(success)
}
}
// MARK: - Helpers
private struct WebSocketOnTextTmpCodable: Codable {
let id: Int?
let params: Params?
fileprivate struct Params: Codable {
let subscription: String
}
}
private func registerWebSocketListeners() {
// Receive response
webSocket.onText { [weak self] ws, string in
guard let self else {
return
}
self.receiveQueue.async {
guard let data = string.data(using: .utf8) else {
return
}
if let tmpCodable = try? self.decoder.decode(WebSocketOnTextTmpCodable.self, from: data) {
if let id = tmpCodable.id {
self.pendingRequests.getValueAsync(key: id) { value in
self.receiveQueue.async {
value?.responseCompletion(string)
}
}
} else if let params = tmpCodable.params {
self.currentSubscriptions.getValueAsync(key: params.subscription) { value in
self.receiveQueue.async {
value?.onNotification(string)
}
}
}
}
}
}
// Handle close
webSocket.onClose.whenComplete { [weak self] result in
guard let self else {
return
}
if !self.closed && self.webSocket.isClosed {
self.reconnectQueue.asyncAfter(deadline: DispatchTime(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + 100_000_000)) {
try? self.reconnect()
}
}
}
}
private func reconnect() throws {
// Delete all subscriptions
for key in currentSubscriptions.dictionary.keys {
currentSubscriptions.getValueAsync(key: key) { value in
self.receiveQueue.async {
value?.onCancel()
}
}
}
for key in pendingRequests.dictionary.keys {
pendingRequests.getValueAsync(key: key) { value in
self.receiveQueue.async {
value?.responseCompletion(nil)
}
}
}
// Reconnect
try WebSocket.connect(to: wsUrl, configuration: .init(maxFrameSize: Int(min(Int64(UInt32.max), Int64(Int.max)))), on: wsEventLoopGroup) { ws in
self.webSocket = ws
self.registerWebSocketListeners()
}.wait()
}
}