GRPCAsyncServerHandlerTests.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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.5)
  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> {
  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() { XCTAsyncTest {
  65. let handler = self.makeHandler(
  66. observer: self.echo(requests:responseStreamWriter:context:)
  67. )
  68. handler.receiveMetadata([:])
  69. await assertThat(self.recorder.metadata, .is([:]))
  70. handler.receiveMessage(ByteBuffer(string: "1"))
  71. handler.receiveMessage(ByteBuffer(string: "2"))
  72. handler.receiveMessage(ByteBuffer(string: "3"))
  73. handler.receiveEnd()
  74. // Wait for tasks to finish.
  75. await handler.userHandlerTask?.value
  76. handler.finish()
  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() { XCTAsyncTest {
  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() { XCTAsyncTest {
  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 testTaskOnlyCreatedAfterHeaders() { XCTAsyncTest {
  128. let handler = self.makeHandler(observer: self.echo(requests:responseStreamWriter:context:))
  129. await assertThat(handler.userHandlerTask, .is(.nil()))
  130. handler.receiveMetadata([:])
  131. await assertThat(handler.userHandlerTask, .is(.notNil()))
  132. } }
  133. func testThrowingDeserializer() { XCTAsyncTest {
  134. let handler = AsyncServerHandler(
  135. context: self.makeCallHandlerContext(),
  136. requestDeserializer: ThrowingStringDeserializer(),
  137. responseSerializer: StringSerializer(),
  138. interceptors: [],
  139. userHandler: self.neverReceivesMessage(requests:responseStreamWriter:context:)
  140. )
  141. handler.receiveMetadata([:])
  142. // Wait for the async user function to have processed the metadata.
  143. try self.recorder.recordedMetadataPromise.futureResult.wait()
  144. await assertThat(self.recorder.metadata, .is([:]))
  145. let buffer = ByteBuffer(string: "hello")
  146. handler.receiveMessage(buffer)
  147. // Wait for tasks to finish.
  148. await handler.userHandlerTask?.value
  149. await assertThat(self.recorder.messages, .isEmpty())
  150. await assertThat(self.recorder.status, .notNil(.hasCode(.internalError)))
  151. } }
  152. func testThrowingSerializer() { XCTAsyncTest {
  153. let handler = AsyncServerHandler(
  154. context: self.makeCallHandlerContext(),
  155. requestDeserializer: StringDeserializer(),
  156. responseSerializer: ThrowingStringSerializer(),
  157. interceptors: [],
  158. userHandler: self.echo(requests:responseStreamWriter:context:)
  159. )
  160. handler.receiveMetadata([:])
  161. await assertThat(self.recorder.metadata, .is([:]))
  162. let buffer = ByteBuffer(string: "hello")
  163. handler.receiveMessage(buffer)
  164. handler.receiveEnd()
  165. // Wait for tasks to finish.
  166. await handler.userHandlerTask?.value
  167. await assertThat(self.recorder.messages, .isEmpty())
  168. await assertThat(self.recorder.status, .notNil(.hasCode(.internalError)))
  169. } }
  170. func testReceiveMessageBeforeHeaders() { XCTAsyncTest {
  171. let handler = self
  172. .makeHandler(observer: self.neverCalled(requests:responseStreamWriter:context:))
  173. handler.receiveMessage(ByteBuffer(string: "foo"))
  174. // Wait for tasks to finish.
  175. await handler.userHandlerTask?.value
  176. await assertThat(self.recorder.metadata, .is(.nil()))
  177. await assertThat(self.recorder.messages, .isEmpty())
  178. await assertThat(self.recorder.status, .notNil(.hasCode(.internalError)))
  179. } }
  180. // TODO: Running this 1000 times shows up a segfault in NIO event loop group.
  181. func testReceiveMultipleHeaders() { XCTAsyncTest {
  182. let handler = self
  183. .makeHandler(observer: self.neverReceivesMessage(requests:responseStreamWriter:context:))
  184. handler.receiveMetadata([:])
  185. // Wait for the async user function to have processed the metadata.
  186. try self.recorder.recordedMetadataPromise.futureResult.wait()
  187. await assertThat(self.recorder.metadata, .is([:]))
  188. handler.receiveMetadata([:])
  189. // Wait for tasks to finish.
  190. await handler.userHandlerTask?.value
  191. await assertThat(self.recorder.messages, .isEmpty())
  192. await assertThat(self.recorder.status, .notNil(.hasCode(.internalError)))
  193. } }
  194. func testFinishBeforeStarting() { XCTAsyncTest {
  195. let handler = self
  196. .makeHandler(observer: self.neverCalled(requests:responseStreamWriter:context:))
  197. handler.finish()
  198. await assertThat(self.recorder.metadata, .is(.nil()))
  199. await assertThat(self.recorder.messages, .isEmpty())
  200. await assertThat(self.recorder.status, .is(.nil()))
  201. await assertThat(self.recorder.trailers, .is(.nil()))
  202. } }
  203. func testFinishAfterHeaders() { XCTAsyncTest {
  204. let handler = self.makeHandler(observer: self.echo(requests:responseStreamWriter:context:))
  205. handler.receiveMetadata([:])
  206. // Wait for the async user function to have processed the metadata.
  207. try self.recorder.recordedMetadataPromise.futureResult.wait()
  208. await assertThat(self.recorder.metadata, .is([:]))
  209. handler.finish()
  210. // Wait for tasks to finish.
  211. await handler.userHandlerTask?.value
  212. await assertThat(self.recorder.messages, .isEmpty())
  213. await assertThat(self.recorder.status, .notNil(.hasCode(.unavailable)))
  214. await assertThat(self.recorder.trailers, .is([:]))
  215. } }
  216. func testFinishAfterMessage() { XCTAsyncTest {
  217. let handler = self.makeHandler(observer: self.echo(requests:responseStreamWriter:context:))
  218. handler.receiveMetadata([:])
  219. handler.receiveMessage(ByteBuffer(string: "hello"))
  220. // Wait for the async user function to have processed the message.
  221. try self.recorder.recordedMessagePromise.futureResult.wait()
  222. handler.finish()
  223. // Wait for tasks to finish.
  224. await handler.userHandlerTask?.value
  225. await assertThat(self.recorder.messages.first, .is(ByteBuffer(string: "hello")))
  226. await assertThat(self.recorder.status, .notNil(.hasCode(.unavailable)))
  227. await assertThat(self.recorder.trailers, .is([:]))
  228. } }
  229. func testHandlerThrowsGRPCStatusOKResultsInUnknownStatus() { XCTAsyncTest {
  230. // Create a user function that immediately throws GRPCStatus.ok.
  231. let handler = self.makeHandler { _, _, _ in
  232. throw GRPCStatus.ok
  233. }
  234. // Send some metadata to trigger the creation of the async task with the user function.
  235. handler.receiveMetadata([:])
  236. // Wait for user handler to finish (it's gonna throw immediately).
  237. await assertThat(await handler.userHandlerTask?.value, .notNil())
  238. // Check the status is `.unknown`.
  239. await assertThat(self.recorder.status, .notNil(.hasCode(.unknown)))
  240. } }
  241. // TODO: We should be consistent about where we put the tasks... maybe even use a task group to simplify cancellation (unless they both go in the enum state which might be better).
  242. func testResponseStreamDrain() { XCTAsyncTest {
  243. // Set up echo handler.
  244. let handler = self.makeHandler(
  245. observer: self.echo(requests:responseStreamWriter:context:)
  246. )
  247. // Send some metadata to trigger the creation of the async task with the user function.
  248. handler.receiveMetadata([:])
  249. // Send two requests and end, pausing the writer in the middle.
  250. switch handler.state {
  251. case let .active(_, _, responseStreamWriter, promise):
  252. handler.receiveMessage(ByteBuffer(string: "diaz"))
  253. await responseStreamWriter.asyncWriter.toggleWritability()
  254. handler.receiveMessage(ByteBuffer(string: "santiago"))
  255. handler.receiveEnd()
  256. await responseStreamWriter.asyncWriter.toggleWritability()
  257. await handler.userHandlerTask?.value
  258. _ = try await promise.futureResult.get()
  259. default:
  260. XCTFail("Unexpected handler state: \(handler.state)")
  261. }
  262. handler.finish()
  263. await assertThat(self.recorder.messages, .is([
  264. ByteBuffer(string: "diaz"),
  265. ByteBuffer(string: "santiago"),
  266. ]))
  267. await assertThat(self.recorder.status, .notNil(.hasCode(.ok)))
  268. } }
  269. }
  270. #endif