TestServiceProvider.swift 10 KB

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