Generator-Client.swift 19 KB

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