Generator-Client.swift 20 KB

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