echo.grpc.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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 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. /// Create a client.
  290. internal init(address: String, secure: Bool = true) {
  291. gRPC.initialize()
  292. channel = Channel(address:address, secure:secure)
  293. metadata = Metadata()
  294. }
  295. /// Create a client that makes secure connections with a custom certificate and (optional) hostname.
  296. internal init(address: String, certificates: String, host: String?) {
  297. gRPC.initialize()
  298. channel = Channel(address:address, certificates:certificates, host:host)
  299. metadata = Metadata()
  300. }
  301. /// Synchronous. Unary.
  302. internal func get(_ request: Echo_EchoRequest)
  303. throws
  304. -> Echo_EchoResponse {
  305. return try Echo_EchoGetCall(channel).run(request:request, metadata:metadata)
  306. }
  307. /// Asynchronous. Unary.
  308. internal func get(_ request: Echo_EchoRequest,
  309. completion: @escaping (Echo_EchoResponse?, CallResult)->())
  310. throws
  311. -> Echo_EchoGetCall {
  312. return try Echo_EchoGetCall(channel).start(request:request,
  313. metadata:metadata,
  314. completion:completion)
  315. }
  316. /// Asynchronous. Server-streaming.
  317. /// Send the initial message.
  318. /// Use methods on the returned object to get streamed responses.
  319. internal func expand(_ request: Echo_EchoRequest, completion: @escaping (CallResult)->())
  320. throws
  321. -> Echo_EchoExpandCall {
  322. return try Echo_EchoExpandCall(channel).start(request:request, metadata:metadata, completion:completion)
  323. }
  324. /// Asynchronous. Client-streaming.
  325. /// Use methods on the returned object to stream messages and
  326. /// to close the connection and wait for a final response.
  327. internal func collect(completion: @escaping (CallResult)->())
  328. throws
  329. -> Echo_EchoCollectCall {
  330. return try Echo_EchoCollectCall(channel).start(metadata:metadata, completion:completion)
  331. }
  332. /// Asynchronous. Bidirectional-streaming.
  333. /// Use methods on the returned object to stream messages,
  334. /// to wait for replies, and to close the connection.
  335. internal func update(completion: @escaping (CallResult)->())
  336. throws
  337. -> Echo_EchoUpdateCall {
  338. return try Echo_EchoUpdateCall(channel).start(metadata:metadata, completion:completion)
  339. }
  340. }
  341. /// Type for errors thrown from generated server code.
  342. internal enum Echo_EchoServerError : Error {
  343. case endOfStream
  344. }
  345. /// To build a server, implement a class that conforms to this protocol.
  346. internal protocol Echo_EchoProvider {
  347. func get(request : Echo_EchoRequest, session : Echo_EchoGetSession) throws -> Echo_EchoResponse
  348. func expand(request : Echo_EchoRequest, session : Echo_EchoExpandSession) throws
  349. func collect(session : Echo_EchoCollectSession) throws
  350. func update(session : Echo_EchoUpdateSession) throws
  351. }
  352. /// Common properties available in each service session.
  353. internal final class Echo_EchoSession {
  354. fileprivate var handler : gRPC.Handler
  355. internal var requestMetadata : Metadata { return handler.requestMetadata }
  356. internal var statusCode : StatusCode = .ok
  357. internal var statusMessage : String = "OK"
  358. internal var initialMetadata : Metadata = Metadata()
  359. internal var trailingMetadata : Metadata = Metadata()
  360. fileprivate init(handler:gRPC.Handler) {
  361. self.handler = handler
  362. }
  363. }
  364. // Get (Unary)
  365. internal final class Echo_EchoGetSession : Echo_EchoSession {
  366. private var provider : Echo_EchoProvider
  367. /// Create a session.
  368. fileprivate init(handler:gRPC.Handler, provider: Echo_EchoProvider) {
  369. self.provider = provider
  370. super.init(handler:handler)
  371. }
  372. /// Run the session. Internal.
  373. fileprivate func run(queue:DispatchQueue) throws {
  374. try handler.receiveMessage(initialMetadata:initialMetadata) {(requestData) in
  375. if let requestData = requestData {
  376. let requestMessage = try Echo_EchoRequest(serializedData:requestData)
  377. let replyMessage = try self.provider.get(request:requestMessage, session: self)
  378. try self.handler.sendResponse(message:replyMessage.serializedData(),
  379. statusCode:self.statusCode,
  380. statusMessage:self.statusMessage,
  381. trailingMetadata:self.trailingMetadata)
  382. }
  383. }
  384. }
  385. }
  386. // Expand (Server Streaming)
  387. internal final class Echo_EchoExpandSession : Echo_EchoSession {
  388. private var provider : Echo_EchoProvider
  389. /// Create a session.
  390. fileprivate init(handler:gRPC.Handler, provider: Echo_EchoProvider) {
  391. self.provider = provider
  392. super.init(handler:handler)
  393. }
  394. /// Send a message. Nonblocking.
  395. internal func send(_ response: Echo_EchoResponse, completion: @escaping ()->()) throws {
  396. try handler.sendResponse(message:response.serializedData()) {completion()}
  397. }
  398. /// Run the session. Internal.
  399. fileprivate func run(queue:DispatchQueue) throws {
  400. try self.handler.receiveMessage(initialMetadata:initialMetadata) {(requestData) in
  401. if let requestData = requestData {
  402. do {
  403. let requestMessage = try Echo_EchoRequest(serializedData:requestData)
  404. // to keep providers from blocking the server thread,
  405. // we dispatch them to another queue.
  406. queue.async {
  407. do {
  408. try self.provider.expand(request:requestMessage, session: self)
  409. try self.handler.sendStatus(statusCode:self.statusCode,
  410. statusMessage:self.statusMessage,
  411. trailingMetadata:self.trailingMetadata,
  412. completion:{})
  413. } catch (let error) {
  414. print("error: \(error)")
  415. }
  416. }
  417. } catch (let error) {
  418. print("error: \(error)")
  419. }
  420. }
  421. }
  422. }
  423. }
  424. // Collect (Client Streaming)
  425. internal final class Echo_EchoCollectSession : Echo_EchoSession {
  426. private var provider : Echo_EchoProvider
  427. /// Create a session.
  428. fileprivate init(handler:gRPC.Handler, provider: Echo_EchoProvider) {
  429. self.provider = provider
  430. super.init(handler:handler)
  431. }
  432. /// Receive a message. Blocks until a message is received or the client closes the connection.
  433. internal func receive() throws -> Echo_EchoRequest {
  434. let sem = DispatchSemaphore(value: 0)
  435. var requestMessage : Echo_EchoRequest?
  436. try self.handler.receiveMessage() {(requestData) in
  437. if let requestData = requestData {
  438. requestMessage = try? Echo_EchoRequest(serializedData:requestData)
  439. }
  440. sem.signal()
  441. }
  442. _ = sem.wait(timeout: DispatchTime.distantFuture)
  443. if requestMessage == nil {
  444. throw Echo_EchoServerError.endOfStream
  445. }
  446. return requestMessage!
  447. }
  448. /// Send a response and close the connection.
  449. internal func sendAndClose(_ response: Echo_EchoResponse) throws {
  450. try self.handler.sendResponse(message:response.serializedData(),
  451. statusCode:self.statusCode,
  452. statusMessage:self.statusMessage,
  453. trailingMetadata:self.trailingMetadata)
  454. }
  455. /// Run the session. Internal.
  456. fileprivate func run(queue:DispatchQueue) throws {
  457. try self.handler.sendMetadata(initialMetadata:initialMetadata) {
  458. queue.async {
  459. do {
  460. try self.provider.collect(session:self)
  461. } catch (let error) {
  462. print("error \(error)")
  463. }
  464. }
  465. }
  466. }
  467. }
  468. // Update (Bidirectional Streaming)
  469. internal final class Echo_EchoUpdateSession : Echo_EchoSession {
  470. private var provider : Echo_EchoProvider
  471. /// Create a session.
  472. fileprivate init(handler:gRPC.Handler, provider: Echo_EchoProvider) {
  473. self.provider = provider
  474. super.init(handler:handler)
  475. }
  476. /// Receive a message. Blocks until a message is received or the client closes the connection.
  477. internal func receive() throws -> Echo_EchoRequest {
  478. let sem = DispatchSemaphore(value: 0)
  479. var requestMessage : Echo_EchoRequest?
  480. try self.handler.receiveMessage() {(requestData) in
  481. if let requestData = requestData {
  482. do {
  483. requestMessage = try Echo_EchoRequest(serializedData:requestData)
  484. } catch (let error) {
  485. print("error \(error)")
  486. }
  487. }
  488. sem.signal()
  489. }
  490. _ = sem.wait(timeout: DispatchTime.distantFuture)
  491. if let requestMessage = requestMessage {
  492. return requestMessage
  493. } else {
  494. throw Echo_EchoServerError.endOfStream
  495. }
  496. }
  497. /// Send a message. Nonblocking.
  498. internal func send(_ response: Echo_EchoResponse, completion: @escaping ()->()) throws {
  499. try handler.sendResponse(message:response.serializedData()) {completion()}
  500. }
  501. /// Close a connection. Blocks until the connection is closed.
  502. internal func close() throws {
  503. let sem = DispatchSemaphore(value: 0)
  504. try self.handler.sendStatus(statusCode:self.statusCode,
  505. statusMessage:self.statusMessage,
  506. trailingMetadata:self.trailingMetadata) {
  507. sem.signal()
  508. }
  509. _ = sem.wait(timeout: DispatchTime.distantFuture)
  510. }
  511. /// Run the session. Internal.
  512. fileprivate func run(queue:DispatchQueue) throws {
  513. try self.handler.sendMetadata(initialMetadata:initialMetadata) {
  514. queue.async {
  515. do {
  516. try self.provider.update(session:self)
  517. } catch (let error) {
  518. print("error \(error)")
  519. }
  520. }
  521. }
  522. }
  523. }
  524. /// Main server for generated service
  525. internal final class Echo_EchoServer {
  526. private var address: String
  527. private var server: gRPC.Server
  528. private var provider: Echo_EchoProvider?
  529. /// Create a server that accepts insecure connections.
  530. internal init(address:String,
  531. provider:Echo_EchoProvider) {
  532. gRPC.initialize()
  533. self.address = address
  534. self.provider = provider
  535. self.server = gRPC.Server(address:address)
  536. }
  537. /// Create a server that accepts secure connections.
  538. internal init?(address:String,
  539. certificateURL:URL,
  540. keyURL:URL,
  541. provider:Echo_EchoProvider) {
  542. gRPC.initialize()
  543. self.address = address
  544. self.provider = provider
  545. guard
  546. let certificate = try? String(contentsOf: certificateURL, encoding: .utf8),
  547. let key = try? String(contentsOf: keyURL, encoding: .utf8)
  548. else {
  549. return nil
  550. }
  551. self.server = gRPC.Server(address:address, key:key, certs:certificate)
  552. }
  553. /// Start the server.
  554. internal func start(queue:DispatchQueue = DispatchQueue.global()) {
  555. guard let provider = self.provider else {
  556. fatalError() // the server requires a provider
  557. }
  558. server.run {(handler) in
  559. print("Server received request to " + handler.host
  560. + " calling " + handler.method
  561. + " from " + handler.caller
  562. + " with " + String(describing:handler.requestMetadata) )
  563. do {
  564. switch handler.method {
  565. case "/echo.Echo/Get":
  566. try Echo_EchoGetSession(handler:handler, provider:provider).run(queue:queue)
  567. case "/echo.Echo/Expand":
  568. try Echo_EchoExpandSession(handler:handler, provider:provider).run(queue:queue)
  569. case "/echo.Echo/Collect":
  570. try Echo_EchoCollectSession(handler:handler, provider:provider).run(queue:queue)
  571. case "/echo.Echo/Update":
  572. try Echo_EchoUpdateSession(handler:handler, provider:provider).run(queue:queue)
  573. default:
  574. // handle unknown requests
  575. try handler.receiveMessage(initialMetadata:Metadata()) {(requestData) in
  576. try handler.sendResponse(statusCode:.unimplemented,
  577. statusMessage:"unknown method " + handler.method,
  578. trailingMetadata:Metadata())
  579. }
  580. }
  581. } catch (let error) {
  582. print("Server error: \(error)")
  583. }
  584. }
  585. }
  586. }