echo.grpc.swift 30 KB

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