Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

T3WebSocketModule.swift

188 lines7.3 KB

1import ExpoModulesCore
2import Foundation
3​
4private final class Connection {
5 let id: Int
6 var task: URLSessionWebSocketTask?
7 var finished = false
8 var requestedCloseCode: Int?
9 var failure: String?
10​
11 init(id: Int) {
12 self.id = id
13 }
15​
16/// A WebSocket client that offers permessage-deflate. React Native's SocketRocket never does,
17/// so a large snapshot reached an iPhone uncompressed. URLSession offers the extension on every
18/// handshake with no public switch, which is what we want here.
19public final class T3WebSocketModule: Module {
20 private var connections: [Int: Connection] = [:]
21 private var nextId = 1
22 private let lock = NSLock()
23 private var session: URLSession?
24 private let delegateQueue: OperationQueue = {
25 let queue = OperationQueue()
26 queue.maxConcurrentOperationCount = 1
27 return queue
28 }()
29​
30 public func definition() -> ModuleDefinition {
31 Name("T3WebSocket")
32 Events("open", "message", "close", "error")
33​
34 Function("connect") { (url: URL, protocols: [String]) -> Int in
35 let connection = self.withLock { () -> Connection in
36 let connection = Connection(id: self.nextId)
37 self.nextId += 1
38 self.connections[connection.id] = connection
39 return connection
40 }
41 let session = self.session ?? self.makeSession()
42 self.session = session
43 let task = protocols.isEmpty
44 ? session.webSocketTask(with: url)
45 : session.webSocketTask(with: url, protocols: protocols)
46 // The app splits frames at 48 KiB, but older servers and the outdated-host probe send whole
47 // messages, so stay well above URLSession's 1 MiB default.
48 task.maximumMessageSize = 128 * 1024 * 1024
49 self.withLock { connection.task = task }
50 task.resume()
51 self.receive(on: connection, task: task)
52 return connection.id
53 }
54​
55 Function("sendText") { (id: Int, text: String) in
56 guard let connection = self.connection(id), let task = connection.task else { return }
57 task.send(.string(text)) { [weak self] error in
58 if let error { self?.fail(connection, task: task, error: error) }
59 }
60 }
61​
62 Function("sendBinary") { (id: Int, bytes: Uint8Array) in
63 guard let connection = self.connection(id), let task = connection.task else { return }
64 let data = Data(bytes: bytes.rawPointer, count: bytes.byteLength)
65 task.send(.data(data)) { [weak self] error in
66 if let error { self?.fail(connection, task: task, error: error) }
67 }
68 }
69​
70 Function("close") { (id: Int, code: Int, reason: String) in
71 guard let connection = self.connection(id) else { return }
72 // URLSession can only send the codes it names; anything else goes out as a normal closure.
73 let closeCode = URLSessionWebSocketTask.CloseCode(rawValue: code).flatMap { $0 == .invalid ? nil : $0 } ?? .normalClosure
74 let task = self.withLock { () -> URLSessionWebSocketTask? in
75 connection.requestedCloseCode = closeCode.rawValue
76 return connection.task
77 }
78 task?.cancel(with: closeCode, reason: reason.isEmpty ? nil : reason.data(using: .utf8))
79 }
80​
81 OnDestroy {
82 self.session?.invalidateAndCancel()
83 }
84 }
85​
86 private func makeSession() -> URLSession {
87 let configuration = URLSessionConfiguration.default
88 // Dev clients register URLProtocol classes that intercept the upgrade and drop the socket.
89 configuration.protocolClasses = []
90 return URLSession(configuration: configuration, delegate: SessionDelegate(module: self), delegateQueue: delegateQueue)
91 }
92​
93 private func connection(_ id: Int) -> Connection? {
94 withLock { connections[id] }
95 }
96​
97 private func connection(for task: URLSessionTask) -> Connection? {
98 withLock { connections.values.first { $0.task === task } }
99 }
100​
101 private func withLock<T>(_ body: () -> T) -> T {
102 lock.lock()
103 defer { lock.unlock() }
104 return body()
105 }
106​
107 private func receive(on connection: Connection, task: URLSessionWebSocketTask) {
108 task.receive { [weak self] result in
109 guard let self else { return }
110 switch result {
111 case .success(.string(let text)):
112 self.sendEvent("message", ["id": connection.id, "text": text])
113 self.receive(on: connection, task: task)
114 case .success(.data(let data)):
115 self.sendEvent("message", ["id": connection.id, "data": data])
116 self.receive(on: connection, task: task)
117 case .success:
118 self.receive(on: connection, task: task)
119 case .failure(let error):
120 self.fail(connection, task: task, error: error)
121 }
122 }
123 }
124​
125 /// Every ending is reported once, from the delegate. A receive or send failure on a task that is
126 /// still running (an oversized message, for one) gets no delegate callback until it is cancelled.
127 private func fail(_ connection: Connection, task: URLSessionWebSocketTask, error: Error) {
128 let live = withLock { () -> Bool in
129 guard !connection.finished else { return false }
130 if connection.failure == nil { connection.failure = error.localizedDescription }
131 return true
132 }
133 guard live, task.state == .running else { return }
134 task.cancel()
135 }
136​
137 fileprivate func didOpen(task: URLSessionWebSocketTask) {
138 guard let connection = connection(for: task) else { return }
139 sendEvent("open", ["id": connection.id])
140 }
141​
142 fileprivate func didClose(task: URLSessionWebSocketTask, code: URLSessionWebSocketTask.CloseCode, reason: Data?) {
143 guard let connection = connection(for: task) else { return }
144 finish(connection, code: code.rawValue, reason: reason.flatMap { String(data: $0, encoding: .utf8) } ?? "", clean: true)
145 }
146​
147 fileprivate func didComplete(task: URLSessionTask, error: Error?) {
148 guard let connection = connection(for: task) else { return }
149 let (requested, failure) = withLock { (connection.requestedCloseCode, connection.failure) }
150 if requested == nil, let message = failure ?? error?.localizedDescription {
151 sendEvent("error", ["id": connection.id, "message": message])
152 }
153 // A task that ends without a close frame is an abnormal closure, as in browsers; one we
154 // cancelled ourselves reports the code we asked for.
155 finish(connection, code: requested ?? (error == nil && failure == nil ? 1005 : 1006), reason: "", clean: requested != nil)
156 }
157​
158 private func finish(_ connection: Connection, code: Int, reason: String, clean: Bool) {
159 let first = withLock { () -> Bool in
160 if connection.finished { return false }
161 connection.finished = true
162 connections.removeValue(forKey: connection.id)
163 return true
164 }
165 guard first else { return }
166 sendEvent("close", ["id": connection.id, "code": code, "reason": reason, "wasClean": clean])
167 }
169​
170private final class SessionDelegate: NSObject, URLSessionWebSocketDelegate {
171 weak var module: T3WebSocketModule?
172​
173 init(module: T3WebSocketModule) {
174 self.module = module
175 }
176​
177 func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) {
178 module?.didOpen(task: webSocketTask)
179 }
180​
181 func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
182 module?.didClose(task: webSocketTask, code: closeCode, reason: reason)
183 }
184​
185 func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
186 module?.didComplete(task: task, error: error)
187 }