ServerCodeTranslator.swift 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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" with input type "Input" and output type "Output", the ``ServerCodeTranslator`` will create
  21. /// a representation for the following generated code:
  22. ///
  23. /// ```swift
  24. /// @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  25. /// public protocol Foo_BarStreamingServiceProtocol: GRPCCore.RegistrableRPCService {
  26. /// func baz(
  27. /// request: GRPCCore.StreamingServerRequest<Foo_Bar_Input>
  28. /// ) async throws -> GRPCCore.StreamingServerResponse<Foo_Bar_Output>
  29. /// }
  30. /// // Conformance to `GRPCCore.RegistrableRPCService`.
  31. /// @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  32. /// extension Foo_Bar.StreamingServiceProtocol {
  33. /// public func registerMethods(with router: inout GRPCCore.RPCRouter) {
  34. /// router.registerHandler(
  35. /// forMethod: Foo_Bar.Method.baz.descriptor,
  36. /// deserializer: GRPCProtobuf.ProtobufDeserializer<Foo_Bar_Input>(),
  37. /// serializer: GRPCProtobuf.ProtobufSerializer<Foo_Bar_Output>(),
  38. /// handler: { request in try await self.baz(request: request) }
  39. /// )
  40. /// }
  41. /// }
  42. /// @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  43. /// public protocol Foo_BarServiceProtocol: Foo_Bar.StreamingServiceProtocol {
  44. /// func baz(
  45. /// request: GRPCCore.ServerRequest<Foo_Bar_Input>
  46. /// ) async throws -> GRPCCore.ServerResponse<Foo_Bar_Output>
  47. /// }
  48. /// // Partial conformance to `Foo_BarStreamingServiceProtocol`.
  49. /// @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  50. /// extension Foo_Bar.ServiceProtocol {
  51. /// public func baz(
  52. /// request: GRPCCore.StreamingServerRequest<Foo_Bar_Input>
  53. /// ) async throws -> GRPCCore.StreamingServerResponse<Foo_Bar_Output> {
  54. /// let response = try await self.baz(request: GRPCCore.ServerRequest(stream: request))
  55. /// return GRPCCore.StreamingServerResponse(single: response)
  56. /// }
  57. /// }
  58. ///```
  59. struct ServerCodeTranslator {
  60. init() {}
  61. func translate(
  62. accessModifier: AccessModifier,
  63. service: ServiceDescriptor,
  64. serializer: (String) -> String,
  65. deserializer: (String) -> String
  66. ) -> [CodeBlock] {
  67. var blocks = [CodeBlock]()
  68. let `extension` = ExtensionDescription(
  69. onType: service.name.typeName,
  70. declarations: [
  71. // protocol StreamingServiceProtocol { ... }
  72. .commentable(
  73. .preFormatted(
  74. Docs.suffix(
  75. self.streamingServiceDocs(serviceName: service.name.identifyingName),
  76. withDocs: service.documentation
  77. )
  78. ),
  79. .protocol(
  80. .streamingService(
  81. accessLevel: accessModifier,
  82. name: "StreamingServiceProtocol",
  83. methods: service.methods
  84. )
  85. )
  86. ),
  87. // protocol ServiceProtocol { ... }
  88. .commentable(
  89. .preFormatted(
  90. Docs.suffix(
  91. self.serviceDocs(serviceName: service.name.identifyingName),
  92. withDocs: service.documentation
  93. )
  94. ),
  95. .protocol(
  96. .service(
  97. accessLevel: accessModifier,
  98. name: "ServiceProtocol",
  99. streamingProtocol: "\(service.name.typeName).StreamingServiceProtocol",
  100. methods: service.methods
  101. )
  102. )
  103. ),
  104. // protocol SimpleServiceProtocol { ... }
  105. .commentable(
  106. .preFormatted(
  107. Docs.suffix(
  108. self.simpleServiceDocs(serviceName: service.name.identifyingName),
  109. withDocs: service.documentation
  110. )
  111. ),
  112. .protocol(
  113. .simpleServiceProtocol(
  114. accessModifier: accessModifier,
  115. name: "SimpleServiceProtocol",
  116. serviceProtocol: "\(service.name.typeName).ServiceProtocol",
  117. methods: service.methods
  118. )
  119. )
  120. ),
  121. ]
  122. )
  123. blocks.append(.declaration(.extension(`extension`)))
  124. // extension <Service>.StreamingServiceProtocol> { ... }
  125. let registerExtension: ExtensionDescription = .registrableRPCServiceDefaultImplementation(
  126. accessLevel: accessModifier,
  127. on: "\(service.name.typeName).StreamingServiceProtocol",
  128. serviceNamespace: service.name.typeName,
  129. methods: service.methods,
  130. serializer: serializer,
  131. deserializer: deserializer
  132. )
  133. blocks.append(
  134. CodeBlock(
  135. comment: .inline("Default implementation of 'registerMethods(with:)'."),
  136. item: .declaration(.extension(registerExtension))
  137. )
  138. )
  139. // extension <Service>_ServiceProtocol { ... }
  140. let streamingServiceDefaultImplExtension: ExtensionDescription =
  141. .streamingServiceProtocolDefaultImplementation(
  142. accessModifier: accessModifier,
  143. on: "\(service.name.typeName).ServiceProtocol",
  144. methods: service.methods
  145. )
  146. blocks.append(
  147. CodeBlock(
  148. comment: .inline(
  149. "Default implementation of streaming methods from 'StreamingServiceProtocol'."
  150. ),
  151. item: .declaration(.extension(streamingServiceDefaultImplExtension))
  152. )
  153. )
  154. // extension <Service>_SimpleServiceProtocol { ... }
  155. let serviceDefaultImplExtension: ExtensionDescription = .serviceProtocolDefaultImplementation(
  156. accessModifier: accessModifier,
  157. on: "\(service.name.typeName).SimpleServiceProtocol",
  158. methods: service.methods
  159. )
  160. blocks.append(
  161. CodeBlock(
  162. comment: .inline("Default implementation of methods from 'ServiceProtocol'."),
  163. item: .declaration(.extension(serviceDefaultImplExtension))
  164. )
  165. )
  166. return blocks
  167. }
  168. private func streamingServiceDocs(serviceName: String) -> String {
  169. return """
  170. /// Streaming variant of the service protocol for the "\(serviceName)" service.
  171. ///
  172. /// This protocol is the lowest-level of the service protocols generated for this service
  173. /// giving you the most flexibility over the implementation of your service. This comes at
  174. /// the cost of more verbose and less strict APIs. Each RPC requires you to implement it in
  175. /// terms of a request stream and response stream. Where only a single request or response
  176. /// message is expected, you are responsible for enforcing this invariant is maintained.
  177. ///
  178. /// Where possible, prefer using the stricter, less-verbose ``ServiceProtocol``
  179. /// or ``SimpleServiceProtocol`` instead.
  180. """
  181. }
  182. private func serviceDocs(serviceName: String) -> String {
  183. return """
  184. /// Service protocol for the "\(serviceName)" service.
  185. ///
  186. /// This protocol is higher level than ``StreamingServiceProtocol`` but lower level than
  187. /// the ``SimpleServiceProtocol``, it provides access to request and response metadata and
  188. /// trailing response metadata. If you don't need these then consider using
  189. /// the ``SimpleServiceProtocol``. If you need fine grained control over your RPCs then
  190. /// use ``StreamingServiceProtocol``.
  191. """
  192. }
  193. private func simpleServiceDocs(serviceName: String) -> String {
  194. return """
  195. /// Simple service protocol for the "\(serviceName)" service.
  196. ///
  197. /// This is the highest level protocol for the service. The API is the easiest to use but
  198. /// doesn't provide access to request or response metadata. If you need access to these
  199. /// then use ``ServiceProtocol`` instead.
  200. """
  201. }
  202. }