_BaseCallHandler.swift 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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 Foundation
  17. import SwiftProtobuf
  18. import NIO
  19. import NIOHTTP1
  20. import Logging
  21. /// Provides a means for decoding incoming gRPC messages into protobuf objects.
  22. ///
  23. /// Calls through to `processMessage` for individual messages it receives, which needs to be implemented by subclasses.
  24. /// - Important: This is **NOT** part of the public API.
  25. public class _BaseCallHandler<RequestPayload: GRPCPayload, ResponsePayload: GRPCPayload>: GRPCCallHandler {
  26. public func makeGRPCServerCodec() -> ChannelHandler {
  27. return HTTP1ToGRPCServerCodec<RequestPayload, ResponsePayload>(logger: self.logger)
  28. }
  29. /// Called when the request head has been received.
  30. ///
  31. /// Overridden by subclasses.
  32. internal func processHead(_ head: HTTPRequestHead, context: ChannelHandlerContext) {
  33. fatalError("needs to be overridden")
  34. }
  35. /// Called whenever a message has been received.
  36. ///
  37. /// Overridden by subclasses.
  38. internal func processMessage(_ message: RequestPayload) throws {
  39. fatalError("needs to be overridden")
  40. }
  41. /// Called when the client has half-closed the stream, indicating that they won't send any further data.
  42. ///
  43. /// Overridden by subclasses if the "end-of-stream" event is relevant.
  44. internal func endOfStreamReceived() throws { }
  45. /// Sends an error status to the client while ensuring that all call context promises are fulfilled.
  46. /// Because only the concrete call subclass knows which promises need to be fulfilled, this method needs to be overridden.
  47. internal func sendErrorStatus(_ status: GRPCStatus) {
  48. fatalError("needs to be overridden")
  49. }
  50. /// Whether this handler can still write messages to the client.
  51. private var serverCanWrite = true
  52. internal let callHandlerContext: CallHandlerContext
  53. internal var errorDelegate: ServerErrorDelegate? {
  54. return self.callHandlerContext.errorDelegate
  55. }
  56. internal var logger: Logger {
  57. return self.callHandlerContext.logger
  58. }
  59. internal init(callHandlerContext: CallHandlerContext) {
  60. self.callHandlerContext = callHandlerContext
  61. }
  62. }
  63. extension _BaseCallHandler: ChannelInboundHandler {
  64. public typealias InboundIn = _GRPCServerRequestPart<RequestPayload>
  65. /// Passes errors to the user-provided `errorHandler`. After an error has been received an
  66. /// appropriate status is written. Errors which don't conform to `GRPCStatusTransformable`
  67. /// return a status with code `.internalError`.
  68. public func errorCaught(context: ChannelHandlerContext, error: Error) {
  69. let status: GRPCStatus
  70. if let errorWithContext = error as? GRPCError.WithContext {
  71. self.errorDelegate?.observeLibraryError(errorWithContext.error)
  72. status = self.errorDelegate?.transformLibraryError(errorWithContext.error)
  73. ?? errorWithContext.error.makeGRPCStatus()
  74. } else {
  75. self.errorDelegate?.observeLibraryError(error)
  76. status = self.errorDelegate?.transformLibraryError(error)
  77. ?? (error as? GRPCStatusTransformable)?.makeGRPCStatus()
  78. ?? .processingError
  79. }
  80. self.sendErrorStatus(status)
  81. }
  82. public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  83. switch self.unwrapInboundIn(data) {
  84. case .head(let head):
  85. self.processHead(head, context: context)
  86. case .message(let message):
  87. do {
  88. try processMessage(message)
  89. } catch {
  90. self.logger.error("error caught while user handler was processing message", metadata: [MetadataKey.error: "\(error)"])
  91. self.errorCaught(context: context, error: error)
  92. }
  93. case .end:
  94. do {
  95. try endOfStreamReceived()
  96. } catch {
  97. self.logger.error("error caught on receiving end of stream", metadata: [MetadataKey.error: "\(error)"])
  98. self.errorCaught(context: context, error: error)
  99. }
  100. }
  101. }
  102. }
  103. extension _BaseCallHandler: ChannelOutboundHandler {
  104. public typealias OutboundIn = _GRPCServerResponsePart<ResponsePayload>
  105. public typealias OutboundOut = _GRPCServerResponsePart<ResponsePayload>
  106. public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
  107. guard self.serverCanWrite else {
  108. promise?.fail(GRPCError.InvalidState("rpc has already finished").captureContext())
  109. return
  110. }
  111. // We can only write one status; make sure we don't write again.
  112. if case .statusAndTrailers = unwrapOutboundIn(data) {
  113. self.serverCanWrite = false
  114. context.writeAndFlush(data, promise: promise)
  115. } else {
  116. context.write(data, promise: promise)
  117. }
  118. }
  119. }