ServerInterceptorPipeline.swift 5.9 KB

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