2
0

ServerInterceptorPipeline.swift 6.4 KB

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