ClientConnectivityHandler.swift 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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 NIO
  17. import NIOHTTP2
  18. internal class ClientConnectivityHandler: ChannelInboundHandler {
  19. typealias InboundIn = HTTP2Frame
  20. private var connectionManager: ConnectionManager
  21. private let idleTimeout: TimeAmount
  22. private var activeStreams = 0
  23. private var scheduledIdle: Scheduled<Void>? = nil
  24. private var state: State = .notReady
  25. private enum State {
  26. // We haven't marked the connection as "ready" yet.
  27. case notReady
  28. // The connection has been marked as "ready".
  29. case ready
  30. // We called `close` on the channel.
  31. case closed
  32. }
  33. init(connectionManager: ConnectionManager, idleTimeout: TimeAmount = .minutes(5)) {
  34. self.connectionManager = connectionManager
  35. self.idleTimeout = idleTimeout
  36. }
  37. func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
  38. switch self.state {
  39. case .notReady, .ready:
  40. if event is NIOHTTP2StreamCreatedEvent {
  41. // We have a stream: don't go idle
  42. self.scheduledIdle?.cancel()
  43. self.scheduledIdle = nil
  44. self.activeStreams += 1
  45. } else if event is StreamClosedEvent {
  46. self.activeStreams -= 1
  47. // No active streams: go idle soon.
  48. if self.activeStreams == 0 {
  49. self.scheduleIdleTimeout(context: context)
  50. }
  51. }
  52. case .closed:
  53. ()
  54. }
  55. context.fireUserInboundEventTriggered(event)
  56. }
  57. func channelActive(context: ChannelHandlerContext) {
  58. switch self.state {
  59. case .notReady:
  60. self.connectionManager.channelActive(channel: context.channel)
  61. case .ready, .closed:
  62. ()
  63. }
  64. context.fireChannelActive()
  65. }
  66. func channelInactive(context: ChannelHandlerContext) {
  67. self.scheduledIdle?.cancel()
  68. self.scheduledIdle = nil
  69. switch self.state {
  70. case .notReady, .ready:
  71. self.connectionManager.channelInactive()
  72. case .closed:
  73. ()
  74. }
  75. context.fireChannelInactive()
  76. }
  77. func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  78. let frame = self.unwrapInboundIn(data)
  79. if frame.streamID == .rootStream {
  80. switch (self.state, frame.payload) {
  81. // We only care about SETTINGS as long as we are in state `.notReady`.
  82. case (.notReady, .settings):
  83. self.state = .ready
  84. let remoteAddressDescription = context.channel.remoteAddress.map { "\($0)" } ?? "n/a"
  85. self.connectionManager.logger.info("gRPC connection ready", metadata: [
  86. "remote_address": "\(remoteAddressDescription)",
  87. "event_loop": "\(context.eventLoop)"
  88. ])
  89. // Start the idle timeout.
  90. self.scheduleIdleTimeout(context: context)
  91. // Let the manager know we're ready.
  92. self.connectionManager.ready()
  93. case (.notReady, .goAway),
  94. (.ready, .goAway):
  95. self.idle(context: context)
  96. default:
  97. ()
  98. }
  99. }
  100. context.fireChannelRead(data)
  101. }
  102. private func scheduleIdleTimeout(context: ChannelHandlerContext) {
  103. guard self.activeStreams == 0 else {
  104. return
  105. }
  106. self.scheduledIdle = context.eventLoop.scheduleTask(in: self.idleTimeout) {
  107. self.idle(context: context)
  108. }
  109. }
  110. private func idle(context: ChannelHandlerContext) {
  111. guard self.activeStreams == 0 else {
  112. return
  113. }
  114. self.state = .closed
  115. self.connectionManager.idle()
  116. context.close(mode: .all, promise: nil)
  117. }
  118. }