GRPCKeepaliveHandlers.swift 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. struct PingHandler {
  19. /// Code for ping
  20. private let pingCode: UInt64
  21. /// The amount of time to wait before sending a keepalive ping.
  22. private let interval: TimeAmount
  23. /// The amount of time to wait for an acknowledgment.
  24. /// If it does not receive an acknowledgment within this time, it will close the connection
  25. private let timeout: TimeAmount
  26. /// Send keepalive pings even if there are no calls in flight.
  27. private let permitWithoutCalls: Bool
  28. /// Maximum number of pings that can be sent when there is no data/header frame to be sent.
  29. private let maximumPingsWithoutData: UInt
  30. /// If there are no data/header frames being received:
  31. /// The minimum amount of time to wait between successive pings.
  32. private let minimumSentPingIntervalWithoutData: TimeAmount
  33. /// If there are no data/header frames being sent:
  34. /// The minimum amount of time expected between receiving successive pings.
  35. /// If the time between successive pings is less than this value, then the ping will be considered a bad ping from the peer.
  36. /// Such a ping counts as a "ping strike".
  37. /// Ping strikes are only applicable to server handler
  38. private let minimumReceivedPingIntervalWithoutData: TimeAmount?
  39. /// Maximum number of bad pings that the server will tolerate before sending an HTTP2 GOAWAY frame and closing the connection.
  40. /// Setting it to `0` allows the server to accept any number of bad pings.
  41. /// Ping strikes are only applicable to server handler
  42. private let maximumPingStrikes: UInt?
  43. /// When the handler started pinging
  44. private var startedAt: NIODeadline?
  45. /// When the last ping was received
  46. private var lastReceivedPingDate: NIODeadline?
  47. /// When the last ping was sent
  48. private var lastSentPingDate: NIODeadline?
  49. /// The number of pings sent on the transport without any data
  50. private var sentPingsWithoutData = 0
  51. /// Number of strikes
  52. private var pingStrikes: UInt = 0
  53. /// The scheduled task which will close the connection.
  54. private var scheduledClose: Scheduled<Void>?
  55. /// Number of active streams
  56. private var activeStreams = 0 {
  57. didSet {
  58. if self.activeStreams > 0 {
  59. self.sentPingsWithoutData = 0
  60. }
  61. }
  62. }
  63. private static let goAwayFrame = HTTP2Frame.FramePayload.goAway(
  64. lastStreamID: .rootStream,
  65. errorCode: .enhanceYourCalm,
  66. opaqueData: nil
  67. )
  68. // For testing only
  69. var _testingOnlyNow: NIODeadline?
  70. enum Action {
  71. case none
  72. case schedulePing(delay: TimeAmount, timeout: TimeAmount)
  73. case cancelScheduledTimeout
  74. case reply(HTTP2Frame.FramePayload)
  75. }
  76. init(
  77. pingCode: UInt64,
  78. interval: TimeAmount,
  79. timeout: TimeAmount,
  80. permitWithoutCalls: Bool,
  81. maximumPingsWithoutData: UInt,
  82. minimumSentPingIntervalWithoutData: TimeAmount,
  83. minimumReceivedPingIntervalWithoutData: TimeAmount? = nil,
  84. maximumPingStrikes: UInt? = nil
  85. ) {
  86. self.pingCode = pingCode
  87. self.interval = interval
  88. self.timeout = timeout
  89. self.permitWithoutCalls = permitWithoutCalls
  90. self.maximumPingsWithoutData = maximumPingsWithoutData
  91. self.minimumSentPingIntervalWithoutData = minimumSentPingIntervalWithoutData
  92. self.minimumReceivedPingIntervalWithoutData = minimumReceivedPingIntervalWithoutData
  93. self.maximumPingStrikes = maximumPingStrikes
  94. }
  95. mutating func streamCreated() -> Action {
  96. self.activeStreams += 1
  97. if self.startedAt == nil {
  98. self.startedAt = self.now()
  99. return .schedulePing(delay: self.interval, timeout: self.timeout)
  100. } else {
  101. return .none
  102. }
  103. }
  104. mutating func streamClosed() -> Action {
  105. self.activeStreams -= 1
  106. return .none
  107. }
  108. mutating func read(pingData: HTTP2PingData, ack: Bool) -> Action {
  109. if ack {
  110. return self.handlePong(pingData)
  111. } else {
  112. return self.handlePing(pingData)
  113. }
  114. }
  115. private func handlePong(_ pingData: HTTP2PingData) -> Action {
  116. if pingData.integer == self.pingCode {
  117. return .cancelScheduledTimeout
  118. } else {
  119. return .none
  120. }
  121. }
  122. private mutating func handlePing(_ pingData: HTTP2PingData) -> Action {
  123. // Do we support ping strikes (only servers support ping strikes)?
  124. if let maximumPingStrikes = self.maximumPingStrikes {
  125. // Is this a ping strike?
  126. if self.isPingStrike {
  127. self.pingStrikes += 1
  128. // A maximum ping strike of zero indicates that we tolerate any number of strikes.
  129. if maximumPingStrikes != 0, self.pingStrikes > maximumPingStrikes {
  130. return .reply(PingHandler.goAwayFrame)
  131. } else {
  132. return .none
  133. }
  134. } else {
  135. // This is a valid ping, reset our strike count and reply with a pong.
  136. self.pingStrikes = 0
  137. self.lastReceivedPingDate = self.now()
  138. return .reply(self.generatePingFrame(code: pingData.integer, ack: true))
  139. }
  140. } else {
  141. // We don't support ping strikes. We'll just reply with a pong.
  142. //
  143. // Note: we don't need to update `pingStrikes` or `lastReceivedPingDate` as we don't
  144. // support ping strikes.
  145. return .reply(self.generatePingFrame(code: pingData.integer, ack: true))
  146. }
  147. }
  148. mutating func pingFired() -> Action {
  149. if self.shouldBlockPing {
  150. return .none
  151. } else {
  152. return .reply(self.generatePingFrame(code: self.pingCode, ack: false))
  153. }
  154. }
  155. private mutating func generatePingFrame(code: UInt64, ack: Bool) -> HTTP2Frame.FramePayload {
  156. if self.activeStreams == 0 {
  157. self.sentPingsWithoutData += 1
  158. }
  159. self.lastSentPingDate = self.now()
  160. return HTTP2Frame.FramePayload.ping(HTTP2PingData(withInteger: code), ack: ack)
  161. }
  162. /// Returns true if, on receipt of a ping, the ping should be regarded as a ping strike.
  163. ///
  164. /// A ping is considered a 'strike' if:
  165. /// - There are no active streams.
  166. /// - We allow pings to be sent when there are no active streams (i.e. `self.permitWithoutCalls`).
  167. /// - The time since the last ping we received is less than the minimum allowed interval.
  168. ///
  169. /// - Precondition: Ping strikes are supported (i.e. `self.maximumPingStrikes != nil`)
  170. private var isPingStrike: Bool {
  171. assert(
  172. self.maximumPingStrikes != nil,
  173. "Ping strikes are not supported but we're checking for one"
  174. )
  175. guard self.activeStreams == 0, self.permitWithoutCalls,
  176. let lastReceivedPingDate = self.lastReceivedPingDate,
  177. let minimumReceivedPingIntervalWithoutData = self.minimumReceivedPingIntervalWithoutData
  178. else {
  179. return false
  180. }
  181. return self.now() - lastReceivedPingDate < minimumReceivedPingIntervalWithoutData
  182. }
  183. private var shouldBlockPing: Bool {
  184. // There is no active call on the transport and pings should not be sent
  185. guard self.activeStreams > 0 || self.permitWithoutCalls else {
  186. return true
  187. }
  188. // There is no active call on the transport but pings should be sent
  189. if self.activeStreams == 0, self.permitWithoutCalls {
  190. // The number of pings already sent on the transport without any data has already exceeded the limit
  191. if self.sentPingsWithoutData > self.maximumPingsWithoutData {
  192. return true
  193. }
  194. // The time elapsed since the previous ping is less than the minimum required
  195. if let lastSentPingDate = self.lastSentPingDate,
  196. self.now() - lastSentPingDate < self.minimumSentPingIntervalWithoutData {
  197. return true
  198. }
  199. return false
  200. }
  201. return false
  202. }
  203. private func now() -> NIODeadline {
  204. return self._testingOnlyNow ?? .now()
  205. }
  206. }