GRPCServerTests.swift 12 KB

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