echo.grpc.swift 24 KB

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