Generator-Client.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. /*
  2. * Copyright 2018, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. import SwiftProtobuf
  18. import SwiftProtobufPluginLibrary
  19. extension Generator {
  20. internal func printClient() {
  21. if self.options.generateClient {
  22. self.println()
  23. self.printServiceClientProtocol()
  24. self.println()
  25. self.printClientProtocolExtension()
  26. self.println()
  27. self.printServiceClientInterceptorFactoryProtocol()
  28. self.println()
  29. self.printServiceClientImplementation()
  30. }
  31. if self.options.generateTestClient {
  32. self.println()
  33. self.printTestClient()
  34. }
  35. }
  36. internal func printFunction(
  37. name: String,
  38. arguments: [String],
  39. returnType: String?,
  40. access: String? = nil,
  41. bodyBuilder: (() -> Void)?
  42. ) {
  43. // Add a space after access, if it exists.
  44. let accessOrEmpty = access.map { $0 + " " } ?? ""
  45. let `return` = returnType.map { "-> " + $0 } ?? ""
  46. let hasBody = bodyBuilder != nil
  47. if arguments.isEmpty {
  48. // Don't bother splitting across multiple lines if there are no arguments.
  49. self.println("\(accessOrEmpty)func \(name)() \(`return`)", newline: !hasBody)
  50. } else {
  51. self.println("\(accessOrEmpty)func \(name)(")
  52. self.withIndentation {
  53. // Add a comma after each argument except the last.
  54. arguments.forEach(beforeLast: {
  55. self.println($0 + ",")
  56. }, onLast: {
  57. self.println($0)
  58. })
  59. }
  60. self.println(") \(`return`)", newline: !hasBody)
  61. }
  62. if let bodyBuilder = bodyBuilder {
  63. self.println(" {")
  64. self.withIndentation {
  65. bodyBuilder()
  66. }
  67. self.println("}")
  68. }
  69. }
  70. private func printServiceClientProtocol() {
  71. self.println(
  72. "/// Usage: instantiate \(self.clientClassName), then call methods of this protocol to make API calls."
  73. )
  74. self.println("\(self.access) protocol \(self.clientProtocolName): GRPCClient {")
  75. self.withIndentation {
  76. self.println("var interceptors: \(self.clientInterceptorProtocolName)? { get }")
  77. for method in service.methods {
  78. self.println()
  79. self.method = method
  80. self.printFunction(
  81. name: self.methodFunctionName,
  82. arguments: self.methodArgumentsWithoutDefaults,
  83. returnType: self.methodReturnType,
  84. bodyBuilder: nil
  85. )
  86. }
  87. }
  88. println("}")
  89. }
  90. private func printClientProtocolExtension() {
  91. self.println("extension \(self.clientProtocolName) {")
  92. // Default method implementations.
  93. self.withIndentation {
  94. self.printMethods()
  95. }
  96. self.println("}")
  97. }
  98. private func printServiceClientInterceptorFactoryProtocol() {
  99. self.println("\(self.access) protocol \(self.clientInterceptorProtocolName) {")
  100. self.withIndentation {
  101. // Method specific interceptors.
  102. for method in service.methods {
  103. self.println()
  104. self.method = method
  105. self.println(
  106. "/// - Returns: Interceptors to use when invoking '\(self.methodFunctionName)'."
  107. )
  108. // Skip the access, we're defining a protocol.
  109. self.printMethodInterceptorFactory(access: nil)
  110. }
  111. }
  112. self.println("}")
  113. }
  114. private func printMethodInterceptorFactory(
  115. access: String?,
  116. bodyBuilder: (() -> Void)? = nil
  117. ) {
  118. self.printFunction(
  119. name: self.methodInterceptorFactoryName,
  120. arguments: [],
  121. returnType: "[ClientInterceptor<\(self.methodInputName), \(self.methodOutputName)>]",
  122. access: access,
  123. bodyBuilder: bodyBuilder
  124. )
  125. }
  126. private func printServiceClientImplementation() {
  127. println("\(access) final class \(clientClassName): \(clientProtocolName) {")
  128. self.withIndentation {
  129. println("\(access) let channel: GRPCChannel")
  130. println("\(access) var defaultCallOptions: CallOptions")
  131. println("\(access) var interceptors: \(clientInterceptorProtocolName)?")
  132. println()
  133. println("/// Creates a client for the \(servicePath) service.")
  134. println("///")
  135. self.printParameters()
  136. println("/// - channel: `GRPCChannel` to the service host.")
  137. println(
  138. "/// - defaultCallOptions: Options to use for each service call if the user doesn't provide them."
  139. )
  140. println("/// - interceptors: A factory providing interceptors for each RPC.")
  141. println("\(access) init(")
  142. self.withIndentation {
  143. println("channel: GRPCChannel,")
  144. println("defaultCallOptions: CallOptions = CallOptions(),")
  145. println("interceptors: \(clientInterceptorProtocolName)? = nil")
  146. }
  147. self.println(") {")
  148. self.withIndentation {
  149. println("self.channel = channel")
  150. println("self.defaultCallOptions = defaultCallOptions")
  151. println("self.interceptors = interceptors")
  152. }
  153. self.println("}")
  154. }
  155. println("}")
  156. }
  157. private func printMethods() {
  158. for method in self.service.methods {
  159. self.println()
  160. self.method = method
  161. switch self.streamType {
  162. case .unary:
  163. self.printUnaryCall()
  164. case .serverStreaming:
  165. self.printServerStreamingCall()
  166. case .clientStreaming:
  167. self.printClientStreamingCall()
  168. case .bidirectionalStreaming:
  169. self.printBidirectionalStreamingCall()
  170. }
  171. }
  172. }
  173. private func printUnaryCall() {
  174. self.println(self.method.documentation(streamingType: self.streamType), newline: false)
  175. self.println("///")
  176. self.printParameters()
  177. self.printRequestParameter()
  178. self.printCallOptionsParameter()
  179. self.println("/// - Returns: A `UnaryCall` with futures for the metadata, status and response.")
  180. self.printFunction(
  181. name: self.methodFunctionName,
  182. arguments: self.methodArguments,
  183. returnType: self.methodReturnType,
  184. access: self.access
  185. ) {
  186. self.println("return self.makeUnaryCall(")
  187. self.withIndentation {
  188. self.println("path: \(self.methodPath),")
  189. self.println("request: request,")
  190. self.println("callOptions: callOptions ?? self.defaultCallOptions,")
  191. self.println(
  192. "interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? []"
  193. )
  194. }
  195. self.println(")")
  196. }
  197. }
  198. private func printServerStreamingCall() {
  199. self.println(self.method.documentation(streamingType: self.streamType), newline: false)
  200. self.println("///")
  201. self.printParameters()
  202. self.printRequestParameter()
  203. self.printCallOptionsParameter()
  204. self.printHandlerParameter()
  205. self.println("/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.")
  206. self.printFunction(
  207. name: self.methodFunctionName,
  208. arguments: self.methodArguments,
  209. returnType: self.methodReturnType,
  210. access: self.access
  211. ) {
  212. self.println("return self.makeServerStreamingCall(")
  213. self.withIndentation {
  214. self.println("path: \(self.methodPath),")
  215. self.println("request: request,")
  216. self.println("callOptions: callOptions ?? self.defaultCallOptions,")
  217. self.println(
  218. "interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? [],"
  219. )
  220. self.println("handler: handler")
  221. }
  222. self.println(")")
  223. }
  224. }
  225. private func printClientStreamingCall() {
  226. self.println(self.method.documentation(streamingType: self.streamType), newline: false)
  227. self.println("///")
  228. self.printClientStreamingDetails()
  229. self.println("///")
  230. self.printParameters()
  231. self.printCallOptionsParameter()
  232. self
  233. .println(
  234. "/// - Returns: A `ClientStreamingCall` with futures for the metadata, status and response."
  235. )
  236. self.printFunction(
  237. name: self.methodFunctionName,
  238. arguments: self.methodArguments,
  239. returnType: self.methodReturnType,
  240. access: self.access
  241. ) {
  242. self.println("return self.makeClientStreamingCall(")
  243. self.withIndentation {
  244. self.println("path: \(self.methodPath),")
  245. self.println("callOptions: callOptions ?? self.defaultCallOptions,")
  246. self.println(
  247. "interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? []"
  248. )
  249. }
  250. self.println(")")
  251. }
  252. }
  253. private func printBidirectionalStreamingCall() {
  254. self.println(self.method.documentation(streamingType: self.streamType), newline: false)
  255. self.println("///")
  256. self.printClientStreamingDetails()
  257. self.println("///")
  258. self.printParameters()
  259. self.printCallOptionsParameter()
  260. self.printHandlerParameter()
  261. self.println("/// - Returns: A `ClientStreamingCall` with futures for the metadata and status.")
  262. self.printFunction(
  263. name: self.methodFunctionName,
  264. arguments: self.methodArguments,
  265. returnType: self.methodReturnType,
  266. access: self.access
  267. ) {
  268. self.println("return self.makeBidirectionalStreamingCall(")
  269. self.withIndentation {
  270. self.println("path: \(self.methodPath),")
  271. self.println("callOptions: callOptions ?? self.defaultCallOptions,")
  272. self.println(
  273. "interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? [],"
  274. )
  275. self.println("handler: handler")
  276. }
  277. self.println(")")
  278. }
  279. }
  280. private func printClientStreamingDetails() {
  281. println("/// Callers should use the `send` method on the returned object to send messages")
  282. println(
  283. "/// to the server. The caller should send an `.end` after the final message has been sent."
  284. )
  285. }
  286. private func printParameters() {
  287. println("/// - Parameters:")
  288. }
  289. private func printRequestParameter() {
  290. println("/// - request: Request to send to \(method.name).")
  291. }
  292. private func printCallOptionsParameter() {
  293. println("/// - callOptions: Call options.")
  294. }
  295. private func printHandlerParameter() {
  296. println("/// - handler: A closure called when each response is received from the server.")
  297. }
  298. }
  299. extension Generator {
  300. fileprivate func printFakeResponseStreams() {
  301. for method in self.service.methods {
  302. self.println()
  303. self.method = method
  304. switch self.streamType {
  305. case .unary, .clientStreaming:
  306. self.printUnaryResponse()
  307. case .serverStreaming, .bidirectionalStreaming:
  308. self.printStreamingResponse()
  309. }
  310. }
  311. }
  312. fileprivate func printUnaryResponse() {
  313. self.printResponseStream(isUnary: true)
  314. self.println()
  315. self.printEnqueueUnaryResponse(isUnary: true)
  316. self.println()
  317. self.printHasResponseStreamEnqueued()
  318. }
  319. fileprivate func printStreamingResponse() {
  320. self.printResponseStream(isUnary: false)
  321. self.println()
  322. self.printEnqueueUnaryResponse(isUnary: false)
  323. self.println()
  324. self.printHasResponseStreamEnqueued()
  325. }
  326. private func printEnqueueUnaryResponse(isUnary: Bool) {
  327. let name: String
  328. let responseArg: String
  329. let responseArgAndType: String
  330. if isUnary {
  331. name = "enqueue\(self.method.name)Response"
  332. responseArg = "response"
  333. responseArgAndType = "_ \(responseArg): \(self.methodOutputName)"
  334. } else {
  335. name = "enqueue\(self.method.name)Responses"
  336. responseArg = "responses"
  337. responseArgAndType = "_ \(responseArg): [\(self.methodOutputName)]"
  338. }
  339. self.printFunction(
  340. name: name,
  341. arguments: [
  342. responseArgAndType,
  343. "_ requestHandler: @escaping (FakeRequestPart<\(self.methodInputName)>) -> () = { _ in }",
  344. ],
  345. returnType: nil,
  346. access: self.access
  347. ) {
  348. self.println("let stream = self.make\(self.method.name)ResponseStream(requestHandler)")
  349. if isUnary {
  350. self.println("// This is the only operation on the stream; try! is fine.")
  351. self.println("try! stream.sendMessage(\(responseArg))")
  352. } else {
  353. self.println("// These are the only operation on the stream; try! is fine.")
  354. self.println("\(responseArg).forEach { try! stream.sendMessage($0) }")
  355. self.println("try! stream.sendEnd()")
  356. }
  357. }
  358. }
  359. private func printResponseStream(isUnary: Bool) {
  360. let type = isUnary ? "FakeUnaryResponse" : "FakeStreamingResponse"
  361. let factory = isUnary ? "makeFakeUnaryResponse" : "makeFakeStreamingResponse"
  362. self
  363. .println(
  364. "/// Make a \(isUnary ? "unary" : "streaming") response for the \(self.method.name) RPC. This must be called"
  365. )
  366. self.println("/// before calling '\(self.methodFunctionName)'. See also '\(type)'.")
  367. self.println("///")
  368. self.println("/// - Parameter requestHandler: a handler for request parts sent by the RPC.")
  369. self.printFunction(
  370. name: "make\(self.method.name)ResponseStream",
  371. arguments: [
  372. "_ requestHandler: @escaping (FakeRequestPart<\(self.methodInputName)>) -> () = { _ in }",
  373. ],
  374. returnType: "\(type)<\(self.methodInputName), \(self.methodOutputName)>",
  375. access: self.access
  376. ) {
  377. self
  378. .println(
  379. "return self.fakeChannel.\(factory)(path: \(self.methodPath), requestHandler: requestHandler)"
  380. )
  381. }
  382. }
  383. private func printHasResponseStreamEnqueued() {
  384. self
  385. .println("/// Returns true if there are response streams enqueued for '\(self.method.name)'")
  386. self.println("\(self.access) var has\(self.method.name)ResponsesRemaining: Bool {")
  387. self.withIndentation {
  388. self.println("return self.fakeChannel.hasFakeResponseEnqueued(forPath: \(self.methodPath))")
  389. }
  390. self.println("}")
  391. }
  392. fileprivate func printTestClient() {
  393. self
  394. .println(
  395. "\(self.access) final class \(self.testClientClassName): \(self.clientProtocolName) {"
  396. )
  397. self.withIndentation {
  398. self.println("private let fakeChannel: FakeChannel")
  399. self.println("\(self.access) var defaultCallOptions: CallOptions")
  400. self.println("\(self.access) var interceptors: \(self.clientInterceptorProtocolName)?")
  401. self.println()
  402. self.println("\(self.access) var channel: GRPCChannel {")
  403. self.withIndentation {
  404. self.println("return self.fakeChannel")
  405. }
  406. self.println("}")
  407. self.println()
  408. self.println("\(self.access) init(")
  409. self.withIndentation {
  410. self.println("fakeChannel: FakeChannel = FakeChannel(),")
  411. self.println("defaultCallOptions callOptions: CallOptions = CallOptions(),")
  412. self.println("interceptors: \(clientInterceptorProtocolName)? = nil")
  413. }
  414. self.println(") {")
  415. self.withIndentation {
  416. self.println("self.fakeChannel = fakeChannel")
  417. self.println("self.defaultCallOptions = callOptions")
  418. self.println("self.interceptors = interceptors")
  419. }
  420. self.println("}")
  421. self.printFakeResponseStreams()
  422. }
  423. self.println("}") // end class
  424. }
  425. }
  426. private extension Generator {
  427. var streamType: StreamingType {
  428. return streamingType(self.method)
  429. }
  430. }
  431. extension Generator {
  432. fileprivate var methodArguments: [String] {
  433. switch self.streamType {
  434. case .unary:
  435. return [
  436. "_ request: \(self.methodInputName)",
  437. "callOptions: CallOptions? = nil",
  438. ]
  439. case .serverStreaming:
  440. return [
  441. "_ request: \(self.methodInputName)",
  442. "callOptions: CallOptions? = nil",
  443. "handler: @escaping (\(methodOutputName)) -> Void",
  444. ]
  445. case .clientStreaming:
  446. return ["callOptions: CallOptions? = nil"]
  447. case .bidirectionalStreaming:
  448. return [
  449. "callOptions: CallOptions? = nil",
  450. "handler: @escaping (\(methodOutputName)) -> Void",
  451. ]
  452. }
  453. }
  454. fileprivate var methodArgumentsWithoutDefaults: [String] {
  455. return self.methodArguments.map { arg in
  456. // Remove default arg from call options.
  457. if arg == "callOptions: CallOptions? = nil" {
  458. return "callOptions: CallOptions?"
  459. } else {
  460. return arg
  461. }
  462. }
  463. }
  464. fileprivate var methodArgumentsWithoutCallOptions: [String] {
  465. return self.methodArguments.filter {
  466. !$0.hasPrefix("callOptions: ")
  467. }
  468. }
  469. fileprivate var methodReturnType: String {
  470. switch self.streamType {
  471. case .unary:
  472. return "UnaryCall<\(self.methodInputName), \(self.methodOutputName)>"
  473. case .serverStreaming:
  474. return "ServerStreamingCall<\(self.methodInputName), \(self.methodOutputName)>"
  475. case .clientStreaming:
  476. return "ClientStreamingCall<\(self.methodInputName), \(self.methodOutputName)>"
  477. case .bidirectionalStreaming:
  478. return "BidirectionalStreamingCall<\(self.methodInputName), \(self.methodOutputName)>"
  479. }
  480. }
  481. }
  482. private extension StreamingType {
  483. var name: String {
  484. switch self {
  485. case .unary:
  486. return "Unary"
  487. case .clientStreaming:
  488. return "Client streaming"
  489. case .serverStreaming:
  490. return "Server streaming"
  491. case .bidirectionalStreaming:
  492. return "Bidirectional streaming"
  493. }
  494. }
  495. }
  496. extension MethodDescriptor {
  497. var documentation: String? {
  498. let comments = self.protoSourceComments(commentPrefix: "")
  499. return comments.isEmpty ? nil : comments
  500. }
  501. fileprivate func documentation(streamingType: StreamingType) -> String {
  502. let sourceComments = self.protoSourceComments()
  503. if sourceComments.isEmpty {
  504. return "/// \(streamingType.name) call to \(self.name)\n" // comments end with "\n" already.
  505. } else {
  506. return sourceComments // already prefixed with "///"
  507. }
  508. }
  509. }
  510. extension Array {
  511. /// Like `forEach` except that the `body` closure operates on all elements except for the last,
  512. /// and the `last` closure only operates on the last element.
  513. fileprivate func forEach(beforeLast body: (Element) -> Void, onLast last: (Element) -> Void) {
  514. for element in self.dropLast() {
  515. body(element)
  516. }
  517. if let lastElement = self.last {
  518. last(lastElement)
  519. }
  520. }
  521. }