MinimalEchoProvider.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright 2021, 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 EchoModel
  17. import GRPC
  18. import NIO
  19. /// The echo provider that comes with the example does some string processing, we'll avoid some of
  20. /// that here so we're looking at the right things.
  21. public class MinimalEchoProvider: Echo_EchoProvider {
  22. public let interceptors: Echo_EchoServerInterceptorFactoryProtocol? = nil
  23. public func get(
  24. request: Echo_EchoRequest,
  25. context: StatusOnlyCallContext
  26. ) -> EventLoopFuture<Echo_EchoResponse> {
  27. return context.eventLoop.makeSucceededFuture(.with { $0.text = request.text })
  28. }
  29. public func expand(
  30. request: Echo_EchoRequest,
  31. context: StreamingResponseCallContext<Echo_EchoResponse>
  32. ) -> EventLoopFuture<GRPCStatus> {
  33. for part in request.text.utf8.split(separator: UInt8(ascii: " ")) {
  34. context.sendResponse(.with { $0.text = String(part)! }, promise: nil)
  35. }
  36. return context.eventLoop.makeSucceededFuture(.ok)
  37. }
  38. public func collect(
  39. context: UnaryResponseCallContext<Echo_EchoResponse>
  40. ) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  41. var parts: [String] = []
  42. func onEvent(_ event: StreamEvent<Echo_EchoRequest>) {
  43. switch event {
  44. case let .message(request):
  45. parts.append(request.text)
  46. case .end:
  47. context.responsePromise.succeed(.with { $0.text = parts.joined(separator: " ") })
  48. }
  49. }
  50. return context.eventLoop.makeSucceededFuture(onEvent(_:))
  51. }
  52. public func update(
  53. context: StreamingResponseCallContext<Echo_EchoResponse>
  54. ) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  55. func onEvent(_ event: StreamEvent<Echo_EchoRequest>) {
  56. switch event {
  57. case let .message(request):
  58. context.sendResponse(.with { $0.text = request.text }, promise: nil)
  59. case .end:
  60. context.statusPromise.succeed(.ok)
  61. }
  62. }
  63. return context.eventLoop.makeSucceededFuture(onEvent(_:))
  64. }
  65. }