2
0

GRPCIdleHandlerStateMachine.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. /*
  2. * Copyright 2020, 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 Logging
  17. import NIOCore
  18. import NIOHTTP2
  19. /// Holds state for the 'GRPCIdleHandler', this isn't really just the idleness of the connection,
  20. /// it also holds state relevant to quiescing the connection as well as logging some HTTP/2 specific
  21. /// information (like stream creation/close events and changes to settings which can be useful when
  22. /// debugging live systems). Much of this information around the connection state is also used to
  23. /// inform the client connection manager since that's strongly tied to various channel and HTTP/2
  24. /// events.
  25. struct GRPCIdleHandlerStateMachine {
  26. /// Our role in the connection.
  27. enum Role {
  28. case server
  29. case client
  30. }
  31. /// The 'operating' state of the connection. This is the primary state we expect to be in: the
  32. /// connection is up and running and there are expected to be active RPCs, although this is by no
  33. /// means a requirement. Some of the situations in which there may be no active RPCs are:
  34. ///
  35. /// 1. Before the connection is 'ready' (that is, seen the first SETTINGS frame),
  36. /// 2. After the connection has dropped to zero active streams and before the idle timeout task
  37. /// has been scheduled.
  38. /// 3. When the connection has zero active streams and the connection was configured without an
  39. /// idle timeout.
  40. fileprivate struct Operating: CanOpenStreams, CanCloseStreams {
  41. /// Our role in the connection.
  42. var role: Role
  43. /// The number of open stream.
  44. var openStreams: Int
  45. /// The last stream ID initiated by the remote peer.
  46. var lastPeerInitiatedStreamID: HTTP2StreamID
  47. /// The maximum number of concurrent streams we are allowed to operate.
  48. var maxConcurrentStreams: Int
  49. /// We keep track of whether we've seen a SETTINGS frame. We expect to see one after the
  50. /// connection preface (RFC 7540 § 3.5). This is primarily for the benefit of the client which
  51. /// determines a connection to be 'ready' once it has seen the first SETTINGS frame. We also
  52. /// won't set an idle timeout until this becomes true.
  53. var hasSeenSettings: Bool
  54. fileprivate init(role: Role) {
  55. self.role = role
  56. self.openStreams = 0
  57. self.lastPeerInitiatedStreamID = .rootStream
  58. // Assumed until we know better.
  59. self.maxConcurrentStreams = 100
  60. self.hasSeenSettings = false
  61. }
  62. fileprivate init(fromWaitingToIdle state: WaitingToIdle) {
  63. self.role = state.role
  64. self.openStreams = 0
  65. self.lastPeerInitiatedStreamID = state.lastPeerInitiatedStreamID
  66. self.maxConcurrentStreams = state.maxConcurrentStreams
  67. // We won't transition to 'WaitingToIdle' unless we've seen a SETTINGS frame.
  68. self.hasSeenSettings = true
  69. }
  70. }
  71. /// The waiting-to-idle state is used when the connection has become 'ready', has no active
  72. /// RPCs and an idle timeout task has been scheduled. In this state, the connection will be closed
  73. /// once the idle is fired. The task will be cancelled on the creation of a stream.
  74. fileprivate struct WaitingToIdle {
  75. /// Our role in the connection.
  76. var role: Role
  77. /// The last stream ID initiated by the remote peer.
  78. var lastPeerInitiatedStreamID: HTTP2StreamID
  79. /// The maximum number of concurrent streams we are allowed to operate.
  80. var maxConcurrentStreams: Int
  81. /// A task which, when fired, will idle the connection.
  82. var idleTask: Scheduled<Void>
  83. fileprivate init(fromOperating state: Operating, idleTask: Scheduled<Void>) {
  84. // We won't transition to this state unless we've seen a SETTINGS frame.
  85. assert(state.hasSeenSettings)
  86. self.role = state.role
  87. self.lastPeerInitiatedStreamID = state.lastPeerInitiatedStreamID
  88. self.maxConcurrentStreams = state.maxConcurrentStreams
  89. self.idleTask = idleTask
  90. }
  91. }
  92. /// The quiescing state is entered only from the operating state. It may be entered if we receive
  93. /// a GOAWAY frame (the remote peer initiated the quiescing) or we initiate graceful shutdown
  94. /// locally.
  95. fileprivate struct Quiescing: TracksOpenStreams, CanCloseStreams {
  96. /// Our role in the connection.
  97. var role: Role
  98. /// The number of open stream.
  99. var openStreams: Int
  100. /// The last stream ID initiated by the remote peer.
  101. var lastPeerInitiatedStreamID: HTTP2StreamID
  102. /// The maximum number of concurrent streams we are allowed to operate.
  103. var maxConcurrentStreams: Int
  104. /// Whether this peer initiated shutting down.
  105. var initiatedByUs: Bool
  106. fileprivate init(fromOperating state: Operating, initiatedByUs: Bool) {
  107. // If we didn't initiate shutdown, the remote peer must have done so by sending a GOAWAY frame
  108. // in which case we must have seen a SETTINGS frame.
  109. assert(initiatedByUs || state.hasSeenSettings)
  110. self.role = state.role
  111. self.initiatedByUs = initiatedByUs
  112. self.openStreams = state.openStreams
  113. self.lastPeerInitiatedStreamID = state.lastPeerInitiatedStreamID
  114. self.maxConcurrentStreams = state.maxConcurrentStreams
  115. }
  116. }
  117. /// The closing state is entered when one of the previous states initiates a connection closure.
  118. /// From this state the only possible transition is to the closed state.
  119. fileprivate struct Closing {
  120. /// Our role in the connection.
  121. var role: Role
  122. /// Should the client connection manager receive an idle event when we close? (If not then it
  123. /// will attempt to establish a new connection immediately.)
  124. var shouldIdle: Bool
  125. fileprivate init(fromOperating state: Operating) {
  126. self.role = state.role
  127. // Idle if there are no open streams and we've seen the first SETTINGS frame.
  128. self.shouldIdle = !state.hasOpenStreams && state.hasSeenSettings
  129. }
  130. fileprivate init(fromQuiescing state: Quiescing) {
  131. self.role = state.role
  132. // If we initiated the quiescing then we shouldn't go idle (we want to shutdown instead).
  133. self.shouldIdle = !state.initiatedByUs
  134. }
  135. fileprivate init(fromWaitingToIdle state: WaitingToIdle, shouldIdle: Bool = true) {
  136. self.role = state.role
  137. self.shouldIdle = shouldIdle
  138. }
  139. }
  140. fileprivate enum State {
  141. case operating(Operating)
  142. case waitingToIdle(WaitingToIdle)
  143. case quiescing(Quiescing)
  144. case closing(Closing)
  145. case closed
  146. }
  147. /// The set of operations that should be performed as a result of interaction with the state
  148. /// machine.
  149. struct Operations {
  150. /// An event to notify the connection manager about.
  151. private(set) var connectionManagerEvent: ConnectionManagerEvent?
  152. /// The value of HTTP/2 SETTINGS_MAX_CONCURRENT_STREAMS changed.
  153. private(set) var maxConcurrentStreamsChange: Int?
  154. /// An idle task, either scheduling or cancelling an idle timeout.
  155. private(set) var idleTask: IdleTask?
  156. /// Send a GOAWAY frame with the last peer initiated stream ID set to this value.
  157. private(set) var sendGoAwayWithLastPeerInitiatedStreamID: HTTP2StreamID?
  158. /// Whether the channel should be closed.
  159. private(set) var shouldCloseChannel: Bool
  160. fileprivate static let none = Operations()
  161. fileprivate mutating func sendGoAwayFrame(lastPeerInitiatedStreamID streamID: HTTP2StreamID) {
  162. self.sendGoAwayWithLastPeerInitiatedStreamID = streamID
  163. }
  164. fileprivate mutating func cancelIdleTask(_ task: Scheduled<Void>) {
  165. self.idleTask = .cancel(task)
  166. }
  167. fileprivate mutating func scheduleIdleTask() {
  168. self.idleTask = .schedule
  169. }
  170. fileprivate mutating func closeChannel() {
  171. self.shouldCloseChannel = true
  172. }
  173. fileprivate mutating func notifyConnectionManager(about event: ConnectionManagerEvent) {
  174. self.connectionManagerEvent = event
  175. }
  176. fileprivate mutating func maxConcurrentStreamsChanged(_ newValue: Int) {
  177. self.maxConcurrentStreamsChange = newValue
  178. }
  179. private init() {
  180. self.connectionManagerEvent = nil
  181. self.idleTask = nil
  182. self.sendGoAwayWithLastPeerInitiatedStreamID = nil
  183. self.shouldCloseChannel = false
  184. }
  185. }
  186. /// An event to notify the 'ConnectionManager' about.
  187. enum ConnectionManagerEvent {
  188. case inactive
  189. case idle
  190. case ready
  191. case quiescing
  192. }
  193. enum IdleTask {
  194. case schedule
  195. case cancel(Scheduled<Void>)
  196. }
  197. /// The current state.
  198. private var state: State
  199. /// A logger.
  200. internal var logger: Logger
  201. /// Create a new state machine.
  202. init(role: Role, logger: Logger) {
  203. self.state = .operating(.init(role: role))
  204. self.logger = logger
  205. }
  206. // MARK: Stream Events
  207. /// An HTTP/2 stream was created.
  208. mutating func streamCreated(withID streamID: HTTP2StreamID) -> Operations {
  209. var operations: Operations = .none
  210. switch self.state {
  211. case var .operating(state):
  212. // Create the stream.
  213. state.streamCreated(streamID, logger: self.logger)
  214. self.state = .operating(state)
  215. case let .waitingToIdle(state):
  216. var operating = Operating(fromWaitingToIdle: state)
  217. operating.streamCreated(streamID, logger: self.logger)
  218. self.state = .operating(operating)
  219. operations.cancelIdleTask(state.idleTask)
  220. case var .quiescing(state):
  221. precondition(state.initiatedByUs)
  222. precondition(state.role == .client)
  223. // If we're a client and we initiated shutdown then it's possible for streams to be created in
  224. // the quiescing state as there's a delay between stream channels (i.e. `HTTP2StreamChannel`)
  225. // being created and us being notified about their creation (via a user event fired by
  226. // the `HTTP2Handler`).
  227. state.openStreams += 1
  228. self.state = .quiescing(state)
  229. case .closing, .closed:
  230. ()
  231. }
  232. return operations
  233. }
  234. /// An HTTP/2 stream was closed.
  235. mutating func streamClosed(withID streamID: HTTP2StreamID) -> Operations {
  236. var operations: Operations = .none
  237. switch self.state {
  238. case var .operating(state):
  239. state.streamClosed(streamID, logger: self.logger)
  240. if state.hasSeenSettings, !state.hasOpenStreams {
  241. operations.scheduleIdleTask()
  242. }
  243. self.state = .operating(state)
  244. case .waitingToIdle:
  245. // If we're waiting to idle then there can't be any streams open which can be closed.
  246. preconditionFailure()
  247. case var .quiescing(state):
  248. state.streamClosed(streamID, logger: self.logger)
  249. if state.hasOpenStreams {
  250. self.state = .quiescing(state)
  251. } else {
  252. self.state = .closing(.init(fromQuiescing: state))
  253. operations.sendGoAwayFrame(lastPeerInitiatedStreamID: state.lastPeerInitiatedStreamID)
  254. operations.closeChannel()
  255. }
  256. case .closing, .closed:
  257. ()
  258. }
  259. return operations
  260. }
  261. // MARK: - Idle Events
  262. /// The given task was scheduled to idle the connection.
  263. mutating func scheduledIdleTimeoutTask(_ task: Scheduled<Void>) -> Operations {
  264. var operations: Operations = .none
  265. switch self.state {
  266. case let .operating(state):
  267. if state.hasOpenStreams {
  268. operations.cancelIdleTask(task)
  269. } else {
  270. self.state = .waitingToIdle(.init(fromOperating: state, idleTask: task))
  271. }
  272. case .waitingToIdle:
  273. // There's already an idle task.
  274. preconditionFailure()
  275. case .quiescing, .closing, .closed:
  276. operations.cancelIdleTask(task)
  277. }
  278. return operations
  279. }
  280. /// The idle timeout task fired, the connection should be idled.
  281. mutating func idleTimeoutTaskFired() -> Operations {
  282. var operations: Operations = .none
  283. switch self.state {
  284. case let .waitingToIdle(state):
  285. self.state = .closing(.init(fromWaitingToIdle: state))
  286. operations.sendGoAwayFrame(lastPeerInitiatedStreamID: state.lastPeerInitiatedStreamID)
  287. operations.closeChannel()
  288. // We're either operating on streams, streams are going away, or the connection is going away
  289. // so we don't need to idle the connection.
  290. case .operating, .quiescing, .closing, .closed:
  291. ()
  292. }
  293. return operations
  294. }
  295. // MARK: - Shutdown Events
  296. /// Close the connection, this can be caused as a result of a keepalive timeout (i.e. the server
  297. /// has become unresponsive), we'll bin this connection as a result.
  298. mutating func shutdownNow() -> Operations {
  299. var operations = Operations.none
  300. switch self.state {
  301. case let .operating(state):
  302. var closing = Closing(fromOperating: state)
  303. closing.shouldIdle = false
  304. self.state = .closing(closing)
  305. operations.closeChannel()
  306. operations.sendGoAwayFrame(lastPeerInitiatedStreamID: state.lastPeerInitiatedStreamID)
  307. case let .waitingToIdle(state):
  308. // Don't idle.
  309. self.state = .closing(Closing(fromWaitingToIdle: state, shouldIdle: false))
  310. operations.closeChannel()
  311. operations.sendGoAwayFrame(lastPeerInitiatedStreamID: state.lastPeerInitiatedStreamID)
  312. operations.cancelIdleTask(state.idleTask)
  313. case let .quiescing(state):
  314. self.state = .closing(Closing(fromQuiescing: state))
  315. // We've already sent a GOAWAY frame if we're in this state, just close.
  316. operations.closeChannel()
  317. case .closing, .closed:
  318. ()
  319. }
  320. return operations
  321. }
  322. /// Initiate a graceful shutdown of this connection, that is, begin quiescing.
  323. mutating func initiateGracefulShutdown() -> Operations {
  324. var operations: Operations = .none
  325. switch self.state {
  326. case let .operating(state):
  327. if state.hasOpenStreams {
  328. // There are open streams: send a GOAWAY frame and wait for the stream count to reach zero.
  329. //
  330. // It's okay if we haven't seen a SETTINGS frame at this point; we've initiated the shutdown
  331. // so making a connection is ready isn't necessary.
  332. operations.notifyConnectionManager(about: .quiescing)
  333. // TODO: we should ratchet down the last initiated stream after 1-RTT.
  334. //
  335. // As a client we will just stop initiating streams.
  336. if state.role == .server {
  337. operations.sendGoAwayFrame(lastPeerInitiatedStreamID: state.lastPeerInitiatedStreamID)
  338. }
  339. self.state = .quiescing(.init(fromOperating: state, initiatedByUs: true))
  340. } else {
  341. // No open streams: send a GOAWAY frame and close the channel.
  342. self.state = .closing(.init(fromOperating: state))
  343. operations.sendGoAwayFrame(lastPeerInitiatedStreamID: state.lastPeerInitiatedStreamID)
  344. operations.closeChannel()
  345. }
  346. case let .waitingToIdle(state):
  347. // There can't be any open streams, but we have a few loose ends to clear up: we need to
  348. // cancel the idle timeout, send a GOAWAY frame and then close. We don't want to idle from the
  349. // closing state: we want to shutdown instead.
  350. self.state = .closing(.init(fromWaitingToIdle: state, shouldIdle: false))
  351. operations.cancelIdleTask(state.idleTask)
  352. operations.sendGoAwayFrame(lastPeerInitiatedStreamID: state.lastPeerInitiatedStreamID)
  353. operations.closeChannel()
  354. case var .quiescing(state):
  355. // We're already quiescing: either the remote initiated it or we're initiating it more than
  356. // once. Set ourselves as the initiator to ensure we don't idle when we eventually close, this
  357. // is important for the client: if the server initiated this then we establish a new
  358. // connection when we close, unless we also initiated shutdown.
  359. state.initiatedByUs = true
  360. self.state = .quiescing(state)
  361. case var .closing(state):
  362. // We've already called 'close()', make sure we don't go idle.
  363. state.shouldIdle = false
  364. self.state = .closing(state)
  365. case .closed:
  366. ()
  367. }
  368. return operations
  369. }
  370. /// We've received a GOAWAY frame from the remote peer. Either the remote peer wants to close the
  371. /// connection or they're responding to us shutting down the connection.
  372. mutating func receiveGoAway() -> Operations {
  373. var operations: Operations = .none
  374. switch self.state {
  375. case let .operating(state):
  376. // A SETTINGS frame MUST follow the connection preface. (RFC 7540 § 3.5)
  377. assert(state.hasSeenSettings)
  378. if state.hasOpenStreams {
  379. operations.notifyConnectionManager(about: .quiescing)
  380. self.state = .quiescing(.init(fromOperating: state, initiatedByUs: false))
  381. } else {
  382. // No open streams, we can close as well.
  383. self.state = .closing(.init(fromOperating: state))
  384. operations.sendGoAwayFrame(lastPeerInitiatedStreamID: state.lastPeerInitiatedStreamID)
  385. operations.closeChannel()
  386. }
  387. case let .waitingToIdle(state):
  388. // There can't be any open streams, but we have a few loose ends to clear up: we need to
  389. // cancel the idle timeout, send a GOAWAY frame and then close.
  390. self.state = .closing(.init(fromWaitingToIdle: state))
  391. operations.cancelIdleTask(state.idleTask)
  392. operations.sendGoAwayFrame(lastPeerInitiatedStreamID: state.lastPeerInitiatedStreamID)
  393. operations.closeChannel()
  394. case .quiescing:
  395. // We're already quiescing, this changes nothing.
  396. ()
  397. case .closing, .closed:
  398. // We're already closing/closed (so must have emitted a GOAWAY frame already). Ignore this.
  399. ()
  400. }
  401. return operations
  402. }
  403. mutating func receiveSettings(_ settings: HTTP2Settings) -> Operations {
  404. // Log the change in settings.
  405. self.logger.debug(
  406. "HTTP2 settings update",
  407. metadata: Dictionary(settings.map {
  408. ("\($0.parameter.loggingMetadataKey)", "\($0.value)")
  409. }, uniquingKeysWith: { a, _ in a })
  410. )
  411. var operations: Operations = .none
  412. switch self.state {
  413. case var .operating(state):
  414. let hasSeenSettingsPreviously = state.hasSeenSettings
  415. // If we hadn't previously seen settings then we need to notify the client connection manager
  416. // that we're now ready.
  417. if !hasSeenSettingsPreviously {
  418. operations.notifyConnectionManager(about: .ready)
  419. state.hasSeenSettings = true
  420. // Now that we know the connection is ready, we may want to start an idle timeout as well.
  421. if !state.hasOpenStreams {
  422. operations.scheduleIdleTask()
  423. }
  424. }
  425. // Update max concurrent streams.
  426. if let maxStreams = settings.last(where: { $0.parameter == .maxConcurrentStreams })?.value {
  427. operations.maxConcurrentStreamsChanged(maxStreams)
  428. state.maxConcurrentStreams = maxStreams
  429. } else if !hasSeenSettingsPreviously {
  430. // We hadn't seen settings before now and max concurrent streams wasn't set we should assume
  431. // the default and emit an update.
  432. operations.maxConcurrentStreamsChanged(100)
  433. state.maxConcurrentStreams = 100
  434. }
  435. self.state = .operating(state)
  436. case var .waitingToIdle(state):
  437. // Update max concurrent streams.
  438. if let maxStreams = settings.last(where: { $0.parameter == .maxConcurrentStreams })?.value {
  439. operations.maxConcurrentStreamsChanged(maxStreams)
  440. state.maxConcurrentStreams = maxStreams
  441. }
  442. self.state = .waitingToIdle(state)
  443. case .quiescing, .closing, .closed:
  444. ()
  445. }
  446. return operations
  447. }
  448. // MARK: - Channel Events
  449. // (Other channel events aren't included here as they don't impact the state machine.)
  450. /// 'channelActive' was called in the idle handler holding this state machine.
  451. mutating func channelInactive() -> Operations {
  452. var operations: Operations = .none
  453. switch self.state {
  454. case let .operating(state):
  455. self.state = .closed
  456. // We unexpectedly became inactive.
  457. if !state.hasSeenSettings || state.hasOpenStreams {
  458. // Haven't seen settings, or we've seen settings and there are open streams.
  459. operations.notifyConnectionManager(about: .inactive)
  460. } else {
  461. // Have seen settings and there are no open streams.
  462. operations.notifyConnectionManager(about: .idle)
  463. }
  464. case let .waitingToIdle(state):
  465. self.state = .closed
  466. // We were going to idle anyway.
  467. operations.notifyConnectionManager(about: .idle)
  468. operations.cancelIdleTask(state.idleTask)
  469. case let .quiescing(state):
  470. self.state = .closed
  471. if state.initiatedByUs || state.hasOpenStreams {
  472. operations.notifyConnectionManager(about: .inactive)
  473. } else {
  474. operations.notifyConnectionManager(about: .idle)
  475. }
  476. case let .closing(state):
  477. self.state = .closed
  478. if state.shouldIdle {
  479. operations.notifyConnectionManager(about: .idle)
  480. } else {
  481. operations.notifyConnectionManager(about: .inactive)
  482. }
  483. case .closed:
  484. ()
  485. }
  486. return operations
  487. }
  488. }
  489. // MARK: - Helper Protocols
  490. private protocol TracksOpenStreams {
  491. /// The number of open streams.
  492. var openStreams: Int { get set }
  493. }
  494. extension TracksOpenStreams {
  495. /// Whether any streams are open.
  496. fileprivate var hasOpenStreams: Bool {
  497. return self.openStreams != 0
  498. }
  499. }
  500. private protocol CanOpenStreams: TracksOpenStreams {
  501. /// The role of this peer in the connection.
  502. var role: GRPCIdleHandlerStateMachine.Role { get }
  503. /// The ID of the stream most recently initiated by the remote peer.
  504. var lastPeerInitiatedStreamID: HTTP2StreamID { get set }
  505. /// The maximum number of concurrent streams.
  506. var maxConcurrentStreams: Int { get set }
  507. mutating func streamCreated(_ streamID: HTTP2StreamID, logger: Logger)
  508. }
  509. extension CanOpenStreams {
  510. fileprivate mutating func streamCreated(_ streamID: HTTP2StreamID, logger: Logger) {
  511. self.openStreams += 1
  512. switch self.role {
  513. case .client where streamID.isServerInitiated:
  514. self.lastPeerInitiatedStreamID = streamID
  515. case .server where streamID.isClientInitiated:
  516. self.lastPeerInitiatedStreamID = streamID
  517. default:
  518. ()
  519. }
  520. logger.debug("HTTP2 stream created", metadata: [
  521. MetadataKey.h2StreamID: "\(streamID)",
  522. MetadataKey.h2ActiveStreams: "\(self.openStreams)",
  523. ])
  524. if self.openStreams == self.maxConcurrentStreams {
  525. logger.warning("HTTP2 max concurrent stream limit reached", metadata: [
  526. MetadataKey.h2ActiveStreams: "\(self.openStreams)",
  527. ])
  528. }
  529. }
  530. }
  531. private protocol CanCloseStreams: TracksOpenStreams {
  532. /// Notes that a stream has closed.
  533. mutating func streamClosed(_ streamID: HTTP2StreamID, logger: Logger)
  534. }
  535. extension CanCloseStreams {
  536. fileprivate mutating func streamClosed(_ streamID: HTTP2StreamID, logger: Logger) {
  537. self.openStreams -= 1
  538. logger.debug("HTTP2 stream closed", metadata: [
  539. MetadataKey.h2StreamID: "\(streamID)",
  540. MetadataKey.h2ActiveStreams: "\(self.openStreams)",
  541. ])
  542. }
  543. }