Connection.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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. package import GRPCCore
  17. internal import NIOConcurrencyHelpers
  18. package import NIOCore
  19. package 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. package struct Connection: Sendable {
  46. /// Events which can happen over the lifetime of the connection.
  47. package 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. package 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. package var events: AsyncStream<Event> {
  95. self.event.stream
  96. }
  97. package 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. package 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. package 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. package func makeStream(
  159. descriptor: MethodDescriptor,
  160. options: CallOptions
  161. ) async throws -> Stream {
  162. let (multiplexer, scheme) = try self.state.withLockedValue { state in
  163. switch state {
  164. case .connected(let connected):
  165. return (connected.multiplexer, connected.scheme)
  166. case .notConnected, .closing, .closed:
  167. throw RPCError(code: .unavailable, message: "subchannel isn't ready")
  168. }
  169. }
  170. let compression: CompressionAlgorithm
  171. if let override = options.compression {
  172. compression = self.enabledCompression.contains(override) ? override : .none
  173. } else {
  174. compression = self.defaultCompression
  175. }
  176. let maxRequestSize = options.maxRequestMessageBytes ?? Self.defaultMaxRequestMessageSizeBytes
  177. do {
  178. let stream = try await multiplexer.openStream { channel in
  179. channel.eventLoop.makeCompletedFuture {
  180. let streamHandler = GRPCClientStreamHandler(
  181. methodDescriptor: descriptor,
  182. scheme: scheme,
  183. outboundEncoding: compression,
  184. acceptedEncodings: self.enabledCompression,
  185. maximumPayloadSize: maxRequestSize
  186. )
  187. try channel.pipeline.syncOperations.addHandler(streamHandler)
  188. return try NIOAsyncChannel(
  189. wrappingChannelSynchronously: channel,
  190. configuration: NIOAsyncChannel.Configuration(
  191. isOutboundHalfClosureEnabled: true,
  192. inboundType: RPCResponsePart.self,
  193. outboundType: RPCRequestPart.self
  194. )
  195. )
  196. }
  197. }
  198. return Stream(wrapping: stream, descriptor: descriptor)
  199. } catch {
  200. throw RPCError(code: .unavailable, message: "subchannel is unavailable", cause: error)
  201. }
  202. }
  203. private func consumeConnectionEvents(
  204. _ connectionEvents: NIOAsyncChannelInboundStream<ClientConnectionEvent>
  205. ) async {
  206. // The connection becomes 'ready' when the initial HTTP/2 SETTINGS frame is received.
  207. // Establishing a TCP connection is insufficient as the TLS handshake may not complete or the
  208. // server might not be configured for gRPC or HTTP/2.
  209. //
  210. // This state is tracked here so that if the connection events sequence finishes and the
  211. // connection never became ready then the connection can report that the connect failed.
  212. var isReady = false
  213. func makeNeverReadyError(cause: (any Error)?) -> RPCError {
  214. return RPCError(
  215. code: .unavailable,
  216. message: """
  217. The server accepted the TCP connection but closed the connection before completing \
  218. the HTTP/2 connection preface.
  219. """,
  220. cause: cause
  221. )
  222. }
  223. do {
  224. var channelCloseReason: ClientConnectionEvent.CloseReason?
  225. for try await connectionEvent in connectionEvents {
  226. switch connectionEvent {
  227. case .ready:
  228. isReady = true
  229. self.event.continuation.yield(.connectSucceeded)
  230. case .closing(let reason):
  231. self.state.withLockedValue { $0.closing() }
  232. switch reason {
  233. case .goAway(let errorCode, let reason):
  234. // The connection will close at some point soon, yield a notification for this
  235. // because the close might not be imminent and this could result in address resolution.
  236. self.event.continuation.yield(.goingAway(errorCode, reason))
  237. case .idle, .keepaliveExpired, .initiatedLocally, .unexpected:
  238. // The connection will be closed imminently in these cases there's no need to do
  239. // anything.
  240. ()
  241. }
  242. // Take the reason with the highest precedence. A GOAWAY may be superseded by user
  243. // closing, for example.
  244. if channelCloseReason.map({ reason.precedence > $0.precedence }) ?? true {
  245. channelCloseReason = reason
  246. }
  247. }
  248. }
  249. let finalEvent: Event
  250. if isReady {
  251. let connectionCloseReason: Self.CloseReason
  252. switch channelCloseReason {
  253. case .keepaliveExpired:
  254. connectionCloseReason = .keepaliveTimeout
  255. case .idle:
  256. // Connection became idle, that's fine.
  257. connectionCloseReason = .idleTimeout
  258. case .goAway:
  259. // Remote peer told us to GOAWAY.
  260. connectionCloseReason = .remote
  261. case .initiatedLocally:
  262. // Shutdown was initiated locally.
  263. connectionCloseReason = .initiatedLocally
  264. case .unexpected(let error, let isIdle):
  265. let error = RPCError(
  266. code: .unavailable,
  267. message: "The TCP connection was dropped unexpectedly.",
  268. cause: error
  269. )
  270. connectionCloseReason = .error(error, wasIdle: isIdle)
  271. case .none:
  272. let error = RPCError(
  273. code: .unavailable,
  274. message: "The TCP connection was dropped unexpectedly.",
  275. cause: nil
  276. )
  277. connectionCloseReason = .error(error, wasIdle: true)
  278. }
  279. finalEvent = .closed(connectionCloseReason)
  280. } else {
  281. // The connection never became ready, this therefore counts as a failed connect attempt.
  282. finalEvent = .connectFailed(makeNeverReadyError(cause: nil))
  283. }
  284. // The connection events sequence has finished: the connection is now closed.
  285. self.state.withLockedValue { $0.closed() }
  286. self.finishStreams(withEvent: finalEvent)
  287. } catch {
  288. let finalEvent: Event
  289. if isReady {
  290. // Any error must come from consuming the inbound channel meaning that the connection
  291. // must be borked, wrap it up and close.
  292. let rpcError = RPCError(code: .unavailable, message: "connection closed", cause: error)
  293. finalEvent = .closed(.error(rpcError, wasIdle: true))
  294. } else {
  295. // The connection never became ready, this therefore counts as a failed connect attempt.
  296. finalEvent = .connectFailed(makeNeverReadyError(cause: error))
  297. }
  298. self.state.withLockedValue { $0.closed() }
  299. self.finishStreams(withEvent: finalEvent)
  300. }
  301. }
  302. private func finishStreams(withEvent event: Event) {
  303. self.event.continuation.yield(event)
  304. self.event.continuation.finish()
  305. self.input.continuation.finish()
  306. }
  307. }
  308. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  309. extension Connection {
  310. package struct Stream {
  311. package typealias Inbound = NIOAsyncChannelInboundStream<RPCResponsePart>
  312. package struct Outbound: ClosableRPCWriterProtocol {
  313. package typealias Element = RPCRequestPart
  314. private let requestWriter: NIOAsyncChannelOutboundWriter<RPCRequestPart>
  315. private let http2Stream: NIOAsyncChannel<RPCResponsePart, RPCRequestPart>
  316. fileprivate init(
  317. requestWriter: NIOAsyncChannelOutboundWriter<RPCRequestPart>,
  318. http2Stream: NIOAsyncChannel<RPCResponsePart, RPCRequestPart>
  319. ) {
  320. self.requestWriter = requestWriter
  321. self.http2Stream = http2Stream
  322. }
  323. package func write(_ element: RPCRequestPart) async throws {
  324. try await self.requestWriter.write(element)
  325. }
  326. package func write(contentsOf elements: some Sequence<Self.Element>) async throws {
  327. try await self.requestWriter.write(contentsOf: elements)
  328. }
  329. package func finish() {
  330. self.requestWriter.finish()
  331. }
  332. package func finish(throwing error: any Error) {
  333. // Fire the error inbound; this fails the inbound writer.
  334. self.http2Stream.channel.pipeline.fireErrorCaught(error)
  335. }
  336. }
  337. let descriptor: MethodDescriptor
  338. private let http2Stream: NIOAsyncChannel<RPCResponsePart, RPCRequestPart>
  339. init(
  340. wrapping stream: NIOAsyncChannel<RPCResponsePart, RPCRequestPart>,
  341. descriptor: MethodDescriptor
  342. ) {
  343. self.http2Stream = stream
  344. self.descriptor = descriptor
  345. }
  346. package func execute<T>(
  347. _ closure: (_ inbound: Inbound, _ outbound: Outbound) async throws -> T
  348. ) async throws -> T where T: Sendable {
  349. try await self.http2Stream.executeThenClose { inbound, outbound in
  350. return try await closure(
  351. inbound,
  352. Outbound(requestWriter: outbound, http2Stream: self.http2Stream)
  353. )
  354. }
  355. }
  356. }
  357. }
  358. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  359. extension Connection {
  360. private enum State: Sendable {
  361. /// The connection is idle or connecting.
  362. case notConnected
  363. /// A TCP connection has been established with the remote peer. However, the connection may not
  364. /// be ready to use yet.
  365. case connected(Connected)
  366. /// The connection has started to close. This may be initiated locally or by the remote.
  367. case closing
  368. /// The connection has closed. This is a terminal state.
  369. case closed
  370. struct Connected: Sendable {
  371. /// The connection channel.
  372. var channel: NIOAsyncChannel<ClientConnectionEvent, Void>
  373. /// Multiplexer for creating HTTP/2 streams.
  374. var multiplexer: NIOHTTP2Handler.AsyncStreamMultiplexer<Void>
  375. /// Whether the connection is plaintext, `false` implies TLS is being used.
  376. var scheme: Scheme
  377. init(_ connection: HTTP2Connection) {
  378. self.channel = connection.channel
  379. self.multiplexer = connection.multiplexer
  380. self.scheme = connection.isPlaintext ? .http : .https
  381. }
  382. }
  383. mutating func connected(_ channel: HTTP2Connection) {
  384. switch self {
  385. case .notConnected:
  386. self = .connected(State.Connected(channel))
  387. case .connected, .closing, .closed:
  388. fatalError("Invalid state: 'run()' must only be called once")
  389. }
  390. }
  391. mutating func beginClosing() -> NIOAsyncChannel<ClientConnectionEvent, Void>? {
  392. switch self {
  393. case .notConnected:
  394. fatalError("Invalid state: 'run()' must be called first")
  395. case .connected(let connected):
  396. self = .closing
  397. return connected.channel
  398. case .closing, .closed:
  399. return nil
  400. }
  401. }
  402. mutating func closing() {
  403. switch self {
  404. case .notConnected:
  405. // Not reachable: happens as a result of a connection event, that can only happen if
  406. // the connection has started (i.e. must be in the 'connected' state or later).
  407. fatalError("Invalid state")
  408. case .connected:
  409. self = .closing
  410. case .closing, .closed:
  411. ()
  412. }
  413. }
  414. mutating func closed() {
  415. self = .closed
  416. }
  417. }
  418. }
  419. extension ClientConnectionEvent.CloseReason {
  420. fileprivate var precedence: Int {
  421. switch self {
  422. case .unexpected:
  423. return -1
  424. case .goAway:
  425. return 0
  426. case .idle:
  427. return 1
  428. case .keepaliveExpired:
  429. return 2
  430. case .initiatedLocally:
  431. return 3
  432. }
  433. }
  434. }