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