ServerCodeTranslator.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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. .preFormatted($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(.preFormatted(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.generatedLowerCase),
  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(
  238. left: .identifierPattern("self"),
  239. right: method.name.generatedLowerCase
  240. )
  241. ),
  242. arguments: [
  243. FunctionArgumentDescription(label: "request", expression: .identifierPattern("request"))
  244. ]
  245. )
  246. let handlerClosureBody = Expression.unaryKeyword(
  247. kind: .try,
  248. expression: .unaryKeyword(kind: .await, expression: getFunctionCall)
  249. )
  250. arguments.append(
  251. .init(
  252. label: "handler",
  253. expression: .closureInvocation(
  254. .init(argumentNames: ["request"], body: [.expression(handlerClosureBody)])
  255. )
  256. )
  257. )
  258. return arguments
  259. }
  260. private func makeServiceProtocol(
  261. for service: CodeGenerationRequest.ServiceDescriptor
  262. ) -> Declaration {
  263. let methods = service.methods.compactMap {
  264. self.makeServiceProtocolMethod(for: $0, in: service)
  265. }
  266. let protocolName = self.protocolName(service: service, streaming: false)
  267. let streamingProtocol = self.protocolNameTypealias(service: service, streaming: true)
  268. return .commentable(
  269. .preFormatted(service.documentation),
  270. .protocol(
  271. ProtocolDescription(
  272. accessModifier: self.accessModifier,
  273. name: protocolName,
  274. conformances: [streamingProtocol],
  275. members: methods
  276. )
  277. )
  278. )
  279. }
  280. private func makeServiceProtocolMethod(
  281. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  282. in service: CodeGenerationRequest.ServiceDescriptor,
  283. accessModifier: AccessModifier? = nil
  284. ) -> Declaration {
  285. let inputStreaming = method.isInputStreaming ? "Stream" : "Single"
  286. let outputStreaming = method.isOutputStreaming ? "Stream" : "Single"
  287. let inputTypealiasComponents = self.methodInputOutputTypealias(
  288. for: method,
  289. service: service,
  290. type: .input
  291. )
  292. let outputTypealiasComponents = self.methodInputOutputTypealias(
  293. for: method,
  294. service: service,
  295. type: .output
  296. )
  297. let functionSignature = FunctionSignatureDescription(
  298. accessModifier: accessModifier,
  299. kind: .function(name: method.name.generatedLowerCase),
  300. parameters: [
  301. .init(
  302. label: "request",
  303. type:
  304. .generic(
  305. wrapper: .member(["ServerRequest", inputStreaming]),
  306. wrapped: .member(inputTypealiasComponents)
  307. )
  308. )
  309. ],
  310. keywords: [.async, .throws],
  311. returnType: .identifierType(
  312. .generic(
  313. wrapper: .member(["ServerResponse", outputStreaming]),
  314. wrapped: .member(outputTypealiasComponents)
  315. )
  316. )
  317. )
  318. return .commentable(
  319. .preFormatted(method.documentation),
  320. .function(FunctionDescription(signature: functionSignature))
  321. )
  322. }
  323. private func makeExtensionServiceProtocol(
  324. for service: CodeGenerationRequest.ServiceDescriptor
  325. ) -> Declaration {
  326. let methods = service.methods.compactMap {
  327. self.makeServiceProtocolExtensionMethod(for: $0, in: service)
  328. }
  329. let protocolName = self.protocolNameTypealias(service: service, streaming: false)
  330. return .extension(
  331. onType: protocolName,
  332. declarations: methods
  333. )
  334. }
  335. private func makeServiceProtocolExtensionMethod(
  336. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  337. in service: CodeGenerationRequest.ServiceDescriptor
  338. ) -> Declaration? {
  339. // The method has the same definition in StreamingServiceProtocol and ServiceProtocol.
  340. if method.isInputStreaming && method.isOutputStreaming {
  341. return nil
  342. }
  343. let response = CodeBlock(item: .declaration(self.makeResponse(for: method)))
  344. let returnStatement = CodeBlock(item: .expression(self.makeReturnStatement(for: method)))
  345. return .function(
  346. signature: self.makeStreamingMethodSignature(
  347. for: method,
  348. in: service,
  349. accessModifier: self.accessModifier
  350. ),
  351. body: [response, returnStatement]
  352. )
  353. }
  354. private func makeResponse(
  355. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor
  356. ) -> Declaration {
  357. let serverRequest: Expression
  358. if !method.isInputStreaming {
  359. // Transform the streaming request into a unary request.
  360. serverRequest = Expression.functionCall(
  361. calledExpression: .memberAccess(
  362. MemberAccessDescription(
  363. left: .identifierPattern("ServerRequest"),
  364. right: "Single"
  365. )
  366. ),
  367. arguments: [
  368. FunctionArgumentDescription(label: "stream", expression: .identifierPattern("request"))
  369. ]
  370. )
  371. } else {
  372. serverRequest = Expression.identifierPattern("request")
  373. }
  374. // Call to the corresponding ServiceProtocol method.
  375. let serviceProtocolMethod = Expression.functionCall(
  376. calledExpression: .memberAccess(
  377. MemberAccessDescription(
  378. left: .identifierPattern("self"),
  379. right: method.name.generatedLowerCase
  380. )
  381. ),
  382. arguments: [FunctionArgumentDescription(label: "request", expression: serverRequest)]
  383. )
  384. let responseValue = Expression.unaryKeyword(
  385. kind: .try,
  386. expression: .unaryKeyword(kind: .await, expression: serviceProtocolMethod)
  387. )
  388. return .variable(kind: .let, left: "response", right: responseValue)
  389. }
  390. private func makeReturnStatement(
  391. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor
  392. ) -> Expression {
  393. let returnValue: Expression
  394. // Transforming the unary response into a streaming one.
  395. if !method.isOutputStreaming {
  396. returnValue = .functionCall(
  397. calledExpression: .memberAccess(
  398. MemberAccessDescription(
  399. left: .identifierType(.member(["ServerResponse"])),
  400. right: "Stream"
  401. )
  402. ),
  403. arguments: [
  404. (FunctionArgumentDescription(label: "single", expression: .identifierPattern("response")))
  405. ]
  406. )
  407. } else {
  408. returnValue = .identifierPattern("response")
  409. }
  410. return .unaryKeyword(kind: .return, expression: returnValue)
  411. }
  412. fileprivate enum InputOutputType {
  413. case input
  414. case output
  415. }
  416. /// Generates the fully qualified name of the typealias for the input or output type of a method.
  417. private func methodInputOutputTypealias(
  418. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  419. service: CodeGenerationRequest.ServiceDescriptor,
  420. type: InputOutputType
  421. ) -> String {
  422. var components: String =
  423. "\(service.namespacedTypealiasGeneratedName).Methods.\(method.name.generatedUpperCase)"
  424. switch type {
  425. case .input:
  426. components.append(".Input")
  427. case .output:
  428. components.append(".Output")
  429. }
  430. return components
  431. }
  432. /// Generates the fully qualified name of a method descriptor.
  433. private func methodDescriptorPath(
  434. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  435. service: CodeGenerationRequest.ServiceDescriptor
  436. ) -> String {
  437. return
  438. "\(service.namespacedTypealiasGeneratedName).Methods.\(method.name.generatedUpperCase).descriptor"
  439. }
  440. /// Generates the fully qualified name of the type alias for a service protocol.
  441. internal func protocolNameTypealias(
  442. service: CodeGenerationRequest.ServiceDescriptor,
  443. streaming: Bool
  444. ) -> String {
  445. if streaming {
  446. return "\(service.namespacedTypealiasGeneratedName).StreamingServiceProtocol"
  447. }
  448. return "\(service.namespacedTypealiasGeneratedName).ServiceProtocol"
  449. }
  450. /// Generates the name of a service protocol.
  451. internal func protocolName(
  452. service: CodeGenerationRequest.ServiceDescriptor,
  453. streaming: Bool
  454. ) -> String {
  455. if streaming {
  456. return "\(service.namespacedGeneratedName)StreamingServiceProtocol"
  457. }
  458. return "\(service.namespacedGeneratedName)ServiceProtocol"
  459. }
  460. }