GRPCIdleHandler.swift 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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 channelInactive(context: ChannelHandlerContext) {
  82. self.scheduledIdle?.cancel()
  83. self.scheduledIdle = nil
  84. switch (self.mode, self.state) {
  85. case (.client(let manager), .notReady),
  86. (.client(let manager), .ready):
  87. manager.channelInactive()
  88. case (.server, .notReady),
  89. (.server, .ready),
  90. (_, .closed):
  91. ()
  92. }
  93. context.fireChannelInactive()
  94. }
  95. func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  96. let frame = self.unwrapInboundIn(data)
  97. if frame.streamID == .rootStream {
  98. switch (self.state, frame.payload) {
  99. // We only care about SETTINGS as long as we are in state `.notReady`.
  100. case (.notReady, .settings):
  101. self.state = .ready
  102. switch self.mode {
  103. case .client(let manager):
  104. let remoteAddressDescription = context.channel.remoteAddress.map { "\($0)" } ?? "n/a"
  105. manager.logger.info("gRPC connection ready", metadata: [
  106. "remote_address": "\(remoteAddressDescription)",
  107. "event_loop": "\(context.eventLoop)"
  108. ])
  109. // Let the manager know we're ready.
  110. manager.ready()
  111. case .server:
  112. ()
  113. }
  114. // Start the idle timeout.
  115. self.scheduleIdleTimeout(context: context)
  116. case (.notReady, .goAway),
  117. (.ready, .goAway):
  118. self.idle(context: context)
  119. default:
  120. ()
  121. }
  122. }
  123. context.fireChannelRead(data)
  124. }
  125. private func scheduleIdleTimeout(context: ChannelHandlerContext) {
  126. guard self.activeStreams == 0 else {
  127. return
  128. }
  129. self.scheduledIdle = context.eventLoop.scheduleTask(in: self.idleTimeout) {
  130. self.idle(context: context)
  131. }
  132. }
  133. private func idle(context: ChannelHandlerContext) {
  134. guard self.activeStreams == 0 else {
  135. return
  136. }
  137. self.state = .closed
  138. switch self.mode {
  139. case .client(let manager):
  140. manager.idle()
  141. case .server:
  142. ()
  143. }
  144. context.close(mode: .all, promise: nil)
  145. }
  146. }