echo.grpc.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. /*
  2. * DO NOT EDIT.
  3. *
  4. * Generated by the protocol buffer compiler.
  5. * Source: echo.proto
  6. *
  7. */
  8. /*
  9. * Copyright 2018, gRPC Authors All rights reserved.
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. import Foundation
  24. import Dispatch
  25. import gRPC
  26. import SwiftProtobuf
  27. /// Type for errors thrown from generated client code.
  28. internal enum Echo_EchoClientError : Error {
  29. case endOfStream
  30. case invalidMessageReceived
  31. case error(c: CallResult)
  32. }
  33. /// Get (Unary)
  34. internal final class Echo_EchoGetCall {
  35. private var call : Call
  36. /// Create a call.
  37. fileprivate init(_ channel: Channel) {
  38. self.call = channel.makeCall("/echo.Echo/Get")
  39. }
  40. /// Run the call. Blocks until the reply is received.
  41. /// - Throws: `BinaryEncodingError` if encoding fails. `CallError` if fails to call. `Echo_EchoClientError` if receives no response.
  42. fileprivate func run(request: Echo_EchoRequest,
  43. metadata: Metadata) throws -> Echo_EchoResponse {
  44. let sem = DispatchSemaphore(value: 0)
  45. var returnCallResult : CallResult!
  46. var returnResponse : Echo_EchoResponse?
  47. _ = try start(request:request, metadata:metadata) {response, callResult in
  48. returnResponse = response
  49. returnCallResult = callResult
  50. sem.signal()
  51. }
  52. _ = sem.wait(timeout: DispatchTime.distantFuture)
  53. if let returnResponse = returnResponse {
  54. return returnResponse
  55. } else {
  56. throw Echo_EchoClientError.error(c: returnCallResult)
  57. }
  58. }
  59. /// Start the call. Nonblocking.
  60. /// - Throws: `BinaryEncodingError` if encoding fails. `CallError` if fails to call.
  61. fileprivate func start(request: Echo_EchoRequest,
  62. metadata: Metadata,
  63. completion: @escaping (Echo_EchoResponse?, CallResult)->())
  64. throws -> Echo_EchoGetCall {
  65. let requestData = try request.serializedData()
  66. try call.start(.unary,
  67. metadata:metadata,
  68. message:requestData)
  69. {(callResult) in
  70. if let responseData = callResult.resultData,
  71. let response = try? Echo_EchoResponse(serializedData:responseData) {
  72. completion(response, callResult)
  73. } else {
  74. completion(nil, callResult)
  75. }
  76. }
  77. return self
  78. }
  79. /// Cancel the call.
  80. internal func cancel() {
  81. call.cancel()
  82. }
  83. }
  84. /// Expand (Server Streaming)
  85. internal final class Echo_EchoExpandCall {
  86. private var call : Call
  87. /// Create a call.
  88. fileprivate init(_ channel: Channel) {
  89. self.call = channel.makeCall("/echo.Echo/Expand")
  90. }
  91. /// Call this once with the message to send. Nonblocking.
  92. fileprivate func start(request: Echo_EchoRequest,
  93. metadata: Metadata,
  94. completion: @escaping (CallResult) -> ())
  95. throws -> Echo_EchoExpandCall {
  96. let requestData = try request.serializedData()
  97. try call.start(.serverStreaming,
  98. metadata:metadata,
  99. message:requestData,
  100. completion:completion)
  101. return self
  102. }
  103. /// Call this to wait for a result. Blocking.
  104. internal func receive() throws -> Echo_EchoResponse {
  105. var returnError : Echo_EchoClientError?
  106. var returnResponse : Echo_EchoResponse!
  107. let sem = DispatchSemaphore(value: 0)
  108. do {
  109. try receive() {response, error in
  110. returnResponse = response
  111. returnError = error
  112. sem.signal()
  113. }
  114. _ = sem.wait(timeout: DispatchTime.distantFuture)
  115. }
  116. if let returnError = returnError {
  117. throw returnError
  118. }
  119. return returnResponse
  120. }
  121. /// Call this to wait for a result. Nonblocking.
  122. internal func receive(completion:@escaping (Echo_EchoResponse?, Echo_EchoClientError?)->()) throws {
  123. do {
  124. try call.receiveMessage() {(responseData) in
  125. if let responseData = responseData {
  126. if let response = try? Echo_EchoResponse(serializedData:responseData) {
  127. completion(response, nil)
  128. } else {
  129. completion(nil, Echo_EchoClientError.invalidMessageReceived)
  130. }
  131. } else {
  132. completion(nil, Echo_EchoClientError.endOfStream)
  133. }
  134. }
  135. }
  136. }
  137. /// Cancel the call.
  138. internal func cancel() {
  139. call.cancel()
  140. }
  141. }
  142. /// Collect (Client Streaming)
  143. internal final class Echo_EchoCollectCall {
  144. private var call : Call
  145. /// Create a call.
  146. fileprivate init(_ channel: Channel) {
  147. self.call = channel.makeCall("/echo.Echo/Collect")
  148. }
  149. /// Call this to start a call. Nonblocking.
  150. fileprivate func start(metadata:Metadata, completion:@escaping (CallResult)->())
  151. throws -> Echo_EchoCollectCall {
  152. try self.call.start(.clientStreaming, metadata:metadata, completion:completion)
  153. return self
  154. }
  155. /// Call this to send each message in the request stream. Nonblocking.
  156. internal func send(_ message:Echo_EchoRequest, errorHandler:@escaping (Error)->()) throws {
  157. let messageData = try message.serializedData()
  158. try call.sendMessage(data:messageData, errorHandler:errorHandler)
  159. }
  160. /// Call this to close the connection and wait for a response. Blocking.
  161. internal func closeAndReceive() throws -> Echo_EchoResponse {
  162. var returnError : Echo_EchoClientError?
  163. var returnResponse : Echo_EchoResponse!
  164. let sem = DispatchSemaphore(value: 0)
  165. do {
  166. try closeAndReceive() {response, error in
  167. returnResponse = response
  168. returnError = error
  169. sem.signal()
  170. }
  171. _ = sem.wait(timeout: DispatchTime.distantFuture)
  172. } catch (let error) {
  173. throw error
  174. }
  175. if let returnError = returnError {
  176. throw returnError
  177. }
  178. return returnResponse
  179. }
  180. /// Call this to close the connection and wait for a response. Nonblocking.
  181. internal func closeAndReceive(completion:@escaping (Echo_EchoResponse?, Echo_EchoClientError?)->())
  182. throws {
  183. do {
  184. try call.receiveMessage() {(responseData) in
  185. if let responseData = responseData,
  186. let response = try? Echo_EchoResponse(serializedData:responseData) {
  187. completion(response, nil)
  188. } else {
  189. completion(nil, Echo_EchoClientError.invalidMessageReceived)
  190. }
  191. }
  192. try call.close(completion:{})
  193. } catch (let error) {
  194. throw error
  195. }
  196. }
  197. /// Cancel the call.
  198. internal func cancel() {
  199. call.cancel()
  200. }
  201. }
  202. /// Update (Bidirectional Streaming)
  203. internal final class Echo_EchoUpdateCall {
  204. private var call : Call
  205. /// Create a call.
  206. fileprivate init(_ channel: Channel) {
  207. self.call = channel.makeCall("/echo.Echo/Update")
  208. }
  209. /// Call this to start a call. Nonblocking.
  210. fileprivate func start(metadata:Metadata, completion:@escaping (CallResult)->())
  211. throws -> Echo_EchoUpdateCall {
  212. try self.call.start(.bidiStreaming, metadata:metadata, completion:completion)
  213. return self
  214. }
  215. /// Call this to wait for a result. Blocking.
  216. internal func receive() throws -> Echo_EchoResponse {
  217. var returnError : Echo_EchoClientError?
  218. var returnMessage : Echo_EchoResponse!
  219. let sem = DispatchSemaphore(value: 0)
  220. do {
  221. try receive() {response, error in
  222. returnMessage = response
  223. returnError = error
  224. sem.signal()
  225. }
  226. _ = sem.wait(timeout: DispatchTime.distantFuture)
  227. }
  228. if let returnError = returnError {
  229. throw returnError
  230. }
  231. return returnMessage
  232. }
  233. /// Call this to wait for a result. Nonblocking.
  234. internal func receive(completion:@escaping (Echo_EchoResponse?, Echo_EchoClientError?)->()) throws {
  235. do {
  236. try call.receiveMessage() {(data) in
  237. if let data = data {
  238. if let returnMessage = try? Echo_EchoResponse(serializedData:data) {
  239. completion(returnMessage, nil)
  240. } else {
  241. completion(nil, Echo_EchoClientError.invalidMessageReceived)
  242. }
  243. } else {
  244. completion(nil, Echo_EchoClientError.endOfStream)
  245. }
  246. }
  247. }
  248. }
  249. /// Call this to send each message in the request stream.
  250. internal func send(_ message:Echo_EchoRequest, errorHandler:@escaping (Error)->()) throws {
  251. let messageData = try message.serializedData()
  252. try call.sendMessage(data:messageData, errorHandler:errorHandler)
  253. }
  254. /// Call this to close the sending connection. Blocking.
  255. internal func closeSend() throws {
  256. let sem = DispatchSemaphore(value: 0)
  257. try closeSend() {
  258. sem.signal()
  259. }
  260. _ = sem.wait(timeout: DispatchTime.distantFuture)
  261. }
  262. /// Call this to close the sending connection. Nonblocking.
  263. internal func closeSend(completion:@escaping ()->()) throws {
  264. try call.close() {
  265. completion()
  266. }
  267. }
  268. /// Cancel the call.
  269. internal func cancel() {
  270. call.cancel()
  271. }
  272. }
  273. /// Call methods of this class to make API calls.
  274. internal final class Echo_EchoService {
  275. public private(set) var channel: Channel
  276. /// This metadata will be sent with all requests.
  277. internal var metadata : Metadata
  278. /// This property allows the service host name to be overridden.
  279. /// For example, it can be used to make calls to "localhost:8080"
  280. /// appear to be to "example.com".
  281. internal var host : String {
  282. get {
  283. return self.channel.host
  284. }
  285. set {
  286. self.channel.host = newValue
  287. }
  288. }
  289. /// This property allows the service timeout to be overridden.
  290. internal var timeout : TimeInterval {
  291. get {
  292. return self.channel.timeout
  293. }
  294. set {
  295. self.channel.timeout = newValue
  296. }
  297. }
  298. /// Create a client.
  299. internal init(address: String, secure: Bool = true) {
  300. gRPC.initialize()
  301. channel = Channel(address:address, secure:secure)
  302. metadata = Metadata()
  303. }
  304. /// Create a client that makes secure connections with a custom certificate and (optional) hostname.
  305. internal init(address: String, certificates: String, host: String?) {
  306. gRPC.initialize()
  307. channel = Channel(address:address, certificates:certificates, host:host)
  308. metadata = Metadata()
  309. }
  310. /// Synchronous. Unary.
  311. internal func get(_ request: Echo_EchoRequest)
  312. throws
  313. -> Echo_EchoResponse {
  314. return try Echo_EchoGetCall(channel).run(request:request, metadata:metadata)
  315. }
  316. /// Asynchronous. Unary.
  317. internal func get(_ request: Echo_EchoRequest,
  318. completion: @escaping (Echo_EchoResponse?, CallResult)->())
  319. throws
  320. -> Echo_EchoGetCall {
  321. return try Echo_EchoGetCall(channel).start(request:request,
  322. metadata:metadata,
  323. completion:completion)
  324. }
  325. /// Asynchronous. Server-streaming.
  326. /// Send the initial message.
  327. /// Use methods on the returned object to get streamed responses.
  328. internal func expand(_ request: Echo_EchoRequest, completion: @escaping (CallResult)->())
  329. throws
  330. -> Echo_EchoExpandCall {
  331. return try Echo_EchoExpandCall(channel).start(request:request, metadata:metadata, completion:completion)
  332. }
  333. /// Asynchronous. Client-streaming.
  334. /// Use methods on the returned object to stream messages and
  335. /// to close the connection and wait for a final response.
  336. internal func collect(completion: @escaping (CallResult)->())
  337. throws
  338. -> Echo_EchoCollectCall {
  339. return try Echo_EchoCollectCall(channel).start(metadata:metadata, completion:completion)
  340. }
  341. /// Asynchronous. Bidirectional-streaming.
  342. /// Use methods on the returned object to stream messages,
  343. /// to wait for replies, and to close the connection.
  344. internal func update(completion: @escaping (CallResult)->())
  345. throws
  346. -> Echo_EchoUpdateCall {
  347. return try Echo_EchoUpdateCall(channel).start(metadata:metadata, completion:completion)
  348. }
  349. }
  350. /// Type for errors thrown from generated server code.
  351. internal enum Echo_EchoServerError : Error {
  352. case endOfStream
  353. }
  354. /// To build a server, implement a class that conforms to this protocol.
  355. internal protocol Echo_EchoProvider {
  356. func get(request : Echo_EchoRequest, session : Echo_EchoGetSession) throws -> Echo_EchoResponse
  357. func expand(request : Echo_EchoRequest, session : Echo_EchoExpandSession) throws
  358. func collect(session : Echo_EchoCollectSession) throws
  359. func update(session : Echo_EchoUpdateSession) throws
  360. }
  361. /// Common properties available in each service session.
  362. internal final class Echo_EchoSession {
  363. fileprivate var handler : gRPC.Handler
  364. internal var requestMetadata : Metadata { return handler.requestMetadata }
  365. internal var statusCode : StatusCode = .ok
  366. internal var statusMessage : String = "OK"
  367. internal var initialMetadata : Metadata = Metadata()
  368. internal var trailingMetadata : Metadata = Metadata()
  369. fileprivate init(handler:gRPC.Handler) {
  370. self.handler = handler
  371. }
  372. }
  373. // Get (Unary)
  374. internal final class Echo_EchoGetSession : Echo_EchoSession {
  375. private var provider : Echo_EchoProvider
  376. /// Create a session.
  377. fileprivate init(handler:gRPC.Handler, provider: Echo_EchoProvider) {
  378. self.provider = provider
  379. super.init(handler:handler)
  380. }
  381. /// Run the session. Internal.
  382. fileprivate func run(queue:DispatchQueue) throws {
  383. try handler.receiveMessage(initialMetadata:initialMetadata) {(requestData) in
  384. if let requestData = requestData {
  385. let requestMessage = try Echo_EchoRequest(serializedData:requestData)
  386. let replyMessage = try self.provider.get(request:requestMessage, session: self)
  387. try self.handler.sendResponse(message:replyMessage.serializedData(),
  388. statusCode:self.statusCode,
  389. statusMessage:self.statusMessage,
  390. trailingMetadata:self.trailingMetadata)
  391. }
  392. }
  393. }
  394. }
  395. // Expand (Server Streaming)
  396. internal final class Echo_EchoExpandSession : Echo_EchoSession {
  397. private var provider : Echo_EchoProvider
  398. /// Create a session.
  399. fileprivate init(handler:gRPC.Handler, provider: Echo_EchoProvider) {
  400. self.provider = provider
  401. super.init(handler:handler)
  402. }
  403. /// Send a message. Nonblocking.
  404. internal func send(_ response: Echo_EchoResponse, completion: @escaping ()->()) throws {
  405. try handler.sendResponse(message:response.serializedData()) {completion()}
  406. }
  407. /// Run the session. Internal.
  408. fileprivate func run(queue:DispatchQueue) throws {
  409. try self.handler.receiveMessage(initialMetadata:initialMetadata) {(requestData) in
  410. if let requestData = requestData {
  411. do {
  412. let requestMessage = try Echo_EchoRequest(serializedData:requestData)
  413. // to keep providers from blocking the server thread,
  414. // we dispatch them to another queue.
  415. queue.async {
  416. do {
  417. try self.provider.expand(request:requestMessage, session: self)
  418. try self.handler.sendStatus(statusCode:self.statusCode,
  419. statusMessage:self.statusMessage,
  420. trailingMetadata:self.trailingMetadata,
  421. completion:{})
  422. } catch (let error) {
  423. print("error: \(error)")
  424. }
  425. }
  426. } catch (let error) {
  427. print("error: \(error)")
  428. }
  429. }
  430. }
  431. }
  432. }
  433. // Collect (Client Streaming)
  434. internal final class Echo_EchoCollectSession : Echo_EchoSession {
  435. private var provider : Echo_EchoProvider
  436. /// Create a session.
  437. fileprivate init(handler:gRPC.Handler, provider: Echo_EchoProvider) {
  438. self.provider = provider
  439. super.init(handler:handler)
  440. }
  441. /// Receive a message. Blocks until a message is received or the client closes the connection.
  442. internal func receive() throws -> Echo_EchoRequest {
  443. let sem = DispatchSemaphore(value: 0)
  444. var requestMessage : Echo_EchoRequest?
  445. try self.handler.receiveMessage() {(requestData) in
  446. if let requestData = requestData {
  447. requestMessage = try? Echo_EchoRequest(serializedData:requestData)
  448. }
  449. sem.signal()
  450. }
  451. _ = sem.wait(timeout: DispatchTime.distantFuture)
  452. if requestMessage == nil {
  453. throw Echo_EchoServerError.endOfStream
  454. }
  455. return requestMessage!
  456. }
  457. /// Send a response and close the connection.
  458. internal func sendAndClose(_ response: Echo_EchoResponse) throws {
  459. try self.handler.sendResponse(message:response.serializedData(),
  460. statusCode:self.statusCode,
  461. statusMessage:self.statusMessage,
  462. trailingMetadata:self.trailingMetadata)
  463. }
  464. /// Run the session. Internal.
  465. fileprivate func run(queue:DispatchQueue) throws {
  466. try self.handler.sendMetadata(initialMetadata:initialMetadata) {
  467. queue.async {
  468. do {
  469. try self.provider.collect(session:self)
  470. } catch (let error) {
  471. print("error \(error)")
  472. }
  473. }
  474. }
  475. }
  476. }
  477. // Update (Bidirectional Streaming)
  478. internal final class Echo_EchoUpdateSession : Echo_EchoSession {
  479. private var provider : Echo_EchoProvider
  480. /// Create a session.
  481. fileprivate init(handler:gRPC.Handler, provider: Echo_EchoProvider) {
  482. self.provider = provider
  483. super.init(handler:handler)
  484. }
  485. /// Receive a message. Blocks until a message is received or the client closes the connection.
  486. internal func receive() throws -> Echo_EchoRequest {
  487. let sem = DispatchSemaphore(value: 0)
  488. var requestMessage : Echo_EchoRequest?
  489. try self.handler.receiveMessage() {(requestData) in
  490. if let requestData = requestData {
  491. do {
  492. requestMessage = try Echo_EchoRequest(serializedData:requestData)
  493. } catch (let error) {
  494. print("error \(error)")
  495. }
  496. }
  497. sem.signal()
  498. }
  499. _ = sem.wait(timeout: DispatchTime.distantFuture)
  500. if let requestMessage = requestMessage {
  501. return requestMessage
  502. } else {
  503. throw Echo_EchoServerError.endOfStream
  504. }
  505. }
  506. /// Send a message. Nonblocking.
  507. internal func send(_ response: Echo_EchoResponse, completion: @escaping ()->()) throws {
  508. try handler.sendResponse(message:response.serializedData()) {completion()}
  509. }
  510. /// Close a connection. Blocks until the connection is closed.
  511. internal func close() throws {
  512. let sem = DispatchSemaphore(value: 0)
  513. try self.handler.sendStatus(statusCode:self.statusCode,
  514. statusMessage:self.statusMessage,
  515. trailingMetadata:self.trailingMetadata) {
  516. sem.signal()
  517. }
  518. _ = sem.wait(timeout: DispatchTime.distantFuture)
  519. }
  520. /// Run the session. Internal.
  521. fileprivate func run(queue:DispatchQueue) throws {
  522. try self.handler.sendMetadata(initialMetadata:initialMetadata) {
  523. queue.async {
  524. do {
  525. try self.provider.update(session:self)
  526. } catch (let error) {
  527. print("error \(error)")
  528. }
  529. }
  530. }
  531. }
  532. }
  533. /// Main server for generated service
  534. internal final class Echo_EchoServer {
  535. private var address: String
  536. private var server: gRPC.Server
  537. private var provider: Echo_EchoProvider?
  538. /// Create a server that accepts insecure connections.
  539. internal init(address:String,
  540. provider:Echo_EchoProvider) {
  541. gRPC.initialize()
  542. self.address = address
  543. self.provider = provider
  544. self.server = gRPC.Server(address:address)
  545. }
  546. /// Create a server that accepts secure connections.
  547. internal init?(address:String,
  548. certificateURL:URL,
  549. keyURL:URL,
  550. provider:Echo_EchoProvider) {
  551. gRPC.initialize()
  552. self.address = address
  553. self.provider = provider
  554. guard
  555. let certificate = try? String(contentsOf: certificateURL, encoding: .utf8),
  556. let key = try? String(contentsOf: keyURL, encoding: .utf8)
  557. else {
  558. return nil
  559. }
  560. self.server = gRPC.Server(address:address, key:key, certs:certificate)
  561. }
  562. /// Start the server.
  563. internal func start(queue:DispatchQueue = DispatchQueue.global()) {
  564. guard let provider = self.provider else {
  565. fatalError() // the server requires a provider
  566. }
  567. server.run {(handler) in
  568. print("Server received request to " + handler.host
  569. + " calling " + handler.method
  570. + " from " + handler.caller
  571. + " with " + String(describing:handler.requestMetadata) )
  572. do {
  573. switch handler.method {
  574. case "/echo.Echo/Get":
  575. try Echo_EchoGetSession(handler:handler, provider:provider).run(queue:queue)
  576. case "/echo.Echo/Expand":
  577. try Echo_EchoExpandSession(handler:handler, provider:provider).run(queue:queue)
  578. case "/echo.Echo/Collect":
  579. try Echo_EchoCollectSession(handler:handler, provider:provider).run(queue:queue)
  580. case "/echo.Echo/Update":
  581. try Echo_EchoUpdateSession(handler:handler, provider:provider).run(queue:queue)
  582. default:
  583. // handle unknown requests
  584. try handler.receiveMessage(initialMetadata:Metadata()) {(requestData) in
  585. try handler.sendResponse(statusCode:.unimplemented,
  586. statusMessage:"unknown method " + handler.method,
  587. trailingMetadata:Metadata())
  588. }
  589. }
  590. } catch (let error) {
  591. print("Server error: \(error)")
  592. }
  593. }
  594. }
  595. }