Generator-Server.swift 7.6 KB

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