ServerInterceptors.swift 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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 server 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 two different types of event:
  24. /// - receiving request parts with `receive(_:context:)`,
  25. /// - sending response parts with `send(_:promise:context:)`.
  26. ///
  27. /// These events flow through a pipeline of interceptors for each RPC. Request parts will enter
  28. /// the head of the interceptor pipeline once the request router has determined that there is a
  29. /// service provider which is able to handle the request stream. Response parts from the service
  30. /// provider enter the tail of the interceptor pipeline and will be sent to the client after
  31. /// traversing the pipeline through to the head.
  32. ///
  33. /// Each of the interceptor functions is provided with a `context` which exposes analogous functions
  34. /// (`receive(_:)` and `send(_:promise:)`) which may be called to forward events to the next
  35. /// interceptor.
  36. ///
  37. /// ### Thread Safety
  38. ///
  39. /// Functions on `context` are not thread safe and **must** be called on the `EventLoop` found on
  40. /// the `context`. Since each interceptor is invoked on the same `EventLoop` this does not usually
  41. /// require any extra attention. However, if work is done on a `DispatchQueue` or _other_
  42. /// `EventLoop` then implementers should ensure that they use `context` from the correct
  43. /// `EventLoop`.
  44. open class ServerInterceptor<Request, Response> {
  45. public init() {}
  46. /// Called when the interceptor has received a request part to handle.
  47. /// - Parameters:
  48. /// - part: The request part which has been received from the client.
  49. /// - context: An interceptor context which may be used to forward the response part.
  50. open func receive(
  51. _ part: GRPCServerRequestPart<Request>,
  52. context: ServerInterceptorContext<Request, Response>
  53. ) {
  54. context.receive(part)
  55. }
  56. /// Called when the interceptor has received a response part to handle.
  57. /// - Parameters:
  58. /// - part: The request part which should be sent to the client.
  59. /// - promise: A promise which should be completed when the response part has been written.
  60. /// - context: An interceptor context which may be used to forward the request part.
  61. open func send(
  62. _ part: GRPCServerResponsePart<Response>,
  63. promise: EventLoopPromise<Void>?,
  64. context: ServerInterceptorContext<Request, Response>
  65. ) {
  66. context.send(part, promise: promise)
  67. }
  68. }
  69. // MARK: Head/Tail
  70. /// An interceptor which offloads requests to the service provider and forwards any response parts
  71. /// to the rest of the pipeline.
  72. internal struct TailServerInterceptor<Request, Response> {
  73. /// Called when a request part has been received.
  74. private let onRequestPart: (GRPCServerRequestPart<Request>) -> Void
  75. init(
  76. _ onRequestPart: @escaping (GRPCServerRequestPart<Request>) -> Void
  77. ) {
  78. self.onRequestPart = onRequestPart
  79. }
  80. internal func receive(
  81. _ part: GRPCServerRequestPart<Request>,
  82. context: ServerInterceptorContext<Request, Response>
  83. ) {
  84. self.onRequestPart(part)
  85. }
  86. internal func send(
  87. _ part: GRPCServerResponsePart<Response>,
  88. promise: EventLoopPromise<Void>?,
  89. context: ServerInterceptorContext<Request, Response>
  90. ) {
  91. context.send(part, promise: promise)
  92. }
  93. }
  94. internal struct HeadServerInterceptor<Request, Response> {
  95. /// The pipeline this interceptor belongs to.
  96. private let pipeline: ServerInterceptorPipeline<Request, Response>
  97. /// Called when a response part has been received.
  98. private let onResponsePart: (GRPCServerResponsePart<Response>, EventLoopPromise<Void>?) -> Void
  99. internal init(
  100. for pipeline: ServerInterceptorPipeline<Request, Response>,
  101. _ onResponsePart: @escaping (GRPCServerResponsePart<Response>, EventLoopPromise<Void>?) -> Void
  102. ) {
  103. self.pipeline = pipeline
  104. self.onResponsePart = onResponsePart
  105. }
  106. internal func receive(
  107. _ part: GRPCServerRequestPart<Request>,
  108. context: ServerInterceptorContext<Request, Response>
  109. ) {
  110. context.receive(part)
  111. }
  112. internal func send(
  113. _ part: GRPCServerResponsePart<Response>,
  114. promise: EventLoopPromise<Void>?,
  115. context: ServerInterceptorContext<Request, Response>
  116. ) {
  117. // Close the pipeline on end.
  118. switch part {
  119. case .metadata, .message:
  120. ()
  121. case .end:
  122. self.pipeline.close()
  123. }
  124. self.onResponsePart(part, promise)
  125. }
  126. }
  127. // MARK: - Any Interceptor
  128. /// A wrapping interceptor which delegates to the implementation of an underlying interceptor.
  129. internal struct AnyServerInterceptor<Request, Response> {
  130. internal enum Implementation {
  131. case head(HeadServerInterceptor<Request, Response>)
  132. case tail(TailServerInterceptor<Request, Response>)
  133. case base(ServerInterceptor<Request, Response>)
  134. }
  135. /// The underlying interceptor implementation.
  136. internal let _implementation: Implementation
  137. internal static func head(
  138. for pipeline: ServerInterceptorPipeline<Request, Response>,
  139. _ onResponsePart: @escaping (GRPCServerResponsePart<Response>, EventLoopPromise<Void>?) -> Void
  140. ) -> AnyServerInterceptor<Request, Response> {
  141. return .init(.head(.init(for: pipeline, onResponsePart)))
  142. }
  143. internal static func tail(
  144. _ onRequestPart: @escaping (GRPCServerRequestPart<Request>) -> Void
  145. ) -> AnyServerInterceptor<Request, Response> {
  146. return .init(.tail(.init(onRequestPart)))
  147. }
  148. /// A user provided interceptor.
  149. /// - Parameter interceptor: The interceptor to wrap.
  150. /// - Returns: An `AnyServerInterceptor` which wraps `interceptor`.
  151. internal static func userProvided(
  152. _ interceptor: ServerInterceptor<Request, Response>
  153. ) -> AnyServerInterceptor<Request, Response> {
  154. return .init(.base(interceptor))
  155. }
  156. private init(_ implementation: Implementation) {
  157. self._implementation = implementation
  158. }
  159. internal func receive(
  160. _ part: GRPCServerRequestPart<Request>,
  161. context: ServerInterceptorContext<Request, Response>
  162. ) {
  163. switch self._implementation {
  164. case let .head(interceptor):
  165. interceptor.receive(part, context: context)
  166. case let .tail(interceptor):
  167. interceptor.receive(part, context: context)
  168. case let .base(interceptor):
  169. interceptor.receive(part, context: context)
  170. }
  171. }
  172. internal func send(
  173. _ part: GRPCServerResponsePart<Response>,
  174. promise: EventLoopPromise<Void>?,
  175. context: ServerInterceptorContext<Request, Response>
  176. ) {
  177. switch self._implementation {
  178. case let .head(interceptor):
  179. interceptor.send(part, promise: promise, context: context)
  180. case let .tail(interceptor):
  181. interceptor.send(part, promise: promise, context: context)
  182. case let .base(interceptor):
  183. interceptor.send(part, promise: promise, context: context)
  184. }
  185. }
  186. }