echo.grpc.swift 26 KB

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