echo.grpc.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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. internal protocol Echo_EchoGetCall: ClientCallUnary { }
  34. fileprivate final class Echo_EchoGetCallImpl: ClientCallUnaryImpl<Echo_EchoRequest, Echo_EchoResponse>, Echo_EchoGetCall {
  35. override class var method: String { return "/echo.Echo/Get" }
  36. }
  37. /// Expand (Server Streaming)
  38. internal protocol Echo_EchoExpandCall {
  39. /// Call this to wait for a result. Blocking.
  40. func receive() throws -> Echo_EchoResponse
  41. /// Call this to wait for a result. Nonblocking.
  42. func receive(completion:@escaping (Echo_EchoResponse?, Echo_EchoClientError?)->()) throws
  43. /// Cancel the call.
  44. func cancel()
  45. }
  46. internal extension Echo_EchoExpandCall {
  47. func receive() throws -> Echo_EchoResponse {
  48. var returnError : Echo_EchoClientError?
  49. var returnResponse : Echo_EchoResponse!
  50. let sem = DispatchSemaphore(value: 0)
  51. do {
  52. try receive() {response, error in
  53. returnResponse = response
  54. returnError = error
  55. sem.signal()
  56. }
  57. _ = sem.wait(timeout: DispatchTime.distantFuture)
  58. }
  59. if let returnError = returnError {
  60. throw returnError
  61. }
  62. return returnResponse
  63. }
  64. }
  65. fileprivate final class Echo_EchoExpandCallImpl: Echo_EchoExpandCall {
  66. private var call : Call
  67. /// Create a call.
  68. init(_ channel: Channel) {
  69. self.call = channel.makeCall("/echo.Echo/Expand")
  70. }
  71. /// Call this once with the message to send. Nonblocking.
  72. func start(request: Echo_EchoRequest,
  73. metadata: Metadata,
  74. completion: ((CallResult) -> ())?)
  75. throws -> Echo_EchoExpandCall {
  76. let requestData = try request.serializedData()
  77. try call.start(.serverStreaming,
  78. metadata:metadata,
  79. message:requestData,
  80. completion:completion)
  81. return self
  82. }
  83. func receive(completion:@escaping (Echo_EchoResponse?, Echo_EchoClientError?)->()) throws {
  84. do {
  85. try call.receiveMessage() {(responseData) in
  86. if let responseData = responseData {
  87. if let response = try? Echo_EchoResponse(serializedData:responseData) {
  88. completion(response, nil)
  89. } else {
  90. completion(nil, Echo_EchoClientError.invalidMessageReceived)
  91. }
  92. } else {
  93. completion(nil, Echo_EchoClientError.endOfStream)
  94. }
  95. }
  96. }
  97. }
  98. /// Cancel the call.
  99. func cancel() {
  100. call.cancel()
  101. }
  102. }
  103. /// Simple fake implementation of Echo_EchoExpandCall that returns a previously-defined set of results.
  104. class Echo_EchoExpandCallTestStub: Echo_EchoExpandCall {
  105. var outputs: [Echo_EchoResponse] = []
  106. func receive(completion:@escaping (Echo_EchoResponse?, Echo_EchoClientError?)->()) throws {
  107. if let output = outputs.first {
  108. outputs.removeFirst()
  109. completion(output, nil)
  110. } else {
  111. completion(nil, Echo_EchoClientError.endOfStream)
  112. }
  113. }
  114. func cancel() { }
  115. }
  116. /// Collect (Client Streaming)
  117. internal protocol Echo_EchoCollectCall {
  118. /// Call this to send each message in the request stream. Nonblocking.
  119. func send(_ message:Echo_EchoRequest, errorHandler:@escaping (Error)->()) throws
  120. /// Call this to close the connection and wait for a response. Blocking.
  121. func closeAndReceive() throws -> Echo_EchoResponse
  122. /// Call this to close the connection and wait for a response. Nonblocking.
  123. func closeAndReceive(completion:@escaping (Echo_EchoResponse?, Echo_EchoClientError?)->()) throws
  124. /// Cancel the call.
  125. func cancel()
  126. }
  127. internal extension Echo_EchoCollectCall {
  128. func closeAndReceive() throws -> Echo_EchoResponse {
  129. var returnError : Echo_EchoClientError?
  130. var returnResponse : Echo_EchoResponse!
  131. let sem = DispatchSemaphore(value: 0)
  132. do {
  133. try closeAndReceive() {response, error in
  134. returnResponse = response
  135. returnError = error
  136. sem.signal()
  137. }
  138. _ = sem.wait(timeout: DispatchTime.distantFuture)
  139. } catch (let error) {
  140. throw error
  141. }
  142. if let returnError = returnError {
  143. throw returnError
  144. }
  145. return returnResponse
  146. }
  147. }
  148. fileprivate final class Echo_EchoCollectCallImpl: Echo_EchoCollectCall {
  149. private var call : Call
  150. /// Create a call.
  151. init(_ channel: Channel) {
  152. self.call = channel.makeCall("/echo.Echo/Collect")
  153. }
  154. /// Call this to start a call. Nonblocking.
  155. func start(metadata:Metadata, completion: ((CallResult)->())?)
  156. throws -> Echo_EchoCollectCall {
  157. try self.call.start(.clientStreaming, metadata:metadata, completion:completion)
  158. return self
  159. }
  160. func send(_ message:Echo_EchoRequest, errorHandler:@escaping (Error)->()) throws {
  161. let messageData = try message.serializedData()
  162. try call.sendMessage(data:messageData, errorHandler:errorHandler)
  163. }
  164. func closeAndReceive(completion:@escaping (Echo_EchoResponse?, Echo_EchoClientError?)->()) throws {
  165. do {
  166. try call.receiveMessage() {(responseData) in
  167. if let responseData = responseData,
  168. let response = try? Echo_EchoResponse(serializedData:responseData) {
  169. completion(response, nil)
  170. } else {
  171. completion(nil, Echo_EchoClientError.invalidMessageReceived)
  172. }
  173. }
  174. try call.close(completion:{})
  175. } catch (let error) {
  176. throw error
  177. }
  178. }
  179. func cancel() {
  180. call.cancel()
  181. }
  182. }
  183. /// Simple fake implementation of Echo_EchoCollectCall
  184. /// stores sent values for later verification and finall returns a previously-defined result.
  185. class Echo_EchoCollectCallTestStub: Echo_EchoCollectCall {
  186. var inputs: [Echo_EchoRequest] = []
  187. var output: Echo_EchoResponse?
  188. func send(_ message:Echo_EchoRequest, errorHandler:@escaping (Error)->()) throws {
  189. inputs.append(message)
  190. }
  191. func closeAndReceive(completion:@escaping (Echo_EchoResponse?, Echo_EchoClientError?)->()) throws {
  192. completion(output!, nil)
  193. }
  194. func cancel() { }
  195. }
  196. /// Update (Bidirectional Streaming)
  197. internal protocol Echo_EchoUpdateCall {
  198. /// Call this to wait for a result. Blocking.
  199. func receive() throws -> Echo_EchoResponse
  200. /// Call this to wait for a result. Nonblocking.
  201. func receive(completion:@escaping (Echo_EchoResponse?, Echo_EchoClientError?)->()) throws
  202. /// Call this to send each message in the request stream.
  203. func send(_ message:Echo_EchoRequest, errorHandler:@escaping (Error)->()) throws
  204. /// Call this to close the sending connection. Blocking.
  205. func closeSend() throws
  206. /// Call this to close the sending connection. Nonblocking.
  207. func closeSend(completion: (()->())?) throws
  208. /// Cancel the call.
  209. func cancel()
  210. }
  211. internal extension Echo_EchoUpdateCall {
  212. func receive() throws -> Echo_EchoResponse {
  213. var returnError : Echo_EchoClientError?
  214. var returnMessage : Echo_EchoResponse!
  215. let sem = DispatchSemaphore(value: 0)
  216. do {
  217. try receive() {response, error in
  218. returnMessage = response
  219. returnError = error
  220. sem.signal()
  221. }
  222. _ = sem.wait(timeout: DispatchTime.distantFuture)
  223. }
  224. if let returnError = returnError {
  225. throw returnError
  226. }
  227. return returnMessage
  228. }
  229. func closeSend() throws {
  230. let sem = DispatchSemaphore(value: 0)
  231. try closeSend() {
  232. sem.signal()
  233. }
  234. _ = sem.wait(timeout: DispatchTime.distantFuture)
  235. }
  236. }
  237. fileprivate final class Echo_EchoUpdateCallImpl: Echo_EchoUpdateCall {
  238. private var call : Call
  239. /// Create a call.
  240. init(_ channel: Channel) {
  241. self.call = channel.makeCall("/echo.Echo/Update")
  242. }
  243. /// Call this to start a call. Nonblocking.
  244. func start(metadata:Metadata, completion: ((CallResult)->())?)
  245. throws -> Echo_EchoUpdateCall {
  246. try self.call.start(.bidiStreaming, metadata:metadata, completion:completion)
  247. return self
  248. }
  249. func receive(completion:@escaping (Echo_EchoResponse?, Echo_EchoClientError?)->()) throws {
  250. do {
  251. try call.receiveMessage() {(data) in
  252. if let data = data {
  253. if let returnMessage = try? Echo_EchoResponse(serializedData:data) {
  254. completion(returnMessage, nil)
  255. } else {
  256. completion(nil, Echo_EchoClientError.invalidMessageReceived)
  257. }
  258. } else {
  259. completion(nil, Echo_EchoClientError.endOfStream)
  260. }
  261. }
  262. }
  263. }
  264. func send(_ message:Echo_EchoRequest, errorHandler:@escaping (Error)->()) throws {
  265. let messageData = try message.serializedData()
  266. try call.sendMessage(data:messageData, errorHandler:errorHandler)
  267. }
  268. func closeSend(completion: (()->())?) throws {
  269. try call.close(completion: completion)
  270. }
  271. func cancel() {
  272. call.cancel()
  273. }
  274. }
  275. /// Simple fake implementation of Echo_EchoUpdateCall that returns a previously-defined set of results
  276. /// and stores sent values for later verification.
  277. class Echo_EchoUpdateCallTestStub: Echo_EchoUpdateCall {
  278. var inputs: [Echo_EchoRequest] = []
  279. var outputs: [Echo_EchoResponse] = []
  280. func receive(completion:@escaping (Echo_EchoResponse?, Echo_EchoClientError?)->()) throws {
  281. if let output = outputs.first {
  282. outputs.removeFirst()
  283. completion(output, nil)
  284. } else {
  285. completion(nil, Echo_EchoClientError.endOfStream)
  286. }
  287. }
  288. func send(_ message:Echo_EchoRequest, errorHandler:@escaping (Error)->()) throws {
  289. inputs.append(message)
  290. }
  291. func closeSend(completion: (()->())?) throws { completion?() }
  292. func cancel() { }
  293. }
  294. /// Instantiate Echo_EchoServiceImpl, then call methods of this protocol to make API calls.
  295. internal protocol Echo_EchoService {
  296. var channel: Channel { get }
  297. /// This metadata will be sent with all requests.
  298. var metadata: Metadata { get }
  299. /// This property allows the service host name to be overridden.
  300. /// For example, it can be used to make calls to "localhost:8080"
  301. /// appear to be to "example.com".
  302. var host : String { get }
  303. /// This property allows the service timeout to be overridden.
  304. var timeout : TimeInterval { get }
  305. /// Synchronous. Unary.
  306. func get(_ request: Echo_EchoRequest) throws -> Echo_EchoResponse
  307. /// Asynchronous. Unary.
  308. func get(_ request: Echo_EchoRequest,
  309. completion: @escaping (Echo_EchoResponse?, CallResult)->()) throws -> Echo_EchoGetCall
  310. /// Asynchronous. Server-streaming.
  311. /// Send the initial message.
  312. /// Use methods on the returned object to get streamed responses.
  313. func expand(_ request: Echo_EchoRequest, completion: ((CallResult)->())?)
  314. throws -> Echo_EchoExpandCall
  315. /// Asynchronous. Client-streaming.
  316. /// Use methods on the returned object to stream messages and
  317. /// to close the connection and wait for a final response.
  318. func collect(completion: ((CallResult)->())?)
  319. throws -> Echo_EchoCollectCall
  320. /// Asynchronous. Bidirectional-streaming.
  321. /// Use methods on the returned object to stream messages,
  322. /// to wait for replies, and to close the connection.
  323. func update(completion: ((CallResult)->())?)
  324. throws -> Echo_EchoUpdateCall
  325. }
  326. internal final class Echo_EchoServiceClient: Echo_EchoService {
  327. internal private(set) var channel: Channel
  328. internal var metadata : Metadata
  329. internal var host : String {
  330. get {
  331. return self.channel.host
  332. }
  333. set {
  334. self.channel.host = newValue
  335. }
  336. }
  337. internal var timeout : TimeInterval {
  338. get {
  339. return self.channel.timeout
  340. }
  341. set {
  342. self.channel.timeout = newValue
  343. }
  344. }
  345. /// Create a client.
  346. internal init(address: String, secure: Bool = true) {
  347. gRPC.initialize()
  348. channel = Channel(address:address, secure:secure)
  349. metadata = Metadata()
  350. }
  351. /// Create a client that makes secure connections with a custom certificate and (optional) hostname.
  352. internal init(address: String, certificates: String, host: String?) {
  353. gRPC.initialize()
  354. channel = Channel(address:address, certificates:certificates, host:host)
  355. metadata = Metadata()
  356. }
  357. /// Synchronous. Unary.
  358. internal func get(_ request: Echo_EchoRequest)
  359. throws
  360. -> Echo_EchoResponse {
  361. return try Echo_EchoGetCallImpl(channel).run(request:request, metadata:metadata)
  362. }
  363. /// Asynchronous. Unary.
  364. internal func get(_ request: Echo_EchoRequest,
  365. completion: @escaping (Echo_EchoResponse?, CallResult)->())
  366. throws
  367. -> Echo_EchoGetCall {
  368. return try Echo_EchoGetCallImpl(channel).start(request:request,
  369. metadata:metadata,
  370. completion:completion)
  371. }
  372. /// Asynchronous. Server-streaming.
  373. /// Send the initial message.
  374. /// Use methods on the returned object to get streamed responses.
  375. internal func expand(_ request: Echo_EchoRequest, completion: ((CallResult)->())?)
  376. throws
  377. -> Echo_EchoExpandCall {
  378. return try Echo_EchoExpandCallImpl(channel).start(request:request, metadata:metadata, completion:completion)
  379. }
  380. /// Asynchronous. Client-streaming.
  381. /// Use methods on the returned object to stream messages and
  382. /// to close the connection and wait for a final response.
  383. internal func collect(completion: ((CallResult)->())?)
  384. throws
  385. -> Echo_EchoCollectCall {
  386. return try Echo_EchoCollectCallImpl(channel).start(metadata:metadata, completion:completion)
  387. }
  388. /// Asynchronous. Bidirectional-streaming.
  389. /// Use methods on the returned object to stream messages,
  390. /// to wait for replies, and to close the connection.
  391. internal func update(completion: ((CallResult)->())?)
  392. throws
  393. -> Echo_EchoUpdateCall {
  394. return try Echo_EchoUpdateCallImpl(channel).start(metadata:metadata, completion:completion)
  395. }
  396. }
  397. /// Simple fake implementation of Echo_EchoService that returns a previously-defined set of results
  398. /// and stores request values passed into it for later verification.
  399. /// Note: completion blocks are NOT called with this default implementation, and asynchronous unary calls are NOT implemented!
  400. class Echo_EchoServiceTestStub: Echo_EchoService {
  401. var channel: Channel { fatalError("not implemented") }
  402. var metadata = Metadata()
  403. var host = ""
  404. var timeout: TimeInterval = 0
  405. var getRequests: [Echo_EchoRequest] = []
  406. var getResponses: [Echo_EchoResponse] = []
  407. func get(_ request: Echo_EchoRequest) throws -> Echo_EchoResponse {
  408. getRequests.append(request)
  409. defer { getResponses.removeFirst() }
  410. return getResponses.first!
  411. }
  412. func get(_ request: Echo_EchoRequest,
  413. completion: @escaping (Echo_EchoResponse?, CallResult)->()) throws -> Echo_EchoGetCall {
  414. fatalError("not implemented")
  415. }
  416. var expandRequests: [Echo_EchoRequest] = []
  417. var expandCalls: [Echo_EchoExpandCall] = []
  418. func expand(_ request: Echo_EchoRequest, completion: ((CallResult)->())?)
  419. throws -> Echo_EchoExpandCall {
  420. expandRequests.append(request)
  421. defer { expandCalls.removeFirst() }
  422. return expandCalls.first!
  423. }
  424. var collectCalls: [Echo_EchoCollectCall] = []
  425. func collect(completion: ((CallResult)->())?)
  426. throws -> Echo_EchoCollectCall {
  427. defer { collectCalls.removeFirst() }
  428. return collectCalls.first!
  429. }
  430. var updateCalls: [Echo_EchoUpdateCall] = []
  431. func update(completion: ((CallResult)->())?)
  432. throws -> Echo_EchoUpdateCall {
  433. defer { updateCalls.removeFirst() }
  434. return updateCalls.first!
  435. }
  436. }
  437. /// Type for errors thrown from generated server code.
  438. internal enum Echo_EchoServerError : Error {
  439. case endOfStream
  440. }
  441. /// To build a server, implement a class that conforms to this protocol.
  442. internal protocol Echo_EchoProvider {
  443. func get(request : Echo_EchoRequest, session : Echo_EchoGetSession) throws -> Echo_EchoResponse
  444. func expand(request : Echo_EchoRequest, session : Echo_EchoExpandSession) throws
  445. func collect(session : Echo_EchoCollectSession) throws
  446. func update(session : Echo_EchoUpdateSession) throws
  447. }
  448. /// Common properties available in each service session.
  449. internal protocol Echo_EchoSession {
  450. var requestMetadata : Metadata { get }
  451. var statusCode : StatusCode { get }
  452. var statusMessage : String { get }
  453. var initialMetadata : Metadata { get }
  454. var trailingMetadata : Metadata { get }
  455. }
  456. fileprivate class Echo_EchoSessionImpl: Echo_EchoSession {
  457. var handler : Handler
  458. var requestMetadata : Metadata { return handler.requestMetadata }
  459. var statusCode : StatusCode = .ok
  460. var statusMessage : String = "OK"
  461. var initialMetadata : Metadata = Metadata()
  462. var trailingMetadata : Metadata = Metadata()
  463. init(handler:Handler) {
  464. self.handler = handler
  465. }
  466. }
  467. class Echo_EchoSessionTestStub: Echo_EchoSession {
  468. var requestMetadata = Metadata()
  469. var statusCode = StatusCode.ok
  470. var statusMessage = "OK"
  471. var initialMetadata = Metadata()
  472. var trailingMetadata = Metadata()
  473. }
  474. // Get (Unary Streaming)
  475. internal protocol Echo_EchoGetSession : Echo_EchoSession { }
  476. fileprivate final class Echo_EchoGetSessionImpl : Echo_EchoSessionImpl, Echo_EchoGetSession {
  477. private var provider : Echo_EchoProvider
  478. /// Create a session.
  479. init(handler:Handler, provider: Echo_EchoProvider) {
  480. self.provider = provider
  481. super.init(handler:handler)
  482. }
  483. /// Run the session. Internal.
  484. func run(queue:DispatchQueue) throws {
  485. try handler.receiveMessage(initialMetadata:initialMetadata) {(requestData) in
  486. if let requestData = requestData {
  487. let requestMessage = try Echo_EchoRequest(serializedData:requestData)
  488. let replyMessage = try self.provider.get(request:requestMessage, session: self)
  489. try self.handler.sendResponse(message:replyMessage.serializedData(),
  490. statusCode:self.statusCode,
  491. statusMessage:self.statusMessage,
  492. trailingMetadata:self.trailingMetadata)
  493. }
  494. }
  495. }
  496. }
  497. /// Trivial fake implementation of Echo_EchoGetSession.
  498. class Echo_EchoGetSessionTestStub : Echo_EchoSessionTestStub, Echo_EchoGetSession { }
  499. // Expand (Server Streaming)
  500. internal protocol Echo_EchoExpandSession : Echo_EchoSession {
  501. /// Send a message. Nonblocking.
  502. func send(_ response: Echo_EchoResponse, completion: ((Bool)->())?) throws
  503. }
  504. fileprivate final class Echo_EchoExpandSessionImpl : Echo_EchoSessionImpl, Echo_EchoExpandSession {
  505. private var provider : Echo_EchoProvider
  506. /// Create a session.
  507. init(handler:Handler, provider: Echo_EchoProvider) {
  508. self.provider = provider
  509. super.init(handler:handler)
  510. }
  511. func send(_ response: Echo_EchoResponse, completion: ((Bool)->())?) throws {
  512. try handler.sendResponse(message:response.serializedData(), completion: completion)
  513. }
  514. /// Run the session. Internal.
  515. func run(queue:DispatchQueue) throws {
  516. try self.handler.receiveMessage(initialMetadata:initialMetadata) {(requestData) in
  517. if let requestData = requestData {
  518. do {
  519. let requestMessage = try Echo_EchoRequest(serializedData:requestData)
  520. // to keep providers from blocking the server thread,
  521. // we dispatch them to another queue.
  522. queue.async {
  523. do {
  524. try self.provider.expand(request:requestMessage, session: self)
  525. try self.handler.sendStatus(statusCode:self.statusCode,
  526. statusMessage:self.statusMessage,
  527. trailingMetadata:self.trailingMetadata,
  528. completion:nil)
  529. } catch (let error) {
  530. print("error: \(error)")
  531. }
  532. }
  533. } catch (let error) {
  534. print("error: \(error)")
  535. }
  536. }
  537. }
  538. }
  539. }
  540. /// Simple fake implementation of Echo_EchoExpandSession that returns a previously-defined set of results
  541. /// and stores sent values for later verification.
  542. class Echo_EchoExpandSessionTestStub : Echo_EchoSessionTestStub, Echo_EchoExpandSession {
  543. var outputs: [Echo_EchoResponse] = []
  544. func send(_ response: Echo_EchoResponse, completion: ((Bool)->())?) throws {
  545. outputs.append(response)
  546. }
  547. func close() throws { }
  548. }
  549. // Collect (Client Streaming)
  550. internal protocol Echo_EchoCollectSession : Echo_EchoSession {
  551. /// Receive a message. Blocks until a message is received or the client closes the connection.
  552. func receive() throws -> Echo_EchoRequest
  553. /// Send a response and close the connection.
  554. func sendAndClose(_ response: Echo_EchoResponse) throws
  555. }
  556. fileprivate final class Echo_EchoCollectSessionImpl : Echo_EchoSessionImpl, Echo_EchoCollectSession {
  557. private var provider : Echo_EchoProvider
  558. /// Create a session.
  559. init(handler:Handler, provider: Echo_EchoProvider) {
  560. self.provider = provider
  561. super.init(handler:handler)
  562. }
  563. func receive() throws -> Echo_EchoRequest {
  564. let sem = DispatchSemaphore(value: 0)
  565. var requestMessage : Echo_EchoRequest?
  566. try self.handler.receiveMessage() {(requestData) in
  567. if let requestData = requestData {
  568. requestMessage = try? Echo_EchoRequest(serializedData:requestData)
  569. }
  570. sem.signal()
  571. }
  572. _ = sem.wait(timeout: DispatchTime.distantFuture)
  573. if requestMessage == nil {
  574. throw Echo_EchoServerError.endOfStream
  575. }
  576. return requestMessage!
  577. }
  578. func sendAndClose(_ response: Echo_EchoResponse) throws {
  579. try self.handler.sendResponse(message:response.serializedData(),
  580. statusCode:self.statusCode,
  581. statusMessage:self.statusMessage,
  582. trailingMetadata:self.trailingMetadata)
  583. }
  584. /// Run the session. Internal.
  585. func run(queue:DispatchQueue) throws {
  586. try self.handler.sendMetadata(initialMetadata:initialMetadata) { _ in
  587. queue.async {
  588. do {
  589. try self.provider.collect(session:self)
  590. } catch (let error) {
  591. print("error \(error)")
  592. }
  593. }
  594. }
  595. }
  596. }
  597. /// Simple fake implementation of Echo_EchoCollectSession that returns a previously-defined set of results
  598. /// and stores sent values for later verification.
  599. class Echo_EchoCollectSessionTestStub: Echo_EchoSessionTestStub, Echo_EchoCollectSession {
  600. var inputs: [Echo_EchoRequest] = []
  601. var output: Echo_EchoResponse?
  602. func receive() throws -> Echo_EchoRequest {
  603. if let input = inputs.first {
  604. inputs.removeFirst()
  605. return input
  606. } else {
  607. throw Echo_EchoClientError.endOfStream
  608. }
  609. }
  610. func sendAndClose(_ response: Echo_EchoResponse) throws {
  611. output = response
  612. }
  613. func close() throws { }
  614. }
  615. // Update (Bidirectional Streaming)
  616. internal protocol Echo_EchoUpdateSession : Echo_EchoSession {
  617. /// Receive a message. Blocks until a message is received or the client closes the connection.
  618. func receive() throws -> Echo_EchoRequest
  619. /// Send a message. Nonblocking.
  620. func send(_ response: Echo_EchoResponse, completion: ((Bool)->())?) throws
  621. /// Close a connection. Blocks until the connection is closed.
  622. func close() throws
  623. }
  624. fileprivate final class Echo_EchoUpdateSessionImpl : Echo_EchoSessionImpl, Echo_EchoUpdateSession {
  625. private var provider : Echo_EchoProvider
  626. /// Create a session.
  627. init(handler:Handler, provider: Echo_EchoProvider) {
  628. self.provider = provider
  629. super.init(handler:handler)
  630. }
  631. func receive() throws -> Echo_EchoRequest {
  632. let sem = DispatchSemaphore(value: 0)
  633. var requestMessage : Echo_EchoRequest?
  634. try self.handler.receiveMessage() {(requestData) in
  635. if let requestData = requestData {
  636. do {
  637. requestMessage = try Echo_EchoRequest(serializedData:requestData)
  638. } catch (let error) {
  639. print("error \(error)")
  640. }
  641. }
  642. sem.signal()
  643. }
  644. _ = sem.wait(timeout: DispatchTime.distantFuture)
  645. if let requestMessage = requestMessage {
  646. return requestMessage
  647. } else {
  648. throw Echo_EchoServerError.endOfStream
  649. }
  650. }
  651. func send(_ response: Echo_EchoResponse, completion: ((Bool)->())?) throws {
  652. try handler.sendResponse(message:response.serializedData(), completion: completion)
  653. }
  654. func close() throws {
  655. let sem = DispatchSemaphore(value: 0)
  656. try self.handler.sendStatus(statusCode:self.statusCode,
  657. statusMessage:self.statusMessage,
  658. trailingMetadata:self.trailingMetadata) { _ in sem.signal() }
  659. _ = sem.wait(timeout: DispatchTime.distantFuture)
  660. }
  661. /// Run the session. Internal.
  662. func run(queue:DispatchQueue) throws {
  663. try self.handler.sendMetadata(initialMetadata:initialMetadata) { _ in
  664. queue.async {
  665. do {
  666. try self.provider.update(session:self)
  667. } catch (let error) {
  668. print("error \(error)")
  669. }
  670. }
  671. }
  672. }
  673. }
  674. /// Simple fake implementation of Echo_EchoUpdateSession that returns a previously-defined set of results
  675. /// and stores sent values for later verification.
  676. class Echo_EchoUpdateSessionTestStub : Echo_EchoSessionTestStub, Echo_EchoUpdateSession {
  677. var inputs: [Echo_EchoRequest] = []
  678. var outputs: [Echo_EchoResponse] = []
  679. func receive() throws -> Echo_EchoRequest {
  680. if let input = inputs.first {
  681. inputs.removeFirst()
  682. return input
  683. } else {
  684. throw Echo_EchoClientError.endOfStream
  685. }
  686. }
  687. func send(_ response: Echo_EchoResponse, completion: ((Bool)->())?) throws {
  688. outputs.append(response)
  689. }
  690. func close() throws { }
  691. }
  692. /// Main server for generated service
  693. internal final class Echo_EchoServer {
  694. private var address: String
  695. private var server: Server
  696. private var provider: Echo_EchoProvider?
  697. /// Create a server that accepts insecure connections.
  698. internal init(address:String,
  699. provider:Echo_EchoProvider) {
  700. gRPC.initialize()
  701. self.address = address
  702. self.provider = provider
  703. self.server = Server(address:address)
  704. }
  705. /// Create a server that accepts secure connections.
  706. internal init?(address:String,
  707. certificateURL:URL,
  708. keyURL:URL,
  709. provider:Echo_EchoProvider) {
  710. gRPC.initialize()
  711. self.address = address
  712. self.provider = provider
  713. guard
  714. let certificate = try? String(contentsOf: certificateURL, encoding: .utf8),
  715. let key = try? String(contentsOf: keyURL, encoding: .utf8)
  716. else {
  717. return nil
  718. }
  719. self.server = Server(address:address, key:key, certs:certificate)
  720. }
  721. /// Start the server.
  722. internal func start(queue:DispatchQueue = DispatchQueue.global()) {
  723. guard let provider = self.provider else {
  724. fatalError() // the server requires a provider
  725. }
  726. server.run {(handler) in
  727. let unwrappedHost = handler.host ?? "(nil)"
  728. let unwrappedMethod = handler.method ?? "(nil)"
  729. let unwrappedCaller = handler.caller ?? "(nil)"
  730. print("Server received request to " + unwrappedHost
  731. + " calling " + unwrappedMethod
  732. + " from " + unwrappedCaller
  733. + " with " + handler.requestMetadata.description)
  734. do {
  735. switch unwrappedMethod {
  736. case "/echo.Echo/Get":
  737. try Echo_EchoGetSessionImpl(handler:handler, provider:provider).run(queue:queue)
  738. case "/echo.Echo/Expand":
  739. try Echo_EchoExpandSessionImpl(handler:handler, provider:provider).run(queue:queue)
  740. case "/echo.Echo/Collect":
  741. try Echo_EchoCollectSessionImpl(handler:handler, provider:provider).run(queue:queue)
  742. case "/echo.Echo/Update":
  743. try Echo_EchoUpdateSessionImpl(handler:handler, provider:provider).run(queue:queue)
  744. default:
  745. // handle unknown requests
  746. try handler.receiveMessage(initialMetadata:Metadata()) {(requestData) in
  747. try handler.sendResponse(statusCode:.unimplemented,
  748. statusMessage:"unknown method " + unwrappedMethod,
  749. trailingMetadata:Metadata())
  750. }
  751. }
  752. } catch (let error) {
  753. print("Server error: \(error)")
  754. }
  755. }
  756. }
  757. }