GRPCKeepaliveHandlers.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. /// Provides keepalive pings.
  19. ///
  20. /// The logic is determined by the gRPC keepalive
  21. /// [documentation] (https://github.com/grpc/grpc/blob/master/doc/keepalive.md).
  22. internal class GRPCClientKeepaliveHandler: ChannelInboundHandler, _ChannelKeepaliveHandler {
  23. typealias InboundIn = HTTP2Frame
  24. typealias OutboundOut = HTTP2Frame
  25. init(configuration: ClientConnectionKeepalive) {
  26. self.pingHandler = PingHandler(
  27. pingCode: 5,
  28. interval: configuration.interval,
  29. timeout: configuration.timeout,
  30. permitWithoutCalls: configuration.permitWithoutCalls,
  31. maximumPingsWithoutData: configuration.maximumPingsWithoutData,
  32. minimumSentPingIntervalWithoutData: configuration.minimumSentPingIntervalWithoutData
  33. )
  34. }
  35. /// The ping handler.
  36. var pingHandler: PingHandler
  37. /// The scheduled task which will ping.
  38. var scheduledPing: RepeatedTask? = nil
  39. /// The scheduled task which will close the connection.
  40. var scheduledClose: Scheduled<Void>? = nil
  41. }
  42. internal class GRPCServerKeepaliveHandler: ChannelInboundHandler, _ChannelKeepaliveHandler {
  43. typealias InboundIn = HTTP2Frame
  44. typealias OutboundOut = HTTP2Frame
  45. init(configuration: ServerConnectionKeepalive) {
  46. self.pingHandler = PingHandler(
  47. pingCode: 10,
  48. interval: configuration.interval,
  49. timeout: configuration.timeout,
  50. permitWithoutCalls: configuration.permitWithoutCalls,
  51. maximumPingsWithoutData: configuration.maximumPingsWithoutData,
  52. minimumSentPingIntervalWithoutData: configuration.minimumSentPingIntervalWithoutData,
  53. minimumReceivedPingIntervalWithoutData: configuration.minimumReceivedPingIntervalWithoutData,
  54. maximumPingStrikes: configuration.maximumPingStrikes
  55. )
  56. }
  57. /// The ping handler.
  58. var pingHandler: PingHandler
  59. /// The scheduled task which will ping.
  60. var scheduledPing: RepeatedTask? = nil
  61. /// The scheduled task which will close the connection.
  62. var scheduledClose: Scheduled<Void>? = nil
  63. }
  64. protocol _ChannelKeepaliveHandler: ChannelInboundHandler where OutboundOut == HTTP2Frame, InboundIn == HTTP2Frame {
  65. var pingHandler: PingHandler { get set }
  66. var scheduledPing: RepeatedTask? { get set }
  67. var scheduledClose: Scheduled<Void>? { get set }
  68. }
  69. extension _ChannelKeepaliveHandler {
  70. func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
  71. if event is NIOHTTP2StreamCreatedEvent {
  72. self.perform(action: self.pingHandler.streamCreated(), context: context)
  73. } else if event is StreamClosedEvent {
  74. self.perform(action: self.pingHandler.streamClosed(), context: context)
  75. }
  76. context.fireUserInboundEventTriggered(event)
  77. }
  78. func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  79. switch self.unwrapInboundIn(data).payload {
  80. case let .ping(pingData, ack: ack):
  81. self.perform(action: self.pingHandler.read(pingData: pingData, ack: ack), context: context)
  82. default:
  83. break
  84. }
  85. context.fireChannelRead(data)
  86. }
  87. func handlerRemoved(context: ChannelHandlerContext) {
  88. self.cancelScheduledPing()
  89. self.cancelScheduledTimeout()
  90. }
  91. private func perform(action: PingHandler.Action, context: ChannelHandlerContext) {
  92. switch action {
  93. case let .schedulePing(delay, timeout):
  94. self.schedulePing(delay: delay, timeout: timeout, context: context)
  95. case .cancelScheduledTimeout:
  96. self.cancelScheduledTimeout()
  97. case let .reply(payload):
  98. self.send(payload: payload, context: context)
  99. case .none:
  100. break
  101. }
  102. }
  103. private func send(payload: HTTP2Frame.FramePayload, context: ChannelHandlerContext) {
  104. let frame = self.wrapOutboundOut(.init(streamID: .rootStream, payload: payload))
  105. context.writeAndFlush(frame, promise: nil)
  106. }
  107. private func schedulePing(delay: TimeAmount, timeout: TimeAmount, context: ChannelHandlerContext) {
  108. guard delay != .nanoseconds(Int64.max) else { return }
  109. self.scheduledPing = context.eventLoop.scheduleRepeatedTask(initialDelay: delay, delay: delay) { _ in
  110. self.perform(action: self.pingHandler.pingFired(), context: context)
  111. // `timeout` is less than `interval`, guaranteeing that the close task
  112. // will be fired before a new ping is triggered.
  113. assert(timeout < delay, "`timeout` must be less than `interval`")
  114. self.scheduleClose(timeout: timeout, context: context)
  115. }
  116. }
  117. private func scheduleClose(timeout: TimeAmount, context: ChannelHandlerContext) {
  118. self.scheduledClose = context.eventLoop.scheduleTask(in: timeout) {
  119. context.fireUserInboundEventTriggered(ConnectionIdledEvent())
  120. }
  121. }
  122. private func cancelScheduledPing() {
  123. self.scheduledPing?.cancel()
  124. self.scheduledPing = nil
  125. }
  126. private func cancelScheduledTimeout() {
  127. self.scheduledClose?.cancel()
  128. self.scheduledClose = nil
  129. }
  130. }
  131. struct PingHandler {
  132. /// Code for ping
  133. private let pingCode: UInt64
  134. /// The amount of time to wait before sending a keepalive ping.
  135. private let interval: TimeAmount
  136. /// The amount of time to wait for an acknowledgment.
  137. /// If it does not receive an acknowledgment within this time, it will close the connection
  138. private let timeout: TimeAmount
  139. /// Send keepalive pings even if there are no calls in flight.
  140. private let permitWithoutCalls: Bool
  141. /// Maximum number of pings that can be sent when there is no data/header frame to be sent.
  142. private let maximumPingsWithoutData: UInt
  143. /// If there are no data/header frames being received:
  144. /// The minimum amount of time to wait between successive pings.
  145. private let minimumSentPingIntervalWithoutData: TimeAmount
  146. /// If there are no data/header frames being sent:
  147. /// The minimum amount of time expected between receiving successive pings.
  148. /// If the time between successive pings is less than this value, then the ping will be considered a bad ping from the peer.
  149. /// Such a ping counts as a "ping strike".
  150. /// Ping strikes are only applicable to server handler
  151. private let minimumReceivedPingIntervalWithoutData: TimeAmount?
  152. /// Maximum number of bad pings that the server will tolerate before sending an HTTP2 GOAWAY frame and closing the connection.
  153. /// Setting it to `0` allows the server to accept any number of bad pings.
  154. /// Ping strikes are only applicable to server handler
  155. private let maximumPingStrikes: UInt?
  156. /// When the handler started pinging
  157. private var startedAt: NIODeadline? = nil
  158. /// When the last ping was received
  159. private var lastReceivedPingDate: NIODeadline? = nil
  160. /// When the last ping was sent
  161. private var lastSentPingDate: NIODeadline? = nil
  162. /// The number of pings sent on the transport without any data
  163. private var sentPingsWithoutData = 0
  164. /// Number of strikes
  165. private var pingStrikes: UInt = 0
  166. /// The scheduled task which will close the connection.
  167. private var scheduledClose: Scheduled<Void>? = nil
  168. /// Number of active streams
  169. private var activeStreams = 0 {
  170. didSet {
  171. if activeStreams > 0 {
  172. self.sentPingsWithoutData = 0
  173. }
  174. }
  175. }
  176. private static let goAwayFrame = HTTP2Frame.FramePayload.goAway(lastStreamID: .rootStream, errorCode: .enhanceYourCalm, opaqueData: nil)
  177. // For testing only
  178. var _testingOnlyNow: NIODeadline?
  179. enum Action {
  180. case none
  181. case schedulePing(delay: TimeAmount, timeout: TimeAmount)
  182. case cancelScheduledTimeout
  183. case reply(HTTP2Frame.FramePayload)
  184. }
  185. init(
  186. pingCode: UInt64,
  187. interval: TimeAmount,
  188. timeout: TimeAmount,
  189. permitWithoutCalls: Bool,
  190. maximumPingsWithoutData: UInt,
  191. minimumSentPingIntervalWithoutData: TimeAmount,
  192. minimumReceivedPingIntervalWithoutData: TimeAmount? = nil,
  193. maximumPingStrikes: UInt? = nil
  194. ) {
  195. self.pingCode = pingCode
  196. self.interval = interval
  197. self.timeout = timeout
  198. self.permitWithoutCalls = permitWithoutCalls
  199. self.maximumPingsWithoutData = maximumPingsWithoutData
  200. self.minimumSentPingIntervalWithoutData = minimumSentPingIntervalWithoutData
  201. self.minimumReceivedPingIntervalWithoutData = minimumReceivedPingIntervalWithoutData
  202. self.maximumPingStrikes = maximumPingStrikes
  203. }
  204. mutating func streamCreated() -> Action {
  205. self.activeStreams += 1
  206. if self.startedAt == nil {
  207. self.startedAt = self.now
  208. return .schedulePing(delay: self.interval, timeout: self.timeout)
  209. } else {
  210. return .none
  211. }
  212. }
  213. mutating func streamClosed() -> Action {
  214. self.activeStreams -= 1
  215. return .none
  216. }
  217. mutating func read(pingData: HTTP2PingData, ack: Bool) -> Action {
  218. let isPong = ack && pingData.integer == self.pingCode
  219. let isIllegalWithoutCalls = !ack && self.activeStreams == 0 && !self.permitWithoutCalls
  220. let isInvalidPing = !ack && self.isPingStrike
  221. let isValidPing = !ack && !self.isPingStrike
  222. if isPong {
  223. return .cancelScheduledTimeout
  224. } else if isIllegalWithoutCalls {
  225. return .reply(PingHandler.goAwayFrame)
  226. } else if isInvalidPing, let maximumPingStrikes = self.maximumPingStrikes {
  227. self.pingStrikes += 1
  228. if self.pingStrikes > maximumPingStrikes && maximumPingStrikes > 0 {
  229. return .reply(PingHandler.goAwayFrame)
  230. } else {
  231. return .none
  232. }
  233. } else if isValidPing {
  234. self.pingStrikes = 0
  235. self.lastReceivedPingDate = self.now
  236. return .reply(self.generatePingFrame(code: pingData.integer, ack: true))
  237. } else {
  238. return .none
  239. }
  240. }
  241. mutating func pingFired() -> Action {
  242. if self.shouldBlockPing {
  243. return .none
  244. } else {
  245. return .reply(self.generatePingFrame(code: pingCode, ack: false))
  246. }
  247. }
  248. private mutating func generatePingFrame(code: UInt64, ack: Bool) -> HTTP2Frame.FramePayload {
  249. if self.activeStreams == 0 {
  250. self.sentPingsWithoutData += 1
  251. }
  252. self.lastSentPingDate = self.now
  253. return HTTP2Frame.FramePayload.ping(HTTP2PingData(withInteger: code), ack: ack)
  254. }
  255. private var isPingStrike: Bool {
  256. guard self.activeStreams == 0 && self.permitWithoutCalls,
  257. let lastReceivedPingDate = self.lastReceivedPingDate,
  258. let minimumReceivedPingIntervalWithoutData = self.minimumReceivedPingIntervalWithoutData else {
  259. return false
  260. }
  261. return self.now - lastReceivedPingDate < minimumReceivedPingIntervalWithoutData
  262. }
  263. private var shouldBlockPing: Bool {
  264. // There is no active call on the transport and pings should not be sent
  265. guard self.activeStreams > 0 || self.permitWithoutCalls else {
  266. return true
  267. }
  268. // There is no active call on the transport but pings should be sent
  269. if self.activeStreams == 0 && self.permitWithoutCalls {
  270. // The number of pings already sent on the transport without any data has already exceeded the limit
  271. if self.sentPingsWithoutData > self.maximumPingsWithoutData {
  272. return true
  273. }
  274. // The time elapsed since the previous ping is less than the minimum required
  275. if let lastSentPingDate = self.lastSentPingDate, self.now - lastSentPingDate < self.minimumSentPingIntervalWithoutData {
  276. return true
  277. }
  278. return false
  279. }
  280. return false
  281. }
  282. private var now: NIODeadline {
  283. return self._testingOnlyNow ?? .now()
  284. }
  285. }