Generator-Client+AsyncAwait.swift 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. /*
  2. * Copyright 2021, 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 SwiftProtobuf
  17. import SwiftProtobufPluginLibrary
  18. // MARK: - Client protocol
  19. extension Generator {
  20. internal func printAsyncServiceClientProtocol() {
  21. let comments = self.service.protoSourceComments()
  22. if !comments.isEmpty {
  23. // Source comments already have the leading '///'
  24. self.println(comments, newline: false)
  25. }
  26. self.printAvailabilityForAsyncAwait()
  27. self.println("\(self.access) protocol \(self.asyncClientProtocolName): GRPCClient {")
  28. self.withIndentation {
  29. self.println("static var serviceDescriptor: GRPCServiceDescriptor { get }")
  30. self.println("var interceptors: \(self.clientInterceptorProtocolName)? { get }")
  31. for method in service.methods {
  32. self.println()
  33. self.method = method
  34. let rpcType = streamingType(self.method)
  35. let callType = Types.call(for: rpcType)
  36. let arguments: [String]
  37. switch rpcType {
  38. case .unary, .serverStreaming:
  39. arguments = [
  40. "_ request: \(self.methodInputName)",
  41. "callOptions: \(Types.clientCallOptions)?",
  42. ]
  43. case .clientStreaming, .bidirectionalStreaming:
  44. arguments = [
  45. "callOptions: \(Types.clientCallOptions)?"
  46. ]
  47. }
  48. self.printFunction(
  49. name: self.methodMakeFunctionCallName,
  50. arguments: arguments,
  51. returnType: "\(callType)<\(self.methodInputName), \(self.methodOutputName)>",
  52. bodyBuilder: nil
  53. )
  54. }
  55. }
  56. self.println("}") // protocol
  57. }
  58. }
  59. // MARK: - Client protocol default implementation: Calls
  60. extension Generator {
  61. internal func printAsyncClientProtocolExtension() {
  62. self.printAvailabilityForAsyncAwait()
  63. self.withIndentation("extension \(self.asyncClientProtocolName)", braces: .curly) {
  64. // Service descriptor.
  65. self.withIndentation(
  66. "\(self.access) static var serviceDescriptor: GRPCServiceDescriptor",
  67. braces: .curly
  68. ) {
  69. self.println("return \(self.serviceClientMetadata).serviceDescriptor")
  70. }
  71. self.println()
  72. // Interceptor factory.
  73. self.withIndentation(
  74. "\(self.access) var interceptors: \(self.clientInterceptorProtocolName)?",
  75. braces: .curly
  76. ) {
  77. self.println("return nil")
  78. }
  79. // 'Unsafe' calls.
  80. for method in self.service.methods {
  81. self.println()
  82. self.method = method
  83. let rpcType = streamingType(self.method)
  84. let callType = Types.call(for: rpcType)
  85. let callTypeWithoutPrefix = Types.call(for: rpcType, withGRPCPrefix: false)
  86. switch rpcType {
  87. case .unary, .serverStreaming:
  88. self.printFunction(
  89. name: self.methodMakeFunctionCallName,
  90. arguments: [
  91. "_ request: \(self.methodInputName)",
  92. "callOptions: \(Types.clientCallOptions)? = nil",
  93. ],
  94. returnType: "\(callType)<\(self.methodInputName), \(self.methodOutputName)>",
  95. access: self.access
  96. ) {
  97. self.withIndentation("return self.make\(callTypeWithoutPrefix)", braces: .round) {
  98. self.println("path: \(self.methodPathUsingClientMetadata),")
  99. self.println("request: request,")
  100. self.println("callOptions: callOptions ?? self.defaultCallOptions,")
  101. self.println(
  102. "interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? []"
  103. )
  104. }
  105. }
  106. case .clientStreaming, .bidirectionalStreaming:
  107. self.printFunction(
  108. name: self.methodMakeFunctionCallName,
  109. arguments: ["callOptions: \(Types.clientCallOptions)? = nil"],
  110. returnType: "\(callType)<\(self.methodInputName), \(self.methodOutputName)>",
  111. access: self.access
  112. ) {
  113. self.withIndentation("return self.make\(callTypeWithoutPrefix)", braces: .round) {
  114. self.println("path: \(self.methodPathUsingClientMetadata),")
  115. self.println("callOptions: callOptions ?? self.defaultCallOptions,")
  116. self.println(
  117. "interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? []"
  118. )
  119. }
  120. }
  121. }
  122. }
  123. }
  124. }
  125. }
  126. // MARK: - Client protocol extension: "Simple, but safe" call wrappers.
  127. extension Generator {
  128. internal func printAsyncClientProtocolSafeWrappersExtension() {
  129. self.printAvailabilityForAsyncAwait()
  130. self.withIndentation("extension \(self.asyncClientProtocolName)", braces: .curly) {
  131. for (i, method) in self.service.methods.enumerated() {
  132. self.method = method
  133. let rpcType = streamingType(self.method)
  134. let callTypeWithoutPrefix = Types.call(for: rpcType, withGRPCPrefix: false)
  135. let streamsResponses = [.serverStreaming, .bidirectionalStreaming].contains(rpcType)
  136. let streamsRequests = [.clientStreaming, .bidirectionalStreaming].contains(rpcType)
  137. // (protocol, requires sendable)
  138. let sequenceProtocols: [(String, Bool)?] =
  139. streamsRequests
  140. ? [("Sequence", false), ("AsyncSequence", true)]
  141. : [nil]
  142. for (j, sequenceProtocol) in sequenceProtocols.enumerated() {
  143. // Print a new line if this is not the first function in the extension.
  144. if i > 0 || j > 0 {
  145. self.println()
  146. }
  147. let functionName =
  148. streamsRequests
  149. ? "\(self.methodFunctionName)<RequestStream>"
  150. : self.methodFunctionName
  151. let requestParamName = streamsRequests ? "requests" : "request"
  152. let requestParamType = streamsRequests ? "RequestStream" : self.methodInputName
  153. let returnType =
  154. streamsResponses
  155. ? Types.responseStream(of: self.methodOutputName)
  156. : self.methodOutputName
  157. let maybeWhereClause = sequenceProtocol.map { protocolName, mustBeSendable -> String in
  158. let constraints = [
  159. "RequestStream: \(protocolName)" + (mustBeSendable ? " & Sendable" : ""),
  160. "RequestStream.Element == \(self.methodInputName)",
  161. ]
  162. return "where " + constraints.joined(separator: ", ")
  163. }
  164. self.printFunction(
  165. name: functionName,
  166. arguments: [
  167. "_ \(requestParamName): \(requestParamType)",
  168. "callOptions: \(Types.clientCallOptions)? = nil",
  169. ],
  170. returnType: returnType,
  171. access: self.access,
  172. async: !streamsResponses,
  173. throws: !streamsResponses,
  174. genericWhereClause: maybeWhereClause
  175. ) {
  176. self.withIndentation(
  177. "return\(!streamsResponses ? " try await" : "") self.perform\(callTypeWithoutPrefix)",
  178. braces: .round
  179. ) {
  180. self.println("path: \(self.methodPathUsingClientMetadata),")
  181. self.println("\(requestParamName): \(requestParamName),")
  182. self.println("callOptions: callOptions ?? self.defaultCallOptions,")
  183. self.println(
  184. "interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? []"
  185. )
  186. }
  187. }
  188. }
  189. }
  190. }
  191. }
  192. }
  193. // MARK: - Client protocol implementation
  194. extension Generator {
  195. internal func printAsyncServiceClientImplementation() {
  196. self.printAvailabilityForAsyncAwait()
  197. self.withIndentation(
  198. "\(self.access) struct \(self.asyncClientStructName): \(self.asyncClientProtocolName)",
  199. braces: .curly
  200. ) {
  201. self.println("\(self.access) var channel: GRPCChannel")
  202. self.println("\(self.access) var defaultCallOptions: CallOptions")
  203. self.println("\(self.access) var interceptors: \(self.clientInterceptorProtocolName)?")
  204. self.println()
  205. self.println("\(self.access) init(")
  206. self.withIndentation {
  207. self.println("channel: GRPCChannel,")
  208. self.println("defaultCallOptions: CallOptions = CallOptions(),")
  209. self.println("interceptors: \(self.clientInterceptorProtocolName)? = nil")
  210. }
  211. self.println(") {")
  212. self.withIndentation {
  213. self.println("self.channel = channel")
  214. self.println("self.defaultCallOptions = defaultCallOptions")
  215. self.println("self.interceptors = interceptors")
  216. }
  217. self.println("}")
  218. }
  219. }
  220. }