2
0

ClientInterceptorPipeline.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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 Logging
  17. import NIO
  18. import NIOHPACK
  19. import NIOHTTP2
  20. /// A pipeline for intercepting client request and response streams.
  21. ///
  22. /// The interceptor pipeline lies between the call object (`UnaryCall`, `ClientStreamingCall`, etc.)
  23. /// and the transport used to send and receive messages from the server (a `NIO.Channel`). It holds
  24. /// a collection of interceptors which may be used to observe or alter messages as the travel
  25. /// through the pipeline.
  26. ///
  27. /// ```
  28. /// ┌───────────────────────────────────────────────────────────────────┐
  29. /// │ Call │
  30. /// └────────────────────────────────────────────────────────┬──────────┘
  31. /// │ send(_:promise) /
  32. /// │ cancel(promise:)
  33. /// ┌────────────────────────────────────────────────────────▼──────────┐
  34. /// │ InterceptorPipeline ╎ │
  35. /// │ ╎ │
  36. /// │ ┌──────────────────────────────────────────────────────▼────────┐ │
  37. /// │ │ Tail Interceptor (hands response parts to a callback) │ │
  38. /// │ └────────▲─────────────────────────────────────────────┬────────┘ │
  39. /// │ ┌────────┴─────────────────────────────────────────────▼────────┐ │
  40. /// │ │ Interceptor 1 │ │
  41. /// │ └────────▲─────────────────────────────────────────────┬────────┘ │
  42. /// │ ┌────────┴─────────────────────────────────────────────▼────────┐ │
  43. /// │ │ Interceptor 2 │ │
  44. /// │ └────────▲─────────────────────────────────────────────┬────────┘ │
  45. /// │ ╎ ╎ │
  46. /// │ ╎ (More interceptors) ╎ │
  47. /// │ ╎ ╎ │
  48. /// │ ┌────────┴─────────────────────────────────────────────▼────────┐ │
  49. /// │ │ Head Interceptor (interacts with transport) │ │
  50. /// │ └────────▲─────────────────────────────────────────────┬────────┘ │
  51. /// │ ╎ receive(_:) │ │
  52. /// └──────────▲─────────────────────────────────────────────┼──────────┘
  53. /// │ receive(_:) │ send(_:promise:) /
  54. /// │ │ cancel(promise:)
  55. /// ┌──────────┴─────────────────────────────────────────────▼──────────┐
  56. /// │ ClientTransport │
  57. /// │ (a NIO.ChannelHandler) │
  58. /// ```
  59. @usableFromInline
  60. internal final class ClientInterceptorPipeline<Request, Response> {
  61. /// A logger.
  62. internal var logger: Logger {
  63. return self.details.options.logger
  64. }
  65. /// The `EventLoop` this RPC is being executed on.
  66. @usableFromInline
  67. internal let eventLoop: EventLoop
  68. /// The details of the call.
  69. internal let details: CallDetails
  70. /// A task for closing the RPC in case of a timeout.
  71. private var scheduledClose: Scheduled<Void>?
  72. /// The contexts associated with the interceptors stored in this pipeline. Context will be removed
  73. /// once the RPC has completed. Contexts are ordered from outbound to inbound, that is, the tail
  74. /// is first and the head is last.
  75. private var contexts: [ClientInterceptorContext<Request, Response>]?
  76. /// Returns the next context in the outbound direction for the context at the given index, if one
  77. /// exists.
  78. /// - Parameter index: The index of the `ClientInterceptorContext` which is requesting the next
  79. /// outbound context.
  80. /// - Returns: The `ClientInterceptorContext` or `nil` if one does not exist.
  81. internal func nextOutboundContext(
  82. forIndex index: Int
  83. ) -> ClientInterceptorContext<Request, Response>? {
  84. return self.context(atIndex: index + 1)
  85. }
  86. /// Returns the next context in the inbound direction for the context at the given index, if one
  87. /// exists.
  88. /// - Parameter index: The index of the `ClientInterceptorContext` which is requesting the next
  89. /// inbound context.
  90. /// - Returns: The `ClientInterceptorContext` or `nil` if one does not exist.
  91. internal func nextInboundContext(
  92. forIndex index: Int
  93. ) -> ClientInterceptorContext<Request, Response>? {
  94. return self.context(atIndex: index - 1)
  95. }
  96. /// Returns the context for the given index, if one exists.
  97. /// - Parameter index: The index of the `ClientInterceptorContext` to return.
  98. /// - Returns: The `ClientInterceptorContext` or `nil` if one does not exist for the given index.
  99. private func context(atIndex index: Int) -> ClientInterceptorContext<Request, Response>? {
  100. return self.contexts?[checked: index]
  101. }
  102. /// The context closest to the `NIO.Channel`, i.e. where inbound events originate. This will be
  103. /// `nil` once the RPC has completed.
  104. @usableFromInline
  105. internal var _head: ClientInterceptorContext<Request, Response>? {
  106. return self.contexts?.last
  107. }
  108. /// The context closest to the application, i.e. where outbound events originate. This will be
  109. /// `nil` once the RPC has completed.
  110. @usableFromInline
  111. internal var _tail: ClientInterceptorContext<Request, Response>? {
  112. return self.contexts?.first
  113. }
  114. internal init(
  115. eventLoop: EventLoop,
  116. details: CallDetails,
  117. interceptors: [ClientInterceptor<Request, Response>],
  118. errorDelegate: ClientErrorDelegate?,
  119. onCancel: @escaping (EventLoopPromise<Void>?) -> Void,
  120. onRequestPart: @escaping (ClientRequestPart<Request>, EventLoopPromise<Void>?) -> Void,
  121. onResponsePart: @escaping (ClientResponsePart<Response>) -> Void
  122. ) {
  123. self.eventLoop = eventLoop
  124. self.details = details
  125. // We know we'll have at least a head and a tail as well as any user provided interceptors.
  126. var contexts: [ClientInterceptorContext<Request, Response>] = []
  127. contexts.reserveCapacity(interceptors.count + 2)
  128. // Start with the tail.
  129. contexts.append(
  130. ClientInterceptorContext(
  131. for: .tail(for: self, errorDelegate: errorDelegate, onResponsePart),
  132. atIndex: contexts.count,
  133. in: self
  134. )
  135. )
  136. // Now the user interceptors.
  137. for interceptor in interceptors {
  138. contexts.append(
  139. ClientInterceptorContext(
  140. for: .userProvided(interceptor),
  141. atIndex: contexts.count,
  142. in: self
  143. )
  144. )
  145. }
  146. // Finally, the head.
  147. contexts.append(
  148. ClientInterceptorContext(
  149. for: .head(onCancel: onCancel, onRequestPart: onRequestPart),
  150. atIndex: contexts.count,
  151. in: self
  152. )
  153. )
  154. self.contexts = contexts
  155. self.setupDeadline()
  156. }
  157. /// Emit a response part message into the interceptor pipeline.
  158. ///
  159. /// This should be called by the transport layer when receiving a response part from the server.
  160. ///
  161. /// - Parameter part: The part to emit into the pipeline.
  162. /// - Important: This *must* to be called from the `eventLoop`.
  163. internal func receive(_ part: ClientResponsePart<Response>) {
  164. self.eventLoop.assertInEventLoop()
  165. self._head?.invokeReceive(part)
  166. }
  167. /// Writes a request message into the interceptor pipeline.
  168. ///
  169. /// This should be called by the call object to send requests parts to the transport.
  170. ///
  171. /// - Parameters:
  172. /// - part: The request part to write.
  173. /// - promise: A promise to complete when the request part has been successfully written.
  174. /// - Important: This *must* to be called from the `eventLoop`.
  175. @inlinable
  176. internal func send(_ part: ClientRequestPart<Request>, promise: EventLoopPromise<Void>?) {
  177. self.eventLoop.assertInEventLoop()
  178. if let tail = self._tail {
  179. tail.invokeSend(part, promise: promise)
  180. } else {
  181. promise?.fail(GRPCError.AlreadyComplete())
  182. }
  183. }
  184. /// Send a request to cancel the RPC through the interceptor pipeline.
  185. ///
  186. /// This should be called by the call object when attempting to cancel the RPC.
  187. ///
  188. /// - Parameter promise: A promise to complete when the cancellation request has been handled.
  189. /// - Important: This *must* to be called from the `eventLoop`.
  190. internal func cancel(promise: EventLoopPromise<Void>?) {
  191. self.eventLoop.assertInEventLoop()
  192. if let tail = self._tail {
  193. tail.invokeCancel(promise: promise)
  194. } else {
  195. promise?.fail(GRPCError.AlreadyComplete())
  196. }
  197. }
  198. }
  199. // MARK: - Lifecycle
  200. extension ClientInterceptorPipeline {
  201. /// Closes the pipeline. This should be called once, by the tail interceptor, to indicate that
  202. /// the RPC has completed.
  203. /// - Important: This *must* to be called from the `eventLoop`.
  204. internal func close() {
  205. self.eventLoop.assertInEventLoop()
  206. // Grab the head, we'll use it to cancel the transport. This is most likely already closed,
  207. // but there's nothing to stop an interceptor from emitting its own error and leaving the
  208. // transport open.
  209. let head = self._head
  210. self.contexts = nil
  211. // Cancel the timeout.
  212. self.scheduledClose?.cancel()
  213. self.scheduledClose = nil
  214. // Cancel the transport.
  215. head?.invokeCancel(promise: nil)
  216. }
  217. /// Sets up a deadline for the pipeline.
  218. private func setupDeadline() {
  219. if self.eventLoop.inEventLoop {
  220. self._setupDeadline()
  221. } else {
  222. self.eventLoop.execute {
  223. self._setupDeadline()
  224. }
  225. }
  226. }
  227. /// Sets up a deadline for the pipeline.
  228. /// - Important: This *must* to be called from the `eventLoop`.
  229. private func _setupDeadline() {
  230. self.eventLoop.assertInEventLoop()
  231. let timeLimit = self.details.options.timeLimit
  232. let deadline = timeLimit.makeDeadline()
  233. // There's no point scheduling this.
  234. if deadline == .distantFuture {
  235. return
  236. }
  237. self.scheduledClose = self.eventLoop.scheduleTask(deadline: deadline) {
  238. // When the error hits the tail we'll call 'close()', this will cancel the transport if
  239. // necessary.
  240. self.receive(.error(GRPCError.RPCTimedOut(timeLimit)))
  241. }
  242. }
  243. }