Connection.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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(any Error, wasIdle: Bool)
  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, .unexpected:
  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:
  259. // Shutdown was initiated locally.
  260. connectionCloseReason = .initiatedLocally
  261. case .unexpected(let error, let isIdle):
  262. let error = RPCError(
  263. code: .unavailable,
  264. message: "The TCP connection was dropped unexpectedly.",
  265. cause: error
  266. )
  267. connectionCloseReason = .error(error, wasIdle: isIdle)
  268. case .none:
  269. let error = RPCError(
  270. code: .unavailable,
  271. message: "The TCP connection was dropped unexpectedly.",
  272. cause: nil
  273. )
  274. connectionCloseReason = .error(error, wasIdle: true)
  275. }
  276. finalEvent = .closed(connectionCloseReason)
  277. } else {
  278. // The connection never became ready, this therefore counts as a failed connect attempt.
  279. finalEvent = .connectFailed(makeNeverReadyError(cause: nil))
  280. }
  281. // The connection events sequence has finished: the connection is now closed.
  282. self.state.withLockedValue { $0.closed() }
  283. self.finishStreams(withEvent: finalEvent)
  284. } catch {
  285. let finalEvent: Event
  286. if isReady {
  287. // Any error must come from consuming the inbound channel meaning that the connection
  288. // must be borked, wrap it up and close.
  289. let rpcError = RPCError(code: .unavailable, message: "connection closed", cause: error)
  290. finalEvent = .closed(.error(rpcError, wasIdle: true))
  291. } else {
  292. // The connection never became ready, this therefore counts as a failed connect attempt.
  293. finalEvent = .connectFailed(makeNeverReadyError(cause: error))
  294. }
  295. self.state.withLockedValue { $0.closed() }
  296. self.finishStreams(withEvent: finalEvent)
  297. }
  298. }
  299. private func finishStreams(withEvent event: Event) {
  300. self.event.continuation.yield(event)
  301. self.event.continuation.finish()
  302. self.input.continuation.finish()
  303. }
  304. }
  305. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  306. extension Connection {
  307. struct Stream {
  308. typealias Inbound = NIOAsyncChannelInboundStream<RPCResponsePart>
  309. struct Outbound: ClosableRPCWriterProtocol {
  310. typealias Element = RPCRequestPart
  311. private let requestWriter: NIOAsyncChannelOutboundWriter<RPCRequestPart>
  312. private let http2Stream: NIOAsyncChannel<RPCResponsePart, RPCRequestPart>
  313. fileprivate init(
  314. requestWriter: NIOAsyncChannelOutboundWriter<RPCRequestPart>,
  315. http2Stream: NIOAsyncChannel<RPCResponsePart, RPCRequestPart>
  316. ) {
  317. self.requestWriter = requestWriter
  318. self.http2Stream = http2Stream
  319. }
  320. func write(_ element: RPCRequestPart) async throws {
  321. try await self.requestWriter.write(element)
  322. }
  323. func write(contentsOf elements: some Sequence<Self.Element>) async throws {
  324. try await self.requestWriter.write(contentsOf: elements)
  325. }
  326. func finish() {
  327. self.requestWriter.finish()
  328. }
  329. func finish(throwing error: any Error) {
  330. // Fire the error inbound; this fails the inbound writer.
  331. self.http2Stream.channel.pipeline.fireErrorCaught(error)
  332. }
  333. }
  334. let descriptor: MethodDescriptor
  335. private let http2Stream: NIOAsyncChannel<RPCResponsePart, RPCRequestPart>
  336. init(
  337. wrapping stream: NIOAsyncChannel<RPCResponsePart, RPCRequestPart>,
  338. descriptor: MethodDescriptor
  339. ) {
  340. self.http2Stream = stream
  341. self.descriptor = descriptor
  342. }
  343. func execute<T>(
  344. _ closure: (_ inbound: Inbound, _ outbound: Outbound) async throws -> T
  345. ) async throws -> T where T: Sendable {
  346. try await self.http2Stream.executeThenClose { inbound, outbound in
  347. return try await closure(
  348. inbound,
  349. Outbound(requestWriter: outbound, http2Stream: self.http2Stream)
  350. )
  351. }
  352. }
  353. }
  354. }
  355. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  356. extension Connection {
  357. private enum State: Sendable {
  358. /// The connection is idle or connecting.
  359. case notConnected
  360. /// A TCP connection has been established with the remote peer. However, the connection may not
  361. /// be ready to use yet.
  362. case connected(Connected)
  363. /// The connection has started to close. This may be initiated locally or by the remote.
  364. case closing
  365. /// The connection has closed. This is a terminal state.
  366. case closed
  367. struct Connected: Sendable {
  368. /// The connection channel.
  369. var channel: NIOAsyncChannel<ClientConnectionEvent, Void>
  370. /// Multiplexer for creating HTTP/2 streams.
  371. var multiplexer: NIOHTTP2Handler.AsyncStreamMultiplexer<Void>
  372. /// Whether the connection is plaintext, `false` implies TLS is being used.
  373. var scheme: GRPCStreamStateMachineConfiguration.Scheme
  374. init(_ connection: HTTP2Connection) {
  375. self.channel = connection.channel
  376. self.multiplexer = connection.multiplexer
  377. self.scheme = connection.isPlaintext ? .http : .https
  378. }
  379. }
  380. mutating func connected(_ channel: HTTP2Connection) {
  381. switch self {
  382. case .notConnected:
  383. self = .connected(State.Connected(channel))
  384. case .connected, .closing, .closed:
  385. fatalError("Invalid state: 'run()' must only be called once")
  386. }
  387. }
  388. mutating func beginClosing() -> NIOAsyncChannel<ClientConnectionEvent, Void>? {
  389. switch self {
  390. case .notConnected:
  391. fatalError("Invalid state: 'run()' must be called first")
  392. case .connected(let connected):
  393. self = .closing
  394. return connected.channel
  395. case .closing, .closed:
  396. return nil
  397. }
  398. }
  399. mutating func closing() {
  400. switch self {
  401. case .notConnected:
  402. // Not reachable: happens as a result of a connection event, that can only happen if
  403. // the connection has started (i.e. must be in the 'connected' state or later).
  404. fatalError("Invalid state")
  405. case .connected:
  406. self = .closing
  407. case .closing, .closed:
  408. ()
  409. }
  410. }
  411. mutating func closed() {
  412. self = .closed
  413. }
  414. }
  415. }
  416. extension ClientConnectionEvent.CloseReason {
  417. fileprivate var precedence: Int {
  418. switch self {
  419. case .unexpected:
  420. return -1
  421. case .goAway:
  422. return 0
  423. case .idle:
  424. return 1
  425. case .keepaliveExpired:
  426. return 2
  427. case .initiatedLocally:
  428. return 3
  429. }
  430. }
  431. }