GRPCServerTests.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. /*
  2. * Copyright 2023, 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 XCTest
  19. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  20. final class GRPCServerTests: XCTestCase {
  21. func withInProcessClientConnectedToServer(
  22. services: [any RegistrableRPCService],
  23. interceptors: [any ServerInterceptor] = [],
  24. _ body: (InProcessTransport.Client, GRPCServer) async throws -> Void
  25. ) async throws {
  26. let inProcess = InProcessTransport()
  27. let server = GRPCServer(
  28. transport: inProcess.server,
  29. services: services,
  30. interceptors: interceptors
  31. )
  32. try await withThrowingTaskGroup(of: Void.self) { group in
  33. group.addTask {
  34. try await server.serve()
  35. }
  36. group.addTask {
  37. try await inProcess.client.connect()
  38. }
  39. try await body(inProcess.client, server)
  40. inProcess.client.beginGracefulShutdown()
  41. server.beginGracefulShutdown()
  42. }
  43. }
  44. func testServerHandlesUnary() async throws {
  45. try await self.withInProcessClientConnectedToServer(services: [BinaryEcho()]) { client, _ in
  46. try await client.withStream(
  47. descriptor: BinaryEcho.Methods.get,
  48. options: .defaults
  49. ) { stream in
  50. try await stream.outbound.write(.metadata([:]))
  51. try await stream.outbound.write(.message([3, 1, 4, 1, 5]))
  52. await stream.outbound.finish()
  53. var responseParts = stream.inbound.makeAsyncIterator()
  54. let metadata = try await responseParts.next()
  55. XCTAssertMetadata(metadata)
  56. let message = try await responseParts.next()
  57. XCTAssertMessage(message) {
  58. XCTAssertEqual($0, [3, 1, 4, 1, 5])
  59. }
  60. let status = try await responseParts.next()
  61. XCTAssertStatus(status) { status, _ in
  62. XCTAssertEqual(status.code, .ok)
  63. }
  64. }
  65. }
  66. }
  67. func testServerHandlesClientStreaming() async throws {
  68. try await self.withInProcessClientConnectedToServer(services: [BinaryEcho()]) { client, _ in
  69. try await client.withStream(
  70. descriptor: BinaryEcho.Methods.collect,
  71. options: .defaults
  72. ) { stream in
  73. try await stream.outbound.write(.metadata([:]))
  74. try await stream.outbound.write(.message([3]))
  75. try await stream.outbound.write(.message([1]))
  76. try await stream.outbound.write(.message([4]))
  77. try await stream.outbound.write(.message([1]))
  78. try await stream.outbound.write(.message([5]))
  79. await stream.outbound.finish()
  80. var responseParts = stream.inbound.makeAsyncIterator()
  81. let metadata = try await responseParts.next()
  82. XCTAssertMetadata(metadata)
  83. let message = try await responseParts.next()
  84. XCTAssertMessage(message) {
  85. XCTAssertEqual($0, [3, 1, 4, 1, 5])
  86. }
  87. let status = try await responseParts.next()
  88. XCTAssertStatus(status) { status, _ in
  89. XCTAssertEqual(status.code, .ok)
  90. }
  91. }
  92. }
  93. }
  94. func testServerHandlesServerStreaming() async throws {
  95. try await self.withInProcessClientConnectedToServer(services: [BinaryEcho()]) { client, _ in
  96. try await client.withStream(
  97. descriptor: BinaryEcho.Methods.expand,
  98. options: .defaults
  99. ) { stream in
  100. try await stream.outbound.write(.metadata([:]))
  101. try await stream.outbound.write(.message([3, 1, 4, 1, 5]))
  102. await stream.outbound.finish()
  103. var responseParts = stream.inbound.makeAsyncIterator()
  104. let metadata = try await responseParts.next()
  105. XCTAssertMetadata(metadata)
  106. for byte in [3, 1, 4, 1, 5] as [UInt8] {
  107. let message = try await responseParts.next()
  108. XCTAssertMessage(message) {
  109. XCTAssertEqual($0, [byte])
  110. }
  111. }
  112. let status = try await responseParts.next()
  113. XCTAssertStatus(status) { status, _ in
  114. XCTAssertEqual(status.code, .ok)
  115. }
  116. }
  117. }
  118. }
  119. func testServerHandlesBidirectionalStreaming() async throws {
  120. try await self.withInProcessClientConnectedToServer(services: [BinaryEcho()]) { client, _ in
  121. try await client.withStream(
  122. descriptor: BinaryEcho.Methods.update,
  123. options: .defaults
  124. ) { stream in
  125. try await stream.outbound.write(.metadata([:]))
  126. for byte in [3, 1, 4, 1, 5] as [UInt8] {
  127. try await stream.outbound.write(.message([byte]))
  128. }
  129. await stream.outbound.finish()
  130. var responseParts = stream.inbound.makeAsyncIterator()
  131. let metadata = try await responseParts.next()
  132. XCTAssertMetadata(metadata)
  133. for byte in [3, 1, 4, 1, 5] as [UInt8] {
  134. let message = try await responseParts.next()
  135. XCTAssertMessage(message) {
  136. XCTAssertEqual($0, [byte])
  137. }
  138. }
  139. let status = try await responseParts.next()
  140. XCTAssertStatus(status) { status, _ in
  141. XCTAssertEqual(status.code, .ok)
  142. }
  143. }
  144. }
  145. }
  146. func testUnimplementedMethod() async throws {
  147. try await self.withInProcessClientConnectedToServer(services: [BinaryEcho()]) { client, _ in
  148. try await client.withStream(
  149. descriptor: MethodDescriptor(service: "not", method: "implemented"),
  150. options: .defaults
  151. ) { stream in
  152. try await stream.outbound.write(.metadata([:]))
  153. await stream.outbound.finish()
  154. var responseParts = stream.inbound.makeAsyncIterator()
  155. let status = try await responseParts.next()
  156. XCTAssertStatus(status) { status, _ in
  157. XCTAssertEqual(status.code, .unimplemented)
  158. }
  159. }
  160. }
  161. }
  162. func testMultipleConcurrentRequests() async throws {
  163. try await self.withInProcessClientConnectedToServer(services: [BinaryEcho()]) { client, _ in
  164. await withThrowingTaskGroup(of: Void.self) { group in
  165. for i in UInt8.min ..< UInt8.max {
  166. group.addTask {
  167. try await client.withStream(
  168. descriptor: BinaryEcho.Methods.get,
  169. options: .defaults
  170. ) { stream in
  171. try await stream.outbound.write(.metadata([:]))
  172. try await stream.outbound.write(.message([i]))
  173. await stream.outbound.finish()
  174. var responseParts = stream.inbound.makeAsyncIterator()
  175. let metadata = try await responseParts.next()
  176. XCTAssertMetadata(metadata)
  177. let message = try await responseParts.next()
  178. XCTAssertMessage(message) { XCTAssertEqual($0, [i]) }
  179. let status = try await responseParts.next()
  180. XCTAssertStatus(status) { status, _ in
  181. XCTAssertEqual(status.code, .ok)
  182. }
  183. }
  184. }
  185. }
  186. }
  187. }
  188. }
  189. func testInterceptorsAreAppliedInOrder() async throws {
  190. let counter1 = AtomicCounter()
  191. let counter2 = AtomicCounter()
  192. try await self.withInProcessClientConnectedToServer(
  193. services: [BinaryEcho()],
  194. interceptors: [
  195. .requestCounter(counter1),
  196. .rejectAll(with: RPCError(code: .unavailable, message: "")),
  197. .requestCounter(counter2),
  198. ]
  199. ) { client, _ in
  200. try await client.withStream(
  201. descriptor: BinaryEcho.Methods.get,
  202. options: .defaults
  203. ) { stream in
  204. try await stream.outbound.write(.metadata([:]))
  205. await stream.outbound.finish()
  206. let parts = try await stream.inbound.collect()
  207. XCTAssertStatus(parts.first) { status, _ in
  208. XCTAssertEqual(status.code, .unavailable)
  209. }
  210. }
  211. }
  212. XCTAssertEqual(counter1.value, 1)
  213. XCTAssertEqual(counter2.value, 0)
  214. }
  215. func testInterceptorsAreNotAppliedToUnimplementedMethods() async throws {
  216. let counter = AtomicCounter()
  217. try await self.withInProcessClientConnectedToServer(
  218. services: [BinaryEcho()],
  219. interceptors: [.requestCounter(counter)]
  220. ) { client, _ in
  221. try await client.withStream(
  222. descriptor: MethodDescriptor(service: "not", method: "implemented"),
  223. options: .defaults
  224. ) { stream in
  225. try await stream.outbound.write(.metadata([:]))
  226. await stream.outbound.finish()
  227. let parts = try await stream.inbound.collect()
  228. XCTAssertStatus(parts.first) { status, _ in
  229. XCTAssertEqual(status.code, .unimplemented)
  230. }
  231. }
  232. }
  233. XCTAssertEqual(counter.value, 0)
  234. }
  235. func testNoNewRPCsAfterServerStopListening() async throws {
  236. try await withInProcessClientConnectedToServer(services: [BinaryEcho()]) { client, server in
  237. // Run an RPC so we know the server is up.
  238. try await self.doEchoGet(using: client)
  239. // New streams should fail immediately after this.
  240. server.beginGracefulShutdown()
  241. // RPC should fail now.
  242. await XCTAssertThrowsRPCErrorAsync {
  243. try await client.withStream(
  244. descriptor: BinaryEcho.Methods.get,
  245. options: .defaults
  246. ) { stream in
  247. XCTFail("Stream shouldn't be opened")
  248. }
  249. } errorHandler: { error in
  250. XCTAssertEqual(error.code, .failedPrecondition)
  251. }
  252. }
  253. }
  254. func testInFlightRPCsCanContinueAfterServerStopListening() async throws {
  255. try await withInProcessClientConnectedToServer(services: [BinaryEcho()]) { client, server in
  256. try await client.withStream(
  257. descriptor: BinaryEcho.Methods.update,
  258. options: .defaults
  259. ) { stream in
  260. try await stream.outbound.write(.metadata([:]))
  261. var iterator = stream.inbound.makeAsyncIterator()
  262. // Don't need to validate the response, just that the server is running.
  263. let metadata = try await iterator.next()
  264. XCTAssertMetadata(metadata)
  265. // New streams should fail immediately after this.
  266. server.beginGracefulShutdown()
  267. try await stream.outbound.write(.message([0]))
  268. await stream.outbound.finish()
  269. let message = try await iterator.next()
  270. XCTAssertMessage(message) { XCTAssertEqual($0, [0]) }
  271. let status = try await iterator.next()
  272. XCTAssertStatus(status)
  273. }
  274. }
  275. }
  276. func testCancelRunningServer() async throws {
  277. let inProcess = InProcessTransport()
  278. let task = Task {
  279. let server = GRPCServer(transport: inProcess.server, services: [BinaryEcho()])
  280. try await server.serve()
  281. }
  282. try await withThrowingTaskGroup(of: Void.self) { group in
  283. group.addTask {
  284. try? await inProcess.client.connect()
  285. }
  286. try await self.doEchoGet(using: inProcess.client)
  287. // The server must be running at this point as an RPC has completed.
  288. task.cancel()
  289. try await task.value
  290. group.cancelAll()
  291. }
  292. }
  293. func testTestRunStoppedServer() async throws {
  294. let server = GRPCServer(transport: InProcessTransport.Server(), services: [])
  295. // Run the server.
  296. let task = Task { try await server.serve() }
  297. task.cancel()
  298. try await task.value
  299. // Server is stopped, should throw an error.
  300. await XCTAssertThrowsErrorAsync(ofType: RuntimeError.self) {
  301. try await server.serve()
  302. } errorHandler: { error in
  303. XCTAssertEqual(error.code, .serverIsStopped)
  304. }
  305. }
  306. func testRunServerWhenTransportThrows() async throws {
  307. let server = GRPCServer(transport: ThrowOnRunServerTransport(), services: [])
  308. await XCTAssertThrowsErrorAsync(ofType: RuntimeError.self) {
  309. try await server.serve()
  310. } errorHandler: { error in
  311. XCTAssertEqual(error.code, .transportError)
  312. }
  313. }
  314. private func doEchoGet(using transport: some ClientTransport) async throws {
  315. try await transport.withStream(
  316. descriptor: BinaryEcho.Methods.get,
  317. options: .defaults
  318. ) { stream in
  319. try await stream.outbound.write(.metadata([:]))
  320. try await stream.outbound.write(.message([0]))
  321. await stream.outbound.finish()
  322. // Don't need to validate the response, just that the server is running.
  323. let parts = try await stream.inbound.collect()
  324. XCTAssertEqual(parts.count, 3)
  325. }
  326. }
  327. }