ServerHandlerStateMachineTests.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /*
  2. * Copyright 2022, 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 NIOEmbedded
  20. import NIOHPACK
  21. import XCTest
  22. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  23. internal final class ServerHandlerStateMachineTests: GRPCTestCase {
  24. private enum InitialState {
  25. case idle
  26. case handling
  27. case draining
  28. case finished
  29. }
  30. private func makeStateMachine(inState state: InitialState = .idle) -> ServerHandlerStateMachine {
  31. var stateMachine = ServerHandlerStateMachine()
  32. switch state {
  33. case .idle:
  34. return stateMachine
  35. case .handling:
  36. stateMachine.handleMetadata().assertInvokeHandler()
  37. stateMachine.handlerInvoked(requestHeaders: [:])
  38. return stateMachine
  39. case .draining:
  40. stateMachine.handleMetadata().assertInvokeHandler()
  41. stateMachine.handlerInvoked(requestHeaders: [:])
  42. stateMachine.handleEnd().assertForward()
  43. return stateMachine
  44. case .finished:
  45. stateMachine.cancel().assertNone()
  46. return stateMachine
  47. }
  48. }
  49. private func makeCallHandlerContext() -> CallHandlerContext {
  50. let loop = EmbeddedEventLoop()
  51. defer {
  52. try! loop.syncShutdownGracefully()
  53. }
  54. return CallHandlerContext(
  55. logger: self.logger,
  56. encoding: .disabled,
  57. eventLoop: loop,
  58. path: "",
  59. responseWriter: NoOpResponseWriter(),
  60. allocator: ByteBufferAllocator(),
  61. closeFuture: loop.makeSucceededVoidFuture()
  62. )
  63. }
  64. // MARK: - Test Cases
  65. func testHandleMetadataWhenIdle() {
  66. var stateMachine = self.makeStateMachine()
  67. // Receiving metadata is the signal to invoke the user handler.
  68. stateMachine.handleMetadata().assertInvokeHandler()
  69. // On invoking the handler we move to the next state. No output.
  70. stateMachine.handlerInvoked(requestHeaders: [:])
  71. }
  72. func testHandleMetadataWhenHandling() {
  73. var stateMachine = self.makeStateMachine(inState: .handling)
  74. // Must not receive metadata more than once.
  75. stateMachine.handleMetadata().assertInvokeCancel()
  76. }
  77. func testHandleMetadataWhenDraining() {
  78. var stateMachine = self.makeStateMachine(inState: .draining)
  79. // We can't receive metadata more than once.
  80. stateMachine.handleMetadata().assertInvokeCancel()
  81. }
  82. func testHandleMetadataWhenFinished() {
  83. var stateMachine = self.makeStateMachine(inState: .finished)
  84. // We can't receive anything when finished.
  85. stateMachine.handleMetadata().assertInvokeCancel()
  86. }
  87. func testHandleMessageWhenIdle() {
  88. var stateMachine = self.makeStateMachine()
  89. // Metadata must be received first.
  90. stateMachine.handleMessage().assertCancel()
  91. }
  92. func testHandleMessageWhenHandling() {
  93. var stateMachine = self.makeStateMachine(inState: .handling)
  94. // Messages are good, we can forward those while handling.
  95. for _ in 0 ..< 10 {
  96. stateMachine.handleMessage().assertForward()
  97. }
  98. }
  99. func testHandleMessageWhenDraining() {
  100. var stateMachine = self.makeStateMachine(inState: .draining)
  101. // We entered the 'draining' state as we received 'end', another message is a protocol
  102. // violation so cancel.
  103. stateMachine.handleMessage().assertCancel()
  104. }
  105. func testHandleMessageWhenFinished() {
  106. var stateMachine = self.makeStateMachine(inState: .finished)
  107. // We can't receive anything when finished.
  108. stateMachine.handleMessage().assertCancel()
  109. }
  110. func testHandleEndWhenIdle() {
  111. var stateMachine = self.makeStateMachine()
  112. // Metadata must be received first.
  113. stateMachine.handleEnd().assertCancel()
  114. }
  115. func testHandleEndWhenHandling() {
  116. var stateMachine = self.makeStateMachine(inState: .handling)
  117. // End is good; it transitions us to the draining state.
  118. stateMachine.handleEnd().assertForward()
  119. }
  120. func testHandleEndWhenDraining() {
  121. var stateMachine = self.makeStateMachine(inState: .draining)
  122. // We entered the 'draining' state as we received 'end', another 'end' is a protocol
  123. // violation so cancel.
  124. stateMachine.handleEnd().assertCancel()
  125. }
  126. func testHandleEndWhenFinished() {
  127. var stateMachine = self.makeStateMachine(inState: .finished)
  128. // We can't receive anything when finished.
  129. stateMachine.handleEnd().assertCancel()
  130. }
  131. func testSendMessageWhenHandling() {
  132. var stateMachine = self.makeStateMachine(inState: .handling)
  133. // The first message should prompt headers to be sent as well.
  134. stateMachine.sendMessage().assertInterceptHeadersThenMessage()
  135. // Additional messages should be just the message.
  136. stateMachine.sendMessage().assertInterceptMessage()
  137. }
  138. func testSendMessageWhenDraining() {
  139. var stateMachine = self.makeStateMachine(inState: .draining)
  140. // The first message should prompt headers to be sent as well.
  141. stateMachine.sendMessage().assertInterceptHeadersThenMessage()
  142. // Additional messages should be just the message.
  143. stateMachine.sendMessage().assertInterceptMessage()
  144. }
  145. func testSendMessageWhenFinished() {
  146. var stateMachine = self.makeStateMachine(inState: .finished)
  147. // We can't send anything if we're finished.
  148. stateMachine.sendMessage().assertDrop()
  149. }
  150. func testSendStatusWhenHandling() {
  151. var stateMachine = self.makeStateMachine(inState: .handling)
  152. // This moves the state machine to the 'finished' state.
  153. stateMachine.sendStatus().assertIntercept()
  154. }
  155. func testSendStatusWhenDraining() {
  156. var stateMachine = self.makeStateMachine(inState: .draining)
  157. // This moves the state machine to the 'finished' state.
  158. stateMachine.sendStatus().assertIntercept()
  159. }
  160. func testSendStatusWhenFinished() {
  161. var stateMachine = self.makeStateMachine(inState: .finished)
  162. // We can't send anything if we're finished.
  163. stateMachine.sendStatus().assertDrop()
  164. }
  165. func testCancelWhenIdle() {
  166. var stateMachine = self.makeStateMachine()
  167. // Cancelling when idle is effectively a no-op; there's nothing to cancel.
  168. stateMachine.cancel().assertNone()
  169. }
  170. func testCancelWhenHandling() {
  171. var stateMachine = self.makeStateMachine(inState: .handling)
  172. // We have things to cancel in this state.
  173. stateMachine.cancel().assertDoCancel()
  174. }
  175. func testCancelWhenDraining() {
  176. var stateMachine = self.makeStateMachine(inState: .draining)
  177. // We have things to cancel in this state.
  178. stateMachine.cancel().assertDoCancel()
  179. }
  180. func testCancelWhenFinished() {
  181. var stateMachine = self.makeStateMachine(inState: .finished)
  182. stateMachine.cancel().assertDoCancel()
  183. }
  184. func testSetResponseHeadersWhenHandling() {
  185. var stateMachine = self.makeStateMachine(inState: .handling)
  186. stateMachine.setResponseHeaders(["foo": "bar"])
  187. stateMachine.sendMessage().assertInterceptHeadersThenMessage { headers in
  188. XCTAssertEqual(headers, ["foo": "bar"])
  189. }
  190. }
  191. func testSetResponseHeadersWhenHandlingAreMovedToDraining() {
  192. var stateMachine = self.makeStateMachine(inState: .handling)
  193. stateMachine.setResponseHeaders(["foo": "bar"])
  194. stateMachine.handleEnd().assertForward()
  195. stateMachine.sendMessage().assertInterceptHeadersThenMessage { headers in
  196. XCTAssertEqual(headers, ["foo": "bar"])
  197. }
  198. }
  199. func testSetResponseHeadersWhenDraining() {
  200. var stateMachine = self.makeStateMachine(inState: .draining)
  201. stateMachine.setResponseHeaders(["foo": "bar"])
  202. stateMachine.sendMessage().assertInterceptHeadersThenMessage { headers in
  203. XCTAssertEqual(headers, ["foo": "bar"])
  204. }
  205. }
  206. func testSetResponseHeadersWhenFinished() {
  207. var stateMachine = self.makeStateMachine(inState: .finished)
  208. stateMachine.setResponseHeaders(["foo": "bar"])
  209. // Nothing we can assert on, only that we don't crash.
  210. }
  211. func testSetResponseTrailersWhenHandling() {
  212. var stateMachine = self.makeStateMachine(inState: .handling)
  213. stateMachine.setResponseTrailers(["foo": "bar"])
  214. stateMachine.sendStatus().assertIntercept { trailers in
  215. XCTAssertEqual(trailers, ["foo": "bar"])
  216. }
  217. }
  218. func testSetResponseTrailersWhenDraining() {
  219. var stateMachine = self.makeStateMachine(inState: .draining)
  220. stateMachine.setResponseTrailers(["foo": "bar"])
  221. stateMachine.sendStatus().assertIntercept { trailers in
  222. XCTAssertEqual(trailers, ["foo": "bar"])
  223. }
  224. }
  225. func testSetResponseTrailersWhenFinished() {
  226. var stateMachine = self.makeStateMachine(inState: .finished)
  227. stateMachine.setResponseTrailers(["foo": "bar"])
  228. // Nothing we can assert on, only that we don't crash.
  229. }
  230. }
  231. // MARK: - Action Assertions
  232. extension ServerHandlerStateMachine.HandleMetadataAction {
  233. func assertInvokeHandler() {
  234. XCTAssertEqual(self, .invokeHandler)
  235. }
  236. func assertInvokeCancel() {
  237. XCTAssertEqual(self, .cancel)
  238. }
  239. }
  240. extension ServerHandlerStateMachine.HandleMessageAction {
  241. func assertForward() {
  242. XCTAssertEqual(self, .forward)
  243. }
  244. func assertCancel() {
  245. XCTAssertEqual(self, .cancel)
  246. }
  247. }
  248. extension ServerHandlerStateMachine.SendMessageAction {
  249. func assertInterceptHeadersThenMessage(_ verify: (HPACKHeaders) -> Void = { _ in }) {
  250. switch self {
  251. case let .intercept(headers: .some(headers)):
  252. verify(headers)
  253. default:
  254. XCTFail("Expected .intercept(.some) but got \(self)")
  255. }
  256. }
  257. func assertInterceptMessage() {
  258. XCTAssertEqual(self, .intercept(headers: nil))
  259. }
  260. func assertDrop() {
  261. XCTAssertEqual(self, .drop)
  262. }
  263. }
  264. extension ServerHandlerStateMachine.SendStatusAction {
  265. func assertIntercept(_ verify: (HPACKHeaders) -> Void = { _ in }) {
  266. switch self {
  267. case let .intercept(_, trailers: trailers):
  268. verify(trailers)
  269. case .drop:
  270. XCTFail("Expected .intercept but got .drop")
  271. }
  272. }
  273. func assertDrop() {
  274. XCTAssertEqual(self, .drop)
  275. }
  276. }
  277. extension ServerHandlerStateMachine.CancelAction {
  278. func assertNone() {
  279. XCTAssertEqual(self, .none)
  280. }
  281. func assertDoCancel() {
  282. XCTAssertEqual(self, .cancelAndNilOutHandlerComponents)
  283. }
  284. }
  285. #endif // compiler(>=5.6)