Generator-Server.swift 7.5 KB

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