2
0

StreamingResponseCallContext.swift 5.3 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 Logging
  18. import NIO
  19. import NIOHPACK
  20. import NIOHTTP1
  21. import SwiftProtobuf
  22. /// Abstract base class exposing a method to send multiple messages over the wire and a promise for the final RPC status.
  23. ///
  24. /// - When `statusPromise` is fulfilled, the call is closed and the provided status transmitted.
  25. /// - If `statusPromise` is failed and the error is of type `GRPCStatusTransformable`,
  26. /// the result of `error.asGRPCStatus()` will be returned to the client.
  27. /// - If `error.asGRPCStatus()` is not available, `GRPCStatus.processingError` is returned to the client.
  28. open class StreamingResponseCallContext<ResponsePayload>: ServerCallContextBase {
  29. typealias WrappedResponse = _GRPCServerResponsePart<ResponsePayload>
  30. public let statusPromise: EventLoopPromise<GRPCStatus>
  31. override public init(eventLoop: EventLoop, headers: HPACKHeaders, logger: Logger) {
  32. self.statusPromise = eventLoop.makePromise()
  33. super.init(eventLoop: eventLoop, headers: headers, logger: logger)
  34. }
  35. @available(*, deprecated, renamed: "init(eventLoop:path:headers:logger:)")
  36. override public init(eventLoop: EventLoop, request: HTTPRequestHead, logger: Logger) {
  37. self.statusPromise = eventLoop.makePromise()
  38. super.init(eventLoop: eventLoop, request: request, logger: logger)
  39. }
  40. /// Send a response to the client.
  41. ///
  42. /// - Parameter message: The message to send to the client.
  43. /// - Parameter compression: Whether compression should be used for this response. If compression
  44. /// is enabled in the call context, the value passed here takes precedence. Defaults to deferring
  45. /// to the value set on the call context.
  46. open func sendResponse(_ message: ResponsePayload,
  47. compression: Compression = .deferToCallDefault) -> EventLoopFuture<Void> {
  48. fatalError("needs to be overridden")
  49. }
  50. }
  51. /// Concrete implementation of `StreamingResponseCallContext` used by our generated code.
  52. open class StreamingResponseCallContextImpl<ResponsePayload>: StreamingResponseCallContext<ResponsePayload> {
  53. public let channel: Channel
  54. /// - Parameters:
  55. /// - channel: The NIO channel the call is handled on.
  56. /// - headers: The headers provided with this call.
  57. /// - errorDelegate: Provides a means for transforming status promise failures to `GRPCStatusTransformable` before
  58. /// sending them to the client.
  59. /// - logger: A logger.
  60. ///
  61. /// Note: `errorDelegate` is not called for status promise that are `succeeded` with a non-OK status.
  62. public init(
  63. channel: Channel,
  64. headers: HPACKHeaders,
  65. errorDelegate: ServerErrorDelegate?,
  66. logger: Logger
  67. ) {
  68. self.channel = channel
  69. super.init(eventLoop: channel.eventLoop, headers: headers, logger: logger)
  70. self.statusPromise.futureResult.whenComplete { result in
  71. switch result {
  72. case let .success(status):
  73. self.channel.writeAndFlush(
  74. self.wrap(.statusAndTrailers(status, self.trailers)),
  75. promise: nil
  76. )
  77. case let .failure(error):
  78. let (status, trailers) = self.processError(error, delegate: errorDelegate)
  79. self.channel.writeAndFlush(self.wrap(.statusAndTrailers(status, trailers)), promise: nil)
  80. }
  81. }
  82. }
  83. /// Wrap the response part in a `NIOAny`. This is useful in order to avoid explicitly spelling
  84. /// out `NIOAny(WrappedResponse(...))`.
  85. private func wrap(_ response: WrappedResponse) -> NIOAny {
  86. return NIOAny(response)
  87. }
  88. @available(*, deprecated, renamed: "init(channel:headers:errorDelegate:logger:)")
  89. public convenience init(
  90. channel: Channel,
  91. request: HTTPRequestHead,
  92. errorDelegate: ServerErrorDelegate?,
  93. logger: Logger
  94. ) {
  95. self.init(
  96. channel: channel,
  97. headers: HPACKHeaders(httpHeaders: request.headers, normalizeHTTPHeaders: false),
  98. errorDelegate: errorDelegate,
  99. logger: logger
  100. )
  101. }
  102. override open func sendResponse(
  103. _ message: ResponsePayload,
  104. compression: Compression = .deferToCallDefault
  105. ) -> EventLoopFuture<Void> {
  106. let messageContext = _MessageContext(
  107. message,
  108. compressed: compression.isEnabled(callDefault: self.compressionEnabled)
  109. )
  110. return self.channel.writeAndFlush(NIOAny(WrappedResponse.message(messageContext)))
  111. }
  112. }
  113. /// Concrete implementation of `StreamingResponseCallContext` used for testing.
  114. ///
  115. /// Simply records all sent messages.
  116. open class StreamingResponseCallContextTestStub<ResponsePayload>: StreamingResponseCallContext<ResponsePayload> {
  117. open var recordedResponses: [ResponsePayload] = []
  118. override open func sendResponse(
  119. _ message: ResponsePayload,
  120. compression: Compression = .deferToCallDefault
  121. ) -> EventLoopFuture<Void> {
  122. self.recordedResponses.append(message)
  123. return eventLoop.makeSucceededFuture(())
  124. }
  125. }