StreamingResponseCallContext.swift 4.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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: GRPCPayload>: 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: GRPCPayload>: 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. // Ensure that any error provided can be transformed to `GRPCStatus`, using "internal server error" as a fallback.
  59. .recover { [weak errorDelegate] error in
  60. errorDelegate?.observeRequestHandlerError(error, request: request)
  61. return errorDelegate?.transformRequestHandlerError(error, request: request)
  62. ?? (error as? GRPCStatusTransformable)?.makeGRPCStatus()
  63. ?? .processingError
  64. }
  65. // Finish the call by returning the final status.
  66. .whenSuccess {
  67. self.channel.writeAndFlush(NIOAny(WrappedResponse.statusAndTrailers($0, self.trailingMetadata)), promise: nil)
  68. }
  69. }
  70. open override func sendResponse(_ message: ResponsePayload, compression: Compression = .deferToCallDefault) -> EventLoopFuture<Void> {
  71. let promise: EventLoopPromise<Void> = eventLoop.makePromise()
  72. let messageContext = _MessageContext(message, compressed: compression.isEnabled(callDefault: self.compressionEnabled))
  73. self.channel.writeAndFlush(NIOAny(WrappedResponse.message(messageContext)), promise: promise)
  74. return promise.futureResult
  75. }
  76. }
  77. /// Concrete implementation of `StreamingResponseCallContext` used for testing.
  78. ///
  79. /// Simply records all sent messages.
  80. open class StreamingResponseCallContextTestStub<ResponsePayload: GRPCPayload>: StreamingResponseCallContext<ResponsePayload> {
  81. open var recordedResponses: [ResponsePayload] = []
  82. open override func sendResponse(_ message: ResponsePayload, compression: Compression = .deferToCallDefault) -> EventLoopFuture<Void> {
  83. recordedResponses.append(message)
  84. return eventLoop.makeSucceededFuture(())
  85. }
  86. }