RPCRouter.swift 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. /*
  2. * Copyright 2023, 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. /// Stores and provides handlers for RPCs.
  17. ///
  18. /// The router stores a handler for each RPC it knows about. Each handler encapsulate the business
  19. /// logic for the RPC which is typically implemented by service owners. To register a handler you
  20. /// can call ``registerHandler(forMethod:deserializer:serializer:handler:)``. You can check whether
  21. /// the router has a handler for a method with ``hasHandler(forMethod:)`` or get a list of all
  22. /// methods with handlers registered by calling ``methods``. You can also remove the handler for a
  23. /// given method by calling ``removeHandler(forMethod:)``.
  24. /// You can also register any interceptors that you want applied to registered handlers via the
  25. /// ``registerInterceptors(pipeline:)`` method.
  26. ///
  27. /// In most cases you won't need to interact with the router directly. Instead you should register
  28. /// your services with ``GRPCServer/init(transport:services:interceptors:)`` which will in turn
  29. /// register each method with the router.
  30. ///
  31. /// You may wish to not serve all methods from your service in which case you can either:
  32. ///
  33. /// 1. Remove individual methods by calling ``removeHandler(forMethod:)``, or
  34. /// 2. Implement ``RegistrableRPCService/registerMethods(with:)`` to register only the methods you
  35. /// want to be served.
  36. public struct RPCRouter<Transport: ServerTransport>: Sendable {
  37. @usableFromInline
  38. struct RPCHandler: Sendable {
  39. @usableFromInline
  40. let _fn:
  41. @Sendable (
  42. _ stream: RPCStream<
  43. RPCAsyncSequence<RPCRequestPart<Transport.Bytes>, any Error>,
  44. RPCWriter<RPCResponsePart<Transport.Bytes>>.Closable
  45. >,
  46. _ context: ServerContext,
  47. _ interceptors: [any ServerInterceptor]
  48. ) async -> Void
  49. @inlinable
  50. init<Input, Output>(
  51. method: MethodDescriptor,
  52. deserializer: some MessageDeserializer<Input>,
  53. serializer: some MessageSerializer<Output>,
  54. handler: @Sendable @escaping (
  55. _ request: StreamingServerRequest<Input>,
  56. _ context: ServerContext
  57. ) async throws -> StreamingServerResponse<Output>
  58. ) {
  59. self._fn = { stream, context, interceptors in
  60. await ServerRPCExecutor.execute(
  61. context: context,
  62. stream: stream,
  63. deserializer: deserializer,
  64. serializer: serializer,
  65. interceptors: interceptors,
  66. handler: handler
  67. )
  68. }
  69. }
  70. @inlinable
  71. func handle(
  72. stream: RPCStream<
  73. RPCAsyncSequence<RPCRequestPart<Transport.Bytes>, any Error>,
  74. RPCWriter<RPCResponsePart<Transport.Bytes>>.Closable
  75. >,
  76. context: ServerContext,
  77. interceptors: [any ServerInterceptor]
  78. ) async {
  79. await self._fn(stream, context, interceptors)
  80. }
  81. }
  82. @usableFromInline
  83. private(set) var handlers:
  84. [MethodDescriptor: (handler: RPCHandler, interceptors: [any ServerInterceptor])]
  85. /// Creates a new router with no methods registered.
  86. public init() {
  87. self.handlers = [:]
  88. }
  89. /// Returns all descriptors known to the router in an undefined order.
  90. public var methods: [MethodDescriptor] {
  91. Array(self.handlers.keys)
  92. }
  93. /// Returns the number of methods registered with the router.
  94. public var count: Int {
  95. self.handlers.count
  96. }
  97. /// Returns whether a handler exists for a given method.
  98. ///
  99. /// - Parameter descriptor: A descriptor of the method.
  100. /// - Returns: Whether a handler exists for the method.
  101. public func hasHandler(forMethod descriptor: MethodDescriptor) -> Bool {
  102. return self.handlers.keys.contains(descriptor)
  103. }
  104. /// Registers a handler with the router.
  105. ///
  106. /// - Note: if a handler already exists for a given method then it will be replaced.
  107. ///
  108. /// - Parameters:
  109. /// - descriptor: A descriptor for the method to register a handler for.
  110. /// - deserializer: A deserializer to deserialize input messages received from the client.
  111. /// - serializer: A serializer to serialize output messages to send to the client.
  112. /// - handler: The function which handles the request and returns a response.
  113. @inlinable
  114. public mutating func registerHandler<Input: Sendable, Output: Sendable>(
  115. forMethod descriptor: MethodDescriptor,
  116. deserializer: some MessageDeserializer<Input>,
  117. serializer: some MessageSerializer<Output>,
  118. handler: @Sendable @escaping (
  119. _ request: StreamingServerRequest<Input>,
  120. _ context: ServerContext
  121. ) async throws -> StreamingServerResponse<Output>
  122. ) {
  123. let handler = RPCHandler(
  124. method: descriptor,
  125. deserializer: deserializer,
  126. serializer: serializer,
  127. handler: handler
  128. )
  129. self.handlers[descriptor] = (handler, [])
  130. }
  131. /// Removes any handler registered for the specified method.
  132. ///
  133. /// - Parameter descriptor: A descriptor of the method to remove a handler for.
  134. /// - Returns: Whether a handler was removed.
  135. @discardableResult
  136. public mutating func removeHandler(forMethod descriptor: MethodDescriptor) -> Bool {
  137. return self.handlers.removeValue(forKey: descriptor) != nil
  138. }
  139. /// Registers applicable interceptors to all currently-registered handlers.
  140. ///
  141. /// - Important: Calling this method will apply the interceptors only to existing handlers. Any handlers registered via
  142. /// ``registerHandler(forMethod:deserializer:serializer:handler:)`` _after_ calling this method will not have
  143. /// any interceptors applied to them. If you want to make sure all registered methods have any applicable interceptors applied,
  144. /// only call this method _after_ you have registered all handlers.
  145. /// - Parameter pipeline: The interceptor pipeline operations to register to all currently-registered handlers. The order of the
  146. /// interceptors matters.
  147. @inlinable
  148. public mutating func registerInterceptors(
  149. pipeline: [ConditionalInterceptor<any ServerInterceptor>]
  150. ) {
  151. for descriptor in self.handlers.keys {
  152. let applicableOperations = pipeline.filter { $0.applies(to: descriptor) }
  153. if !applicableOperations.isEmpty {
  154. self.handlers[descriptor]?.interceptors = applicableOperations.map { $0.interceptor }
  155. }
  156. }
  157. }
  158. }
  159. extension RPCRouter {
  160. internal func handle(
  161. stream: RPCStream<
  162. RPCAsyncSequence<RPCRequestPart<Transport.Bytes>, any Error>,
  163. RPCWriter<RPCResponsePart<Transport.Bytes>>.Closable
  164. >,
  165. context: ServerContext
  166. ) async {
  167. if let (handler, interceptors) = self.handlers[stream.descriptor] {
  168. await handler.handle(stream: stream, context: context, interceptors: interceptors)
  169. } else {
  170. // If this throws then the stream must be closed which we can't do anything about, so ignore
  171. // any error.
  172. try? await stream.outbound.write(.status(.rpcNotImplemented, [:]))
  173. await stream.outbound.finish()
  174. }
  175. }
  176. }
  177. extension Status {
  178. fileprivate static let rpcNotImplemented = Status(
  179. code: .unimplemented,
  180. message: "Requested RPC isn't implemented by this server."
  181. )
  182. }