ServerInterceptorPipeline.swift 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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. @usableFromInline
  19. internal final class ServerInterceptorPipeline<Request, Response> {
  20. /// The `EventLoop` this RPC is being executed on.
  21. @usableFromInline
  22. internal let eventLoop: EventLoop
  23. /// The path of the RPC in the format "/Service/Method", e.g. "/echo.Echo/Get".
  24. @usableFromInline
  25. internal let path: String
  26. /// The type of the RPC, e.g. "unary".
  27. @usableFromInline
  28. internal let type: GRPCCallType
  29. /// A logger.
  30. @usableFromInline
  31. internal let logger: Logger
  32. /// A reference to a 'UserInfo'.
  33. @usableFromInline
  34. internal let userInfoRef: Ref<UserInfo>
  35. /// The contexts associated with the interceptors stored in this pipeline. Contexts will be
  36. /// removed once the RPC has completed. Contexts are ordered from inbound to outbound, that is,
  37. /// the head is first and the tail is last.
  38. @usableFromInline
  39. internal var _contexts: InterceptorContextList<ServerInterceptorContext<Request, Response>>?
  40. /// Returns the next context in the outbound direction for the context at the given index, if one
  41. /// exists.
  42. /// - Parameter index: The index of the `ServerInterceptorContext` which is requesting the next
  43. /// outbound context.
  44. /// - Returns: The `ServerInterceptorContext` or `nil` if one does not exist.
  45. @inlinable
  46. internal func nextOutboundContext(
  47. forIndex index: Int
  48. ) -> ServerInterceptorContext<Request, Response>? {
  49. return self._context(atIndex: index - 1)
  50. }
  51. /// Returns the next context in the inbound direction for the context at the given index, if one
  52. /// exists.
  53. /// - Parameter index: The index of the `ServerInterceptorContext` which is requesting the next
  54. /// inbound context.
  55. /// - Returns: The `ServerInterceptorContext` or `nil` if one does not exist.
  56. @inlinable
  57. internal func nextInboundContext(
  58. forIndex index: Int
  59. ) -> ServerInterceptorContext<Request, Response>? {
  60. return self._context(atIndex: index + 1)
  61. }
  62. /// Returns the context for the given index, if one exists.
  63. /// - Parameter index: The index of the `ServerInterceptorContext` to return.
  64. /// - Returns: The `ServerInterceptorContext` or `nil` if one does not exist for the given index.
  65. @inlinable
  66. internal func _context(atIndex index: Int) -> ServerInterceptorContext<Request, Response>? {
  67. return self._contexts?[checked: index]
  68. }
  69. /// The context closest to the `NIO.Channel`, i.e. where inbound events originate. This will be
  70. /// `nil` once the RPC has completed.
  71. @inlinable
  72. internal var head: ServerInterceptorContext<Request, Response>? {
  73. return self._contexts?.first
  74. }
  75. /// The context closest to the application, i.e. where outbound events originate. This will be
  76. /// `nil` once the RPC has completed.
  77. @inlinable
  78. internal var tail: ServerInterceptorContext<Request, Response>? {
  79. return self._contexts?.last
  80. }
  81. @inlinable
  82. internal init(
  83. logger: Logger,
  84. eventLoop: EventLoop,
  85. path: String,
  86. callType: GRPCCallType,
  87. userInfoRef: Ref<UserInfo>,
  88. interceptors: [ServerInterceptor<Request, Response>],
  89. onRequestPart: @escaping (GRPCServerRequestPart<Request>) -> Void,
  90. onResponsePart: @escaping (GRPCServerResponsePart<Response>, EventLoopPromise<Void>?) -> Void
  91. ) {
  92. self.logger = logger
  93. self.eventLoop = eventLoop
  94. self.path = path
  95. self.type = callType
  96. self.userInfoRef = userInfoRef
  97. // We need space for the head and tail as well as any user provided interceptors.
  98. self._contexts = InterceptorContextList(
  99. for: self,
  100. interceptors: interceptors,
  101. onRequestPart: onRequestPart,
  102. onResponsePart: onResponsePart
  103. )
  104. }
  105. /// Emit a request part message into the interceptor pipeline.
  106. ///
  107. /// - Parameter part: The part to emit into the pipeline.
  108. /// - Important: This *must* to be called from the `eventLoop`.
  109. @inlinable
  110. internal func receive(_ part: GRPCServerRequestPart<Request>) {
  111. self.eventLoop.assertInEventLoop()
  112. self.head?.invokeReceive(part)
  113. }
  114. /// Write a response message into the interceptor pipeline.
  115. ///
  116. /// - Parameters:
  117. /// - part: The response part to sent.
  118. /// - promise: A promise to complete when the response part has been successfully written.
  119. /// - Important: This *must* to be called from the `eventLoop`.
  120. @inlinable
  121. internal func send(_ part: GRPCServerResponsePart<Response>, promise: EventLoopPromise<Void>?) {
  122. self.eventLoop.assertInEventLoop()
  123. if let tail = self.tail {
  124. tail.invokeSend(part, promise: promise)
  125. } else {
  126. promise?.fail(GRPCError.AlreadyComplete())
  127. }
  128. }
  129. @inlinable
  130. internal func close() {
  131. self.eventLoop.assertInEventLoop()
  132. self._contexts = nil
  133. }
  134. }
  135. extension InterceptorContextList {
  136. @inlinable
  137. init<Request, Response>(
  138. for pipeline: ServerInterceptorPipeline<Request, Response>,
  139. interceptors: [ServerInterceptor<Request, Response>],
  140. onRequestPart: @escaping (GRPCServerRequestPart<Request>) -> Void,
  141. onResponsePart: @escaping (GRPCServerResponsePart<Response>, EventLoopPromise<Void>?) -> Void
  142. ) where Element == ServerInterceptorContext<Request, Response> {
  143. let middle = interceptors.enumerated().map { index, interceptor in
  144. ServerInterceptorContext(
  145. for: .userProvided(interceptor),
  146. atIndex: index,
  147. in: pipeline
  148. )
  149. }
  150. let first = ServerInterceptorContext<Request, Response>(
  151. for: .head(for: pipeline, onResponsePart),
  152. atIndex: middle.startIndex - 1,
  153. in: pipeline
  154. )
  155. let last = ServerInterceptorContext<Request, Response>(
  156. for: .tail(onRequestPart),
  157. atIndex: middle.endIndex,
  158. in: pipeline
  159. )
  160. self.init(first: first, middle: middle, last: last)
  161. }
  162. }