GRPCIdleHandler.swift 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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 GRPCIdleHandler: ChannelInboundHandler {
  19. typealias InboundIn = HTTP2Frame
  20. /// The amount of time to wait before closing the channel when there are no active streams.
  21. private let idleTimeout: TimeAmount
  22. /// The number of active streams.
  23. private var activeStreams = 0
  24. /// The scheduled task which will close the channel.
  25. private var scheduledIdle: Scheduled<Void>? = nil
  26. /// Client and server have slightly different behaviours; track which we are following.
  27. private var mode: Mode
  28. /// The mode of operation: the client tracks additional connection state in the connection
  29. /// manager.
  30. internal enum Mode {
  31. case client(ConnectionManager)
  32. case server
  33. }
  34. /// The current connection state.
  35. private var state: State = .notReady
  36. private enum State {
  37. // We haven't marked the connection as "ready" yet.
  38. case notReady
  39. // The connection has been marked as "ready".
  40. case ready
  41. // We called `close` on the channel.
  42. case closed
  43. }
  44. init(mode: Mode, idleTimeout: TimeAmount = .minutes(5)) {
  45. self.mode = mode
  46. self.idleTimeout = idleTimeout
  47. }
  48. func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
  49. switch self.state {
  50. case .notReady, .ready:
  51. if event is NIOHTTP2StreamCreatedEvent {
  52. // We have a stream: don't go idle
  53. self.scheduledIdle?.cancel()
  54. self.scheduledIdle = nil
  55. self.activeStreams += 1
  56. } else if event is StreamClosedEvent {
  57. self.activeStreams -= 1
  58. // No active streams: go idle soon.
  59. if self.activeStreams == 0 {
  60. self.scheduleIdleTimeout(context: context)
  61. }
  62. } else if event is ConnectionIdledEvent {
  63. // Force idle (closing) because we received a `ConnectionIdledEvent` from a keepalive handler
  64. self.idle(context: context, force: true)
  65. }
  66. case .closed:
  67. ()
  68. }
  69. context.fireUserInboundEventTriggered(event)
  70. }
  71. func channelActive(context: ChannelHandlerContext) {
  72. switch (self.mode, self.state) {
  73. // The client should become active: we'll only schedule the idling when the channel
  74. // becomes 'ready'.
  75. case (.client(let manager), .notReady):
  76. manager.channelActive(channel: context.channel)
  77. case (.server, .notReady),
  78. (_, .ready),
  79. (_, .closed):
  80. ()
  81. }
  82. context.fireChannelActive()
  83. }
  84. func handlerRemoved(context: ChannelHandlerContext) {
  85. self.scheduledIdle?.cancel()
  86. }
  87. func channelInactive(context: ChannelHandlerContext) {
  88. self.scheduledIdle?.cancel()
  89. self.scheduledIdle = nil
  90. switch (self.mode, self.state) {
  91. case (.client(let manager), .notReady),
  92. (.client(let manager), .ready):
  93. manager.channelInactive()
  94. case (.server, .notReady),
  95. (.server, .ready),
  96. (_, .closed):
  97. ()
  98. }
  99. context.fireChannelInactive()
  100. }
  101. func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  102. let frame = self.unwrapInboundIn(data)
  103. if frame.streamID == .rootStream {
  104. switch (self.state, frame.payload) {
  105. // We only care about SETTINGS as long as we are in state `.notReady`.
  106. case (.notReady, .settings):
  107. self.state = .ready
  108. switch self.mode {
  109. case .client(let manager):
  110. let remoteAddressDescription = context.channel.remoteAddress.map { "\($0)" } ?? "n/a"
  111. manager.logger.info("gRPC connection ready", metadata: [
  112. "remote_address": "\(remoteAddressDescription)",
  113. "event_loop": "\(context.eventLoop)"
  114. ])
  115. // Let the manager know we're ready.
  116. manager.ready()
  117. case .server:
  118. ()
  119. }
  120. // Start the idle timeout.
  121. self.scheduleIdleTimeout(context: context)
  122. case (.notReady, .goAway),
  123. (.ready, .goAway):
  124. self.idle(context: context)
  125. default:
  126. ()
  127. }
  128. }
  129. context.fireChannelRead(data)
  130. }
  131. private func scheduleIdleTimeout(context: ChannelHandlerContext) {
  132. guard self.activeStreams == 0 else {
  133. return
  134. }
  135. self.scheduledIdle = context.eventLoop.scheduleTask(in: self.idleTimeout) {
  136. self.idle(context: context)
  137. }
  138. }
  139. private func idle(context: ChannelHandlerContext, force: Bool = false) {
  140. // Don't idle if there are active streams unless we manually request
  141. // example: keepalive handler sends a `ConnectionIdledEvent` event
  142. guard self.activeStreams == 0 || force else {
  143. return
  144. }
  145. switch self.state {
  146. case .notReady, .ready:
  147. self.state = .closed
  148. switch self.mode {
  149. case .client(let manager):
  150. manager.idle()
  151. case .server:
  152. ()
  153. }
  154. context.close(mode: .all, promise: nil)
  155. // We need to guard against double closure here. We may go idle as a result of receiving a
  156. // GOAWAY frame or because our scheduled idle timeout fired.
  157. case .closed:
  158. ()
  159. }
  160. }
  161. }