InProcessTransportTests.swift 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. /*
  2. * Copyright 2024-2025, 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.runConnections()
  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 runConnections() 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: PeerInfoDeserializer(),
  70. options: .defaults
  71. ) {
  72. try $0.message
  73. }
  74. #expect(peerInfo.local == peerInfo.remote)
  75. }
  76. }
  77. }
  78. private struct TestService: RegistrableRPCService {
  79. func cancellation(
  80. request: ServerRequest<String>,
  81. context: ServerContext
  82. ) async throws -> StreamingServerResponse<String> {
  83. switch request.message {
  84. case "await-cancelled":
  85. return StreamingServerResponse { body in
  86. try await context.cancellation.cancelled
  87. try await body.write("isCancelled=\(context.cancellation.isCancelled)")
  88. return [:]
  89. }
  90. case "with-cancellation-handler":
  91. let signal = AsyncStream.makeStream(of: Void.self)
  92. return StreamingServerResponse { body in
  93. try await withRPCCancellationHandler {
  94. for await _ in signal.stream {}
  95. try await body.write("isCancelled=\(context.cancellation.isCancelled)")
  96. return [:]
  97. } onCancelRPC: {
  98. signal.continuation.finish()
  99. }
  100. }
  101. default:
  102. throw RPCError(code: .invalidArgument, message: "Invalid argument '\(request.message)'")
  103. }
  104. }
  105. func peerInfo(
  106. request: ServerRequest<Void>,
  107. context: ServerContext
  108. ) async throws -> ServerResponse<PeerInfo> {
  109. let peerInfo = PeerInfo(local: context.localPeer, remote: context.remotePeer)
  110. return ServerResponse(message: peerInfo)
  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: PeerInfoSerializer(),
  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 PeerInfo: Codable {
  146. var local: String
  147. var remote: String
  148. }
  149. private struct PeerInfoSerializer: MessageSerializer {
  150. func serialize(_ message: PeerInfo) throws -> [UInt8] {
  151. Array("\(message.local) \(message.remote)".utf8)
  152. }
  153. }
  154. private struct PeerInfoDeserializer: MessageDeserializer {
  155. func deserialize(_ serializedMessageBytes: [UInt8]) throws -> PeerInfo {
  156. let stringPeerInfo = String(decoding: serializedMessageBytes, as: UTF8.self)
  157. let peerInfoComponents = stringPeerInfo.split(separator: " ")
  158. return PeerInfo(local: String(peerInfoComponents[0]), remote: String(peerInfoComponents[1]))
  159. }
  160. }
  161. private struct UTF8Serializer: MessageSerializer {
  162. func serialize(_ message: String) throws -> [UInt8] {
  163. Array(message.utf8)
  164. }
  165. }
  166. private struct UTF8Deserializer: MessageDeserializer {
  167. func deserialize(_ serializedMessageBytes: [UInt8]) throws -> String {
  168. String(decoding: serializedMessageBytes, as: UTF8.self)
  169. }
  170. }
  171. private struct VoidSerializer: MessageSerializer {
  172. func serialize(_ message: Void) throws -> [UInt8] {
  173. []
  174. }
  175. }
  176. private struct VoidDeserializer: MessageDeserializer {
  177. func deserialize(_ serializedMessageBytes: [UInt8]) throws {
  178. }
  179. }