ClientCallUnary.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright 2018, 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 Dispatch
  17. import Foundation
  18. import SwiftProtobuf
  19. public protocol ClientCallUnary: ClientCall {}
  20. open class ClientCallUnaryBase<InputType: Message, OutputType: Message>: ClientCallBase, ClientCallUnary {
  21. /// Run the call. Blocks until the reply is received.
  22. /// - Throws: `BinaryEncodingError` if encoding fails. `CallError` if fails to call. `ClientError` if receives no response.
  23. public func run(request: InputType, metadata: Metadata) throws -> OutputType {
  24. let sem = DispatchSemaphore(value: 0)
  25. var returnCallResult: CallResult!
  26. var returnResponse: OutputType?
  27. _ = try start(request: request, metadata: metadata) { response, callResult in
  28. returnResponse = response
  29. returnCallResult = callResult
  30. sem.signal()
  31. }
  32. _ = sem.wait()
  33. if let returnResponse = returnResponse {
  34. return returnResponse
  35. } else {
  36. throw ClientError.error(c: returnCallResult)
  37. }
  38. }
  39. /// Start the call. Nonblocking.
  40. /// - Throws: `BinaryEncodingError` if encoding fails. `CallError` if fails to call.
  41. public func start(request: InputType,
  42. metadata: Metadata,
  43. completion: @escaping ((OutputType?, CallResult) -> Void)) throws -> Self {
  44. let requestData = try request.serializedData()
  45. try call.start(.unary, metadata: metadata, message: requestData) { callResult in
  46. if let responseData = callResult.resultData,
  47. let response = try? OutputType(serializedData: responseData) {
  48. completion(response, callResult)
  49. } else {
  50. completion(nil, callResult)
  51. }
  52. }
  53. return self
  54. }
  55. }