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