client-call-unary.swift 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /// {{ method|methodDescriptorName }} (Unary)
  2. {{ access }} protocol {{ .|call:file,service,method }} {
  3. /// Cancel the call.
  4. func cancel()
  5. }
  6. /// {{ method|methodDescriptorName }} (Unary)
  7. fileprivate final class {{ .|call:file,service,method }}Impl: {{ .|call:file,service,method }} {
  8. private var call : Call
  9. /// Create a call.
  10. init(_ channel: Channel) {
  11. self.call = channel.makeCall("{{ .|path:file,service,method }}")
  12. }
  13. /// Run the call. Blocks until the reply is received.
  14. /// - Throws: `BinaryEncodingError` if encoding fails. `CallError` if fails to call. `{{ .|clienterror:file,service }}` if receives no response.
  15. func run(request: {{ method|input }},
  16. metadata: Metadata) throws -> {{ method|output }} {
  17. let sem = DispatchSemaphore(value: 0)
  18. var returnCallResult : CallResult!
  19. var returnResponse : {{ method|output }}?
  20. _ = try start(request:request, metadata:metadata) {response, callResult in
  21. returnResponse = response
  22. returnCallResult = callResult
  23. sem.signal()
  24. }
  25. _ = sem.wait(timeout: DispatchTime.distantFuture)
  26. if let returnResponse = returnResponse {
  27. return returnResponse
  28. } else {
  29. throw {{ .|clienterror:file,service }}.error(c: returnCallResult)
  30. }
  31. }
  32. /// Start the call. Nonblocking.
  33. /// - Throws: `BinaryEncodingError` if encoding fails. `CallError` if fails to call.
  34. func start(request: {{ method|input }},
  35. metadata: Metadata,
  36. completion: @escaping ({{ method|output }}?, CallResult)->())
  37. throws -> {{ .|call:file,service,method }} {
  38. let requestData = try request.serializedData()
  39. try call.start(.unary,
  40. metadata:metadata,
  41. message:requestData)
  42. {(callResult) in
  43. if let responseData = callResult.resultData,
  44. let response = try? {{ method|output }}(serializedData:responseData) {
  45. completion(response, callResult)
  46. } else {
  47. completion(nil, callResult)
  48. }
  49. }
  50. return self
  51. }
  52. func cancel() {
  53. call.cancel()
  54. }
  55. }