GRPCAsyncServerHandlerTests.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. /*
  2. * Copyright 2021, 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. #if compiler(>=5.6)
  17. @testable import GRPC
  18. import NIOCore
  19. import XCTest
  20. // MARK: - Tests
  21. @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *)
  22. class AsyncServerHandlerTests: ServerHandlerTestCaseBase {
  23. private func makeHandler(
  24. encoding: ServerMessageEncoding = .disabled,
  25. observer: @escaping @Sendable (
  26. GRPCAsyncRequestStream<String>,
  27. GRPCAsyncResponseStreamWriter<String>,
  28. GRPCAsyncServerCallContext
  29. ) async throws -> Void
  30. ) -> AsyncServerHandler<StringSerializer, StringDeserializer, String, String> {
  31. return AsyncServerHandler(
  32. context: self.makeCallHandlerContext(encoding: encoding),
  33. requestDeserializer: StringDeserializer(),
  34. responseSerializer: StringSerializer(),
  35. interceptors: [],
  36. userHandler: observer
  37. )
  38. }
  39. @Sendable private func echo(
  40. requests: GRPCAsyncRequestStream<String>,
  41. responseStreamWriter: GRPCAsyncResponseStreamWriter<String>,
  42. context: GRPCAsyncServerCallContext
  43. ) async throws {
  44. for try await message in requests {
  45. try await responseStreamWriter.send(message)
  46. }
  47. }
  48. @Sendable private func neverReceivesMessage(
  49. requests: GRPCAsyncRequestStream<String>,
  50. responseStreamWriter: GRPCAsyncResponseStreamWriter<String>,
  51. context: GRPCAsyncServerCallContext
  52. ) async throws {
  53. for try await message in requests {
  54. XCTFail("Unexpected message: '\(message)'")
  55. }
  56. }
  57. @Sendable private func neverCalled(
  58. requests: GRPCAsyncRequestStream<String>,
  59. responseStreamWriter: GRPCAsyncResponseStreamWriter<String>,
  60. context: GRPCAsyncServerCallContext
  61. ) async throws {
  62. XCTFail("This observer should never be called")
  63. }
  64. func testHappyPath() async throws {
  65. let handler = self.makeHandler(
  66. observer: self.echo(requests:responseStreamWriter:context:)
  67. )
  68. handler.receiveMetadata([:])
  69. handler.receiveMessage(ByteBuffer(string: "1"))
  70. handler.receiveMessage(ByteBuffer(string: "2"))
  71. handler.receiveMessage(ByteBuffer(string: "3"))
  72. handler.receiveEnd()
  73. // Wait for tasks to finish.
  74. await handler.userHandlerTask?.value
  75. handler.finish()
  76. await assertThat(self.recorder.metadata, .is([:]))
  77. await assertThat(
  78. self.recorder.messages,
  79. .is([ByteBuffer(string: "1"), ByteBuffer(string: "2"), ByteBuffer(string: "3")])
  80. )
  81. await assertThat(self.recorder.messageMetadata.map { $0.compress }, .is([false, false, false]))
  82. await assertThat(self.recorder.status, .notNil(.hasCode(.ok)))
  83. await assertThat(self.recorder.trailers, .is([:]))
  84. }
  85. func testHappyPathWithCompressionEnabled() async throws {
  86. let handler = self.makeHandler(
  87. encoding: .enabled(.init(decompressionLimit: .absolute(.max))),
  88. observer: self.echo(requests:responseStreamWriter:context:)
  89. )
  90. handler.receiveMetadata([:])
  91. handler.receiveMessage(ByteBuffer(string: "1"))
  92. handler.receiveMessage(ByteBuffer(string: "2"))
  93. handler.receiveMessage(ByteBuffer(string: "3"))
  94. handler.receiveEnd()
  95. // Wait for tasks to finish.
  96. await handler.userHandlerTask?.value
  97. await assertThat(
  98. self.recorder.messages,
  99. .is([ByteBuffer(string: "1"), ByteBuffer(string: "2"), ByteBuffer(string: "3")])
  100. )
  101. await assertThat(self.recorder.messageMetadata.map { $0.compress }, .is([true, true, true]))
  102. }
  103. func testHappyPathWithCompressionEnabledButDisabledByCaller() async throws {
  104. let handler = self.makeHandler(
  105. encoding: .enabled(.init(decompressionLimit: .absolute(.max)))
  106. ) { requests, responseStreamWriter, context in
  107. context.compressionEnabled = false
  108. return try await self.echo(
  109. requests: requests,
  110. responseStreamWriter: responseStreamWriter,
  111. context: context
  112. )
  113. }
  114. handler.receiveMetadata([:])
  115. handler.receiveMessage(ByteBuffer(string: "1"))
  116. handler.receiveMessage(ByteBuffer(string: "2"))
  117. handler.receiveMessage(ByteBuffer(string: "3"))
  118. handler.receiveEnd()
  119. // Wait for tasks to finish.
  120. await handler.userHandlerTask?.value
  121. await assertThat(
  122. self.recorder.messages,
  123. .is([ByteBuffer(string: "1"), ByteBuffer(string: "2"), ByteBuffer(string: "3")])
  124. )
  125. await assertThat(self.recorder.messageMetadata.map { $0.compress }, .is([false, false, false]))
  126. }
  127. func testResponseHeadersAndTrailersSentFromContext() async throws {
  128. let handler = self.makeHandler { _, responseStreamWriter, context in
  129. context.initialResponseMetadata = ["pontiac": "bandit"]
  130. try await responseStreamWriter.send("1")
  131. context.trailingResponseMetadata = ["disco": "strangler"]
  132. }
  133. handler.receiveMetadata([:])
  134. handler.receiveEnd()
  135. // Wait for tasks to finish.
  136. await handler.userHandlerTask?.value
  137. await assertThat(self.recorder.metadata, .is(["pontiac": "bandit"]))
  138. await assertThat(self.recorder.trailers, .is(["disco": "strangler"]))
  139. }
  140. func testResponseHeadersDroppedIfSetAfterFirstResponse() async throws {
  141. let handler = self.makeHandler { _, responseStreamWriter, context in
  142. try await responseStreamWriter.send("1")
  143. context.initialResponseMetadata = ["pontiac": "bandit"]
  144. context.trailingResponseMetadata = ["disco": "strangler"]
  145. }
  146. handler.receiveMetadata([:])
  147. handler.receiveEnd()
  148. // Wait for tasks to finish.
  149. await handler.userHandlerTask?.value
  150. await assertThat(self.recorder.metadata, .is([:]))
  151. await assertThat(self.recorder.trailers, .is(["disco": "strangler"]))
  152. }
  153. func testTaskOnlyCreatedAfterHeaders() async throws {
  154. let handler = self.makeHandler(observer: self.echo(requests:responseStreamWriter:context:))
  155. await assertThat(handler.userHandlerTask, .nil())
  156. handler.receiveMetadata([:])
  157. await assertThat(handler.userHandlerTask, .notNil())
  158. }
  159. func testThrowingDeserializer() async throws {
  160. let handler = AsyncServerHandler(
  161. context: self.makeCallHandlerContext(),
  162. requestDeserializer: ThrowingStringDeserializer(),
  163. responseSerializer: StringSerializer(),
  164. interceptors: [],
  165. userHandler: self.neverReceivesMessage(requests:responseStreamWriter:context:)
  166. )
  167. handler.receiveMetadata([:])
  168. handler.receiveMessage(ByteBuffer(string: "hello"))
  169. // Wait for tasks to finish.
  170. await handler.userHandlerTask?.value
  171. await assertThat(self.recorder.metadata, .nil())
  172. await assertThat(self.recorder.messages, .isEmpty())
  173. await assertThat(self.recorder.status, .notNil(.hasCode(.internalError)))
  174. }
  175. func testThrowingSerializer() async throws {
  176. let handler = AsyncServerHandler(
  177. context: self.makeCallHandlerContext(),
  178. requestDeserializer: StringDeserializer(),
  179. responseSerializer: ThrowingStringSerializer(),
  180. interceptors: [],
  181. userHandler: self.echo(requests:responseStreamWriter:context:)
  182. )
  183. handler.receiveMetadata([:])
  184. handler.receiveMessage(ByteBuffer(string: "hello"))
  185. handler.receiveEnd()
  186. // Wait for tasks to finish.
  187. await handler.userHandlerTask?.value
  188. await assertThat(self.recorder.metadata, .is([:]))
  189. await assertThat(self.recorder.messages, .isEmpty())
  190. await assertThat(self.recorder.status, .notNil(.hasCode(.internalError)))
  191. }
  192. func testReceiveMessageBeforeHeaders() async throws {
  193. let handler = self
  194. .makeHandler(observer: self.neverCalled(requests:responseStreamWriter:context:))
  195. handler.receiveMessage(ByteBuffer(string: "foo"))
  196. // Wait for tasks to finish.
  197. await handler.userHandlerTask?.value
  198. await assertThat(self.recorder.metadata, .nil())
  199. await assertThat(self.recorder.messages, .isEmpty())
  200. await assertThat(self.recorder.status, .notNil(.hasCode(.internalError)))
  201. }
  202. func testReceiveMultipleHeaders() async throws {
  203. let handler = self
  204. .makeHandler(observer: self.neverReceivesMessage(requests:responseStreamWriter:context:))
  205. handler.receiveMetadata([:])
  206. handler.receiveMetadata([:])
  207. // Wait for tasks to finish.
  208. await handler.userHandlerTask?.value
  209. await assertThat(self.recorder.metadata, .nil())
  210. await assertThat(self.recorder.messages, .isEmpty())
  211. await assertThat(self.recorder.status, .notNil(.hasCode(.internalError)))
  212. }
  213. func testFinishBeforeStarting() async throws {
  214. let handler = self
  215. .makeHandler(observer: self.neverCalled(requests:responseStreamWriter:context:))
  216. handler.finish()
  217. await assertThat(self.recorder.metadata, .nil())
  218. await assertThat(self.recorder.messages, .isEmpty())
  219. await assertThat(self.recorder.status, .nil())
  220. await assertThat(self.recorder.trailers, .nil())
  221. }
  222. func testFinishAfterHeaders() async throws {
  223. let handler = self.makeHandler(observer: self.echo(requests:responseStreamWriter:context:))
  224. handler.receiveMetadata([:])
  225. handler.finish()
  226. // Wait for tasks to finish.
  227. await handler.userHandlerTask?.value
  228. await assertThat(self.recorder.metadata, .nil())
  229. await assertThat(self.recorder.messages, .isEmpty())
  230. await assertThat(self.recorder.status, .nil())
  231. await assertThat(self.recorder.trailers, .nil())
  232. }
  233. func testFinishAfterMessage() async throws {
  234. let handler = self.makeHandler(observer: self.echo(requests:responseStreamWriter:context:))
  235. handler.receiveMetadata([:])
  236. handler.receiveMessage(ByteBuffer(string: "hello"))
  237. // Wait for the async user function to have processed the message.
  238. try self.recorder.recordedMessagePromise.futureResult.wait()
  239. handler.finish()
  240. // Wait for tasks to finish.
  241. await handler.userHandlerTask?.value
  242. await assertThat(self.recorder.messages.first, .is(ByteBuffer(string: "hello")))
  243. await assertThat(self.recorder.status, .nil())
  244. await assertThat(self.recorder.trailers, .nil())
  245. }
  246. func testErrorAfterHeaders() async throws {
  247. let handler = self.makeHandler(observer: self.echo(requests:responseStreamWriter:context:))
  248. handler.receiveMetadata([:])
  249. handler.receiveError(CancellationError())
  250. // Wait for tasks to finish.
  251. await handler.userHandlerTask?.value
  252. await assertThat(self.recorder.status, .notNil(.hasCode(.unavailable)))
  253. await assertThat(self.recorder.trailers, .is([:]))
  254. }
  255. func testErrorAfterMessage() async throws {
  256. let handler = self.makeHandler(observer: self.echo(requests:responseStreamWriter:context:))
  257. handler.receiveMetadata([:])
  258. handler.receiveMessage(ByteBuffer(string: "hello"))
  259. // Wait for the async user function to have processed the message.
  260. try self.recorder.recordedMessagePromise.futureResult.wait()
  261. handler.receiveError(CancellationError())
  262. // Wait for tasks to finish.
  263. await handler.userHandlerTask?.value
  264. await assertThat(self.recorder.messages.first, .is(ByteBuffer(string: "hello")))
  265. await assertThat(self.recorder.status, .notNil(.hasCode(.unavailable)))
  266. await assertThat(self.recorder.trailers, .is([:]))
  267. }
  268. func testHandlerThrowsGRPCStatusOKResultsInUnknownStatus() async throws {
  269. // Create a user function that immediately throws GRPCStatus.ok.
  270. let handler = self.makeHandler { _, _, _ in
  271. throw GRPCStatus.ok
  272. }
  273. // Send some metadata to trigger the creation of the async task with the user function.
  274. handler.receiveMetadata([:])
  275. // Wait for user handler to finish (it's gonna throw immediately).
  276. await assertThat(await handler.userHandlerTask?.value, .notNil())
  277. // Check the status is `.unknown`.
  278. await assertThat(self.recorder.status, .notNil(.hasCode(.unknown)))
  279. }
  280. func testResponseStreamDrain() async throws {
  281. // Set up echo handler.
  282. let handler = self.makeHandler(
  283. observer: self.echo(requests:responseStreamWriter:context:)
  284. )
  285. // Send some metadata to trigger the creation of the async task with the user function.
  286. handler.receiveMetadata([:])
  287. // Send two requests and end, pausing the writer in the middle.
  288. switch handler.state {
  289. case let .active(activeState):
  290. handler.receiveMessage(ByteBuffer(string: "diaz"))
  291. await activeState.responseStreamWriter.asyncWriter.toggleWritability()
  292. handler.receiveMessage(ByteBuffer(string: "santiago"))
  293. handler.receiveEnd()
  294. await activeState.responseStreamWriter.asyncWriter.toggleWritability()
  295. await handler.userHandlerTask?.value
  296. _ = try await activeState._userHandlerPromise.futureResult.get()
  297. default:
  298. XCTFail("Unexpected handler state: \(handler.state)")
  299. }
  300. handler.finish()
  301. await assertThat(self.recorder.messages, .is([
  302. ByteBuffer(string: "diaz"),
  303. ByteBuffer(string: "santiago"),
  304. ]))
  305. await assertThat(self.recorder.status, .notNil(.hasCode(.ok)))
  306. }
  307. }
  308. #endif