RPCRouter.swift 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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. ///
  25. /// In most cases you won't need to interact with the router directly. Instead you should register
  26. /// your services with ``GRPCServer/Services-swift.struct/register(_:)`` which will in turn register
  27. /// each method with the router.
  28. ///
  29. /// You may wish to not serve all methods from your service in which case you can either:
  30. ///
  31. /// 1. Remove individual methods by calling ``removeHandler(forMethod:)``, or
  32. /// 2. Implement ``RegistrableRPCService/registerMethods(with:)`` to register only the methods you
  33. /// want to be served.
  34. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  35. public struct RPCRouter: Sendable {
  36. @usableFromInline
  37. struct RPCHandler: Sendable {
  38. @usableFromInline
  39. let _fn:
  40. @Sendable (
  41. _ stream: RPCStream<RPCAsyncSequence<RPCRequestPart>, RPCWriter<RPCResponsePart>.Closable>,
  42. _ interceptors: [any ServerInterceptor]
  43. ) async -> Void
  44. @inlinable
  45. init<Input, Output>(
  46. method: MethodDescriptor,
  47. deserializer: some MessageDeserializer<Input>,
  48. serializer: some MessageSerializer<Output>,
  49. handler: @Sendable @escaping (
  50. _ request: ServerRequest.Stream<Input>
  51. ) async throws -> ServerResponse.Stream<Output>
  52. ) {
  53. self._fn = { stream, interceptors in
  54. await ServerRPCExecutor.execute(
  55. stream: stream,
  56. deserializer: deserializer,
  57. serializer: serializer,
  58. interceptors: interceptors,
  59. handler: handler
  60. )
  61. }
  62. }
  63. @inlinable
  64. func handle(
  65. stream: RPCStream<RPCAsyncSequence<RPCRequestPart>, RPCWriter<RPCResponsePart>.Closable>,
  66. interceptors: [any ServerInterceptor]
  67. ) async {
  68. await self._fn(stream, interceptors)
  69. }
  70. }
  71. @usableFromInline
  72. private(set) var handlers: [MethodDescriptor: RPCHandler]
  73. /// Creates a new router with no methods registered.
  74. public init() {
  75. self.handlers = [:]
  76. }
  77. /// Returns all descriptors known to the router in an undefined order.
  78. public var methods: [MethodDescriptor] {
  79. Array(self.handlers.keys)
  80. }
  81. /// Returns the number of methods registered with the router.
  82. public var count: Int {
  83. self.handlers.count
  84. }
  85. /// Returns whether a handler exists for a given method.
  86. ///
  87. /// - Parameter descriptor: A descriptor of the method.
  88. /// - Returns: Whether a handler exists for the method.
  89. public func hasHandler(forMethod descriptor: MethodDescriptor) -> Bool {
  90. return self.handlers.keys.contains(descriptor)
  91. }
  92. /// Registers a handler with the router.
  93. ///
  94. /// - Note: if a handler already exists for a given method then it will be replaced.
  95. ///
  96. /// - Parameters:
  97. /// - descriptor: A descriptor for the method to register a handler for.
  98. /// - deserializer: A deserializer to deserialize input messages received from the client.
  99. /// - serializer: A serializer to serialize output messages to send to the client.
  100. /// - handler: The function which handles the request and returns a response.
  101. @inlinable
  102. public mutating func registerHandler<Input: Sendable, Output: Sendable>(
  103. forMethod descriptor: MethodDescriptor,
  104. deserializer: some MessageDeserializer<Input>,
  105. serializer: some MessageSerializer<Output>,
  106. handler: @Sendable @escaping (
  107. _ request: ServerRequest.Stream<Input>
  108. ) async throws -> ServerResponse.Stream<Output>
  109. ) {
  110. self.handlers[descriptor] = RPCHandler(
  111. method: descriptor,
  112. deserializer: deserializer,
  113. serializer: serializer,
  114. handler: handler
  115. )
  116. }
  117. /// Removes any handler registered for the specified method.
  118. ///
  119. /// - Parameter descriptor: A descriptor of the method to remove a handler for.
  120. /// - Returns: Whether a handler was removed.
  121. @discardableResult
  122. public mutating func removeHandler(forMethod descriptor: MethodDescriptor) -> Bool {
  123. return self.handlers.removeValue(forKey: descriptor) != nil
  124. }
  125. }
  126. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  127. extension RPCRouter {
  128. internal func handle(
  129. stream: RPCStream<RPCAsyncSequence<RPCRequestPart>, RPCWriter<RPCResponsePart>.Closable>,
  130. interceptors: [any ServerInterceptor]
  131. ) async {
  132. if let handler = self.handlers[stream.descriptor] {
  133. await handler.handle(stream: stream, interceptors: interceptors)
  134. } else {
  135. // If this throws then the stream must be closed which we can't do anything about, so ignore
  136. // any error.
  137. try? await stream.outbound.write(.status(.rpcNotImplemented, [:]))
  138. stream.outbound.finish()
  139. }
  140. }
  141. }
  142. extension Status {
  143. fileprivate static let rpcNotImplemented = Status(
  144. code: .unimplemented,
  145. message: "Requested RPC isn't implemented by this server."
  146. )
  147. }