GRPCIdleHandler.swift 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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. }
  63. case .closed:
  64. ()
  65. }
  66. context.fireUserInboundEventTriggered(event)
  67. }
  68. func channelActive(context: ChannelHandlerContext) {
  69. switch (self.mode, self.state) {
  70. // The client should become active: we'll only schedule the idling when the channel
  71. // becomes 'ready'.
  72. case (.client(let manager), .notReady):
  73. manager.channelActive(channel: context.channel)
  74. case (.server, .notReady),
  75. (_, .ready),
  76. (_, .closed):
  77. ()
  78. }
  79. context.fireChannelActive()
  80. }
  81. func handlerRemoved(context: ChannelHandlerContext) {
  82. self.scheduledIdle?.cancel()
  83. }
  84. func channelInactive(context: ChannelHandlerContext) {
  85. self.scheduledIdle?.cancel()
  86. self.scheduledIdle = nil
  87. switch (self.mode, self.state) {
  88. case (.client(let manager), .notReady),
  89. (.client(let manager), .ready):
  90. manager.channelInactive()
  91. case (.server, .notReady),
  92. (.server, .ready),
  93. (_, .closed):
  94. ()
  95. }
  96. context.fireChannelInactive()
  97. }
  98. func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  99. let frame = self.unwrapInboundIn(data)
  100. if frame.streamID == .rootStream {
  101. switch (self.state, frame.payload) {
  102. // We only care about SETTINGS as long as we are in state `.notReady`.
  103. case (.notReady, .settings):
  104. self.state = .ready
  105. switch self.mode {
  106. case .client(let manager):
  107. let remoteAddressDescription = context.channel.remoteAddress.map { "\($0)" } ?? "n/a"
  108. manager.logger.info("gRPC connection ready", metadata: [
  109. "remote_address": "\(remoteAddressDescription)",
  110. "event_loop": "\(context.eventLoop)"
  111. ])
  112. // Let the manager know we're ready.
  113. manager.ready()
  114. case .server:
  115. ()
  116. }
  117. // Start the idle timeout.
  118. self.scheduleIdleTimeout(context: context)
  119. case (.notReady, .goAway),
  120. (.ready, .goAway):
  121. self.idle(context: context)
  122. default:
  123. ()
  124. }
  125. }
  126. context.fireChannelRead(data)
  127. }
  128. private func scheduleIdleTimeout(context: ChannelHandlerContext) {
  129. guard self.activeStreams == 0 else {
  130. return
  131. }
  132. self.scheduledIdle = context.eventLoop.scheduleTask(in: self.idleTimeout) {
  133. self.idle(context: context)
  134. }
  135. }
  136. private func idle(context: ChannelHandlerContext) {
  137. // Don't idle if there are active streams.
  138. guard self.activeStreams == 0 else {
  139. return
  140. }
  141. switch self.state {
  142. case .notReady, .ready:
  143. self.state = .closed
  144. switch self.mode {
  145. case .client(let manager):
  146. manager.idle()
  147. case .server:
  148. ()
  149. }
  150. context.close(mode: .all, promise: nil)
  151. // We need to guard against double closure here. We may go idle as a result of receiving a
  152. // GOAWAY frame or because our scheduled idle timeout fired.
  153. case .closed:
  154. ()
  155. }
  156. }
  157. }