Generator-Client.swift 18 KB

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