WebSocketRequest.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. //
  2. // WebSocketRequest.swift
  3. //
  4. // Copyright (c) 2014-2024 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. #if canImport(Darwin) && !canImport(FoundationNetworking) // Only Apple platforms support URLSessionWebSocketTask.
  25. import Foundation
  26. /// `Request` subclass which manages a WebSocket connection using `URLSessionWebSocketTask`.
  27. ///
  28. /// - Note: This type is currently experimental. There will be breaking changes before the final public release,
  29. /// especially around adoption of the typed throws feature in Swift 6. Please report any missing features or
  30. /// bugs to https://github.com/Alamofire/Alamofire/issues.
  31. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  32. @_spi(WebSocket) public final class WebSocketRequest: Request, @unchecked Sendable {
  33. enum IncomingEvent {
  34. case connected(protocol: String?)
  35. case receivedMessage(URLSessionWebSocketTask.Message)
  36. case disconnected(closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?)
  37. case completed(Completion)
  38. }
  39. public struct Event<Success: Sendable, Failure: Error>: Sendable {
  40. public enum Kind: Sendable {
  41. case connected(protocol: String?)
  42. case receivedMessage(Success)
  43. case serializerFailed(Failure)
  44. // Only received if the server disconnects or we cancel with code, not if we do a simple cancel or error.
  45. case disconnected(closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?)
  46. case completed(Completion)
  47. }
  48. weak var socket: WebSocketRequest?
  49. public let kind: Kind
  50. public var message: Success? {
  51. guard case let .receivedMessage(message) = kind else { return nil }
  52. return message
  53. }
  54. init(socket: WebSocketRequest, kind: Kind) {
  55. self.socket = socket
  56. self.kind = kind
  57. }
  58. public func close(sending closeCode: URLSessionWebSocketTask.CloseCode, reason: Data? = nil) {
  59. socket?.close(sending: closeCode, reason: reason)
  60. }
  61. public func cancel() {
  62. socket?.cancel()
  63. }
  64. public func sendPing(respondingOn queue: DispatchQueue = .main, onResponse: @escaping @Sendable (PingResponse) -> Void) {
  65. socket?.sendPing(respondingOn: queue, onResponse: onResponse)
  66. }
  67. }
  68. public struct Completion: Sendable {
  69. /// Last `URLRequest` issued by the instance.
  70. public let request: URLRequest?
  71. /// Last `HTTPURLResponse` received by the instance.
  72. public let response: HTTPURLResponse?
  73. /// Last `URLSessionTaskMetrics` produced for the instance.
  74. public let metrics: URLSessionTaskMetrics?
  75. /// `AFError` produced for the instance, if any.
  76. public let error: AFError?
  77. }
  78. public struct Configuration {
  79. public static var `default`: Self { Self() }
  80. public static func `protocol`(_ protocol: String) -> Self {
  81. Self(protocol: `protocol`)
  82. }
  83. public static func maximumMessageSize(_ maximumMessageSize: Int) -> Self {
  84. Self(maximumMessageSize: maximumMessageSize)
  85. }
  86. public static func pingInterval(_ pingInterval: TimeInterval) -> Self {
  87. Self(pingInterval: pingInterval)
  88. }
  89. public let `protocol`: String?
  90. public let maximumMessageSize: Int
  91. public let pingInterval: TimeInterval?
  92. init(protocol: String? = nil, maximumMessageSize: Int = 1_048_576, pingInterval: TimeInterval? = nil) {
  93. self.protocol = `protocol`
  94. self.maximumMessageSize = maximumMessageSize
  95. self.pingInterval = pingInterval
  96. }
  97. }
  98. /// Response to a sent ping.
  99. public enum PingResponse: Sendable {
  100. public struct Pong: Sendable {
  101. let start: Date
  102. let end: Date
  103. let latency: TimeInterval
  104. }
  105. /// Received a pong with the associated state.
  106. case pong(Pong)
  107. /// Received an error.
  108. case error(any Error)
  109. /// Did not send the ping, the request is cancelled or suspended.
  110. case unsent
  111. }
  112. struct SocketMutableState {
  113. var enqueuedSends: [(message: URLSessionWebSocketTask.Message,
  114. queue: DispatchQueue,
  115. completionHandler: @Sendable (Result<Void, any Error>) -> Void)] = []
  116. var handlers: [(queue: DispatchQueue, handler: (_ event: IncomingEvent) -> Void)] = []
  117. var pingTimerItem: DispatchWorkItem?
  118. }
  119. let socketMutableState = Protected(SocketMutableState())
  120. var socket: URLSessionWebSocketTask? {
  121. task as? URLSessionWebSocketTask
  122. }
  123. public let convertible: any URLRequestConvertible
  124. public let configuration: Configuration
  125. init(id: UUID = UUID(),
  126. convertible: any URLRequestConvertible,
  127. configuration: Configuration,
  128. underlyingQueue: DispatchQueue,
  129. serializationQueue: DispatchQueue,
  130. eventMonitor: (any EventMonitor)?,
  131. interceptor: (any RequestInterceptor)?,
  132. delegate: any RequestDelegate) {
  133. self.convertible = convertible
  134. self.configuration = configuration
  135. super.init(id: id,
  136. underlyingQueue: underlyingQueue,
  137. serializationQueue: serializationQueue,
  138. eventMonitor: eventMonitor,
  139. interceptor: interceptor,
  140. delegate: delegate)
  141. }
  142. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  143. var copiedRequest = request
  144. let task: URLSessionWebSocketTask
  145. if let `protocol` = configuration.protocol {
  146. copiedRequest.headers.update(.websocketProtocol(`protocol`))
  147. task = session.webSocketTask(with: copiedRequest)
  148. } else {
  149. task = session.webSocketTask(with: copiedRequest)
  150. }
  151. task.maximumMessageSize = configuration.maximumMessageSize
  152. return task
  153. }
  154. override func didCreateTask(_ task: URLSessionTask) {
  155. super.didCreateTask(task)
  156. guard let webSocketTask = task as? URLSessionWebSocketTask else {
  157. fatalError("Invalid task of type \(task.self) created for WebSocketRequest.")
  158. }
  159. // TODO: What about the any old tasks? Reset their receive?
  160. listen(to: webSocketTask)
  161. // Empty pending messages.
  162. socketMutableState.write { state in
  163. guard !state.enqueuedSends.isEmpty else { return }
  164. let sends = state.enqueuedSends
  165. self.underlyingQueue.async {
  166. for send in sends {
  167. webSocketTask.send(send.message) { error in
  168. send.queue.async {
  169. send.completionHandler(Result(value: (), error: error))
  170. }
  171. }
  172. }
  173. }
  174. state.enqueuedSends = []
  175. }
  176. }
  177. func didClose() {
  178. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  179. mutableState.write { mutableState in
  180. // Check whether error is cancellation or other websocket closing error.
  181. // If so, remove it.
  182. // Otherwise keep it.
  183. if case let .sessionTaskFailed(error) = mutableState.error, (error as? URLError)?.code == .cancelled {
  184. mutableState.error = nil
  185. }
  186. }
  187. // TODO: Still issue this event?
  188. eventMonitor?.requestDidCancel(self)
  189. }
  190. @discardableResult
  191. public func close(sending closeCode: URLSessionWebSocketTask.CloseCode, reason: Data? = nil) -> Self {
  192. cancelAutomaticPing()
  193. mutableState.write { mutableState in
  194. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  195. mutableState.state = .cancelled
  196. underlyingQueue.async { self.didClose() }
  197. guard let task = mutableState.tasks.last, task.state != .completed else {
  198. underlyingQueue.async { self.finish() }
  199. return
  200. }
  201. // Resume to ensure metrics are gathered.
  202. task.resume()
  203. // Cast from state directly, not the property, otherwise the lock is recursive.
  204. (mutableState.tasks.last as? URLSessionWebSocketTask)?.cancel(with: closeCode, reason: reason)
  205. underlyingQueue.async { self.didCancelTask(task) }
  206. }
  207. return self
  208. }
  209. @discardableResult
  210. override public func cancel() -> Self {
  211. cancelAutomaticPing()
  212. return super.cancel()
  213. }
  214. func didConnect(protocol: String?) {
  215. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  216. socketMutableState.read { state in
  217. // TODO: Capture HTTPURLResponse here too?
  218. for handler in state.handlers {
  219. // Saved handler calls out to serializationQueue immediately, then to handler's queue.
  220. handler.handler(.connected(protocol: `protocol`))
  221. }
  222. }
  223. if let pingInterval = configuration.pingInterval {
  224. startAutomaticPing(every: pingInterval)
  225. }
  226. }
  227. @preconcurrency
  228. public func sendPing(respondingOn queue: DispatchQueue = .main, onResponse: @escaping @Sendable (PingResponse) -> Void) {
  229. guard isResumed else {
  230. queue.async { onResponse(.unsent) }
  231. return
  232. }
  233. let start = Date()
  234. let startTimestamp = ProcessInfo.processInfo.systemUptime
  235. socket?.sendPing { error in
  236. // Calls back on delegate queue / rootQueue / underlyingQueue
  237. if let error {
  238. queue.async {
  239. onResponse(.error(error))
  240. }
  241. // TODO: What to do with failed ping? Configure for failure, auto retry, or stop pinging?
  242. } else {
  243. let end = Date()
  244. let endTimestamp = ProcessInfo.processInfo.systemUptime
  245. let pong = PingResponse.Pong(start: start, end: end, latency: endTimestamp - startTimestamp)
  246. queue.async {
  247. onResponse(.pong(pong))
  248. }
  249. }
  250. }
  251. }
  252. func startAutomaticPing(every pingInterval: TimeInterval) {
  253. socketMutableState.write { mutableState in
  254. guard isResumed else {
  255. // Defer out of lock.
  256. defer { cancelAutomaticPing() }
  257. return
  258. }
  259. let item = DispatchWorkItem { [weak self] in
  260. guard let self, isResumed else { return }
  261. sendPing(respondingOn: underlyingQueue) { response in
  262. guard case .pong = response else { return }
  263. self.startAutomaticPing(every: pingInterval)
  264. }
  265. }
  266. mutableState.pingTimerItem = item
  267. underlyingQueue.asyncAfter(deadline: .now() + pingInterval, execute: item)
  268. }
  269. }
  270. @available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
  271. func startAutomaticPing(every duration: Duration) {
  272. let interval = TimeInterval(duration.components.seconds) + (Double(duration.components.attoseconds) / 1e18)
  273. startAutomaticPing(every: interval)
  274. }
  275. func cancelAutomaticPing() {
  276. socketMutableState.write { mutableState in
  277. mutableState.pingTimerItem?.cancel()
  278. mutableState.pingTimerItem = nil
  279. }
  280. }
  281. func didDisconnect(closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
  282. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  283. cancelAutomaticPing()
  284. socketMutableState.read { state in
  285. for handler in state.handlers {
  286. // Saved handler calls out to serializationQueue immediately, then to handler's queue.
  287. handler.handler(.disconnected(closeCode: closeCode, reason: reason))
  288. }
  289. }
  290. }
  291. private func listen(to task: URLSessionWebSocketTask) {
  292. // TODO: Do we care about the cycle while receiving?
  293. task.receive { result in
  294. switch result {
  295. case let .success(message):
  296. self.socketMutableState.read { state in
  297. for handler in state.handlers {
  298. // Saved handler calls out to serializationQueue immediately, then to handler's queue.
  299. handler.handler(.receivedMessage(message))
  300. }
  301. }
  302. self.listen(to: task)
  303. case .failure:
  304. // It doesn't seem like any relevant errors are received here, just incorrect garbage, like errors when
  305. // the socket disconnects.
  306. break
  307. }
  308. }
  309. }
  310. @preconcurrency
  311. @discardableResult
  312. public func streamSerializer<Serializer>(
  313. _ serializer: Serializer,
  314. on queue: DispatchQueue = .main,
  315. handler: @escaping @Sendable (_ event: Event<Serializer.Output, Serializer.Failure>) -> Void
  316. ) -> Self where Serializer: WebSocketMessageSerializer, Serializer.Failure == any Error {
  317. forIncomingEvent(on: queue) { incomingEvent in
  318. let event: Event<Serializer.Output, Serializer.Failure>
  319. switch incomingEvent {
  320. case let .connected(`protocol`):
  321. event = .init(socket: self, kind: .connected(protocol: `protocol`))
  322. case let .receivedMessage(message):
  323. do {
  324. let serializedMessage = try serializer.decode(message)
  325. event = .init(socket: self, kind: .receivedMessage(serializedMessage))
  326. } catch {
  327. event = .init(socket: self, kind: .serializerFailed(error))
  328. }
  329. case let .disconnected(closeCode, reason):
  330. event = .init(socket: self, kind: .disconnected(closeCode: closeCode, reason: reason))
  331. case let .completed(completion):
  332. event = .init(socket: self, kind: .completed(completion))
  333. }
  334. queue.async { handler(event) }
  335. }
  336. }
  337. @preconcurrency
  338. @discardableResult
  339. public func streamDecodableEvents<Value>(
  340. _ type: Value.Type = Value.self,
  341. on queue: DispatchQueue = .main,
  342. using decoder: any DataDecoder = JSONDecoder(),
  343. handler: @escaping @Sendable (_ event: Event<Value, any Error>) -> Void
  344. ) -> Self where Value: Decodable {
  345. streamSerializer(DecodableWebSocketMessageDecoder<Value>(decoder: decoder), on: queue, handler: handler)
  346. }
  347. @preconcurrency
  348. @discardableResult
  349. public func streamDecodable<Value>(
  350. _ type: Value.Type = Value.self,
  351. on queue: DispatchQueue = .main,
  352. using decoder: any DataDecoder = JSONDecoder(),
  353. handler: @escaping @Sendable (_ value: Value) -> Void
  354. ) -> Self where Value: Decodable & Sendable {
  355. streamDecodableEvents(Value.self, on: queue) { event in
  356. event.message.map(handler)
  357. }
  358. }
  359. @preconcurrency
  360. @discardableResult
  361. public func streamMessageEvents(
  362. on queue: DispatchQueue = .main,
  363. handler: @escaping @Sendable (_ event: Event<URLSessionWebSocketTask.Message, Never>) -> Void
  364. ) -> Self {
  365. forIncomingEvent(on: queue) { incomingEvent in
  366. let event: Event<URLSessionWebSocketTask.Message, Never> = switch incomingEvent {
  367. case let .connected(`protocol`):
  368. .init(socket: self, kind: .connected(protocol: `protocol`))
  369. case let .receivedMessage(message):
  370. .init(socket: self, kind: .receivedMessage(message))
  371. case let .disconnected(closeCode, reason):
  372. .init(socket: self, kind: .disconnected(closeCode: closeCode, reason: reason))
  373. case let .completed(completion):
  374. .init(socket: self, kind: .completed(completion))
  375. }
  376. queue.async { handler(event) }
  377. }
  378. }
  379. @preconcurrency
  380. @discardableResult
  381. public func streamMessages(
  382. on queue: DispatchQueue = .main,
  383. handler: @escaping @Sendable (_ message: URLSessionWebSocketTask.Message) -> Void
  384. ) -> Self {
  385. streamMessageEvents(on: queue) { event in
  386. event.message.map(handler)
  387. }
  388. }
  389. func forIncomingEvent(on queue: DispatchQueue, handler: @escaping @Sendable (IncomingEvent) -> Void) -> Self {
  390. socketMutableState.write { state in
  391. state.handlers.append((queue: queue, handler: { incomingEvent in
  392. self.serializationQueue.async {
  393. handler(incomingEvent)
  394. }
  395. }))
  396. }
  397. appendResponseSerializer {
  398. self.responseSerializerDidComplete {
  399. self.serializationQueue.async {
  400. handler(.completed(.init(request: self.request,
  401. response: self.response,
  402. metrics: self.metrics,
  403. error: self.error)))
  404. }
  405. }
  406. }
  407. return self
  408. }
  409. @preconcurrency
  410. public func send(_ message: URLSessionWebSocketTask.Message,
  411. queue: DispatchQueue = .main,
  412. completionHandler: @escaping @Sendable (Result<Void, any Error>) -> Void) {
  413. guard !(isCancelled || isFinished) else { return }
  414. guard let socket else {
  415. // URLSessionWebSocketTask not created yet, enqueue the send.
  416. socketMutableState.write { mutableState in
  417. mutableState.enqueuedSends.append((message, queue, completionHandler))
  418. }
  419. return
  420. }
  421. socket.send(message) { error in
  422. queue.async {
  423. completionHandler(Result(value: (), error: error))
  424. }
  425. }
  426. }
  427. }
  428. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  429. public protocol WebSocketMessageSerializer<Output, Failure>: Sendable {
  430. associatedtype Output: Sendable
  431. associatedtype Failure: Error = any Error
  432. func decode(_ message: URLSessionWebSocketTask.Message) throws -> Output
  433. }
  434. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  435. extension WebSocketMessageSerializer {
  436. public static func json<Value>(
  437. decoding _: Value.Type = Value.self,
  438. using decoder: JSONDecoder = JSONDecoder()
  439. ) -> DecodableWebSocketMessageDecoder<Value> where Self == DecodableWebSocketMessageDecoder<Value> {
  440. Self(decoder: decoder)
  441. }
  442. static var passthrough: PassthroughWebSocketMessageDecoder {
  443. PassthroughWebSocketMessageDecoder()
  444. }
  445. }
  446. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  447. struct PassthroughWebSocketMessageDecoder: WebSocketMessageSerializer {
  448. typealias Failure = Never
  449. func decode(_ message: URLSessionWebSocketTask.Message) -> URLSessionWebSocketTask.Message {
  450. message
  451. }
  452. }
  453. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  454. public struct DecodableWebSocketMessageDecoder<Value: Decodable & Sendable>: WebSocketMessageSerializer {
  455. public enum Error: Swift.Error {
  456. case decoding(any Swift.Error)
  457. case unknownMessage(description: String)
  458. }
  459. public let decoder: any DataDecoder
  460. public init(decoder: any DataDecoder) {
  461. self.decoder = decoder
  462. }
  463. public func decode(_ message: URLSessionWebSocketTask.Message) throws -> Value {
  464. let data: Data
  465. switch message {
  466. case let .data(messageData):
  467. data = messageData
  468. case let .string(string):
  469. data = Data(string.utf8)
  470. @unknown default:
  471. throw Error.unknownMessage(description: String(describing: message))
  472. }
  473. do {
  474. return try decoder.decode(Value.self, from: data)
  475. } catch {
  476. throw Error.decoding(error)
  477. }
  478. }
  479. }
  480. #endif