Generator-Client.swift 16 KB

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