ServerCodeTranslator.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. /*
  2. * Copyright 2023, 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. /// Creates a representation for the server code that will be generated based on the ``CodeGenerationRequest`` object
  17. /// specifications, using types from ``StructuredSwiftRepresentation``.
  18. ///
  19. /// For example, in the case of a service called "Bar", in the "foo" namespace which has
  20. /// one method "baz", the ``ServerCodeTranslator`` will create
  21. /// a representation for the following generated code:
  22. ///
  23. /// ```swift
  24. /// public protocol foo_BarServiceStreamingProtocol: GRPCCore.RegistrableRPCService {
  25. /// func baz(
  26. /// request: ServerRequest.Stream<foo.Method.baz.Input>
  27. /// ) async throws -> ServerResponse.Stream<foo.Method.baz.Output>
  28. /// }
  29. /// // Generated conformance to `RegistrableRPCService`.
  30. /// extension foo.Bar.StreamingServiceProtocol {
  31. /// public func registerRPCs(with router: inout RPCRouter) {
  32. /// router.registerHandler(
  33. /// for: foo.Method.baz.descriptor,
  34. /// deserializer: ProtobufDeserializer<foo.Methods.baz.Input>(),
  35. /// serializer: ProtobufSerializer<foo.Methods.baz.Output>(),
  36. /// handler: { request in try await self.baz(request: request) }
  37. /// )
  38. /// }
  39. /// }
  40. /// public protocol foo_BarServiceProtocol: foo.Bar.StreamingServiceProtocol {
  41. /// func baz(
  42. /// request: ServerRequest.Single<foo.Bar.Methods.baz.Input>
  43. /// ) async throws -> ServerResponse.Single<foo.Bar.Methods.baz.Output>
  44. /// }
  45. /// // Generated partial conformance to `foo_BarStreamingServiceProtocol`.
  46. /// extension foo.Bar.ServiceProtocol {
  47. /// public func baz(
  48. /// request: ServerRequest.Stream<foo.Bar.Methods.baz.Input>
  49. /// ) async throws -> ServerResponse.Stream<foo.Bar.Methods.baz.Output> {
  50. /// let response = try await self.baz(request: ServerRequest.Single(stream: request)
  51. /// return ServerResponse.Stream(single: response)
  52. /// }
  53. /// }
  54. ///```
  55. struct ServerCodeTranslator: SpecializedTranslator {
  56. var accessLevel: SourceGenerator.Configuration.AccessLevel
  57. init(accessLevel: SourceGenerator.Configuration.AccessLevel) {
  58. self.accessLevel = accessLevel
  59. }
  60. func translate(from codeGenerationRequest: CodeGenerationRequest) throws -> [CodeBlock] {
  61. var codeBlocks = [CodeBlock]()
  62. for service in codeGenerationRequest.services {
  63. // Create the streaming protocol that declares the service methods as bidirectional streaming.
  64. let streamingProtocol = CodeBlockItem.declaration(self.makeStreamingProtocol(for: service))
  65. codeBlocks.append(CodeBlock(item: streamingProtocol))
  66. // Create extension for implementing the 'registerRPCs' function which is a 'RegistrableRPCService' requirement.
  67. let conformanceToRPCServiceExtension = CodeBlockItem.declaration(
  68. self.makeConformanceToRPCServiceExtension(for: service, in: codeGenerationRequest)
  69. )
  70. codeBlocks.append(
  71. CodeBlock(
  72. comment: .doc("Conformance to `GRPCCore.RegistrableRPCService`."),
  73. item: conformanceToRPCServiceExtension
  74. )
  75. )
  76. // Create the service protocol that declares the service methods as they are described in the Source IDL (unary,
  77. // client/server streaming or bidirectional streaming).
  78. let serviceProtocol = CodeBlockItem.declaration(self.makeServiceProtocol(for: service))
  79. codeBlocks.append(CodeBlock(item: serviceProtocol))
  80. // Create extension for partial conformance to the streaming protocol.
  81. let extensionServiceProtocol = CodeBlockItem.declaration(
  82. self.makeExtensionServiceProtocol(for: service)
  83. )
  84. codeBlocks.append(
  85. CodeBlock(
  86. comment: .doc(
  87. "Partial conformance to `\(self.protocolName(service: service, streaming: true))`."
  88. ),
  89. item: extensionServiceProtocol
  90. )
  91. )
  92. }
  93. return codeBlocks
  94. }
  95. }
  96. extension ServerCodeTranslator {
  97. private func makeStreamingProtocol(
  98. for service: CodeGenerationRequest.ServiceDescriptor
  99. ) -> Declaration {
  100. let methods = service.methods.compactMap {
  101. Declaration.commentable(
  102. .doc($0.documentation),
  103. .function(
  104. FunctionDescription(
  105. signature: self.makeStreamingMethodSignature(for: $0, in: service)
  106. )
  107. )
  108. )
  109. }
  110. let streamingProtocol = Declaration.protocol(
  111. .init(
  112. accessModifier: self.accessModifier,
  113. name: self.protocolName(service: service, streaming: true),
  114. conformances: ["GRPCCore.RegistrableRPCService"],
  115. members: methods
  116. )
  117. )
  118. return .commentable(.doc(service.documentation), streamingProtocol)
  119. }
  120. private func makeStreamingMethodSignature(
  121. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  122. in service: CodeGenerationRequest.ServiceDescriptor,
  123. accessModifier: AccessModifier? = nil
  124. ) -> FunctionSignatureDescription {
  125. return FunctionSignatureDescription(
  126. accessModifier: accessModifier,
  127. kind: .function(name: method.name),
  128. parameters: [
  129. .init(
  130. label: "request",
  131. type: .generic(
  132. wrapper: .member(["ServerRequest", "Stream"]),
  133. wrapped: .member(
  134. self.methodInputOutputTypealias(for: method, service: service, type: .input)
  135. )
  136. )
  137. )
  138. ],
  139. keywords: [.async, .throws],
  140. returnType: .identifierType(
  141. .generic(
  142. wrapper: .member(["ServerResponse", "Stream"]),
  143. wrapped: .member(
  144. self.methodInputOutputTypealias(for: method, service: service, type: .output)
  145. )
  146. )
  147. )
  148. )
  149. }
  150. private func makeConformanceToRPCServiceExtension(
  151. for service: CodeGenerationRequest.ServiceDescriptor,
  152. in codeGenerationRequest: CodeGenerationRequest
  153. ) -> Declaration {
  154. let streamingProtocol = self.protocolNameTypealias(service: service, streaming: true)
  155. let registerRPCMethod = self.makeRegisterRPCsMethod(for: service, in: codeGenerationRequest)
  156. return .extension(
  157. onType: streamingProtocol,
  158. declarations: [registerRPCMethod]
  159. )
  160. }
  161. private func makeRegisterRPCsMethod(
  162. for service: CodeGenerationRequest.ServiceDescriptor,
  163. in codeGenerationRequest: CodeGenerationRequest
  164. ) -> Declaration {
  165. let registerRPCsSignature = FunctionSignatureDescription(
  166. accessModifier: self.accessModifier,
  167. kind: .function(name: "registerMethods"),
  168. parameters: [
  169. .init(
  170. label: "with",
  171. name: "router",
  172. type: .member(["GRPCCore", "RPCRouter"]),
  173. `inout`: true
  174. )
  175. ]
  176. )
  177. let registerRPCsBody = self.makeRegisterRPCsMethodBody(for: service, in: codeGenerationRequest)
  178. return .function(signature: registerRPCsSignature, body: registerRPCsBody)
  179. }
  180. private func makeRegisterRPCsMethodBody(
  181. for service: CodeGenerationRequest.ServiceDescriptor,
  182. in codeGenerationRequest: CodeGenerationRequest
  183. ) -> [CodeBlock] {
  184. let registerHandlerCalls = service.methods.compactMap {
  185. CodeBlock.expression(
  186. Expression.functionCall(
  187. calledExpression: .memberAccess(
  188. MemberAccessDescription(left: .identifierPattern("router"), right: "registerHandler")
  189. ),
  190. arguments: self.makeArgumentsForRegisterHandler(
  191. for: $0,
  192. in: service,
  193. from: codeGenerationRequest
  194. )
  195. )
  196. )
  197. }
  198. return registerHandlerCalls
  199. }
  200. private func makeArgumentsForRegisterHandler(
  201. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  202. in service: CodeGenerationRequest.ServiceDescriptor,
  203. from codeGenerationRequest: CodeGenerationRequest
  204. ) -> [FunctionArgumentDescription] {
  205. var arguments = [FunctionArgumentDescription]()
  206. arguments.append(
  207. .init(
  208. label: "for",
  209. expression: .identifierPattern(
  210. self.methodDescriptorPath(for: method, service: service)
  211. )
  212. )
  213. )
  214. arguments.append(
  215. .init(
  216. label: "deserializer",
  217. expression: .identifierPattern(
  218. codeGenerationRequest.lookupDeserializer(
  219. self.methodInputOutputTypealias(for: method, service: service, type: .input)
  220. )
  221. )
  222. )
  223. )
  224. arguments.append(
  225. .init(
  226. label: "serializer",
  227. expression:
  228. .identifierPattern(
  229. codeGenerationRequest.lookupSerializer(
  230. self.methodInputOutputTypealias(for: method, service: service, type: .output)
  231. )
  232. )
  233. )
  234. )
  235. let getFunctionCall = Expression.functionCall(
  236. calledExpression: .memberAccess(
  237. MemberAccessDescription(left: .identifierPattern("self"), right: method.name)
  238. ),
  239. arguments: [
  240. FunctionArgumentDescription(label: "request", expression: .identifierPattern("request"))
  241. ]
  242. )
  243. let handlerClosureBody = Expression.unaryKeyword(
  244. kind: .try,
  245. expression: .unaryKeyword(kind: .await, expression: getFunctionCall)
  246. )
  247. arguments.append(
  248. .init(
  249. label: "handler",
  250. expression: .closureInvocation(
  251. .init(argumentNames: ["request"], body: [.expression(handlerClosureBody)])
  252. )
  253. )
  254. )
  255. return arguments
  256. }
  257. private func makeServiceProtocol(
  258. for service: CodeGenerationRequest.ServiceDescriptor
  259. ) -> Declaration {
  260. let methods = service.methods.compactMap {
  261. self.makeServiceProtocolMethod(for: $0, in: service)
  262. }
  263. let protocolName = self.protocolName(service: service, streaming: false)
  264. let streamingProtocol = self.protocolNameTypealias(service: service, streaming: true)
  265. return .commentable(
  266. .doc(service.documentation),
  267. .protocol(
  268. ProtocolDescription(
  269. accessModifier: self.accessModifier,
  270. name: protocolName,
  271. conformances: [streamingProtocol],
  272. members: methods
  273. )
  274. )
  275. )
  276. }
  277. private func makeServiceProtocolMethod(
  278. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  279. in service: CodeGenerationRequest.ServiceDescriptor,
  280. accessModifier: AccessModifier? = nil
  281. ) -> Declaration {
  282. let inputStreaming = method.isInputStreaming ? "Stream" : "Single"
  283. let outputStreaming = method.isOutputStreaming ? "Stream" : "Single"
  284. let inputTypealiasComponents = self.methodInputOutputTypealias(
  285. for: method,
  286. service: service,
  287. type: .input
  288. )
  289. let outputTypealiasComponents = self.methodInputOutputTypealias(
  290. for: method,
  291. service: service,
  292. type: .output
  293. )
  294. let functionSignature = FunctionSignatureDescription(
  295. accessModifier: accessModifier,
  296. kind: .function(name: method.name),
  297. parameters: [
  298. .init(
  299. label: "request",
  300. type:
  301. .generic(
  302. wrapper: .member(["ServerRequest", inputStreaming]),
  303. wrapped: .member(inputTypealiasComponents)
  304. )
  305. )
  306. ],
  307. keywords: [.async, .throws],
  308. returnType: .identifierType(
  309. .generic(
  310. wrapper: .member(["ServerResponse", outputStreaming]),
  311. wrapped: .member(outputTypealiasComponents)
  312. )
  313. )
  314. )
  315. return .commentable(
  316. .doc(method.documentation),
  317. .function(FunctionDescription(signature: functionSignature))
  318. )
  319. }
  320. private func makeExtensionServiceProtocol(
  321. for service: CodeGenerationRequest.ServiceDescriptor
  322. ) -> Declaration {
  323. let methods = service.methods.compactMap {
  324. self.makeServiceProtocolExtensionMethod(for: $0, in: service)
  325. }
  326. let protocolName = self.protocolNameTypealias(service: service, streaming: false)
  327. return .extension(
  328. onType: protocolName,
  329. declarations: methods
  330. )
  331. }
  332. private func makeServiceProtocolExtensionMethod(
  333. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  334. in service: CodeGenerationRequest.ServiceDescriptor
  335. ) -> Declaration? {
  336. // The method has the same definition in StreamingServiceProtocol and ServiceProtocol.
  337. if method.isInputStreaming && method.isOutputStreaming {
  338. return nil
  339. }
  340. let response = CodeBlock(item: .declaration(self.makeResponse(for: method)))
  341. let returnStatement = CodeBlock(item: .expression(self.makeReturnStatement(for: method)))
  342. return .function(
  343. signature: self.makeStreamingMethodSignature(
  344. for: method,
  345. in: service,
  346. accessModifier: self.accessModifier
  347. ),
  348. body: [response, returnStatement]
  349. )
  350. }
  351. private func makeResponse(
  352. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor
  353. ) -> Declaration {
  354. let serverRequest: Expression
  355. if !method.isInputStreaming {
  356. // Transform the streaming request into a unary request.
  357. serverRequest = Expression.functionCall(
  358. calledExpression: .memberAccess(
  359. MemberAccessDescription(
  360. left: .identifierPattern("ServerRequest"),
  361. right: "Single"
  362. )
  363. ),
  364. arguments: [
  365. FunctionArgumentDescription(label: "stream", expression: .identifierPattern("request"))
  366. ]
  367. )
  368. } else {
  369. serverRequest = Expression.identifierPattern("request")
  370. }
  371. // Call to the corresponding ServiceProtocol method.
  372. let serviceProtocolMethod = Expression.functionCall(
  373. calledExpression: .memberAccess(
  374. MemberAccessDescription(left: .identifierPattern("self"), right: method.name)
  375. ),
  376. arguments: [FunctionArgumentDescription(label: "request", expression: serverRequest)]
  377. )
  378. let responseValue = Expression.unaryKeyword(
  379. kind: .try,
  380. expression: .unaryKeyword(kind: .await, expression: serviceProtocolMethod)
  381. )
  382. return .variable(kind: .let, left: "response", right: responseValue)
  383. }
  384. private func makeReturnStatement(
  385. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor
  386. ) -> Expression {
  387. let returnValue: Expression
  388. // Transforming the unary response into a streaming one.
  389. if !method.isOutputStreaming {
  390. returnValue = .functionCall(
  391. calledExpression: .memberAccess(
  392. MemberAccessDescription(
  393. left: .identifierType(.member(["ServerResponse"])),
  394. right: "Stream"
  395. )
  396. ),
  397. arguments: [
  398. (FunctionArgumentDescription(label: "single", expression: .identifierPattern("response")))
  399. ]
  400. )
  401. } else {
  402. returnValue = .identifierPattern("response")
  403. }
  404. return .unaryKeyword(kind: .return, expression: returnValue)
  405. }
  406. fileprivate enum InputOutputType {
  407. case input
  408. case output
  409. }
  410. /// Generates the fully qualified name of the typealias for the input or output type of a method.
  411. private func methodInputOutputTypealias(
  412. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  413. service: CodeGenerationRequest.ServiceDescriptor,
  414. type: InputOutputType
  415. ) -> String {
  416. var components: String = "\(service.namespacedTypealiasPrefix).Methods.\(method.name)"
  417. switch type {
  418. case .input:
  419. components.append(".Input")
  420. case .output:
  421. components.append(".Output")
  422. }
  423. return components
  424. }
  425. /// Generates the fully qualified name of a method descriptor.
  426. private func methodDescriptorPath(
  427. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  428. service: CodeGenerationRequest.ServiceDescriptor
  429. ) -> String {
  430. return "\(service.namespacedTypealiasPrefix).Methods.\(method.name).descriptor"
  431. }
  432. /// Generates the fully qualified name of the type alias for a service protocol.
  433. internal func protocolNameTypealias(
  434. service: CodeGenerationRequest.ServiceDescriptor,
  435. streaming: Bool
  436. ) -> String {
  437. if streaming {
  438. return "\(service.namespacedTypealiasPrefix).StreamingServiceProtocol"
  439. }
  440. return "\(service.namespacedTypealiasPrefix).ServiceProtocol"
  441. }
  442. /// Generates the name of a service protocol.
  443. internal func protocolName(
  444. service: CodeGenerationRequest.ServiceDescriptor,
  445. streaming: Bool
  446. ) -> String {
  447. if streaming {
  448. return "\(service.namespacedPrefix)StreamingServiceProtocol"
  449. }
  450. return "\(service.namespacedPrefix)ServiceProtocol"
  451. }
  452. }