InProcessTransportTests.swift 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. /*
  2. * Copyright 2024, 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 GRPCCore
  17. import GRPCInProcessTransport
  18. import Testing
  19. @Suite("InProcess transport")
  20. struct InProcessTransportTests {
  21. private static let cancellationModes = ["await-cancelled", "with-cancellation-handler"]
  22. private func withTestServerAndClient(
  23. execute: (GRPCServer, GRPCClient) async throws -> Void
  24. ) async throws {
  25. try await withThrowingDiscardingTaskGroup { group in
  26. let inProcess = InProcessTransport()
  27. let server = GRPCServer(transport: inProcess.server, services: [TestService()])
  28. group.addTask {
  29. try await server.serve()
  30. }
  31. let client = GRPCClient(transport: inProcess.client)
  32. group.addTask {
  33. try await client.run()
  34. }
  35. try await execute(server, client)
  36. }
  37. }
  38. @Test("RPC cancelled by graceful shutdown", arguments: Self.cancellationModes)
  39. func cancelledByGracefulShutdown(mode: String) async throws {
  40. try await self.withTestServerAndClient { server, client in
  41. try await client.serverStreaming(
  42. request: ClientRequest(message: mode),
  43. descriptor: .testCancellation,
  44. serializer: UTF8Serializer(),
  45. deserializer: UTF8Deserializer(),
  46. options: .defaults
  47. ) { response in
  48. // Got initial metadata, begin shutdown to cancel the RPC.
  49. server.beginGracefulShutdown()
  50. // Now wait for the response.
  51. let messages = try await response.messages.reduce(into: []) { $0.append($1) }
  52. #expect(messages == ["isCancelled=true"])
  53. }
  54. // Finally, shutdown the client so its run() method returns.
  55. client.beginGracefulShutdown()
  56. }
  57. }
  58. }
  59. private struct TestService: RegistrableRPCService {
  60. func cancellation(
  61. request: ServerRequest<String>,
  62. context: ServerContext
  63. ) async throws -> StreamingServerResponse<String> {
  64. switch request.message {
  65. case "await-cancelled":
  66. return StreamingServerResponse { body in
  67. try await context.cancellation.cancelled
  68. try await body.write("isCancelled=\(context.cancellation.isCancelled)")
  69. return [:]
  70. }
  71. case "with-cancellation-handler":
  72. let signal = AsyncStream.makeStream(of: Void.self)
  73. return StreamingServerResponse { body in
  74. try await withRPCCancellationHandler {
  75. for await _ in signal.stream {}
  76. try await body.write("isCancelled=\(context.cancellation.isCancelled)")
  77. return [:]
  78. } onCancelRPC: {
  79. signal.continuation.finish()
  80. }
  81. }
  82. default:
  83. throw RPCError(code: .invalidArgument, message: "Invalid argument '\(request.message)'")
  84. }
  85. }
  86. func registerMethods(with router: inout RPCRouter) {
  87. router.registerHandler(
  88. forMethod: .testCancellation,
  89. deserializer: UTF8Deserializer(),
  90. serializer: UTF8Serializer(),
  91. handler: {
  92. try await self.cancellation(request: ServerRequest(stream: $0), context: $1)
  93. }
  94. )
  95. }
  96. }
  97. extension MethodDescriptor {
  98. fileprivate static let testCancellation = Self(service: "test", method: "cancellation")
  99. }
  100. private struct UTF8Serializer: MessageSerializer {
  101. func serialize(_ message: String) throws -> [UInt8] {
  102. Array(message.utf8)
  103. }
  104. }
  105. private struct UTF8Deserializer: MessageDeserializer {
  106. func deserialize(_ serializedMessageBytes: [UInt8]) throws -> String {
  107. String(decoding: serializedMessageBytes, as: UTF8.self)
  108. }
  109. }