Generator-Server.swift 6.9 KB

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