Generator-Client.swift 19 KB

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