Generator-Server.swift 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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 printServer() {
  21. if self.options.generateServer {
  22. self.printServerProtocol()
  23. self.println()
  24. self.printServerProtocolExtension()
  25. self.println()
  26. self.printServerProtocolAsyncAwait()
  27. self.println()
  28. self.printServerProtocolExtensionAsyncAwait()
  29. self.println()
  30. // Both implementations share definitions for interceptors and metadata.
  31. self.printServerInterceptorFactoryProtocol()
  32. self.println()
  33. self.printServerMetadata()
  34. }
  35. }
  36. private func printServerProtocol() {
  37. let comments = self.service.protoSourceComments()
  38. if !comments.isEmpty {
  39. // Source comments already have the leading '///'
  40. self.println(comments, newline: false)
  41. self.println("///")
  42. }
  43. println("/// To build a server, implement a class that conforms to this protocol.")
  44. println("\(access) protocol \(providerName): CallHandlerProvider {")
  45. self.withIndentation {
  46. println("var interceptors: \(self.serverInterceptorProtocolName)? { get }")
  47. for method in service.methods {
  48. self.method = method
  49. self.println()
  50. switch streamingType(method) {
  51. case .unary:
  52. println(self.method.protoSourceComments(), newline: false)
  53. println(
  54. "func \(methodFunctionName)(request: \(methodInputName), context: StatusOnlyCallContext) -> EventLoopFuture<\(methodOutputName)>"
  55. )
  56. case .serverStreaming:
  57. println(self.method.protoSourceComments(), newline: false)
  58. println(
  59. "func \(methodFunctionName)(request: \(methodInputName), context: StreamingResponseCallContext<\(methodOutputName)>) -> EventLoopFuture<GRPCStatus>"
  60. )
  61. case .clientStreaming:
  62. println(self.method.protoSourceComments(), newline: false)
  63. println(
  64. "func \(methodFunctionName)(context: UnaryResponseCallContext<\(methodOutputName)>) -> EventLoopFuture<(StreamEvent<\(methodInputName)>) -> Void>"
  65. )
  66. case .bidirectionalStreaming:
  67. println(self.method.protoSourceComments(), newline: false)
  68. println(
  69. "func \(methodFunctionName)(context: StreamingResponseCallContext<\(methodOutputName)>) -> EventLoopFuture<(StreamEvent<\(methodInputName)>) -> Void>"
  70. )
  71. }
  72. }
  73. }
  74. println("}")
  75. }
  76. private func printServerProtocolExtension() {
  77. self.println("extension \(self.providerName) {")
  78. self.withIndentation {
  79. self.withIndentation("\(self.access) var serviceName: Substring", braces: .curly) {
  80. /// This API returns a Substring (hence the '[...]')
  81. self.println("return \(self.serviceServerMetadata).serviceDescriptor.fullName[...]")
  82. }
  83. self.println()
  84. self.println(
  85. "/// Determines, calls and returns the appropriate request handler, depending on the request's method."
  86. )
  87. self.println("/// Returns nil for methods not handled by this service.")
  88. self.printFunction(
  89. name: "handle",
  90. arguments: [
  91. "method name: Substring",
  92. "context: CallHandlerContext",
  93. ],
  94. returnType: "GRPCServerHandlerProtocol?",
  95. access: self.access
  96. ) {
  97. self.println("switch name {")
  98. for method in self.service.methods {
  99. self.method = method
  100. self.println("case \"\(method.name)\":")
  101. self.withIndentation {
  102. // Get the factory name.
  103. let callHandlerType: String
  104. switch streamingType(method) {
  105. case .unary:
  106. callHandlerType = "UnaryServerHandler"
  107. case .serverStreaming:
  108. callHandlerType = "ServerStreamingServerHandler"
  109. case .clientStreaming:
  110. callHandlerType = "ClientStreamingServerHandler"
  111. case .bidirectionalStreaming:
  112. callHandlerType = "BidirectionalStreamingServerHandler"
  113. }
  114. self.println("return \(callHandlerType)(")
  115. self.withIndentation {
  116. self.println("context: context,")
  117. self.println("requestDeserializer: ProtobufDeserializer<\(self.methodInputName)>(),")
  118. self.println("responseSerializer: ProtobufSerializer<\(self.methodOutputName)>(),")
  119. self.println(
  120. "interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? [],"
  121. )
  122. switch streamingType(method) {
  123. case .unary, .serverStreaming:
  124. self.println("userFunction: self.\(self.methodFunctionName)(request:context:)")
  125. case .clientStreaming, .bidirectionalStreaming:
  126. self.println("observerFactory: self.\(self.methodFunctionName)(context:)")
  127. }
  128. }
  129. self.println(")")
  130. }
  131. self.println()
  132. }
  133. // Default case.
  134. self.println("default:")
  135. self.withIndentation {
  136. self.println("return nil")
  137. }
  138. self.println("}")
  139. }
  140. }
  141. self.println("}")
  142. }
  143. private func printServerInterceptorFactoryProtocol() {
  144. self.println("\(self.access) protocol \(self.serverInterceptorProtocolName): Sendable {")
  145. self.withIndentation {
  146. // Method specific interceptors.
  147. for method in service.methods {
  148. self.println()
  149. self.method = method
  150. self.println(
  151. "/// - Returns: Interceptors to use when handling '\(self.methodFunctionName)'."
  152. )
  153. self.println("/// Defaults to calling `self.makeInterceptors()`.")
  154. // Skip the access, we're defining a protocol.
  155. self.printMethodInterceptorFactory(access: nil)
  156. }
  157. }
  158. self.println("}")
  159. }
  160. private func printMethodInterceptorFactory(
  161. access: String?,
  162. bodyBuilder: (() -> Void)? = nil
  163. ) {
  164. self.printFunction(
  165. name: self.methodInterceptorFactoryName,
  166. arguments: [],
  167. returnType: "[ServerInterceptor<\(self.methodInputName), \(self.methodOutputName)>]",
  168. access: access,
  169. bodyBuilder: bodyBuilder
  170. )
  171. }
  172. func printServerInterceptorFactoryProtocolExtension() {
  173. self.println("extension \(self.serverInterceptorProtocolName) {")
  174. self.withIndentation {
  175. // Default interceptor factory.
  176. self.printFunction(
  177. name: "makeInterceptors<Request: SwiftProtobuf.Message, Response: SwiftProtobuf.Message>",
  178. arguments: [],
  179. returnType: "[ServerInterceptor<Request, Response>]",
  180. access: self.access
  181. ) {
  182. self.println("return []")
  183. }
  184. for method in self.service.methods {
  185. self.println()
  186. self.method = method
  187. self.printMethodInterceptorFactory(access: self.access) {
  188. self.println("return self.makeInterceptors()")
  189. }
  190. }
  191. }
  192. self.println("}")
  193. }
  194. }