MinimalEchoProvider.swift 2.4 KB

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