InProcessTransportTests.swift 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. @Test("Peer info")
  59. func peerInfo() async throws {
  60. try await self.withTestServerAndClient { server, client in
  61. defer {
  62. client.beginGracefulShutdown()
  63. server.beginGracefulShutdown()
  64. }
  65. let peerInfo = try await client.unary(
  66. request: ClientRequest(message: ()),
  67. descriptor: .peerInfo,
  68. serializer: VoidSerializer(),
  69. deserializer: UTF8Deserializer(),
  70. options: .defaults
  71. ) {
  72. try $0.message
  73. }
  74. let match = peerInfo.wholeMatch(of: /in-process:\d+/)
  75. #expect(match != nil)
  76. }
  77. }
  78. }
  79. private struct TestService: RegistrableRPCService {
  80. func cancellation(
  81. request: ServerRequest<String>,
  82. context: ServerContext
  83. ) async throws -> StreamingServerResponse<String> {
  84. switch request.message {
  85. case "await-cancelled":
  86. return StreamingServerResponse { body in
  87. try await context.cancellation.cancelled
  88. try await body.write("isCancelled=\(context.cancellation.isCancelled)")
  89. return [:]
  90. }
  91. case "with-cancellation-handler":
  92. let signal = AsyncStream.makeStream(of: Void.self)
  93. return StreamingServerResponse { body in
  94. try await withRPCCancellationHandler {
  95. for await _ in signal.stream {}
  96. try await body.write("isCancelled=\(context.cancellation.isCancelled)")
  97. return [:]
  98. } onCancelRPC: {
  99. signal.continuation.finish()
  100. }
  101. }
  102. default:
  103. throw RPCError(code: .invalidArgument, message: "Invalid argument '\(request.message)'")
  104. }
  105. }
  106. func peerInfo(
  107. request: ServerRequest<Void>,
  108. context: ServerContext
  109. ) async throws -> ServerResponse<String> {
  110. return ServerResponse(message: context.peer)
  111. }
  112. func registerMethods(with router: inout RPCRouter) {
  113. router.registerHandler(
  114. forMethod: .testCancellation,
  115. deserializer: UTF8Deserializer(),
  116. serializer: UTF8Serializer(),
  117. handler: {
  118. try await self.cancellation(request: ServerRequest(stream: $0), context: $1)
  119. }
  120. )
  121. router.registerHandler(
  122. forMethod: .peerInfo,
  123. deserializer: VoidDeserializer(),
  124. serializer: UTF8Serializer(),
  125. handler: {
  126. let response = try await self.peerInfo(
  127. request: ServerRequest<Void>(stream: $0),
  128. context: $1
  129. )
  130. return StreamingServerResponse(single: response)
  131. }
  132. )
  133. }
  134. }
  135. extension MethodDescriptor {
  136. fileprivate static let testCancellation = Self(
  137. fullyQualifiedService: "test",
  138. method: "cancellation"
  139. )
  140. fileprivate static let peerInfo = Self(
  141. fullyQualifiedService: "test",
  142. method: "peerInfo"
  143. )
  144. }
  145. private struct UTF8Serializer: MessageSerializer {
  146. func serialize(_ message: String) throws -> [UInt8] {
  147. Array(message.utf8)
  148. }
  149. }
  150. private struct UTF8Deserializer: MessageDeserializer {
  151. func deserialize(_ serializedMessageBytes: [UInt8]) throws -> String {
  152. String(decoding: serializedMessageBytes, as: UTF8.self)
  153. }
  154. }
  155. private struct VoidSerializer: MessageSerializer {
  156. func serialize(_ message: Void) throws -> [UInt8] {
  157. []
  158. }
  159. }
  160. private struct VoidDeserializer: MessageDeserializer {
  161. func deserialize(_ serializedMessageBytes: [UInt8]) throws {
  162. }
  163. }