ClientConnectionHandler.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  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 NIOCore
  17. import NIOHTTP2
  18. /// An event which happens on a client's HTTP/2 connection.
  19. package enum ClientConnectionEvent: Sendable {
  20. package enum CloseReason: Sendable {
  21. /// The server sent a GOAWAY frame to the client.
  22. case goAway(HTTP2ErrorCode, String)
  23. /// The keep alive timer fired and subsequently timed out.
  24. case keepaliveExpired
  25. /// The connection became idle.
  26. case idle
  27. /// The local peer initiated the close.
  28. case initiatedLocally
  29. /// The connection was closed unexpectedly
  30. case unexpected((any Error)?, isIdle: Bool)
  31. }
  32. /// The connection is now ready.
  33. case ready
  34. /// The connection has started shutting down, no new streams should be created.
  35. case closing(CloseReason)
  36. }
  37. /// A `ChannelHandler` which manages part of the lifecycle of a gRPC connection over HTTP/2.
  38. ///
  39. /// This handler is responsible for managing several aspects of the connection. These include:
  40. /// 1. Periodically sending keep alive pings to the server (if configured) and closing the
  41. /// connection if necessary.
  42. /// 2. Closing the connection if it is idle (has no open streams) for a configured amount of time.
  43. /// 3. Forwarding lifecycle events to the next handler.
  44. ///
  45. /// Some of the behaviours are described in [gRFC A8](https://github.com/grpc/proposal/blob/master/A8-client-side-keepalive.md).
  46. package final class ClientConnectionHandler: ChannelInboundHandler, ChannelOutboundHandler {
  47. package typealias InboundIn = HTTP2Frame
  48. package typealias InboundOut = ClientConnectionEvent
  49. package typealias OutboundIn = Never
  50. package typealias OutboundOut = HTTP2Frame
  51. package enum OutboundEvent: Hashable, Sendable {
  52. /// Close the connection gracefully
  53. case closeGracefully
  54. }
  55. /// The `EventLoop` of the `Channel` this handler exists in.
  56. private let eventLoop: any EventLoop
  57. /// The maximum amount of time the connection may be idle for. If the connection remains idle
  58. /// (i.e. has no open streams) for this period of time then the connection will be gracefully
  59. /// closed.
  60. private var maxIdleTimer: Timer?
  61. /// The amount of time to wait before sending a keep alive ping.
  62. private var keepaliveTimer: Timer?
  63. /// The amount of time the client has to reply after sending a keep alive ping. Only used if
  64. /// `keepaliveTimer` is set.
  65. private var keepaliveTimeoutTimer: Timer
  66. /// Opaque data sent in keep alive pings.
  67. private let keepalivePingData: HTTP2PingData
  68. /// The current state of the connection.
  69. private var state: StateMachine
  70. /// Whether a flush is pending.
  71. private var flushPending: Bool
  72. /// Whether `channelRead` has been called and `channelReadComplete` hasn't yet been called.
  73. /// Resets once `channelReadComplete` returns.
  74. private var inReadLoop: Bool
  75. /// The context of the channel this handler is in.
  76. private var context: ChannelHandlerContext?
  77. /// Creates a new handler which manages the lifecycle of a connection.
  78. ///
  79. /// - Parameters:
  80. /// - eventLoop: The `EventLoop` of the `Channel` this handler is placed in.
  81. /// - maxIdleTime: The maximum amount time a connection may be idle for before being closed.
  82. /// - keepaliveTime: The amount of time to wait after reading data before sending a keep-alive
  83. /// ping.
  84. /// - keepaliveTimeout: The amount of time the client has to reply after the server sends a
  85. /// keep-alive ping to keep the connection open. The connection is closed if no reply
  86. /// is received.
  87. /// - keepaliveWithoutCalls: Whether the client sends keep-alive pings when there are no calls
  88. /// in progress.
  89. package init(
  90. eventLoop: any EventLoop,
  91. maxIdleTime: TimeAmount?,
  92. keepaliveTime: TimeAmount?,
  93. keepaliveTimeout: TimeAmount?,
  94. keepaliveWithoutCalls: Bool
  95. ) {
  96. self.eventLoop = eventLoop
  97. self.maxIdleTimer = maxIdleTime.map { Timer(delay: $0) }
  98. self.keepaliveTimer = keepaliveTime.map { Timer(delay: $0, repeat: true) }
  99. self.keepaliveTimeoutTimer = Timer(delay: keepaliveTimeout ?? .seconds(20))
  100. self.keepalivePingData = HTTP2PingData(withInteger: .random(in: .min ... .max))
  101. self.state = StateMachine(allowKeepaliveWithoutCalls: keepaliveWithoutCalls)
  102. self.flushPending = false
  103. self.inReadLoop = false
  104. }
  105. package func handlerAdded(context: ChannelHandlerContext) {
  106. assert(context.eventLoop === self.eventLoop)
  107. self.context = context
  108. }
  109. package func handlerRemoved(context: ChannelHandlerContext) {
  110. self.context = nil
  111. }
  112. package func channelInactive(context: ChannelHandlerContext) {
  113. switch self.state.closed() {
  114. case .none:
  115. ()
  116. case .unexpectedClose(let error, let isIdle):
  117. let event = self.wrapInboundOut(.closing(.unexpected(error, isIdle: isIdle)))
  118. context.fireChannelRead(event)
  119. case .succeed(let promise):
  120. promise.succeed()
  121. }
  122. self.keepaliveTimer?.cancel()
  123. self.keepaliveTimeoutTimer.cancel()
  124. }
  125. package func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
  126. switch event {
  127. case let event as NIOHTTP2StreamCreatedEvent:
  128. self._streamCreated(event.streamID, channel: context.channel)
  129. case let event as StreamClosedEvent:
  130. self._streamClosed(event.streamID, channel: context.channel)
  131. default:
  132. ()
  133. }
  134. context.fireUserInboundEventTriggered(event)
  135. }
  136. package func errorCaught(context: ChannelHandlerContext, error: any Error) {
  137. // Store the error and close, this will result in the final close event being fired down
  138. // the pipeline with an appropriate close reason and appropriate error. (This avoids
  139. // the async channel just throwing the error.)
  140. self.state.receivedError(error)
  141. context.close(mode: .all, promise: nil)
  142. }
  143. package func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  144. let frame = self.unwrapInboundIn(data)
  145. self.inReadLoop = true
  146. switch frame.payload {
  147. case .goAway(_, let errorCode, let data):
  148. // Receiving a GOAWAY frame means we need to stop creating streams immediately and start
  149. // closing the connection.
  150. switch self.state.beginGracefulShutdown(promise: nil) {
  151. case .sendGoAway(let close):
  152. // gRPC servers may indicate why the GOAWAY was sent in the opaque data.
  153. let message = data.map { String(buffer: $0) } ?? ""
  154. context.fireChannelRead(self.wrapInboundOut(.closing(.goAway(errorCode, message))))
  155. // Clients should send GOAWAYs when closing a connection.
  156. self.writeAndFlushGoAway(context: context, errorCode: .noError)
  157. if close {
  158. context.close(promise: nil)
  159. }
  160. case .none:
  161. ()
  162. }
  163. case .ping(let data, let ack):
  164. // Pings are ack'd by the HTTP/2 handler so we only pay attention to acks here, and in
  165. // particular only those carrying the keep-alive data.
  166. if ack, data == self.keepalivePingData {
  167. let loopBound = LoopBoundView(handler: self, context: context)
  168. self.keepaliveTimeoutTimer.cancel()
  169. self.keepaliveTimer?.schedule(on: context.eventLoop) {
  170. loopBound.keepaliveTimerFired()
  171. }
  172. }
  173. case .settings(.settings(_)):
  174. let isInitialSettings = self.state.receivedSettings()
  175. // The first settings frame indicates that the connection is now ready to use. The channel
  176. // becoming active is insufficient as, for example, a TLS handshake may fail after
  177. // establishing the TCP connection, or the server isn't configured for gRPC (or HTTP/2).
  178. if isInitialSettings {
  179. let loopBound = LoopBoundView(handler: self, context: context)
  180. self.keepaliveTimer?.schedule(on: context.eventLoop) {
  181. loopBound.keepaliveTimerFired()
  182. }
  183. self.maxIdleTimer?.schedule(on: context.eventLoop) {
  184. loopBound.maxIdleTimerFired()
  185. }
  186. context.fireChannelRead(self.wrapInboundOut(.ready))
  187. }
  188. default:
  189. ()
  190. }
  191. }
  192. package func channelReadComplete(context: ChannelHandlerContext) {
  193. while self.flushPending {
  194. self.flushPending = false
  195. context.flush()
  196. }
  197. self.inReadLoop = false
  198. context.fireChannelReadComplete()
  199. }
  200. package func triggerUserOutboundEvent(
  201. context: ChannelHandlerContext,
  202. event: Any,
  203. promise: EventLoopPromise<Void>?
  204. ) {
  205. if let event = event as? OutboundEvent {
  206. switch event {
  207. case .closeGracefully:
  208. switch self.state.beginGracefulShutdown(promise: promise) {
  209. case .sendGoAway(let close):
  210. context.fireChannelRead(self.wrapInboundOut(.closing(.initiatedLocally)))
  211. // The client could send a GOAWAY at this point but it's not really necessary, the server
  212. // can't open streams anyway, the client will just close the connection when it's done.
  213. if close {
  214. context.close(promise: nil)
  215. }
  216. case .none:
  217. ()
  218. }
  219. }
  220. } else {
  221. context.triggerUserOutboundEvent(event, promise: promise)
  222. }
  223. }
  224. }
  225. extension ClientConnectionHandler {
  226. struct LoopBoundView: @unchecked Sendable {
  227. private let handler: ClientConnectionHandler
  228. private let context: ChannelHandlerContext
  229. init(handler: ClientConnectionHandler, context: ChannelHandlerContext) {
  230. self.handler = handler
  231. self.context = context
  232. }
  233. func keepaliveTimerFired() {
  234. self.context.eventLoop.assertInEventLoop()
  235. self.handler.keepaliveTimerFired(context: self.context)
  236. }
  237. func keepaliveTimeoutExpired() {
  238. self.context.eventLoop.assertInEventLoop()
  239. self.handler.keepaliveTimeoutExpired(context: self.context)
  240. }
  241. func maxIdleTimerFired() {
  242. self.context.eventLoop.assertInEventLoop()
  243. self.handler.maxIdleTimerFired(context: self.context)
  244. }
  245. }
  246. }
  247. extension ClientConnectionHandler {
  248. package struct HTTP2StreamDelegate: @unchecked Sendable, NIOHTTP2StreamDelegate {
  249. // @unchecked is okay: the only methods do the appropriate event-loop dance.
  250. private let handler: ClientConnectionHandler
  251. init(_ handler: ClientConnectionHandler) {
  252. self.handler = handler
  253. }
  254. package func streamCreated(_ id: HTTP2StreamID, channel: any Channel) {
  255. if self.handler.eventLoop.inEventLoop {
  256. self.handler._streamCreated(id, channel: channel)
  257. } else {
  258. self.handler.eventLoop.execute {
  259. self.handler._streamCreated(id, channel: channel)
  260. }
  261. }
  262. }
  263. package func streamClosed(_ id: HTTP2StreamID, channel: any Channel) {
  264. if self.handler.eventLoop.inEventLoop {
  265. self.handler._streamClosed(id, channel: channel)
  266. } else {
  267. self.handler.eventLoop.execute {
  268. self.handler._streamClosed(id, channel: channel)
  269. }
  270. }
  271. }
  272. }
  273. package var http2StreamDelegate: HTTP2StreamDelegate {
  274. return HTTP2StreamDelegate(self)
  275. }
  276. private func _streamCreated(_ id: HTTP2StreamID, channel: any Channel) {
  277. self.eventLoop.assertInEventLoop()
  278. // Stream created, so the connection isn't idle.
  279. self.maxIdleTimer?.cancel()
  280. self.state.streamOpened(id)
  281. }
  282. private func _streamClosed(_ id: HTTP2StreamID, channel: any Channel) {
  283. guard let context = self.context else { return }
  284. self.eventLoop.assertInEventLoop()
  285. switch self.state.streamClosed(id) {
  286. case .startIdleTimer(let cancelKeepalive):
  287. // All streams are closed, restart the idle timer, and stop the keep-alive timer (it may
  288. // not stop if keep-alive is allowed when there are no active calls).
  289. let loopBound = LoopBoundView(handler: self, context: context)
  290. self.maxIdleTimer?.schedule(on: context.eventLoop) {
  291. loopBound.maxIdleTimerFired()
  292. }
  293. if cancelKeepalive {
  294. self.keepaliveTimer?.cancel()
  295. }
  296. case .close:
  297. // Connection was closing but waiting for all streams to close. They must all be closed
  298. // now so close the connection.
  299. context.close(promise: nil)
  300. case .none:
  301. ()
  302. }
  303. }
  304. }
  305. extension ClientConnectionHandler {
  306. private func maybeFlush(context: ChannelHandlerContext) {
  307. if self.inReadLoop {
  308. self.flushPending = true
  309. } else {
  310. context.flush()
  311. }
  312. }
  313. private func keepaliveTimerFired(context: ChannelHandlerContext) {
  314. guard self.state.sendKeepalivePing() else { return }
  315. // Cancel the keep alive timer when the client sends a ping. The timer is resumed when the ping
  316. // is acknowledged.
  317. self.keepaliveTimer?.cancel()
  318. let ping = HTTP2Frame(streamID: .rootStream, payload: .ping(self.keepalivePingData, ack: false))
  319. context.write(self.wrapOutboundOut(ping), promise: nil)
  320. self.maybeFlush(context: context)
  321. // Schedule a timeout on waiting for the response.
  322. let loopBound = LoopBoundView(handler: self, context: context)
  323. self.keepaliveTimeoutTimer.schedule(on: context.eventLoop) {
  324. loopBound.keepaliveTimeoutExpired()
  325. }
  326. }
  327. private func keepaliveTimeoutExpired(context: ChannelHandlerContext) {
  328. guard self.state.beginClosing() else { return }
  329. context.fireChannelRead(self.wrapInboundOut(.closing(.keepaliveExpired)))
  330. self.writeAndFlushGoAway(context: context, message: "keepalive_expired")
  331. context.close(promise: nil)
  332. }
  333. private func maxIdleTimerFired(context: ChannelHandlerContext) {
  334. guard self.state.beginClosing() else { return }
  335. context.fireChannelRead(self.wrapInboundOut(.closing(.idle)))
  336. self.writeAndFlushGoAway(context: context, message: "idle")
  337. context.close(promise: nil)
  338. }
  339. private func writeAndFlushGoAway(
  340. context: ChannelHandlerContext,
  341. errorCode: HTTP2ErrorCode = .noError,
  342. message: String? = nil
  343. ) {
  344. let goAway = HTTP2Frame(
  345. streamID: .rootStream,
  346. payload: .goAway(
  347. lastStreamID: 0,
  348. errorCode: errorCode,
  349. opaqueData: message.map { context.channel.allocator.buffer(string: $0) }
  350. )
  351. )
  352. context.write(self.wrapOutboundOut(goAway), promise: nil)
  353. self.maybeFlush(context: context)
  354. }
  355. }
  356. extension ClientConnectionHandler {
  357. struct StateMachine {
  358. private var state: State
  359. private enum State {
  360. case active(Active)
  361. case closing(Closing)
  362. case closed
  363. struct Active {
  364. var openStreams: Set<HTTP2StreamID>
  365. var allowKeepaliveWithoutCalls: Bool
  366. var receivedConnectionPreface: Bool
  367. var error: (any Error)?
  368. init(allowKeepaliveWithoutCalls: Bool) {
  369. self.openStreams = []
  370. self.allowKeepaliveWithoutCalls = allowKeepaliveWithoutCalls
  371. self.receivedConnectionPreface = false
  372. self.error = nil
  373. }
  374. mutating func receivedSettings() -> Bool {
  375. let isFirstSettingsFrame = !self.receivedConnectionPreface
  376. self.receivedConnectionPreface = true
  377. return isFirstSettingsFrame
  378. }
  379. }
  380. struct Closing {
  381. var allowKeepaliveWithoutCalls: Bool
  382. var openStreams: Set<HTTP2StreamID>
  383. var closePromise: Optional<EventLoopPromise<Void>>
  384. init(from state: Active, closePromise: EventLoopPromise<Void>?) {
  385. self.openStreams = state.openStreams
  386. self.allowKeepaliveWithoutCalls = state.allowKeepaliveWithoutCalls
  387. self.closePromise = closePromise
  388. }
  389. }
  390. }
  391. init(allowKeepaliveWithoutCalls: Bool) {
  392. self.state = .active(State.Active(allowKeepaliveWithoutCalls: allowKeepaliveWithoutCalls))
  393. }
  394. /// Record that a SETTINGS frame was received from the remote peer.
  395. ///
  396. /// - Returns: `true` if this was the first SETTINGS frame received.
  397. mutating func receivedSettings() -> Bool {
  398. switch self.state {
  399. case .active(var active):
  400. let isFirstSettingsFrame = active.receivedSettings()
  401. self.state = .active(active)
  402. return isFirstSettingsFrame
  403. case .closing, .closed:
  404. return false
  405. }
  406. }
  407. /// Record that an error was received.
  408. mutating func receivedError(_ error: any Error) {
  409. switch self.state {
  410. case .active(var active):
  411. active.error = error
  412. self.state = .active(active)
  413. case .closing, .closed:
  414. ()
  415. }
  416. }
  417. /// Record that the stream with the given ID has been opened.
  418. mutating func streamOpened(_ id: HTTP2StreamID) {
  419. switch self.state {
  420. case .active(var state):
  421. let (inserted, _) = state.openStreams.insert(id)
  422. assert(inserted, "Can't open stream \(Int(id)), it's already open")
  423. self.state = .active(state)
  424. case .closing(var state):
  425. let (inserted, _) = state.openStreams.insert(id)
  426. assert(inserted, "Can't open stream \(Int(id)), it's already open")
  427. self.state = .closing(state)
  428. case .closed:
  429. ()
  430. }
  431. }
  432. enum OnStreamClosed: Equatable {
  433. /// Start the idle timer, after which the connection should be closed gracefully.
  434. case startIdleTimer(cancelKeepalive: Bool)
  435. /// Close the connection.
  436. case close
  437. /// Do nothing.
  438. case none
  439. }
  440. /// Record that the stream with the given ID has been closed.
  441. mutating func streamClosed(_ id: HTTP2StreamID) -> OnStreamClosed {
  442. let onStreamClosed: OnStreamClosed
  443. switch self.state {
  444. case .active(var state):
  445. let removedID = state.openStreams.remove(id)
  446. assert(removedID != nil, "Can't close stream \(Int(id)), it wasn't open")
  447. if state.openStreams.isEmpty {
  448. onStreamClosed = .startIdleTimer(cancelKeepalive: !state.allowKeepaliveWithoutCalls)
  449. } else {
  450. onStreamClosed = .none
  451. }
  452. self.state = .active(state)
  453. case .closing(var state):
  454. let removedID = state.openStreams.remove(id)
  455. assert(removedID != nil, "Can't close stream \(Int(id)), it wasn't open")
  456. onStreamClosed = state.openStreams.isEmpty ? .close : .none
  457. self.state = .closing(state)
  458. case .closed:
  459. onStreamClosed = .none
  460. }
  461. return onStreamClosed
  462. }
  463. /// Returns whether a keep alive ping should be sent to the server.
  464. mutating func sendKeepalivePing() -> Bool {
  465. let sendKeepalivePing: Bool
  466. // Only send a ping if there are open streams or there are no open streams and keep alive
  467. // is permitted when there are no active calls.
  468. switch self.state {
  469. case .active(let state):
  470. sendKeepalivePing = !state.openStreams.isEmpty || state.allowKeepaliveWithoutCalls
  471. case .closing(let state):
  472. sendKeepalivePing = !state.openStreams.isEmpty || state.allowKeepaliveWithoutCalls
  473. case .closed:
  474. sendKeepalivePing = false
  475. }
  476. return sendKeepalivePing
  477. }
  478. enum OnGracefulShutDown: Equatable {
  479. case sendGoAway(Bool)
  480. case none
  481. }
  482. mutating func beginGracefulShutdown(promise: EventLoopPromise<Void>?) -> OnGracefulShutDown {
  483. let onGracefulShutdown: OnGracefulShutDown
  484. switch self.state {
  485. case .active(let state):
  486. // Only close immediately if there are no open streams. The client doesn't need to
  487. // ratchet down the last stream ID as only the client creates streams in gRPC.
  488. let close = state.openStreams.isEmpty
  489. onGracefulShutdown = .sendGoAway(close)
  490. self.state = .closing(State.Closing(from: state, closePromise: promise))
  491. case .closing(var state):
  492. state.closePromise.setOrCascade(to: promise)
  493. self.state = .closing(state)
  494. onGracefulShutdown = .none
  495. case .closed:
  496. onGracefulShutdown = .none
  497. }
  498. return onGracefulShutdown
  499. }
  500. /// Returns whether the connection should be closed.
  501. mutating func beginClosing() -> Bool {
  502. switch self.state {
  503. case .active(let active):
  504. self.state = .closing(State.Closing(from: active, closePromise: nil))
  505. return true
  506. case .closing, .closed:
  507. return false
  508. }
  509. }
  510. enum OnClosed {
  511. case succeed(EventLoopPromise<Void>)
  512. case unexpectedClose((any Error)?, isIdle: Bool)
  513. case none
  514. }
  515. /// Marks the state as closed.
  516. mutating func closed() -> OnClosed {
  517. switch self.state {
  518. case .active(let state):
  519. self.state = .closed
  520. return .unexpectedClose(state.error, isIdle: state.openStreams.isEmpty)
  521. case .closing(let closing):
  522. self.state = .closed
  523. return closing.closePromise.map { .succeed($0) } ?? .none
  524. case .closed:
  525. self.state = .closed
  526. return .none
  527. }
  528. }
  529. }
  530. }