AsyncUnaryRequestMaker.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 GRPC
  17. import Logging
  18. import NIO
  19. /// Makes unary requests to the server and records performance statistics.
  20. final class AsyncUnaryRequestMaker: RequestMaker {
  21. private let client: Grpc_Testing_BenchmarkServiceClient
  22. private let requestMessage: Grpc_Testing_SimpleRequest
  23. private let logger: Logger
  24. private let stats: StatsWithLock
  25. /// Initialiser to gather requirements.
  26. /// - Parameters:
  27. /// - config: config from the driver describing what to do.
  28. /// - client: client interface to the server.
  29. /// - requestMessage: Pre-made request message to use possibly repeatedly.
  30. /// - logger: Where to log useful diagnostics.
  31. /// - stats: Where to record statistics on latency.
  32. init(config: Grpc_Testing_ClientConfig,
  33. client: Grpc_Testing_BenchmarkServiceClient,
  34. requestMessage: Grpc_Testing_SimpleRequest,
  35. logger: Logger,
  36. stats: StatsWithLock) {
  37. self.client = client
  38. self.requestMessage = requestMessage
  39. self.logger = logger
  40. self.stats = stats
  41. }
  42. /// Initiate a request sequence to the server - in this case a single unary requests and wait for a response.
  43. /// - returns: A future which completes when the request-response sequence is complete.
  44. func makeRequest() -> EventLoopFuture<GRPCStatus> {
  45. let startTime = grpcTimeNow()
  46. let result = self.client.unaryCall(self.requestMessage)
  47. // Log latency stats on completion.
  48. result.status.whenSuccess { status in
  49. if status.isOk {
  50. let endTime = grpcTimeNow()
  51. self.stats.add(latency: endTime - startTime)
  52. } else {
  53. self.logger.error(
  54. "Bad status from unary request",
  55. metadata: ["status": "\(status)"]
  56. )
  57. }
  58. }
  59. return result.status
  60. }
  61. /// Request termination of the request-response sequence.
  62. func requestStop() {
  63. // No action here - we could potentially try and cancel the request easiest to just wait.
  64. }
  65. }