Connection.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. /*
  2. * Copyright 2024, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import GRPCCore
  17. import NIOConcurrencyHelpers
  18. import NIOCore
  19. import NIOHTTP2
  20. /// A `Connection` provides communication to a single remote peer.
  21. ///
  22. /// Each `Connection` object is 'one-shot': it may only be used for a single connection over
  23. /// its lifetime. If a connect attempt fails then the `Connection` must be discarded and a new one
  24. /// must be created. However, an active connection may be used multiple times to provide streams
  25. /// to the backend.
  26. ///
  27. /// To use the `Connection` you must run it in a task. You can consume event updates by listening
  28. /// to `events`:
  29. ///
  30. /// ```swift
  31. /// await withTaskGroup(of: Void.self) { group in
  32. /// group.addTask { await connection.run() }
  33. ///
  34. /// for await event in connection.events {
  35. /// switch event {
  36. /// case .connectSucceeded:
  37. /// // ...
  38. /// default:
  39. /// // ...
  40. /// }
  41. /// }
  42. /// }
  43. /// ```
  44. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  45. struct Connection: Sendable {
  46. /// Events which can happen over the lifetime of the connection.
  47. enum Event: Sendable {
  48. /// The connect attempt succeeded and the connection is ready to use.
  49. case connectSucceeded
  50. /// The connect attempt failed.
  51. case connectFailed(any Error)
  52. /// The connection received a GOAWAY and will close soon. No new streams
  53. /// should be opened on this connection.
  54. case goingAway(HTTP2ErrorCode, String)
  55. /// The connection is closed.
  56. case closed(Connection.CloseReason)
  57. }
  58. /// The reason the connection closed.
  59. enum CloseReason: Sendable {
  60. /// Closed because an idle timeout fired.
  61. case idleTimeout
  62. /// Closed because a keepalive timer fired.
  63. case keepaliveTimeout
  64. /// Closed because the caller initiated shutdown and all RPCs on the connection finished.
  65. case initiatedLocally
  66. /// Closed because the remote peer initiate shutdown (i.e. sent a GOAWAY frame).
  67. case remote
  68. /// Closed because the connection encountered an unexpected error.
  69. case error(Error)
  70. }
  71. /// Inputs to the 'run' method.
  72. private enum Input: Sendable {
  73. case close
  74. }
  75. /// Events which have happened to the connection.
  76. private let event: (stream: AsyncStream<Event>, continuation: AsyncStream<Event>.Continuation)
  77. /// Events which the connection must react to.
  78. private let input: (stream: AsyncStream<Input>, continuation: AsyncStream<Input>.Continuation)
  79. /// The address to connect to.
  80. private let address: SocketAddress
  81. /// The default compression algorithm used for requests.
  82. private let defaultCompression: CompressionAlgorithm
  83. /// The set of enabled compression algorithms.
  84. private let enabledCompression: CompressionAlgorithmSet
  85. /// A connector used to establish a connection.
  86. private let http2Connector: any HTTP2Connector
  87. /// The state of the connection.
  88. private let state: NIOLockedValueBox<State>
  89. /// The default max request message size in bytes, 4 MiB.
  90. private static var defaultMaxRequestMessageSizeBytes: Int {
  91. 4 * 1024 * 1024
  92. }
  93. /// A stream of events which can happen to the connection.
  94. var events: AsyncStream<Event> {
  95. self.event.stream
  96. }
  97. init(
  98. address: SocketAddress,
  99. http2Connector: any HTTP2Connector,
  100. defaultCompression: CompressionAlgorithm,
  101. enabledCompression: CompressionAlgorithmSet
  102. ) {
  103. self.address = address
  104. self.defaultCompression = defaultCompression
  105. self.enabledCompression = enabledCompression
  106. self.http2Connector = http2Connector
  107. self.event = AsyncStream.makeStream(of: Event.self)
  108. self.input = AsyncStream.makeStream(of: Input.self)
  109. self.state = NIOLockedValueBox(.notConnected)
  110. }
  111. /// Connect and run the connection.
  112. ///
  113. /// This function returns when the connection has closed. You can observe connection events
  114. /// by consuming the ``events`` sequence.
  115. func run() async {
  116. let connectResult = await Result {
  117. try await self.http2Connector.establishConnection(to: self.address)
  118. }
  119. switch connectResult {
  120. case .success(let connected):
  121. // Connected successfully, update state and report the event.
  122. self.state.withLockedValue { state in
  123. state.connected(connected)
  124. }
  125. await withDiscardingTaskGroup { group in
  126. // Add a task to run the connection and consume events.
  127. group.addTask {
  128. try? await connected.channel.executeThenClose { inbound, outbound in
  129. await self.consumeConnectionEvents(inbound)
  130. }
  131. }
  132. // Meanwhile, consume input events. This sequence will end when the connection has closed.
  133. for await input in self.input.stream {
  134. switch input {
  135. case .close:
  136. let asyncChannel = self.state.withLockedValue { $0.beginClosing() }
  137. if let channel = asyncChannel?.channel {
  138. let event = ClientConnectionHandler.OutboundEvent.closeGracefully
  139. channel.triggerUserOutboundEvent(event, promise: nil)
  140. }
  141. }
  142. }
  143. }
  144. case .failure(let error):
  145. // Connect failed, this connection is no longer useful.
  146. self.state.withLockedValue { $0.closed() }
  147. self.finishStreams(withEvent: .connectFailed(error))
  148. }
  149. }
  150. /// Gracefully close the connection.
  151. func close() {
  152. self.input.continuation.yield(.close)
  153. }
  154. /// Make a stream using the connection if it's connected.
  155. ///
  156. /// - Parameter descriptor: A descriptor of the method to create a stream for.
  157. /// - Returns: The open stream.
  158. func makeStream(descriptor: MethodDescriptor, options: CallOptions) async throws -> Stream {
  159. let (multiplexer, scheme) = try self.state.withLockedValue { state in
  160. switch state {
  161. case .connected(let connected):
  162. return (connected.multiplexer, connected.scheme)
  163. case .notConnected, .closing, .closed:
  164. throw RPCError(code: .unavailable, message: "subchannel isn't ready")
  165. }
  166. }
  167. let compression: CompressionAlgorithm
  168. if let override = options.compression {
  169. compression = self.enabledCompression.contains(override) ? override : .none
  170. } else {
  171. compression = self.defaultCompression
  172. }
  173. let maxRequestSize = options.maxRequestMessageBytes ?? Self.defaultMaxRequestMessageSizeBytes
  174. do {
  175. let stream = try await multiplexer.openStream { channel in
  176. channel.eventLoop.makeCompletedFuture {
  177. let streamHandler = GRPCClientStreamHandler(
  178. methodDescriptor: descriptor,
  179. scheme: scheme,
  180. outboundEncoding: compression,
  181. acceptedEncodings: self.enabledCompression,
  182. maximumPayloadSize: maxRequestSize
  183. )
  184. try channel.pipeline.syncOperations.addHandler(streamHandler)
  185. return try NIOAsyncChannel(
  186. wrappingChannelSynchronously: channel,
  187. configuration: NIOAsyncChannel.Configuration(
  188. isOutboundHalfClosureEnabled: true,
  189. inboundType: RPCResponsePart.self,
  190. outboundType: RPCRequestPart.self
  191. )
  192. )
  193. }
  194. }
  195. return Stream(wrapping: stream, descriptor: descriptor)
  196. } catch {
  197. throw RPCError(code: .unavailable, message: "subchannel is unavailable", cause: error)
  198. }
  199. }
  200. private func consumeConnectionEvents(
  201. _ connectionEvents: NIOAsyncChannelInboundStream<ClientConnectionEvent>
  202. ) async {
  203. // The connection becomes 'ready' when the initial HTTP/2 SETTINGS frame is received.
  204. // Establishing a TCP connection is insufficient as the TLS handshake may not complete or the
  205. // server might not be configured for gRPC or HTTP/2.
  206. //
  207. // This state is tracked here so that if the connection events sequence finishes and the
  208. // connection never became ready then the connection can report that the connect failed.
  209. var isReady = false
  210. func makeNeverReadyError(cause: (any Error)?) -> RPCError {
  211. return RPCError(
  212. code: .unavailable,
  213. message: """
  214. The server accepted the TCP connection but closed the connection before completing \
  215. the HTTP/2 connection preface.
  216. """,
  217. cause: cause
  218. )
  219. }
  220. do {
  221. var channelCloseReason: ClientConnectionEvent.CloseReason?
  222. for try await connectionEvent in connectionEvents {
  223. switch connectionEvent {
  224. case .ready:
  225. isReady = true
  226. self.event.continuation.yield(.connectSucceeded)
  227. case .closing(let reason):
  228. self.state.withLockedValue { $0.closing() }
  229. switch reason {
  230. case .goAway(let errorCode, let reason):
  231. // The connection will close at some point soon, yield a notification for this
  232. // because the close might not be imminent and this could result in address resolution.
  233. self.event.continuation.yield(.goingAway(errorCode, reason))
  234. case .idle, .keepaliveExpired, .initiatedLocally:
  235. // The connection will be closed imminently in these cases there's no need to do
  236. // anything.
  237. ()
  238. }
  239. // Take the reason with the highest precedence. A GOAWAY may be superseded by user
  240. // closing, for example.
  241. if channelCloseReason.map({ reason.precedence > $0.precedence }) ?? true {
  242. channelCloseReason = reason
  243. }
  244. }
  245. }
  246. let finalEvent: Event
  247. if isReady {
  248. let connectionCloseReason: Self.CloseReason
  249. switch channelCloseReason {
  250. case .keepaliveExpired:
  251. connectionCloseReason = .keepaliveTimeout
  252. case .idle:
  253. // Connection became idle, that's fine.
  254. connectionCloseReason = .idleTimeout
  255. case .goAway:
  256. // Remote peer told us to GOAWAY.
  257. connectionCloseReason = .remote
  258. case .initiatedLocally, .none:
  259. // Shutdown was initiated locally.
  260. connectionCloseReason = .initiatedLocally
  261. }
  262. finalEvent = .closed(connectionCloseReason)
  263. } else {
  264. // The connection never became ready, this therefore counts as a failed connect attempt.
  265. finalEvent = .connectFailed(makeNeverReadyError(cause: nil))
  266. }
  267. // The connection events sequence has finished: the connection is now closed.
  268. self.state.withLockedValue { $0.closed() }
  269. self.finishStreams(withEvent: finalEvent)
  270. } catch {
  271. let finalEvent: Event
  272. if isReady {
  273. // Any error must come from consuming the inbound channel meaning that the connection
  274. // must be borked, wrap it up and close.
  275. let rpcError = RPCError(code: .unavailable, message: "connection closed", cause: error)
  276. finalEvent = .closed(.error(rpcError))
  277. } else {
  278. // The connection never became ready, this therefore counts as a failed connect attempt.
  279. finalEvent = .connectFailed(makeNeverReadyError(cause: error))
  280. }
  281. self.state.withLockedValue { $0.closed() }
  282. self.finishStreams(withEvent: finalEvent)
  283. }
  284. }
  285. private func finishStreams(withEvent event: Event) {
  286. self.event.continuation.yield(event)
  287. self.event.continuation.finish()
  288. self.input.continuation.finish()
  289. }
  290. }
  291. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  292. extension Connection {
  293. struct Stream {
  294. typealias Inbound = NIOAsyncChannelInboundStream<RPCResponsePart>
  295. struct Outbound: ClosableRPCWriterProtocol {
  296. typealias Element = RPCRequestPart
  297. private let requestWriter: NIOAsyncChannelOutboundWriter<RPCRequestPart>
  298. private let http2Stream: NIOAsyncChannel<RPCResponsePart, RPCRequestPart>
  299. fileprivate init(
  300. requestWriter: NIOAsyncChannelOutboundWriter<RPCRequestPart>,
  301. http2Stream: NIOAsyncChannel<RPCResponsePart, RPCRequestPart>
  302. ) {
  303. self.requestWriter = requestWriter
  304. self.http2Stream = http2Stream
  305. }
  306. func write(contentsOf elements: some Sequence<Self.Element>) async throws {
  307. try await self.requestWriter.write(contentsOf: elements)
  308. }
  309. func finish() {
  310. self.requestWriter.finish()
  311. }
  312. func finish(throwing error: any Error) {
  313. // Fire the error inbound; this fails the inbound writer.
  314. self.http2Stream.channel.pipeline.fireErrorCaught(error)
  315. }
  316. }
  317. let descriptor: MethodDescriptor
  318. private let http2Stream: NIOAsyncChannel<RPCResponsePart, RPCRequestPart>
  319. init(
  320. wrapping stream: NIOAsyncChannel<RPCResponsePart, RPCRequestPart>,
  321. descriptor: MethodDescriptor
  322. ) {
  323. self.http2Stream = stream
  324. self.descriptor = descriptor
  325. }
  326. func execute<T>(
  327. _ closure: (_ inbound: Inbound, _ outbound: Outbound) async throws -> T
  328. ) async throws -> T where T: Sendable {
  329. try await self.http2Stream.executeThenClose { inbound, outbound in
  330. return try await closure(
  331. inbound,
  332. Outbound(requestWriter: outbound, http2Stream: self.http2Stream)
  333. )
  334. }
  335. }
  336. }
  337. }
  338. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  339. extension Connection {
  340. private enum State {
  341. /// The connection is idle or connecting.
  342. case notConnected
  343. /// A TCP connection has been established with the remote peer. However, the connection may not
  344. /// be ready to use yet.
  345. case connected(Connected)
  346. /// The connection has started to close. This may be initiated locally or by the remote.
  347. case closing
  348. /// The connection has closed. This is a terminal state.
  349. case closed
  350. struct Connected {
  351. /// The connection channel.
  352. var channel: NIOAsyncChannel<ClientConnectionEvent, Void>
  353. /// Multiplexer for creating HTTP/2 streams.
  354. var multiplexer: NIOHTTP2Handler.AsyncStreamMultiplexer<Void>
  355. /// Whether the connection is plaintext, `false` implies TLS is being used.
  356. var scheme: Scheme
  357. init(_ connection: HTTP2Connection) {
  358. self.channel = connection.channel
  359. self.multiplexer = connection.multiplexer
  360. self.scheme = connection.isPlaintext ? .http : .https
  361. }
  362. }
  363. mutating func connected(_ channel: HTTP2Connection) {
  364. switch self {
  365. case .notConnected:
  366. self = .connected(State.Connected(channel))
  367. case .connected, .closing, .closed:
  368. fatalError("Invalid state: 'run()' must only be called once")
  369. }
  370. }
  371. mutating func beginClosing() -> NIOAsyncChannel<ClientConnectionEvent, Void>? {
  372. switch self {
  373. case .notConnected:
  374. fatalError("Invalid state: 'run()' must be called first")
  375. case .connected(let connected):
  376. self = .closing
  377. return connected.channel
  378. case .closing, .closed:
  379. return nil
  380. }
  381. }
  382. mutating func closing() {
  383. switch self {
  384. case .notConnected:
  385. // Not reachable: happens as a result of a connection event, that can only happen if
  386. // the connection has started (i.e. must be in the 'connected' state or later).
  387. fatalError("Invalid state")
  388. case .connected:
  389. self = .closing
  390. case .closing, .closed:
  391. ()
  392. }
  393. }
  394. mutating func closed() {
  395. self = .closed
  396. }
  397. }
  398. }
  399. extension ClientConnectionEvent.CloseReason {
  400. fileprivate var precedence: Int {
  401. switch self {
  402. case .goAway:
  403. return 0
  404. case .idle:
  405. return 1
  406. case .keepaliveExpired:
  407. return 2
  408. case .initiatedLocally:
  409. return 3
  410. }
  411. }
  412. }