StreamingResponseCallContext.swift 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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. /// Abstract base class exposing a method to send multiple messages over the wire and a promise for the final RPC status.
  22. ///
  23. /// - When `statusPromise` is fulfilled, the call is closed and the provided status transmitted.
  24. /// - If `statusPromise` is failed and the error is of type `GRPCStatusTransformable`,
  25. /// the result of `error.asGRPCStatus()` will be returned to the client.
  26. /// - If `error.asGRPCStatus()` is not available, `GRPCStatus.processingError` is returned to the client.
  27. open class StreamingResponseCallContext<ResponsePayload>: ServerCallContextBase {
  28. typealias WrappedResponse = _GRPCServerResponsePart<ResponsePayload>
  29. public let statusPromise: EventLoopPromise<GRPCStatus>
  30. public override init(eventLoop: EventLoop, request: HTTPRequestHead, logger: Logger) {
  31. self.statusPromise = eventLoop.makePromise()
  32. super.init(eventLoop: eventLoop, request: request, logger: logger)
  33. }
  34. /// Send a response to the client.
  35. ///
  36. /// - Parameter message: The message to send to the client.
  37. /// - Parameter compression: Whether compression should be used for this response. If compression
  38. /// is enabled in the call context, the value passed here takes precedence. Defaults to deferring
  39. /// to the value set on the call context.
  40. open func sendResponse(_ message: ResponsePayload, compression: Compression = .deferToCallDefault) -> EventLoopFuture<Void> {
  41. fatalError("needs to be overridden")
  42. }
  43. }
  44. /// Concrete implementation of `StreamingResponseCallContext` used by our generated code.
  45. open class StreamingResponseCallContextImpl<ResponsePayload>: StreamingResponseCallContext<ResponsePayload> {
  46. public let channel: Channel
  47. /// - Parameters:
  48. /// - channel: The NIO channel the call is handled on.
  49. /// - request: The headers provided with this call.
  50. /// - errorDelegate: Provides a means for transforming status promise failures to `GRPCStatusTransformable` before
  51. /// sending them to the client.
  52. ///
  53. /// Note: `errorDelegate` is not called for status promise that are `succeeded` with a non-OK status.
  54. public init(channel: Channel, request: HTTPRequestHead, errorDelegate: ServerErrorDelegate?, logger: Logger) {
  55. self.channel = channel
  56. super.init(eventLoop: channel.eventLoop, request: request, logger: logger)
  57. statusPromise.futureResult
  58. .map {
  59. GRPCStatusAndMetadata(status: $0, metadata: nil)
  60. }
  61. // Ensure that any error provided can be transformed to `GRPCStatus`, using "internal server error" as a fallback.
  62. .recover { [weak errorDelegate] error in
  63. errorDelegate?.observeRequestHandlerError(error, request: request)
  64. if let transformed: GRPCStatusAndMetadata = errorDelegate?.transformRequestHandlerError(error, request: request) {
  65. return transformed
  66. }
  67. if let grpcStatusTransformable = error as? GRPCStatusTransformable {
  68. return GRPCStatusAndMetadata(status: grpcStatusTransformable.makeGRPCStatus(), metadata: nil)
  69. }
  70. return GRPCStatusAndMetadata(status: .processingError, metadata: nil)
  71. }
  72. // Finish the call by returning the final status.
  73. .whenSuccess { statusAndMetadata in
  74. if let metadata = statusAndMetadata.metadata {
  75. self.trailingMetadata.add(contentsOf: metadata)
  76. }
  77. self.channel.writeAndFlush(NIOAny(WrappedResponse.statusAndTrailers(statusAndMetadata.status, self.trailingMetadata)), promise: nil)
  78. }
  79. }
  80. open override func sendResponse(_ message: ResponsePayload, compression: Compression = .deferToCallDefault) -> EventLoopFuture<Void> {
  81. let messageContext = _MessageContext(message, compressed: compression.isEnabled(callDefault: self.compressionEnabled))
  82. return self.channel.writeAndFlush(NIOAny(WrappedResponse.message(messageContext)))
  83. }
  84. }
  85. /// Concrete implementation of `StreamingResponseCallContext` used for testing.
  86. ///
  87. /// Simply records all sent messages.
  88. open class StreamingResponseCallContextTestStub<ResponsePayload>: StreamingResponseCallContext<ResponsePayload> {
  89. open var recordedResponses: [ResponsePayload] = []
  90. open override func sendResponse(_ message: ResponsePayload, compression: Compression = .deferToCallDefault) -> EventLoopFuture<Void> {
  91. recordedResponses.append(message)
  92. return eventLoop.makeSucceededFuture(())
  93. }
  94. }