GRPCServerRequestRoutingHandler.swift 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. /*
  2. * Copyright 2019, 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 SwiftProtobuf
  17. import NIO
  18. import NIOHTTP1
  19. import Logging
  20. /// Processes individual gRPC messages and stream-close events on an HTTP2 channel.
  21. public protocol GRPCCallHandler: ChannelHandler {
  22. var _codec: ChannelHandler { get }
  23. }
  24. /// Provides `GRPCCallHandler` objects for the methods on a particular service name.
  25. ///
  26. /// Implemented by the generated code.
  27. public protocol CallHandlerProvider: class {
  28. /// The name of the service this object is providing methods for, including the package path.
  29. ///
  30. /// - Example: "io.grpc.Echo.EchoService"
  31. var serviceName: Substring { get }
  32. /// Determines, calls and returns the appropriate request handler (`GRPCCallHandler`), depending on the request's
  33. /// method. Returns nil for methods not handled by this service.
  34. func handleMethod(_ methodName: Substring, callHandlerContext: CallHandlerContext) -> GRPCCallHandler?
  35. }
  36. // This is public because it will be passed into generated code, all members are `internal` because
  37. // the context will get passed from generated code back into gRPC library code and all members should
  38. // be considered an implementation detail to the user.
  39. public struct CallHandlerContext {
  40. internal var errorDelegate: ServerErrorDelegate?
  41. internal var logger: Logger
  42. internal var encoding: ServerMessageEncoding
  43. }
  44. /// Attempts to route a request to a user-provided call handler. Also validates that the request has
  45. /// a suitable 'content-type' for gRPC.
  46. ///
  47. /// Once the request headers are available, asks the `CallHandlerProvider` corresponding to the request's service name
  48. /// for a `GRPCCallHandler` object. That object is then forwarded the individual gRPC messages.
  49. ///
  50. /// After the pipeline has been configured with the `GRPCCallHandler`, this handler removes itself
  51. /// from the pipeline.
  52. public final class GRPCServerRequestRoutingHandler {
  53. private let logger: Logger
  54. private let servicesByName: [Substring: CallHandlerProvider]
  55. private let encoding: ServerMessageEncoding
  56. private weak var errorDelegate: ServerErrorDelegate?
  57. private enum State: Equatable {
  58. case notConfigured
  59. case configuring([InboundOut])
  60. }
  61. private var state: State = .notConfigured
  62. public init(
  63. servicesByName: [Substring: CallHandlerProvider],
  64. encoding: ServerMessageEncoding,
  65. errorDelegate: ServerErrorDelegate?,
  66. logger: Logger
  67. ) {
  68. self.servicesByName = servicesByName
  69. self.encoding = encoding
  70. self.errorDelegate = errorDelegate
  71. self.logger = logger
  72. }
  73. }
  74. extension GRPCServerRequestRoutingHandler: ChannelInboundHandler, RemovableChannelHandler {
  75. public typealias InboundIn = HTTPServerRequestPart
  76. public typealias InboundOut = HTTPServerRequestPart
  77. public typealias OutboundOut = HTTPServerResponsePart
  78. public func errorCaught(context: ChannelHandlerContext, error: Error) {
  79. let status: GRPCStatus
  80. if let errorWithContext = error as? GRPCError.WithContext {
  81. self.errorDelegate?.observeLibraryError(errorWithContext.error)
  82. status = errorWithContext.error.makeGRPCStatus()
  83. } else {
  84. self.errorDelegate?.observeLibraryError(error)
  85. status = (error as? GRPCStatusTransformable)?.makeGRPCStatus() ?? .processingError
  86. }
  87. switch self.state {
  88. case .notConfigured:
  89. // We don't know what protocol we're speaking at this point. We'll just have to close the
  90. // channel.
  91. ()
  92. case .configuring(let messages):
  93. // first! is fine here: we only go from `.notConfigured` to `.configuring` when we receive
  94. // and validate the request head.
  95. let head = messages.compactMap { part -> HTTPRequestHead? in
  96. switch part {
  97. case .head(let head):
  98. return head
  99. default:
  100. return nil
  101. }
  102. }.first!
  103. let responseHead = self.makeResponseHead(requestHead: head, status: status)
  104. context.write(self.wrapOutboundOut(.head(responseHead)), promise: nil)
  105. context.write(self.wrapOutboundOut(.end(nil)), promise: nil)
  106. context.flush()
  107. }
  108. context.close(mode: .all, promise: nil)
  109. }
  110. public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  111. let requestPart = self.unwrapInboundIn(data)
  112. switch self.unwrapInboundIn(data) {
  113. case .head(let requestHead):
  114. precondition(.notConfigured == self.state)
  115. // Validate the 'content-type' is related to gRPC before proceeding.
  116. let maybeContentType = requestHead.headers.first(name: GRPCHeaderName.contentType)
  117. guard let contentType = maybeContentType, contentType.starts(with: ContentType.commonPrefix) else {
  118. self.logger.warning(
  119. "received request whose 'content-type' does not exist or start with '\(ContentType.commonPrefix)'",
  120. metadata: ["content-type": "\(String(describing: maybeContentType))"]
  121. )
  122. // From: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
  123. //
  124. // If 'content-type' does not begin with "application/grpc", gRPC servers SHOULD respond
  125. // with HTTP status of 415 (Unsupported Media Type). This will prevent other HTTP/2
  126. // clients from interpreting a gRPC error response, which uses status 200 (OK), as
  127. // successful.
  128. let responseHead = HTTPResponseHead(
  129. version: requestHead.version,
  130. status: .unsupportedMediaType
  131. )
  132. // Fail the call. Note: we're not speaking gRPC here, so no status or message.
  133. context.write(self.wrapOutboundOut(.head(responseHead)), promise: nil)
  134. context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil)
  135. return
  136. }
  137. // Do we know how to handle this RPC?
  138. guard let callHandler = self.makeCallHandler(channel: context.channel, requestHead: requestHead) else {
  139. self.logger.warning(
  140. "unable to make call handler; the RPC is not implemented on this server",
  141. metadata: ["uri": "\(requestHead.uri)"]
  142. )
  143. let status = GRPCError.RPCNotImplemented(rpc: requestHead.uri).makeGRPCStatus()
  144. let responseHead = self.makeResponseHead(requestHead: requestHead, status: status)
  145. // Write back a 'trailers-only' response.
  146. context.write(self.wrapOutboundOut(.head(responseHead)), promise: nil)
  147. context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil)
  148. return
  149. }
  150. self.logger.debug("received request head, configuring pipeline")
  151. // Buffer the request head; we'll replay it in the next handler when we're removed from the
  152. // pipeline.
  153. self.state = .configuring([requestPart])
  154. // Configure the rest of the pipeline to serve the RPC.
  155. let httpToGRPC = HTTP1ToGRPCServerCodec(encoding: self.encoding, logger: self.logger)
  156. let codec = callHandler._codec
  157. context.pipeline.addHandlers([httpToGRPC, codec, callHandler], position: .after(self)).whenSuccess {
  158. context.pipeline.removeHandler(self, promise: nil)
  159. }
  160. case .body, .end:
  161. switch self.state {
  162. case .notConfigured:
  163. // We can reach this point if we're receiving messages for a method that isn't implemented,
  164. // in which case we just drop the messages; our response should already be in-flight.
  165. ()
  166. case .configuring(var buffer):
  167. // We received a message while the pipeline was being configured; hold on to it while we
  168. // finish configuring the pipeline.
  169. buffer.append(requestPart)
  170. self.state = .configuring(buffer)
  171. }
  172. }
  173. }
  174. public func handlerRemoved(context: ChannelHandlerContext) {
  175. switch self.state {
  176. case .notConfigured:
  177. ()
  178. case .configuring(let messages):
  179. for message in messages {
  180. context.fireChannelRead(self.wrapInboundOut(message))
  181. }
  182. }
  183. }
  184. private func makeCallHandler(channel: Channel, requestHead: HTTPRequestHead) -> GRPCCallHandler? {
  185. // URI format: "/package.Servicename/MethodName", resulting in the following components separated by a slash:
  186. // - uriComponents[0]: empty
  187. // - uriComponents[1]: service name (including the package name);
  188. // `CallHandlerProvider`s should provide the service name including the package name.
  189. // - uriComponents[2]: method name.
  190. self.logger.debug("making call handler", metadata: ["path": "\(requestHead.uri)"])
  191. let uriComponents = requestHead.uri.split(separator: "/")
  192. let context = CallHandlerContext(
  193. errorDelegate: self.errorDelegate,
  194. logger: self.logger,
  195. encoding: self.encoding
  196. )
  197. guard uriComponents.count >= 2,
  198. let providerForServiceName = servicesByName[uriComponents[0]],
  199. let callHandler = providerForServiceName.handleMethod(uriComponents[1], callHandlerContext: context) else {
  200. self.logger.notice("could not create handler", metadata: ["path": "\(requestHead.uri)"])
  201. return nil
  202. }
  203. return callHandler
  204. }
  205. private func makeResponseHead(requestHead: HTTPRequestHead, status: GRPCStatus) -> HTTPResponseHead {
  206. var headers: HTTPHeaders = [
  207. GRPCHeaderName.contentType: ContentType.protobuf.canonicalValue,
  208. GRPCHeaderName.statusCode: "\(status.code.rawValue)",
  209. ]
  210. if let message = status.message.flatMap(GRPCStatusMessageMarshaller.marshall) {
  211. headers.add(name: GRPCHeaderName.statusMessage, value: message)
  212. }
  213. return HTTPResponseHead(version: requestHead.version, status: .ok, headers: headers)
  214. }
  215. }