Generator-Client.swift 16 KB

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