TestServiceProvider.swift 10 KB

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