Generator-Client.swift 15 KB

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