Generator-Client.swift 20 KB

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