ClientInterceptors.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. /// A base class for client interceptors.
  18. ///
  19. /// Interceptors allow request and response and response parts to be observed, mutated or dropped
  20. /// as necessary. The default behaviour for this base class is to forward any events to the next
  21. /// interceptor.
  22. ///
  23. /// Interceptors may observe three different types of event:
  24. /// - reading response parts with `read(_:context:)`,
  25. /// - writing request parts with `write(_:promise:context:)`, and
  26. /// - RPC cancellation with `cancel(context:)`.
  27. ///
  28. /// These events flow through a pipeline of interceptors for each RPC. Request parts sent from the
  29. /// call object (such as `UnaryCall` and `BidirectionalStreamingCall`) will traverse the pipeline
  30. /// from its tail via `write(_:context:)` eventually reaching the head of the pipeline where it will
  31. /// be sent sent to the server.
  32. ///
  33. /// Response parts, or errors, received from the transport fill be fired back through the
  34. /// interceptor pipeline via `read(_:context:)`. Note that the `end` and `error` response parts are
  35. /// terminal: the pipeline will be torn down once these parts reach the the tail of the pipeline.
  36. ///
  37. /// Each of interceptor functions is provided with a `context` which exposes analogous functions
  38. /// (`read(_:)`, `write(_:promise:)`, and `cancel(promise:)`) which may be called to forward events
  39. /// to the next interceptor.
  40. ///
  41. /// ### Thread Safety
  42. ///
  43. /// Functions on `context` are not thread safe and **must** be called on the `EventLoop` found on
  44. /// the `context`. Since each interceptor is invoked on the same `EventLoop` this does not usually
  45. /// require any extra attention. However, if work is done on a `DispatchQueue` or _other_
  46. /// `EventLoop` then implementers should be ensure that they use `context` from the correct
  47. /// `EventLoop`.
  48. open class ClientInterceptor<Request, Response> {
  49. /// Called when the interceptor has received a response part to handle.
  50. /// - Parameters:
  51. /// - part: The response part which has been received from the server.
  52. /// - context: An interceptor context which may be used to forward the response part.
  53. public func read(
  54. _ part: ClientResponsePart<Response>,
  55. context: ClientInterceptorContext<Request, Response>
  56. ) {
  57. context.read(part)
  58. }
  59. /// Called when the interceptor has received a request part to handle.
  60. /// - Parameters:
  61. /// - part: The request part which should be sent to the server.
  62. /// - promise: A promise which should be completed when the response part has been handled.
  63. /// - context: An interceptor context which may be used to forward the request part.
  64. public func write(
  65. _ part: ClientRequestPart<Request>,
  66. promise: EventLoopPromise<Void>?,
  67. context: ClientInterceptorContext<Request, Response>
  68. ) {
  69. context.write(part, promise: promise)
  70. }
  71. /// Called when the interceptor has received a request to cancel the RPC.
  72. /// - Parameters:
  73. /// - promise: A promise which should be cancellation request has been handled.
  74. /// - context: An interceptor context which may be used to forward the cancellation request.
  75. public func cancel(
  76. promise: EventLoopPromise<Void>?,
  77. context: ClientInterceptorContext<Request, Response>
  78. ) {
  79. context.cancel(promise: promise)
  80. }
  81. }
  82. // MARK: - Head/Tail
  83. /// An interceptor which offloads requests to the transport and forwards any response parts to the
  84. /// rest of the pipeline.
  85. @usableFromInline
  86. internal struct HeadClientInterceptor<Request, Response>: ClientInterceptorProtocol {
  87. /// Called when a cancellation has been requested.
  88. private let onCancel: (EventLoopPromise<Void>?) -> Void
  89. /// Called when a request part has been written.
  90. @usableFromInline
  91. internal let _onRequestPart: (ClientRequestPart<Request>, EventLoopPromise<Void>?) -> Void
  92. init(
  93. onCancel: @escaping (EventLoopPromise<Void>?) -> Void,
  94. onRequestPart: @escaping (ClientRequestPart<Request>, EventLoopPromise<Void>?) -> Void
  95. ) {
  96. self.onCancel = onCancel
  97. self._onRequestPart = onRequestPart
  98. }
  99. @inlinable
  100. internal func write(
  101. _ part: ClientRequestPart<Request>,
  102. promise: EventLoopPromise<Void>?,
  103. context: ClientInterceptorContext<Request, Response>
  104. ) {
  105. self._onRequestPart(part, promise)
  106. }
  107. internal func cancel(
  108. promise: EventLoopPromise<Void>?,
  109. context: ClientInterceptorContext<Request, Response>
  110. ) {
  111. self.onCancel(promise)
  112. }
  113. internal func read(
  114. _ part: ClientResponsePart<Response>,
  115. context: ClientInterceptorContext<Request, Response>
  116. ) {
  117. context.read(part)
  118. }
  119. }
  120. /// An interceptor which offloads responses to a provided callback and forwards any requests parts
  121. /// and cancellation requests to rest of the pipeline.
  122. @usableFromInline
  123. internal struct TailClientInterceptor<Request, Response>: ClientInterceptorProtocol {
  124. /// The pipeline this interceptor belongs to.
  125. private let pipeline: ClientInterceptorPipeline<Request, Response>
  126. /// A user-provided error delegate.
  127. private let errorDelegate: ClientErrorDelegate?
  128. /// A response part handler; typically this will complete some promises, for streaming responses
  129. /// it will also invoke a user-supplied handler. This closure may also be provided by the user.
  130. /// We need to be careful about re-entrancy.
  131. private let onResponsePart: (ClientResponsePart<Response>) -> Void
  132. internal init(
  133. for pipeline: ClientInterceptorPipeline<Request, Response>,
  134. errorDelegate: ClientErrorDelegate?,
  135. _ onResponsePart: @escaping (ClientResponsePart<Response>) -> Void
  136. ) {
  137. self.pipeline = pipeline
  138. self.errorDelegate = errorDelegate
  139. self.onResponsePart = onResponsePart
  140. }
  141. internal func read(
  142. _ part: ClientResponsePart<Response>,
  143. context: ClientInterceptorContext<Request, Response>
  144. ) {
  145. switch part {
  146. case .metadata, .message:
  147. self.onResponsePart(part)
  148. case .end:
  149. // We're about to complete, close the pipeline before calling out via `onResponsePart`.
  150. self.pipeline.close()
  151. self.onResponsePart(part)
  152. case let .error(error):
  153. // We're about to complete, close the pipeline before calling out via the error delegate
  154. // or `onResponsePart`.
  155. self.pipeline.close()
  156. var unwrappedError: Error
  157. // Unwrap the error, if possible.
  158. if let errorContext = error as? GRPCError.WithContext {
  159. unwrappedError = errorContext.error
  160. self.errorDelegate?.didCatchError(
  161. errorContext.error,
  162. logger: context.logger,
  163. file: errorContext.file,
  164. line: errorContext.line
  165. )
  166. } else {
  167. unwrappedError = error
  168. self.errorDelegate?.didCatchErrorWithoutContext(
  169. error,
  170. logger: context.logger
  171. )
  172. }
  173. // Emit the unwrapped error.
  174. self.onResponsePart(.error(unwrappedError))
  175. }
  176. }
  177. @inlinable
  178. internal func write(
  179. _ part: ClientRequestPart<Request>,
  180. promise: EventLoopPromise<Void>?,
  181. context: ClientInterceptorContext<Request, Response>
  182. ) {
  183. context.write(part, promise: promise)
  184. }
  185. internal func cancel(
  186. promise: EventLoopPromise<Void>?,
  187. context: ClientInterceptorContext<Request, Response>
  188. ) {
  189. context.cancel(promise: promise)
  190. }
  191. }
  192. // MARK: - Any Interceptor
  193. /// A wrapping interceptor which delegates to the implementation of an underlying interceptor.
  194. @usableFromInline
  195. internal struct AnyClientInterceptor<Request, Response>: ClientInterceptorProtocol {
  196. @usableFromInline
  197. internal enum Implementation {
  198. case head(HeadClientInterceptor<Request, Response>)
  199. case tail(TailClientInterceptor<Request, Response>)
  200. case base(ClientInterceptor<Request, Response>)
  201. }
  202. /// The underlying interceptor implementation.
  203. @usableFromInline
  204. internal let _implementation: Implementation
  205. /// Makes a head interceptor.
  206. /// - Returns: An `AnyClientInterceptor` which wraps a `HeadClientInterceptor`.
  207. internal static func head(
  208. onCancel: @escaping (EventLoopPromise<Void>?) -> Void,
  209. onRequestPart: @escaping (ClientRequestPart<Request>, EventLoopPromise<Void>?) -> Void
  210. ) -> AnyClientInterceptor<Request, Response> {
  211. return .init(.head(.init(onCancel: onCancel, onRequestPart: onRequestPart)))
  212. }
  213. /// Makes a tail interceptor.
  214. /// - Parameters:
  215. /// - pipeline: The pipeline the tail interceptor belongs to.
  216. /// - errorDelegate: An error delegate.
  217. /// - onResponsePart: A handler called for each response part received from the pipeline.
  218. /// - Returns: An `AnyClientInterceptor` which wraps a `TailClientInterceptor`.
  219. internal static func tail(
  220. for pipeline: ClientInterceptorPipeline<Request, Response>,
  221. errorDelegate: ClientErrorDelegate?,
  222. _ onResponsePart: @escaping (ClientResponsePart<Response>) -> Void
  223. ) -> AnyClientInterceptor<Request, Response> {
  224. let tail = TailClientInterceptor(for: pipeline, errorDelegate: errorDelegate, onResponsePart)
  225. return .init(.tail(tail))
  226. }
  227. /// A user provided interceptor.
  228. /// - Parameter interceptor: The interceptor to wrap.
  229. /// - Returns: An `AnyClientInterceptor` which wraps `interceptor`.
  230. internal static func userProvided(
  231. _ interceptor: ClientInterceptor<Request, Response>
  232. ) -> AnyClientInterceptor<Request, Response> {
  233. return .init(.base(interceptor))
  234. }
  235. private init(_ implementation: Implementation) {
  236. self._implementation = implementation
  237. }
  238. internal func read(
  239. _ part: ClientResponsePart<Response>,
  240. context: ClientInterceptorContext<Request, Response>
  241. ) {
  242. switch self._implementation {
  243. case let .head(handler):
  244. handler.read(part, context: context)
  245. case let .tail(handler):
  246. handler.read(part, context: context)
  247. case let .base(handler):
  248. handler.read(part, context: context)
  249. }
  250. }
  251. @inlinable
  252. internal func write(
  253. _ part: ClientRequestPart<Request>,
  254. promise: EventLoopPromise<Void>?,
  255. context: ClientInterceptorContext<Request, Response>
  256. ) {
  257. switch self._implementation {
  258. case let .head(handler):
  259. handler.write(part, promise: promise, context: context)
  260. case let .tail(handler):
  261. handler.write(part, promise: promise, context: context)
  262. case let .base(handler):
  263. handler.write(part, promise: promise, context: context)
  264. }
  265. }
  266. internal func cancel(
  267. promise: EventLoopPromise<Void>?,
  268. context: ClientInterceptorContext<Request, Response>
  269. ) {
  270. switch self._implementation {
  271. case let .head(handler):
  272. handler.cancel(promise: promise, context: context)
  273. case let .tail(handler):
  274. handler.cancel(promise: promise, context: context)
  275. case let .base(handler):
  276. handler.cancel(promise: promise, context: context)
  277. }
  278. }
  279. }