ClientConnectionHandler.swift 17 KB

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