echo.grpc.swift 21 KB

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