StreamingResponseCallContext.swift 4.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. // 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 messageContext = _MessageContext(message, compressed: compression.isEnabled(callDefault: self.compressionEnabled))
  72. return self.channel.writeAndFlush(NIOAny(WrappedResponse.message(messageContext)))
  73. }
  74. }
  75. /// Concrete implementation of `StreamingResponseCallContext` used for testing.
  76. ///
  77. /// Simply records all sent messages.
  78. open class StreamingResponseCallContextTestStub<ResponsePayload>: StreamingResponseCallContext<ResponsePayload> {
  79. open var recordedResponses: [ResponsePayload] = []
  80. open override func sendResponse(_ message: ResponsePayload, compression: Compression = .deferToCallDefault) -> EventLoopFuture<Void> {
  81. recordedResponses.append(message)
  82. return eventLoop.makeSucceededFuture(())
  83. }
  84. }