WebSocketRequest.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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: @Sendable @escaping (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: @Sendable @escaping (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. #if swift(>=5.8)
  271. @available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
  272. func startAutomaticPing(every duration: Duration) {
  273. let interval = TimeInterval(duration.components.seconds) + (Double(duration.components.attoseconds) / 1e18)
  274. startAutomaticPing(every: interval)
  275. }
  276. #endif
  277. func cancelAutomaticPing() {
  278. socketMutableState.write { mutableState in
  279. mutableState.pingTimerItem?.cancel()
  280. mutableState.pingTimerItem = nil
  281. }
  282. }
  283. func didDisconnect(closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
  284. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  285. cancelAutomaticPing()
  286. socketMutableState.read { state in
  287. for handler in state.handlers {
  288. // Saved handler calls out to serializationQueue immediately, then to handler's queue.
  289. handler.handler(.disconnected(closeCode: closeCode, reason: reason))
  290. }
  291. }
  292. }
  293. private func listen(to task: URLSessionWebSocketTask) {
  294. // TODO: Do we care about the cycle while receiving?
  295. task.receive { result in
  296. switch result {
  297. case let .success(message):
  298. self.socketMutableState.read { state in
  299. for handler in state.handlers {
  300. // Saved handler calls out to serializationQueue immediately, then to handler's queue.
  301. handler.handler(.receivedMessage(message))
  302. }
  303. }
  304. self.listen(to: task)
  305. case .failure:
  306. // It doesn't seem like any relevant errors are received here, just incorrect garbage, like errors when
  307. // the socket disconnects.
  308. break
  309. }
  310. }
  311. }
  312. @preconcurrency
  313. @discardableResult
  314. public func streamSerializer<Serializer>(
  315. _ serializer: Serializer,
  316. on queue: DispatchQueue = .main,
  317. handler: @Sendable @escaping (_ event: Event<Serializer.Output, Serializer.Failure>) -> Void
  318. ) -> Self where Serializer: WebSocketMessageSerializer, Serializer.Failure == any Error {
  319. forIncomingEvent(on: queue) { incomingEvent in
  320. let event: Event<Serializer.Output, Serializer.Failure>
  321. switch incomingEvent {
  322. case let .connected(`protocol`):
  323. event = .init(socket: self, kind: .connected(protocol: `protocol`))
  324. case let .receivedMessage(message):
  325. do {
  326. let serializedMessage = try serializer.decode(message)
  327. event = .init(socket: self, kind: .receivedMessage(serializedMessage))
  328. } catch {
  329. event = .init(socket: self, kind: .serializerFailed(error))
  330. }
  331. case let .disconnected(closeCode, reason):
  332. event = .init(socket: self, kind: .disconnected(closeCode: closeCode, reason: reason))
  333. case let .completed(completion):
  334. event = .init(socket: self, kind: .completed(completion))
  335. }
  336. queue.async { handler(event) }
  337. }
  338. }
  339. @preconcurrency
  340. @discardableResult
  341. public func streamDecodableEvents<Value>(
  342. _ type: Value.Type = Value.self,
  343. on queue: DispatchQueue = .main,
  344. using decoder: any DataDecoder = JSONDecoder(),
  345. handler: @Sendable @escaping (_ event: Event<Value, any Error>) -> Void
  346. ) -> Self where Value: Decodable {
  347. streamSerializer(DecodableWebSocketMessageDecoder<Value>(decoder: decoder), on: queue, handler: handler)
  348. }
  349. @preconcurrency
  350. @discardableResult
  351. public func streamDecodable<Value>(
  352. _ type: Value.Type = Value.self,
  353. on queue: DispatchQueue = .main,
  354. using decoder: any DataDecoder = JSONDecoder(),
  355. handler: @Sendable @escaping (_ value: Value) -> Void
  356. ) -> Self where Value: Decodable & Sendable {
  357. streamDecodableEvents(Value.self, on: queue) { event in
  358. event.message.map(handler)
  359. }
  360. }
  361. @preconcurrency
  362. @discardableResult
  363. public func streamMessageEvents(
  364. on queue: DispatchQueue = .main,
  365. handler: @Sendable @escaping (_ event: Event<URLSessionWebSocketTask.Message, Never>) -> Void
  366. ) -> Self {
  367. forIncomingEvent(on: queue) { incomingEvent in
  368. let event: Event<URLSessionWebSocketTask.Message, Never> = switch incomingEvent {
  369. case let .connected(`protocol`):
  370. .init(socket: self, kind: .connected(protocol: `protocol`))
  371. case let .receivedMessage(message):
  372. .init(socket: self, kind: .receivedMessage(message))
  373. case let .disconnected(closeCode, reason):
  374. .init(socket: self, kind: .disconnected(closeCode: closeCode, reason: reason))
  375. case let .completed(completion):
  376. .init(socket: self, kind: .completed(completion))
  377. }
  378. queue.async { handler(event) }
  379. }
  380. }
  381. @preconcurrency
  382. @discardableResult
  383. public func streamMessages(
  384. on queue: DispatchQueue = .main,
  385. handler: @Sendable @escaping (_ message: URLSessionWebSocketTask.Message) -> Void
  386. ) -> Self {
  387. streamMessageEvents(on: queue) { event in
  388. event.message.map(handler)
  389. }
  390. }
  391. func forIncomingEvent(on queue: DispatchQueue, handler: @Sendable @escaping (IncomingEvent) -> Void) -> Self {
  392. socketMutableState.write { state in
  393. state.handlers.append((queue: queue, handler: { incomingEvent in
  394. self.serializationQueue.async {
  395. handler(incomingEvent)
  396. }
  397. }))
  398. }
  399. appendResponseSerializer {
  400. self.responseSerializerDidComplete {
  401. self.serializationQueue.async {
  402. handler(.completed(.init(request: self.request,
  403. response: self.response,
  404. metrics: self.metrics,
  405. error: self.error)))
  406. }
  407. }
  408. }
  409. return self
  410. }
  411. @preconcurrency
  412. public func send(_ message: URLSessionWebSocketTask.Message,
  413. queue: DispatchQueue = .main,
  414. completionHandler: @Sendable @escaping (Result<Void, any Error>) -> Void) {
  415. guard !(isCancelled || isFinished) else { return }
  416. guard let socket else {
  417. // URLSessionWebSocketTask not created yet, enqueue the send.
  418. socketMutableState.write { mutableState in
  419. mutableState.enqueuedSends.append((message, queue, completionHandler))
  420. }
  421. return
  422. }
  423. socket.send(message) { error in
  424. queue.async {
  425. completionHandler(Result(value: (), error: error))
  426. }
  427. }
  428. }
  429. }
  430. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  431. public protocol WebSocketMessageSerializer<Output, Failure>: Sendable {
  432. associatedtype Output: Sendable
  433. associatedtype Failure: Error = any Error
  434. func decode(_ message: URLSessionWebSocketTask.Message) throws -> Output
  435. }
  436. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  437. extension WebSocketMessageSerializer {
  438. public static func json<Value>(
  439. decoding _: Value.Type = Value.self,
  440. using decoder: JSONDecoder = JSONDecoder()
  441. ) -> DecodableWebSocketMessageDecoder<Value> where Self == DecodableWebSocketMessageDecoder<Value> {
  442. Self(decoder: decoder)
  443. }
  444. static var passthrough: PassthroughWebSocketMessageDecoder {
  445. PassthroughWebSocketMessageDecoder()
  446. }
  447. }
  448. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  449. struct PassthroughWebSocketMessageDecoder: WebSocketMessageSerializer {
  450. public typealias Failure = Never
  451. public func decode(_ message: URLSessionWebSocketTask.Message) -> URLSessionWebSocketTask.Message {
  452. message
  453. }
  454. }
  455. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  456. public struct DecodableWebSocketMessageDecoder<Value: Decodable & Sendable>: WebSocketMessageSerializer {
  457. public enum Error: Swift.Error {
  458. case decoding(any Swift.Error)
  459. case unknownMessage(description: String)
  460. }
  461. public let decoder: any DataDecoder
  462. public init(decoder: any DataDecoder) {
  463. self.decoder = decoder
  464. }
  465. public func decode(_ message: URLSessionWebSocketTask.Message) throws -> Value {
  466. let data: Data
  467. switch message {
  468. case let .data(messageData):
  469. data = messageData
  470. case let .string(string):
  471. data = Data(string.utf8)
  472. @unknown default:
  473. throw Error.unknownMessage(description: String(describing: message))
  474. }
  475. do {
  476. return try decoder.decode(Value.self, from: data)
  477. } catch {
  478. throw Error.decoding(error)
  479. }
  480. }
  481. }
  482. #endif