echo.grpc.swift 21 KB

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