ServerTests.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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 XCTest
  19. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  20. final class ServerTests: XCTestCase {
  21. func makeInProcessPair() -> (client: InProcessClientTransport, server: InProcessServerTransport) {
  22. let server = InProcessServerTransport()
  23. let client = InProcessClientTransport(
  24. server: server,
  25. executionConfigurations: ClientRPCExecutionConfigurationCollection()
  26. )
  27. return (client, server)
  28. }
  29. func withInProcessClientConnectedToServer(
  30. services: [any RegistrableRPCService],
  31. interceptors: [any ServerInterceptor] = [],
  32. _ body: (InProcessClientTransport, Server) async throws -> Void
  33. ) async throws {
  34. let inProcess = self.makeInProcessPair()
  35. let server = Server()
  36. server.transports.add(inProcess.server)
  37. for service in services {
  38. server.services.register(service)
  39. }
  40. for interceptor in interceptors {
  41. server.interceptors.add(interceptor)
  42. }
  43. try await withThrowingTaskGroup(of: Void.self) { group in
  44. group.addTask {
  45. try await server.run()
  46. }
  47. group.addTask {
  48. try await inProcess.client.connect(lazily: true)
  49. }
  50. try await body(inProcess.client, server)
  51. inProcess.client.close()
  52. server.stopListening()
  53. }
  54. }
  55. func testServerHandlesUnary() async throws {
  56. try await self.withInProcessClientConnectedToServer(services: [BinaryEcho()]) { client, _ in
  57. try await client.withStream(descriptor: BinaryEcho.Methods.get) { stream in
  58. try await stream.outbound.write(.metadata([:]))
  59. try await stream.outbound.write(.message([3, 1, 4, 1, 5]))
  60. stream.outbound.finish()
  61. var responseParts = stream.inbound.makeAsyncIterator()
  62. let metadata = try await responseParts.next()
  63. XCTAssertMetadata(metadata)
  64. let message = try await responseParts.next()
  65. XCTAssertMessage(message) {
  66. XCTAssertEqual($0, [3, 1, 4, 1, 5])
  67. }
  68. let status = try await responseParts.next()
  69. XCTAssertStatus(status) { status, _ in
  70. XCTAssertEqual(status.code, .ok)
  71. }
  72. }
  73. }
  74. }
  75. func testServerHandlesClientStreaming() async throws {
  76. try await self.withInProcessClientConnectedToServer(services: [BinaryEcho()]) { client, _ in
  77. try await client.withStream(descriptor: BinaryEcho.Methods.collect) { stream in
  78. try await stream.outbound.write(.metadata([:]))
  79. try await stream.outbound.write(.message([3]))
  80. try await stream.outbound.write(.message([1]))
  81. try await stream.outbound.write(.message([4]))
  82. try await stream.outbound.write(.message([1]))
  83. try await stream.outbound.write(.message([5]))
  84. stream.outbound.finish()
  85. var responseParts = stream.inbound.makeAsyncIterator()
  86. let metadata = try await responseParts.next()
  87. XCTAssertMetadata(metadata)
  88. let message = try await responseParts.next()
  89. XCTAssertMessage(message) {
  90. XCTAssertEqual($0, [3, 1, 4, 1, 5])
  91. }
  92. let status = try await responseParts.next()
  93. XCTAssertStatus(status) { status, _ in
  94. XCTAssertEqual(status.code, .ok)
  95. }
  96. }
  97. }
  98. }
  99. func testServerHandlesServerStreaming() async throws {
  100. try await self.withInProcessClientConnectedToServer(services: [BinaryEcho()]) { client, _ in
  101. try await client.withStream(descriptor: BinaryEcho.Methods.expand) { stream in
  102. try await stream.outbound.write(.metadata([:]))
  103. try await stream.outbound.write(.message([3, 1, 4, 1, 5]))
  104. stream.outbound.finish()
  105. var responseParts = stream.inbound.makeAsyncIterator()
  106. let metadata = try await responseParts.next()
  107. XCTAssertMetadata(metadata)
  108. for byte in [3, 1, 4, 1, 5] as [UInt8] {
  109. let message = try await responseParts.next()
  110. XCTAssertMessage(message) {
  111. XCTAssertEqual($0, [byte])
  112. }
  113. }
  114. let status = try await responseParts.next()
  115. XCTAssertStatus(status) { status, _ in
  116. XCTAssertEqual(status.code, .ok)
  117. }
  118. }
  119. }
  120. }
  121. func testServerHandlesBidirectionalStreaming() async throws {
  122. try await self.withInProcessClientConnectedToServer(services: [BinaryEcho()]) { client, _ in
  123. try await client.withStream(descriptor: BinaryEcho.Methods.update) { 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. 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. ) { stream in
  150. try await stream.outbound.write(.metadata([:]))
  151. stream.outbound.finish()
  152. var responseParts = stream.inbound.makeAsyncIterator()
  153. let status = try await responseParts.next()
  154. XCTAssertStatus(status) { status, _ in
  155. XCTAssertEqual(status.code, .unimplemented)
  156. }
  157. }
  158. }
  159. }
  160. func testMultipleConcurrentRequests() async throws {
  161. try await self.withInProcessClientConnectedToServer(services: [BinaryEcho()]) { client, _ in
  162. await withThrowingTaskGroup(of: Void.self) { group in
  163. for i in UInt8.min ..< UInt8.max {
  164. group.addTask {
  165. try await client.withStream(descriptor: BinaryEcho.Methods.get) { stream in
  166. try await stream.outbound.write(.metadata([:]))
  167. try await stream.outbound.write(.message([i]))
  168. stream.outbound.finish()
  169. var responseParts = stream.inbound.makeAsyncIterator()
  170. let metadata = try await responseParts.next()
  171. XCTAssertMetadata(metadata)
  172. let message = try await responseParts.next()
  173. XCTAssertMessage(message) { XCTAssertEqual($0, [i]) }
  174. let status = try await responseParts.next()
  175. XCTAssertStatus(status) { status, _ in
  176. XCTAssertEqual(status.code, .ok)
  177. }
  178. }
  179. }
  180. }
  181. }
  182. }
  183. }
  184. func testInterceptorsAreAppliedInOrder() async throws {
  185. let counter1 = ManagedAtomic(0)
  186. let counter2 = ManagedAtomic(0)
  187. try await self.withInProcessClientConnectedToServer(
  188. services: [BinaryEcho()],
  189. interceptors: [
  190. .requestCounter(counter1),
  191. .rejectAll(with: RPCError(code: .unavailable, message: "")),
  192. .requestCounter(counter2),
  193. ]
  194. ) { client, _ in
  195. try await client.withStream(descriptor: BinaryEcho.Methods.get) { stream in
  196. try await stream.outbound.write(.metadata([:]))
  197. stream.outbound.finish()
  198. let parts = try await stream.inbound.collect()
  199. XCTAssertStatus(parts.first) { status, _ in
  200. XCTAssertEqual(status.code, .unavailable)
  201. }
  202. }
  203. }
  204. XCTAssertEqual(counter1.load(ordering: .sequentiallyConsistent), 1)
  205. XCTAssertEqual(counter2.load(ordering: .sequentiallyConsistent), 0)
  206. }
  207. func testInterceptorsAreNotAppliedToUnimplementedMethods() async throws {
  208. let counter = ManagedAtomic(0)
  209. try await self.withInProcessClientConnectedToServer(
  210. services: [BinaryEcho()],
  211. interceptors: [.requestCounter(counter)]
  212. ) { client, _ in
  213. try await client.withStream(
  214. descriptor: MethodDescriptor(service: "not", method: "implemented")
  215. ) { stream in
  216. try await stream.outbound.write(.metadata([:]))
  217. stream.outbound.finish()
  218. let parts = try await stream.inbound.collect()
  219. XCTAssertStatus(parts.first) { status, _ in
  220. XCTAssertEqual(status.code, .unimplemented)
  221. }
  222. }
  223. }
  224. XCTAssertEqual(counter.load(ordering: .sequentiallyConsistent), 0)
  225. }
  226. func testNoNewRPCsAfterServerStopListening() async throws {
  227. try await withInProcessClientConnectedToServer(services: [BinaryEcho()]) { client, server in
  228. // Run an RPC so we know the server is up.
  229. try await self.doEchoGet(using: client)
  230. // New streams should fail immediately after this.
  231. server.stopListening()
  232. // RPC should fail now.
  233. await XCTAssertThrowsRPCErrorAsync {
  234. try await client.withStream(descriptor: BinaryEcho.Methods.get) { stream in
  235. XCTFail("Stream shouldn't be opened")
  236. }
  237. } errorHandler: { error in
  238. XCTAssertEqual(error.code, .failedPrecondition)
  239. }
  240. }
  241. }
  242. func testInFlightRPCsCanContinueAfterServerStopListening() async throws {
  243. try await withInProcessClientConnectedToServer(services: [BinaryEcho()]) { client, server in
  244. try await client.withStream(descriptor: BinaryEcho.Methods.update) { stream in
  245. try await stream.outbound.write(.metadata([:]))
  246. var iterator = stream.inbound.makeAsyncIterator()
  247. // Don't need to validate the response, just that the server is running.
  248. let metadata = try await iterator.next()
  249. XCTAssertMetadata(metadata)
  250. // New streams should fail immediately after this.
  251. server.stopListening()
  252. try await stream.outbound.write(.message([0]))
  253. stream.outbound.finish()
  254. let message = try await iterator.next()
  255. XCTAssertMessage(message) { XCTAssertEqual($0, [0]) }
  256. let status = try await iterator.next()
  257. XCTAssertStatus(status)
  258. }
  259. }
  260. }
  261. func testCancelRunningServer() async throws {
  262. let inProcess = self.makeInProcessPair()
  263. let task = Task {
  264. let server = Server()
  265. server.services.register(BinaryEcho())
  266. server.transports.add(inProcess.server)
  267. try await server.run()
  268. }
  269. try await withThrowingTaskGroup(of: Void.self) { group in
  270. group.addTask {
  271. try? await inProcess.client.connect(lazily: true)
  272. }
  273. try await self.doEchoGet(using: inProcess.client)
  274. // The server must be running at this point as an RPC has completed.
  275. task.cancel()
  276. try await task.value
  277. group.cancelAll()
  278. }
  279. }
  280. func testTestRunServerWithNoTransport() async throws {
  281. let server = Server()
  282. await XCTAssertThrowsErrorAsync(ofType: ServerError.self) {
  283. try await server.run()
  284. } errorHandler: { error in
  285. XCTAssertEqual(error.code, .noTransportsConfigured)
  286. }
  287. }
  288. func testTestRunStoppedServer() async throws {
  289. let server = Server()
  290. server.transports.add(InProcessServerTransport())
  291. // Run the server.
  292. let task = Task { try await server.run() }
  293. task.cancel()
  294. try await task.value
  295. // Server is stopped, should throw an error.
  296. await XCTAssertThrowsErrorAsync(ofType: ServerError.self) {
  297. try await server.run()
  298. } errorHandler: { error in
  299. XCTAssertEqual(error.code, .serverIsStopped)
  300. }
  301. }
  302. func testRunServerWhenTransportThrows() async throws {
  303. let server = Server()
  304. server.transports.add(ThrowOnRunServerTransport())
  305. await XCTAssertThrowsErrorAsync(ofType: ServerError.self) {
  306. try await server.run()
  307. } errorHandler: { error in
  308. XCTAssertEqual(error.code, .failedToStartTransport)
  309. }
  310. }
  311. func testRunServerDrainsRunningTransportsWhenOneFailsToStart() async throws {
  312. let server = Server()
  313. // Register the in process transport first and allow it to come up.
  314. let inProcess = self.makeInProcessPair()
  315. server.transports.add(inProcess.server)
  316. // Register a transport waits for a signal before throwing.
  317. let signal = AsyncStream.makeStream(of: Void.self)
  318. server.transports.add(ThrowOnSignalServerTransport(signal: signal.stream))
  319. // Connect the in process client and start an RPC. When the stream is opened signal the
  320. // other transport to throw. This stream should be failed by the server.
  321. await withThrowingTaskGroup(of: Void.self) { group in
  322. group.addTask {
  323. try await inProcess.client.connect(lazily: true)
  324. }
  325. group.addTask {
  326. try await inProcess.client.withStream(descriptor: BinaryEcho.Methods.get) { stream in
  327. // The stream is open to the in-process transport. Let the other transport start.
  328. signal.continuation.finish()
  329. try await stream.outbound.write(.metadata([:]))
  330. stream.outbound.finish()
  331. let parts = try await stream.inbound.collect()
  332. XCTAssertStatus(parts.first) { status, _ in
  333. XCTAssertEqual(status.code, .unavailable)
  334. }
  335. }
  336. }
  337. await XCTAssertThrowsErrorAsync(ofType: ServerError.self) {
  338. try await server.run()
  339. } errorHandler: { error in
  340. XCTAssertEqual(error.code, .failedToStartTransport)
  341. }
  342. group.cancelAll()
  343. }
  344. }
  345. func testInterceptorsDescription() async throws {
  346. let server = Server()
  347. server.interceptors.add(.rejectAll(with: .init(code: .aborted, message: "")))
  348. server.interceptors.add(.requestCounter(.init(0)))
  349. let description = String(describing: server.interceptors)
  350. let expected = #"["RejectAllServerInterceptor", "RequestCountingServerInterceptor"]"#
  351. XCTAssertEqual(description, expected)
  352. }
  353. func testServicesDescription() async throws {
  354. let server = Server()
  355. let methods: [(String, String)] = [
  356. ("helloworld.Greeter", "SayHello"),
  357. ("echo.Echo", "Foo"),
  358. ("echo.Echo", "Bar"),
  359. ("echo.Echo", "Baz"),
  360. ]
  361. for (service, method) in methods {
  362. let descriptor = MethodDescriptor(service: service, method: method)
  363. server.services.router.registerHandler(
  364. forMethod: descriptor,
  365. deserializer: IdentityDeserializer(),
  366. serializer: IdentitySerializer()
  367. ) { _ in
  368. fatalError("Unreachable")
  369. }
  370. }
  371. let description = String(describing: server.services)
  372. let expected = """
  373. ["echo.Echo/Bar", "echo.Echo/Baz", "echo.Echo/Foo", "helloworld.Greeter/SayHello"]
  374. """
  375. XCTAssertEqual(description, expected)
  376. }
  377. private func doEchoGet(using transport: some ClientTransport) async throws {
  378. try await transport.withStream(descriptor: BinaryEcho.Methods.get) { stream in
  379. try await stream.outbound.write(.metadata([:]))
  380. try await stream.outbound.write(.message([0]))
  381. stream.outbound.finish()
  382. // Don't need to validate the response, just that the server is running.
  383. let parts = try await stream.inbound.collect()
  384. XCTAssertEqual(parts.count, 3)
  385. }
  386. }
  387. }