WriteCapturingHandler.swift 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Copyright 2020, 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 NIO
  17. /// A handler which redirects all writes into a callback until the `.end` part is seen, after which
  18. /// all writes will be failed.
  19. ///
  20. /// This handler is intended for use with 'fake' response streams the 'FakeChannel'.
  21. internal final class WriteCapturingHandler<Request>: ChannelOutboundHandler {
  22. typealias OutboundIn = _GRPCClientRequestPart<Request>
  23. typealias RequestHandler = (FakeRequestPart<Request>) -> Void
  24. private var state: State
  25. private enum State {
  26. case active(RequestHandler)
  27. case inactive
  28. }
  29. internal init(requestHandler: @escaping RequestHandler) {
  30. self.state = .active(requestHandler)
  31. }
  32. internal func write(
  33. context: ChannelHandlerContext,
  34. data: NIOAny,
  35. promise: EventLoopPromise<Void>?
  36. ) {
  37. guard case let .active(handler) = self.state else {
  38. promise?.fail(ChannelError.ioOnClosedChannel)
  39. return
  40. }
  41. switch self.unwrapOutboundIn(data) {
  42. case let .head(requestHead):
  43. handler(.metadata(requestHead.customMetadata))
  44. case let .message(messageContext):
  45. handler(.message(messageContext.message))
  46. case .end:
  47. handler(.end)
  48. // We're done now.
  49. self.state = .inactive
  50. }
  51. promise?.succeed(())
  52. }
  53. }