TestServiceProvider.swift 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. /*
  2. * Copyright 2019, 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 GRPC
  18. import GRPCInteroperabilityTestModels
  19. import NIO
  20. /// A service prodiver for the gRPC interoperaability test suite.
  21. ///
  22. /// See: https://github.com/grpc/grpc/blob/master/doc/interop-test-descriptions.md#server
  23. public class TestServiceProvider: Grpc_Testing_TestServiceProvider {
  24. public init() { }
  25. private static let echoMetadataNotImplemented = GRPCStatus(
  26. code: .unimplemented,
  27. message: "Echoing metadata is not yet supported")
  28. /// Features that this server implements.
  29. ///
  30. /// Some 'features' are methods, whilst others optionally modify the outcome of those methods. The
  31. /// specification is not explicit about where these modifying features should be implemented (i.e.
  32. /// which methods should support them) and they are not listed in the individual metdod
  33. /// descriptions. As such implementation of these modifying features within each method is
  34. /// determined by the features required by each test.
  35. public static var implementedFeatures: Set<ServerFeature> {
  36. return [
  37. .emptyCall,
  38. .unaryCall,
  39. .streamingOutputCall,
  40. .streamingInputCall,
  41. .fullDuplexCall,
  42. .echoStatus
  43. ]
  44. }
  45. /// Server implements `emptyCall` which immediately returns the empty message.
  46. public func emptyCall(
  47. request: Grpc_Testing_Empty,
  48. context: StatusOnlyCallContext
  49. ) -> EventLoopFuture<Grpc_Testing_Empty> {
  50. return context.eventLoop.makeSucceededFuture(Grpc_Testing_Empty())
  51. }
  52. /// Server implements `unaryCall` which immediately returns a `SimpleResponse` with a payload
  53. /// body of size `SimpleRequest.responseSize` bytes and type as appropriate for the
  54. /// `SimpleRequest.responseType`.
  55. ///
  56. /// If the server does not support the `responseType`, then it should fail the RPC with
  57. /// `INVALID_ARGUMENT`.
  58. public func unaryCall(
  59. request: Grpc_Testing_SimpleRequest,
  60. context: StatusOnlyCallContext
  61. ) -> EventLoopFuture<Grpc_Testing_SimpleResponse> {
  62. if request.shouldEchoStatus {
  63. let code = GRPCStatus.Code(rawValue: numericCast(request.responseStatus.code)) ?? .unknown
  64. return context.eventLoop.makeFailedFuture(GRPCStatus(code: code, message: request.responseStatus.message))
  65. }
  66. if context.request.headers.shouldEchoMetadata {
  67. return context.eventLoop.makeFailedFuture(TestServiceProvider.echoMetadataNotImplemented)
  68. }
  69. if case .UNRECOGNIZED = request.responseType {
  70. return context.eventLoop.makeFailedFuture(GRPCStatus(code: .invalidArgument, message: nil))
  71. }
  72. let response = Grpc_Testing_SimpleResponse.with { response in
  73. response.payload = Grpc_Testing_Payload.with { payload in
  74. payload.body = Data(repeating: 0, count: numericCast(request.responseSize))
  75. payload.type = request.responseType
  76. }
  77. }
  78. return context.eventLoop.makeSucceededFuture(response)
  79. }
  80. /// Server gets the default `SimpleRequest` proto as the request. The content of the request is
  81. /// ignored. It returns the `SimpleResponse` proto with the payload set to current timestamp.
  82. /// The timestamp is an integer representing current time with nanosecond resolution. This
  83. /// integer is formated as ASCII decimal in the response. The format is not really important as
  84. /// long as the response payload is different for each request. In addition it adds cache control
  85. /// headers such that the response can be cached by proxies in the response path. Server should
  86. /// be behind a caching proxy for this test to pass. Currently we set the max-age to 60 seconds.
  87. public func cacheableUnaryCall(
  88. request: Grpc_Testing_SimpleRequest,
  89. context: StatusOnlyCallContext
  90. ) -> EventLoopFuture<Grpc_Testing_SimpleResponse> {
  91. let status = GRPCStatus(
  92. code: .unimplemented,
  93. message: "'cacheableUnaryCall' requires control of the initial metadata which isn't supported"
  94. )
  95. return context.eventLoop.makeFailedFuture(status)
  96. }
  97. /// Server implements `streamingOutputCall` by replying, in order, with one
  98. /// `StreamingOutputCallResponse` for each `ResponseParameter`s in `StreamingOutputCallRequest`.
  99. /// Each `StreamingOutputCallResponse` should have a payload body of size `ResponseParameter.size`
  100. /// bytes, as specified by its respective `ResponseParameter`. After sending all responses, it
  101. /// closes with OK.
  102. public func streamingOutputCall(
  103. request: Grpc_Testing_StreamingOutputCallRequest,
  104. context: StreamingResponseCallContext<Grpc_Testing_StreamingOutputCallResponse>
  105. ) -> EventLoopFuture<GRPCStatus> {
  106. var responseQueue = context.eventLoop.makeSucceededFuture(())
  107. for responseParameter in request.responseParameters {
  108. responseQueue = responseQueue.flatMap {
  109. let response = Grpc_Testing_StreamingOutputCallResponse.with { response in
  110. response.payload = Grpc_Testing_Payload.with { payload in
  111. payload.body = Data(repeating: 0, count: numericCast(responseParameter.size))
  112. }
  113. }
  114. return context.sendResponse(response)
  115. }
  116. }
  117. return responseQueue.map { GRPCStatus.ok }
  118. }
  119. /// Server implements `streamingInputCall` which upon half close immediately returns a
  120. /// `StreamingInputCallResponse` where `aggregatedPayloadSize` is the sum of all request payload
  121. /// bodies received.
  122. public func streamingInputCall(
  123. context: UnaryResponseCallContext<Grpc_Testing_StreamingInputCallResponse>
  124. ) -> EventLoopFuture<(StreamEvent<Grpc_Testing_StreamingInputCallRequest>) -> Void> {
  125. var aggregatePayloadSize = 0
  126. return context.eventLoop.makeSucceededFuture({ event in
  127. switch event {
  128. case .message(let request):
  129. aggregatePayloadSize += request.payload.body.count
  130. case .end:
  131. context.responsePromise.succeed(Grpc_Testing_StreamingInputCallResponse.with { response in
  132. response.aggregatedPayloadSize = numericCast(aggregatePayloadSize)
  133. })
  134. }
  135. })
  136. }
  137. /// Server implements `fullDuplexCall` by replying, in order, with one
  138. /// `StreamingOutputCallResponse` for each `ResponseParameter`s in each
  139. /// `StreamingOutputCallRequest`. Each `StreamingOutputCallResponse` should have a payload body
  140. /// of size `ResponseParameter.size` bytes, as specified by its respective `ResponseParameter`s.
  141. /// After receiving half close and sending all responses, it closes with OK.
  142. public func fullDuplexCall(
  143. context: StreamingResponseCallContext<Grpc_Testing_StreamingOutputCallResponse>
  144. ) -> EventLoopFuture<(StreamEvent<Grpc_Testing_StreamingOutputCallRequest>) -> Void> {
  145. // We don't have support for this yet so just fail the call.
  146. if context.request.headers.shouldEchoMetadata {
  147. return context.eventLoop.makeFailedFuture(TestServiceProvider.echoMetadataNotImplemented)
  148. }
  149. var sendQueue = context.eventLoop.makeSucceededFuture(())
  150. func streamHandler(_ event: StreamEvent<Grpc_Testing_StreamingOutputCallRequest>) {
  151. switch event {
  152. case .message(let message):
  153. if message.shouldEchoStatus {
  154. let code = GRPCStatus.Code(rawValue: numericCast(message.responseStatus.code))
  155. let status = GRPCStatus(code: code ?? .unknown, message: message.responseStatus.message)
  156. context.statusPromise.succeed(status)
  157. } else {
  158. for responseParameter in message.responseParameters {
  159. let response = Grpc_Testing_StreamingOutputCallResponse.with { response in
  160. response.payload = .zeros(count: numericCast(responseParameter.size))
  161. }
  162. sendQueue = sendQueue.flatMap {
  163. context.sendResponse(response)
  164. }
  165. }
  166. }
  167. case .end:
  168. sendQueue.map { GRPCStatus.ok }.cascade(to: context.statusPromise)
  169. }
  170. }
  171. return context.eventLoop.makeSucceededFuture(streamHandler(_:))
  172. }
  173. /// This is not implemented as it is not described in the specification.
  174. ///
  175. /// See: https://github.com/grpc/grpc/blob/master/doc/interop-test-descriptions.md
  176. public func halfDuplexCall(
  177. context: StreamingResponseCallContext<Grpc_Testing_StreamingOutputCallResponse>
  178. ) -> EventLoopFuture<(StreamEvent<Grpc_Testing_StreamingOutputCallRequest>) -> Void> {
  179. let status = GRPCStatus(
  180. code: .unimplemented,
  181. message: "'halfDuplexCall' was not described in the specification"
  182. )
  183. return context.eventLoop.makeFailedFuture(status)
  184. }
  185. }