TestServiceAsyncProvider.swift 9.3 KB

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