GRPCKeepaliveHandlers.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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(
  177. lastStreamID: .rootStream,
  178. errorCode: .enhanceYourCalm, opaqueData: nil
  179. )
  180. // For testing only
  181. var _testingOnlyNow: NIODeadline?
  182. enum Action {
  183. case none
  184. case schedulePing(delay: TimeAmount, timeout: TimeAmount)
  185. case cancelScheduledTimeout
  186. case reply(HTTP2Frame.FramePayload)
  187. }
  188. init(
  189. pingCode: UInt64,
  190. interval: TimeAmount,
  191. timeout: TimeAmount,
  192. permitWithoutCalls: Bool,
  193. maximumPingsWithoutData: UInt,
  194. minimumSentPingIntervalWithoutData: TimeAmount,
  195. minimumReceivedPingIntervalWithoutData: TimeAmount? = nil,
  196. maximumPingStrikes: UInt? = nil
  197. ) {
  198. self.pingCode = pingCode
  199. self.interval = interval
  200. self.timeout = timeout
  201. self.permitWithoutCalls = permitWithoutCalls
  202. self.maximumPingsWithoutData = maximumPingsWithoutData
  203. self.minimumSentPingIntervalWithoutData = minimumSentPingIntervalWithoutData
  204. self.minimumReceivedPingIntervalWithoutData = minimumReceivedPingIntervalWithoutData
  205. self.maximumPingStrikes = maximumPingStrikes
  206. }
  207. mutating func streamCreated() -> Action {
  208. self.activeStreams += 1
  209. if self.startedAt == nil {
  210. self.startedAt = self.now()
  211. return .schedulePing(delay: self.interval, timeout: self.timeout)
  212. } else {
  213. return .none
  214. }
  215. }
  216. mutating func streamClosed() -> Action {
  217. self.activeStreams -= 1
  218. return .none
  219. }
  220. mutating func read(pingData: HTTP2PingData, ack: Bool) -> Action {
  221. if ack {
  222. return self.handlePong(pingData)
  223. } else {
  224. return self.handlePing(pingData)
  225. }
  226. }
  227. private func handlePong(_ pingData: HTTP2PingData) -> Action {
  228. if pingData.integer == self.pingCode {
  229. return .cancelScheduledTimeout
  230. } else {
  231. return .none
  232. }
  233. }
  234. private mutating func handlePing(_ pingData: HTTP2PingData) -> Action {
  235. // Do we support ping strikes (only servers support ping strikes)?
  236. if let maximumPingStrikes = self.maximumPingStrikes {
  237. // Is this a ping strike?
  238. if self.isPingStrike {
  239. self.pingStrikes += 1
  240. // A maximum ping strike of zero indicates that we tolerate any number of strikes.
  241. if maximumPingStrikes != 0, self.pingStrikes > maximumPingStrikes {
  242. return .reply(PingHandler.goAwayFrame)
  243. } else {
  244. return .none
  245. }
  246. } else {
  247. // This is a valid ping, reset our strike count and reply with a pong.
  248. self.pingStrikes = 0
  249. self.lastReceivedPingDate = self.now()
  250. return .reply(self.generatePingFrame(code: pingData.integer, ack: true))
  251. }
  252. } else {
  253. // We don't support ping strikes. We'll just reply with a pong.
  254. //
  255. // Note: we don't need to update `pingStrikes` or `lastReceivedPingDate` as we don't
  256. // support ping strikes.
  257. return .reply(self.generatePingFrame(code: pingData.integer, ack: true))
  258. }
  259. }
  260. mutating func pingFired() -> Action {
  261. if self.shouldBlockPing {
  262. return .none
  263. } else {
  264. return .reply(self.generatePingFrame(code: self.pingCode, ack: false))
  265. }
  266. }
  267. private mutating func generatePingFrame(code: UInt64, ack: Bool) -> HTTP2Frame.FramePayload {
  268. if self.activeStreams == 0 {
  269. self.sentPingsWithoutData += 1
  270. }
  271. self.lastSentPingDate = self.now()
  272. return HTTP2Frame.FramePayload.ping(HTTP2PingData(withInteger: code), ack: ack)
  273. }
  274. /// Returns true if, on receipt of a ping, the ping should be regarded as a ping strike.
  275. ///
  276. /// A ping is considered a 'strike' if:
  277. /// - There are no active streams.
  278. /// - We allow pings to be sent when there are no active streams (i.e. `self.permitWithoutCalls`).
  279. /// - The time since the last ping we received is less than the minimum allowed interval.
  280. ///
  281. /// - Precondition: Ping strikes are supported (i.e. `self.maximumPingStrikes != nil`)
  282. private var isPingStrike: Bool {
  283. assert(self.maximumPingStrikes != nil, "Ping strikes are not supported but we're checking for one")
  284. guard self.activeStreams == 0 && self.permitWithoutCalls,
  285. let lastReceivedPingDate = self.lastReceivedPingDate,
  286. let minimumReceivedPingIntervalWithoutData = self.minimumReceivedPingIntervalWithoutData else {
  287. return false
  288. }
  289. return self.now() - lastReceivedPingDate < minimumReceivedPingIntervalWithoutData
  290. }
  291. private var shouldBlockPing: Bool {
  292. // There is no active call on the transport and pings should not be sent
  293. guard self.activeStreams > 0 || self.permitWithoutCalls else {
  294. return true
  295. }
  296. // There is no active call on the transport but pings should be sent
  297. if self.activeStreams == 0 && self.permitWithoutCalls {
  298. // The number of pings already sent on the transport without any data has already exceeded the limit
  299. if self.sentPingsWithoutData > self.maximumPingsWithoutData {
  300. return true
  301. }
  302. // The time elapsed since the previous ping is less than the minimum required
  303. if let lastSentPingDate = self.lastSentPingDate, self.now() - lastSentPingDate < self.minimumSentPingIntervalWithoutData {
  304. return true
  305. }
  306. return false
  307. }
  308. return false
  309. }
  310. private func now() -> NIODeadline {
  311. return self._testingOnlyNow ?? .now()
  312. }
  313. }