Generator-Server.swift 7.5 KB

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