InProcessTransportTests.swift 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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: (
  24. GRPCServer<InProcessTransport.Server>,
  25. GRPCClient<InProcessTransport.Client>
  26. ) async throws -> Void
  27. ) async throws {
  28. try await withThrowingDiscardingTaskGroup { group in
  29. let inProcess = InProcessTransport()
  30. let server = GRPCServer(transport: inProcess.server, services: [TestService()])
  31. group.addTask {
  32. try await server.serve()
  33. }
  34. let client = GRPCClient(transport: inProcess.client)
  35. group.addTask {
  36. try await client.runConnections()
  37. }
  38. try await execute(server, client)
  39. }
  40. }
  41. @Test("RPC cancelled by graceful shutdown", arguments: Self.cancellationModes)
  42. func cancelledByGracefulShutdown(mode: String) async throws {
  43. try await self.withTestServerAndClient { server, client in
  44. try await client.serverStreaming(
  45. request: ClientRequest(message: mode),
  46. descriptor: .testCancellation,
  47. serializer: UTF8Serializer(),
  48. deserializer: UTF8Deserializer(),
  49. options: .defaults
  50. ) { response in
  51. // Got initial metadata, begin shutdown to cancel the RPC.
  52. server.beginGracefulShutdown()
  53. // Now wait for the response.
  54. let messages = try await response.messages.reduce(into: []) { $0.append($1) }
  55. #expect(messages == ["isCancelled=true"])
  56. }
  57. // Finally, shutdown the client so its runConnections() method returns.
  58. client.beginGracefulShutdown()
  59. }
  60. }
  61. @Test("Peer info")
  62. func peerInfo() async throws {
  63. try await self.withTestServerAndClient { server, client in
  64. defer {
  65. client.beginGracefulShutdown()
  66. server.beginGracefulShutdown()
  67. }
  68. let peerInfo = try await client.unary(
  69. request: ClientRequest(message: ()),
  70. descriptor: .peerInfo,
  71. serializer: VoidSerializer(),
  72. deserializer: PeerInfoDeserializer(),
  73. options: .defaults
  74. ) {
  75. try $0.message
  76. }
  77. #expect(peerInfo.local == peerInfo.remote)
  78. }
  79. }
  80. }
  81. private struct TestService: RegistrableRPCService {
  82. func cancellation(
  83. request: ServerRequest<String>,
  84. context: ServerContext
  85. ) async throws -> StreamingServerResponse<String> {
  86. switch request.message {
  87. case "await-cancelled":
  88. return StreamingServerResponse { body in
  89. try await context.cancellation.cancelled
  90. try await body.write("isCancelled=\(context.cancellation.isCancelled)")
  91. return [:]
  92. }
  93. case "with-cancellation-handler":
  94. let signal = AsyncStream.makeStream(of: Void.self)
  95. return StreamingServerResponse { body in
  96. try await withRPCCancellationHandler {
  97. for await _ in signal.stream {}
  98. try await body.write("isCancelled=\(context.cancellation.isCancelled)")
  99. return [:]
  100. } onCancelRPC: {
  101. signal.continuation.finish()
  102. }
  103. }
  104. default:
  105. throw RPCError(code: .invalidArgument, message: "Invalid argument '\(request.message)'")
  106. }
  107. }
  108. func peerInfo(
  109. request: ServerRequest<Void>,
  110. context: ServerContext
  111. ) async throws -> ServerResponse<PeerInfo> {
  112. let peerInfo = PeerInfo(local: context.localPeer, remote: context.remotePeer)
  113. return ServerResponse(message: peerInfo)
  114. }
  115. func registerMethods<Transport: ServerTransport>(with router: inout RPCRouter<Transport>) {
  116. router.registerHandler(
  117. forMethod: .testCancellation,
  118. deserializer: UTF8Deserializer(),
  119. serializer: UTF8Serializer(),
  120. handler: {
  121. try await self.cancellation(request: ServerRequest(stream: $0), context: $1)
  122. }
  123. )
  124. router.registerHandler(
  125. forMethod: .peerInfo,
  126. deserializer: VoidDeserializer(),
  127. serializer: PeerInfoSerializer(),
  128. handler: {
  129. let response = try await self.peerInfo(
  130. request: ServerRequest<Void>(stream: $0),
  131. context: $1
  132. )
  133. return StreamingServerResponse(single: response)
  134. }
  135. )
  136. }
  137. }
  138. extension MethodDescriptor {
  139. fileprivate static let testCancellation = Self(
  140. fullyQualifiedService: "test",
  141. method: "cancellation"
  142. )
  143. fileprivate static let peerInfo = Self(
  144. fullyQualifiedService: "test",
  145. method: "peerInfo"
  146. )
  147. }
  148. private struct PeerInfo: Codable {
  149. var local: String
  150. var remote: String
  151. }
  152. private struct PeerInfoSerializer: MessageSerializer {
  153. func serialize<Bytes: GRPCContiguousBytes>(_ message: PeerInfo) throws -> Bytes {
  154. Bytes("\(message.local) \(message.remote)".utf8)
  155. }
  156. }
  157. private struct PeerInfoDeserializer: MessageDeserializer {
  158. func deserialize<Bytes: GRPCContiguousBytes>(_ serializedMessageBytes: Bytes) throws -> PeerInfo {
  159. let stringPeerInfo = serializedMessageBytes.withUnsafeBytes {
  160. String(decoding: $0, as: UTF8.self)
  161. }
  162. let peerInfoComponents = stringPeerInfo.split(separator: " ")
  163. return PeerInfo(local: String(peerInfoComponents[0]), remote: String(peerInfoComponents[1]))
  164. }
  165. }
  166. private struct UTF8Serializer: MessageSerializer {
  167. func serialize<Bytes: GRPCContiguousBytes>(_ message: String) throws -> Bytes {
  168. Bytes(message.utf8)
  169. }
  170. }
  171. private struct UTF8Deserializer: MessageDeserializer {
  172. func deserialize<Bytes: GRPCContiguousBytes>(_ serializedMessageBytes: Bytes) throws -> String {
  173. serializedMessageBytes.withUnsafeBytes {
  174. String(decoding: $0, as: UTF8.self)
  175. }
  176. }
  177. }
  178. private struct VoidSerializer: MessageSerializer {
  179. func serialize<Bytes: GRPCContiguousBytes>(_ message: Void) throws -> Bytes {
  180. Bytes(repeating: 0, count: 0)
  181. }
  182. }
  183. private struct VoidDeserializer: MessageDeserializer {
  184. func deserialize<Bytes: GRPCContiguousBytes>(_ serializedMessageBytes: Bytes) throws {
  185. }
  186. }