GRPCStreamStateMachineTests.swift 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369
  1. /*
  2. * Copyright 2024, 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 GRPCCore
  17. import NIOCore
  18. import NIOHPACK
  19. import XCTest
  20. @testable import GRPCHTTP2Core
  21. private enum TargetStateMachineState: CaseIterable {
  22. case clientIdleServerIdle
  23. case clientOpenServerIdle
  24. case clientOpenServerOpen
  25. case clientOpenServerClosed
  26. case clientClosedServerIdle
  27. case clientClosedServerOpen
  28. case clientClosedServerClosed
  29. }
  30. extension HPACKHeaders {
  31. // Client
  32. fileprivate static let clientInitialMetadata: Self = [
  33. GRPCHTTP2Keys.path.rawValue: "test/test",
  34. GRPCHTTP2Keys.scheme.rawValue: "http",
  35. GRPCHTTP2Keys.method.rawValue: "POST",
  36. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  37. GRPCHTTP2Keys.te.rawValue: "trailers",
  38. ]
  39. fileprivate static let clientInitialMetadataWithDeflateCompression: Self = [
  40. GRPCHTTP2Keys.path.rawValue: "test/test",
  41. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  42. GRPCHTTP2Keys.method.rawValue: "POST",
  43. GRPCHTTP2Keys.scheme.rawValue: "https",
  44. GRPCHTTP2Keys.te.rawValue: "trailers",
  45. GRPCHTTP2Keys.acceptEncoding.rawValue: "deflate",
  46. GRPCHTTP2Keys.encoding.rawValue: "deflate",
  47. ]
  48. fileprivate static let clientInitialMetadataWithGzipCompression: Self = [
  49. GRPCHTTP2Keys.path.rawValue: "test/test",
  50. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  51. GRPCHTTP2Keys.method.rawValue: "POST",
  52. GRPCHTTP2Keys.scheme.rawValue: "https",
  53. GRPCHTTP2Keys.te.rawValue: "trailers",
  54. GRPCHTTP2Keys.acceptEncoding.rawValue: "gzip",
  55. GRPCHTTP2Keys.encoding.rawValue: "gzip",
  56. ]
  57. fileprivate static let receivedWithoutContentType: Self = [
  58. GRPCHTTP2Keys.path.rawValue: "test/test"
  59. ]
  60. fileprivate static let receivedWithInvalidContentType: Self = [
  61. GRPCHTTP2Keys.path.rawValue: "test/test",
  62. GRPCHTTP2Keys.contentType.rawValue: "invalid/invalid",
  63. ]
  64. fileprivate static let receivedWithoutEndpoint: Self = [
  65. GRPCHTTP2Keys.contentType.rawValue: "application/grpc"
  66. ]
  67. fileprivate static let receivedWithoutTE: Self = [
  68. GRPCHTTP2Keys.path.rawValue: "test/test",
  69. GRPCHTTP2Keys.scheme.rawValue: "http",
  70. GRPCHTTP2Keys.method.rawValue: "POST",
  71. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  72. ]
  73. fileprivate static let receivedWithInvalidTE: Self = [
  74. GRPCHTTP2Keys.path.rawValue: "test/test",
  75. GRPCHTTP2Keys.scheme.rawValue: "http",
  76. GRPCHTTP2Keys.method.rawValue: "POST",
  77. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  78. GRPCHTTP2Keys.te.rawValue: "invalidte",
  79. ]
  80. fileprivate static let receivedWithoutMethod: Self = [
  81. GRPCHTTP2Keys.path.rawValue: "test/test",
  82. GRPCHTTP2Keys.scheme.rawValue: "http",
  83. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  84. GRPCHTTP2Keys.te.rawValue: "trailers",
  85. ]
  86. fileprivate static let receivedWithInvalidMethod: Self = [
  87. GRPCHTTP2Keys.path.rawValue: "test/test",
  88. GRPCHTTP2Keys.scheme.rawValue: "http",
  89. GRPCHTTP2Keys.method.rawValue: "GET",
  90. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  91. GRPCHTTP2Keys.te.rawValue: "trailers",
  92. ]
  93. fileprivate static let receivedWithoutScheme: Self = [
  94. GRPCHTTP2Keys.path.rawValue: "test/test",
  95. GRPCHTTP2Keys.method.rawValue: "POST",
  96. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  97. GRPCHTTP2Keys.te.rawValue: "trailers",
  98. ]
  99. fileprivate static let receivedWithInvalidScheme: Self = [
  100. GRPCHTTP2Keys.path.rawValue: "test/test",
  101. GRPCHTTP2Keys.scheme.rawValue: "invalidscheme",
  102. GRPCHTTP2Keys.method.rawValue: "POST",
  103. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  104. GRPCHTTP2Keys.te.rawValue: "trailers",
  105. ]
  106. // Server
  107. fileprivate static let serverInitialMetadata: Self = [
  108. GRPCHTTP2Keys.status.rawValue: "200",
  109. GRPCHTTP2Keys.contentType.rawValue: ContentType.grpc.canonicalValue,
  110. GRPCHTTP2Keys.acceptEncoding.rawValue: "deflate",
  111. ]
  112. fileprivate static let serverInitialMetadataWithDeflateCompression: Self = [
  113. GRPCHTTP2Keys.status.rawValue: "200",
  114. GRPCHTTP2Keys.contentType.rawValue: ContentType.grpc.canonicalValue,
  115. GRPCHTTP2Keys.encoding.rawValue: "deflate",
  116. GRPCHTTP2Keys.acceptEncoding.rawValue: "deflate",
  117. ]
  118. fileprivate static let serverTrailers: Self = [
  119. GRPCHTTP2Keys.status.rawValue: "200",
  120. GRPCHTTP2Keys.contentType.rawValue: ContentType.grpc.canonicalValue,
  121. GRPCHTTP2Keys.grpcStatus.rawValue: "0",
  122. ]
  123. }
  124. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  125. final class GRPCStreamClientStateMachineTests: XCTestCase {
  126. private func makeClientStateMachine(
  127. targetState: TargetStateMachineState,
  128. compressionEnabled: Bool = false
  129. ) -> GRPCStreamStateMachine {
  130. var stateMachine = GRPCStreamStateMachine(
  131. configuration: .client(
  132. .init(
  133. methodDescriptor: .init(service: "test", method: "test"),
  134. scheme: .http,
  135. outboundEncoding: compressionEnabled ? .deflate : .identity,
  136. acceptedEncodings: [.deflate]
  137. )
  138. ),
  139. maximumPayloadSize: 100,
  140. skipAssertions: true
  141. )
  142. let serverMetadata: HPACKHeaders =
  143. compressionEnabled ? .serverInitialMetadataWithDeflateCompression : .serverInitialMetadata
  144. switch targetState {
  145. case .clientIdleServerIdle:
  146. break
  147. case .clientOpenServerIdle:
  148. // Open client
  149. XCTAssertNoThrow(try stateMachine.send(metadata: []))
  150. case .clientOpenServerOpen:
  151. // Open client
  152. XCTAssertNoThrow(try stateMachine.send(metadata: []))
  153. // Open server
  154. XCTAssertNoThrow(try stateMachine.receive(headers: serverMetadata, endStream: false))
  155. case .clientOpenServerClosed:
  156. // Open client
  157. XCTAssertNoThrow(try stateMachine.send(metadata: []))
  158. // Open server
  159. XCTAssertNoThrow(try stateMachine.receive(headers: serverMetadata, endStream: false))
  160. // Close server
  161. XCTAssertNoThrow(try stateMachine.receive(headers: .serverTrailers, endStream: true))
  162. case .clientClosedServerIdle:
  163. // Open client
  164. XCTAssertNoThrow(try stateMachine.send(metadata: []))
  165. // Close client
  166. XCTAssertNoThrow(try stateMachine.closeOutbound())
  167. case .clientClosedServerOpen:
  168. // Open client
  169. XCTAssertNoThrow(try stateMachine.send(metadata: []))
  170. // Open server
  171. XCTAssertNoThrow(try stateMachine.receive(headers: serverMetadata, endStream: false))
  172. // Close client
  173. XCTAssertNoThrow(try stateMachine.closeOutbound())
  174. case .clientClosedServerClosed:
  175. // Open client
  176. XCTAssertNoThrow(try stateMachine.send(metadata: []))
  177. // Open server
  178. XCTAssertNoThrow(try stateMachine.receive(headers: serverMetadata, endStream: false))
  179. // Close client
  180. XCTAssertNoThrow(try stateMachine.closeOutbound())
  181. // Close server
  182. XCTAssertNoThrow(try stateMachine.receive(headers: .serverTrailers, endStream: true))
  183. }
  184. return stateMachine
  185. }
  186. // - MARK: Send Metadata
  187. func testSendMetadataWhenClientIdleAndServerIdle() throws {
  188. var stateMachine = self.makeClientStateMachine(targetState: .clientIdleServerIdle)
  189. XCTAssertNoThrow(try stateMachine.send(metadata: []))
  190. }
  191. func testSendMetadataWhenClientAlreadyOpen() throws {
  192. for targetState in [
  193. TargetStateMachineState.clientOpenServerIdle, .clientOpenServerOpen, .clientOpenServerClosed,
  194. ] {
  195. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  196. // Try sending metadata again: should throw
  197. XCTAssertThrowsError(ofType: RPCError.self, try stateMachine.send(metadata: .init())) {
  198. error in
  199. XCTAssertEqual(error.code, .internalError)
  200. XCTAssertEqual(error.message, "Client is already open: shouldn't be sending metadata.")
  201. }
  202. }
  203. }
  204. func testSendMetadataWhenClientAlreadyClosed() throws {
  205. for targetState in [
  206. TargetStateMachineState.clientClosedServerIdle, .clientClosedServerOpen,
  207. .clientClosedServerClosed,
  208. ] {
  209. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  210. // Try sending metadata again: should throw
  211. XCTAssertThrowsError(ofType: RPCError.self, try stateMachine.send(metadata: .init())) {
  212. error in
  213. XCTAssertEqual(error.code, .internalError)
  214. XCTAssertEqual(error.message, "Client is closed: can't send metadata.")
  215. }
  216. }
  217. }
  218. // - MARK: Send Message
  219. func testSendMessageWhenClientIdleAndServerIdle() {
  220. var stateMachine = self.makeClientStateMachine(targetState: .clientIdleServerIdle)
  221. // Try to send a message without opening (i.e. without sending initial metadata)
  222. XCTAssertThrowsError(
  223. ofType: RPCError.self,
  224. try stateMachine.send(message: [])
  225. ) { error in
  226. XCTAssertEqual(error.code, .internalError)
  227. XCTAssertEqual(error.message, "Client not yet open.")
  228. }
  229. }
  230. func testSendMessageWhenClientOpen() {
  231. for targetState in [
  232. TargetStateMachineState.clientOpenServerIdle, .clientOpenServerOpen, .clientOpenServerClosed,
  233. ] {
  234. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  235. // Now send a message
  236. XCTAssertNoThrow(try stateMachine.send(message: []))
  237. }
  238. }
  239. func testSendMessageWhenClientClosed() {
  240. for targetState in [
  241. TargetStateMachineState.clientClosedServerIdle, .clientClosedServerOpen,
  242. .clientClosedServerClosed,
  243. ] {
  244. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  245. // Try sending another message: it should fail
  246. XCTAssertThrowsError(
  247. ofType: RPCError.self,
  248. try stateMachine.send(message: [])
  249. ) { error in
  250. XCTAssertEqual(error.code, .internalError)
  251. XCTAssertEqual(error.message, "Client is closed, cannot send a message.")
  252. }
  253. }
  254. }
  255. // - MARK: Send Status and Trailers
  256. func testSendStatusAndTrailers() {
  257. for targetState in TargetStateMachineState.allCases {
  258. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  259. // This operation is never allowed on the client.
  260. XCTAssertThrowsError(
  261. ofType: RPCError.self,
  262. try stateMachine.send(
  263. status: Status(code: .ok, message: ""),
  264. metadata: .init()
  265. )
  266. ) { error in
  267. XCTAssertEqual(error.code, .internalError)
  268. XCTAssertEqual(error.message, "Client cannot send status and trailer.")
  269. }
  270. }
  271. }
  272. // - MARK: Receive initial metadata
  273. func testReceiveInitialMetadataWhenClientIdleAndServerIdle() {
  274. var stateMachine = self.makeClientStateMachine(targetState: .clientIdleServerIdle)
  275. XCTAssertThrowsError(
  276. ofType: RPCError.self,
  277. try stateMachine.receive(headers: .init(), endStream: false)
  278. ) { error in
  279. XCTAssertEqual(error.code, .internalError)
  280. XCTAssertEqual(error.message, "Server cannot have sent metadata if the client is idle.")
  281. }
  282. }
  283. func testReceiveInvalidInitialMetadataWhenServerIdle() throws {
  284. for targetState in [
  285. TargetStateMachineState.clientOpenServerIdle, .clientClosedServerIdle,
  286. ] {
  287. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  288. // Receive metadata with unexpected non-200 status code
  289. let action = try stateMachine.receive(
  290. headers: [GRPCHTTP2Keys.status.rawValue: "300"],
  291. endStream: false
  292. )
  293. XCTAssertEqual(
  294. action,
  295. .receivedStatusAndMetadata(
  296. status: .init(code: .unknown, message: "Unexpected non-200 HTTP Status Code."),
  297. metadata: [":status": "300"]
  298. )
  299. )
  300. }
  301. }
  302. func testReceiveInitialMetadataWhenServerIdle() throws {
  303. for targetState in [
  304. TargetStateMachineState.clientOpenServerIdle, .clientClosedServerIdle,
  305. ] {
  306. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  307. // Receive metadata = open server
  308. let action = try stateMachine.receive(
  309. headers: [
  310. GRPCHTTP2Keys.status.rawValue: "200",
  311. GRPCHTTP2Keys.contentType.rawValue: ContentType.grpc.canonicalValue,
  312. GRPCHTTP2Keys.encoding.rawValue: "deflate",
  313. "custom": "123",
  314. "custom-bin": String(base64Encoding: [42, 43, 44]),
  315. ],
  316. endStream: false
  317. )
  318. var expectedMetadata: Metadata = [
  319. ":status": "200",
  320. "content-type": "application/grpc",
  321. "grpc-encoding": "deflate",
  322. "custom": "123",
  323. ]
  324. expectedMetadata.addBinary([42, 43, 44], forKey: "custom-bin")
  325. XCTAssertEqual(action, .receivedMetadata(expectedMetadata))
  326. }
  327. }
  328. func testReceiveInitialMetadataWhenServerOpen() throws {
  329. for targetState in [
  330. TargetStateMachineState.clientOpenServerOpen, .clientClosedServerOpen,
  331. ] {
  332. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  333. // Receiving initial metadata again should throw if grpc-status is not present.
  334. XCTAssertThrowsError(
  335. ofType: RPCError.self,
  336. try stateMachine.receive(
  337. headers: [
  338. GRPCHTTP2Keys.status.rawValue: "200",
  339. GRPCHTTP2Keys.contentType.rawValue: ContentType.grpc.canonicalValue,
  340. GRPCHTTP2Keys.encoding.rawValue: "deflate",
  341. "custom": "123",
  342. "custom-bin": String(base64Encoding: [42, 43, 44]),
  343. ],
  344. endStream: false
  345. )
  346. ) { error in
  347. XCTAssertEqual(error.code, .unknown)
  348. XCTAssertEqual(
  349. error.message,
  350. "Non-initial metadata must be a trailer containing a valid grpc-status"
  351. )
  352. }
  353. // Now make sure everything works well if we include grpc-status
  354. let action = try stateMachine.receive(
  355. headers: [
  356. GRPCHTTP2Keys.status.rawValue: "200",
  357. GRPCHTTP2Keys.grpcStatus.rawValue: String(Status.Code.ok.rawValue),
  358. GRPCHTTP2Keys.contentType.rawValue: ContentType.grpc.canonicalValue,
  359. GRPCHTTP2Keys.encoding.rawValue: "deflate",
  360. "custom": "123",
  361. "custom-bin": String(base64Encoding: [42, 43, 44]),
  362. ],
  363. endStream: false
  364. )
  365. var expectedMetadata: Metadata = [
  366. ":status": "200",
  367. "content-type": "application/grpc",
  368. "grpc-encoding": "deflate",
  369. "custom": "123",
  370. ]
  371. expectedMetadata.removeAllValues(forKey: GRPCHTTP2Keys.grpcStatus.rawValue)
  372. expectedMetadata.addBinary([42, 43, 44], forKey: "custom-bin")
  373. XCTAssertEqual(
  374. action,
  375. .receivedStatusAndMetadata(
  376. status: Status(code: .ok, message: ""),
  377. metadata: expectedMetadata
  378. )
  379. )
  380. }
  381. }
  382. func testReceiveInitialMetadataWhenServerClosed() {
  383. for targetState in [TargetStateMachineState.clientOpenServerClosed, .clientClosedServerClosed] {
  384. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  385. XCTAssertThrowsError(
  386. ofType: RPCError.self,
  387. try stateMachine.receive(headers: .init(), endStream: false)
  388. ) { error in
  389. XCTAssertEqual(error.code, .internalError)
  390. XCTAssertEqual(error.message, "Server is closed, nothing could have been sent.")
  391. }
  392. }
  393. }
  394. // - MARK: Receive end trailers
  395. func testReceiveEndTrailerWhenClientIdleAndServerIdle() {
  396. var stateMachine = self.makeClientStateMachine(targetState: .clientIdleServerIdle)
  397. // Receive an end trailer
  398. XCTAssertThrowsError(
  399. ofType: RPCError.self,
  400. try stateMachine.receive(headers: .init(), endStream: true)
  401. ) { error in
  402. XCTAssertEqual(error.code, .internalError)
  403. XCTAssertEqual(error.message, "Server cannot have sent metadata if the client is idle.")
  404. }
  405. }
  406. func testReceiveEndTrailerWhenClientOpenAndServerIdle() throws {
  407. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerIdle)
  408. // Receive a trailers-only response
  409. let trailersOnlyResponse: HPACKHeaders = [
  410. GRPCHTTP2Keys.status.rawValue: "200",
  411. GRPCHTTP2Keys.contentType.rawValue: ContentType.grpc.canonicalValue,
  412. GRPCHTTP2Keys.grpcStatus.rawValue: String(Status.Code.internalError.rawValue),
  413. GRPCHTTP2Keys.grpcStatusMessage.rawValue: GRPCStatusMessageMarshaller.marshall(
  414. "Some status message"
  415. )!,
  416. "custom-key": "custom-value",
  417. ]
  418. let trailers = try stateMachine.receive(headers: trailersOnlyResponse, endStream: true)
  419. switch trailers {
  420. case .receivedStatusAndMetadata(let status, let metadata):
  421. XCTAssertEqual(status, Status(code: .internalError, message: "Some status message"))
  422. XCTAssertEqual(
  423. metadata,
  424. [
  425. ":status": "200",
  426. "content-type": "application/grpc",
  427. "custom-key": "custom-value",
  428. ]
  429. )
  430. case .receivedMetadata, .doNothing, .rejectRPC:
  431. XCTFail("Expected .receivedStatusAndMetadata")
  432. }
  433. }
  434. func testReceiveEndTrailerWhenServerOpen() throws {
  435. for targetState in [TargetStateMachineState.clientOpenServerOpen, .clientClosedServerOpen] {
  436. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  437. // Receive an end trailer
  438. let action = try stateMachine.receive(
  439. headers: [
  440. GRPCHTTP2Keys.status.rawValue: "200",
  441. GRPCHTTP2Keys.grpcStatus.rawValue: String(Status.Code.ok.rawValue),
  442. GRPCHTTP2Keys.contentType.rawValue: ContentType.grpc.canonicalValue,
  443. GRPCHTTP2Keys.encoding.rawValue: "deflate",
  444. "custom": "123",
  445. ],
  446. endStream: true
  447. )
  448. let expectedMetadata: Metadata = [
  449. ":status": "200",
  450. "content-type": "application/grpc",
  451. "grpc-encoding": "deflate",
  452. "custom": "123",
  453. ]
  454. XCTAssertEqual(
  455. action,
  456. .receivedStatusAndMetadata(
  457. status: .init(code: .ok, message: ""),
  458. metadata: expectedMetadata
  459. )
  460. )
  461. }
  462. }
  463. func testReceiveEndTrailerWhenClientOpenAndServerClosed() {
  464. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerClosed)
  465. // Receive another end trailer
  466. XCTAssertThrowsError(
  467. ofType: RPCError.self,
  468. try stateMachine.receive(headers: .init(), endStream: true)
  469. ) { error in
  470. XCTAssertEqual(error.code, .internalError)
  471. XCTAssertEqual(error.message, "Server is closed, nothing could have been sent.")
  472. }
  473. }
  474. func testReceiveEndTrailerWhenClientClosedAndServerIdle() throws {
  475. var stateMachine = self.makeClientStateMachine(targetState: .clientClosedServerIdle)
  476. // Server sends a trailers-only response
  477. let trailersOnlyResponse: HPACKHeaders = [
  478. GRPCHTTP2Keys.status.rawValue: "200",
  479. GRPCHTTP2Keys.contentType.rawValue: ContentType.grpc.canonicalValue,
  480. GRPCHTTP2Keys.grpcStatus.rawValue: String(Status.Code.internalError.rawValue),
  481. GRPCHTTP2Keys.grpcStatusMessage.rawValue: GRPCStatusMessageMarshaller.marshall(
  482. "Some status message"
  483. )!,
  484. "custom-key": "custom-value",
  485. ]
  486. let trailers = try stateMachine.receive(headers: trailersOnlyResponse, endStream: true)
  487. switch trailers {
  488. case .receivedStatusAndMetadata(let status, let metadata):
  489. XCTAssertEqual(status, Status(code: .internalError, message: "Some status message"))
  490. XCTAssertEqual(
  491. metadata,
  492. [
  493. ":status": "200",
  494. "content-type": "application/grpc",
  495. "custom-key": "custom-value",
  496. ]
  497. )
  498. case .receivedMetadata, .doNothing, .rejectRPC:
  499. XCTFail("Expected .receivedStatusAndMetadata")
  500. }
  501. }
  502. func testReceiveEndTrailerWhenClientClosedAndServerClosed() {
  503. var stateMachine = self.makeClientStateMachine(targetState: .clientClosedServerClosed)
  504. // Close server again (endStream = true) and assert we don't throw.
  505. // This can happen if the previous close was caused by a grpc-status header
  506. // and then the server sends an empty frame with EOS set.
  507. XCTAssertEqual(try stateMachine.receive(headers: .init(), endStream: true), .doNothing)
  508. }
  509. // - MARK: Receive message
  510. func testReceiveMessageWhenClientIdleAndServerIdle() {
  511. var stateMachine = self.makeClientStateMachine(targetState: .clientIdleServerIdle)
  512. XCTAssertThrowsError(
  513. ofType: RPCError.self,
  514. try stateMachine.receive(buffer: .init(), endStream: false)
  515. ) { error in
  516. XCTAssertEqual(error.code, .internalError)
  517. XCTAssertEqual(
  518. error.message,
  519. "Cannot have received anything from server if client is not yet open."
  520. )
  521. }
  522. }
  523. func testReceiveMessageWhenServerIdle() {
  524. for targetState in [TargetStateMachineState.clientOpenServerIdle, .clientClosedServerIdle] {
  525. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  526. XCTAssertThrowsError(
  527. ofType: RPCError.self,
  528. try stateMachine.receive(buffer: .init(), endStream: false)
  529. ) { error in
  530. XCTAssertEqual(error.code, .internalError)
  531. XCTAssertEqual(
  532. error.message,
  533. "Server cannot have sent a message before sending the initial metadata."
  534. )
  535. }
  536. }
  537. }
  538. func testReceiveMessageWhenServerOpen() throws {
  539. for targetState in [TargetStateMachineState.clientOpenServerOpen, .clientClosedServerOpen] {
  540. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  541. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: false))
  542. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: true))
  543. }
  544. }
  545. func testReceiveMessageWhenServerClosed() {
  546. for targetState in [TargetStateMachineState.clientOpenServerClosed, .clientClosedServerClosed] {
  547. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  548. XCTAssertThrowsError(
  549. ofType: RPCError.self,
  550. try stateMachine.receive(buffer: .init(), endStream: false)
  551. ) { error in
  552. XCTAssertEqual(error.code, .internalError)
  553. XCTAssertEqual(error.message, "Cannot have received anything from a closed server.")
  554. }
  555. }
  556. }
  557. // - MARK: Next outbound message
  558. func testNextOutboundMessageWhenClientIdleAndServerIdle() {
  559. var stateMachine = self.makeClientStateMachine(targetState: .clientIdleServerIdle)
  560. XCTAssertThrowsError(
  561. ofType: RPCError.self,
  562. try stateMachine.nextOutboundMessage()
  563. ) { error in
  564. XCTAssertEqual(error.code, .internalError)
  565. XCTAssertEqual(error.message, "Client is not open yet.")
  566. }
  567. }
  568. func testNextOutboundMessageWhenClientOpenAndServerOpenOrIdle() throws {
  569. for targetState in [TargetStateMachineState.clientOpenServerIdle, .clientOpenServerOpen] {
  570. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  571. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .awaitMoreMessages)
  572. XCTAssertNoThrow(try stateMachine.send(message: [42, 42]))
  573. let expectedBytes: [UInt8] = [
  574. 0, // compression flag: unset
  575. 0, 0, 0, 2, // message length: 2 bytes
  576. 42, 42, // original message
  577. ]
  578. XCTAssertEqual(
  579. try stateMachine.nextOutboundMessage(),
  580. .sendMessage(ByteBuffer(bytes: expectedBytes))
  581. )
  582. // And then make sure that nothing else is returned anymore
  583. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .awaitMoreMessages)
  584. }
  585. }
  586. func testNextOutboundMessageWhenClientOpenAndServerIdle_WithCompression() throws {
  587. var stateMachine = self.makeClientStateMachine(
  588. targetState: .clientOpenServerIdle,
  589. compressionEnabled: true
  590. )
  591. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .awaitMoreMessages)
  592. let originalMessage = [UInt8]([42, 42, 43, 43])
  593. XCTAssertNoThrow(try stateMachine.send(message: originalMessage))
  594. let request = try stateMachine.nextOutboundMessage()
  595. let framedMessage = try self.frameMessage(originalMessage, compress: true)
  596. XCTAssertEqual(request, .sendMessage(framedMessage))
  597. }
  598. func testNextOutboundMessageWhenClientOpenAndServerOpen_WithCompression() throws {
  599. var stateMachine = self.makeClientStateMachine(
  600. targetState: .clientOpenServerOpen,
  601. compressionEnabled: true
  602. )
  603. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .awaitMoreMessages)
  604. let originalMessage = [UInt8]([42, 42, 43, 43])
  605. XCTAssertNoThrow(try stateMachine.send(message: originalMessage))
  606. let request = try stateMachine.nextOutboundMessage()
  607. let framedMessage = try self.frameMessage(originalMessage, compress: true)
  608. XCTAssertEqual(request, .sendMessage(framedMessage))
  609. }
  610. func testNextOutboundMessageWhenClientOpenAndServerClosed() throws {
  611. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerClosed)
  612. // No more messages to send
  613. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .noMoreMessages)
  614. // Queue a message, but assert the action is .noMoreMessages nevertheless,
  615. // because the server is closed.
  616. XCTAssertNoThrow(try stateMachine.send(message: [42, 42]))
  617. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .noMoreMessages)
  618. }
  619. func testNextOutboundMessageWhenClientClosedAndServerIdle() throws {
  620. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerIdle)
  621. // Send a message and close client
  622. XCTAssertNoThrow(try stateMachine.send(message: [42, 42]))
  623. XCTAssertNoThrow(try stateMachine.closeOutbound())
  624. // Make sure that getting the next outbound message _does_ return the message
  625. // we have enqueued.
  626. let request = try stateMachine.nextOutboundMessage()
  627. let expectedBytes: [UInt8] = [
  628. 0, // compression flag: unset
  629. 0, 0, 0, 2, // message length: 2 bytes
  630. 42, 42, // original message
  631. ]
  632. XCTAssertEqual(request, .sendMessage(ByteBuffer(bytes: expectedBytes)))
  633. // And then make sure that nothing else is returned anymore
  634. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .noMoreMessages)
  635. }
  636. func testNextOutboundMessageWhenClientClosedAndServerOpen() throws {
  637. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerOpen)
  638. // Send a message and close client
  639. XCTAssertNoThrow(try stateMachine.send(message: [42, 42]))
  640. XCTAssertNoThrow(try stateMachine.closeOutbound())
  641. // Make sure that getting the next outbound message _does_ return the message
  642. // we have enqueued.
  643. let request = try stateMachine.nextOutboundMessage()
  644. let expectedBytes: [UInt8] = [
  645. 0, // compression flag: unset
  646. 0, 0, 0, 2, // message length: 2 bytes
  647. 42, 42, // original message
  648. ]
  649. XCTAssertEqual(request, .sendMessage(ByteBuffer(bytes: expectedBytes)))
  650. // And then make sure that nothing else is returned anymore
  651. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .noMoreMessages)
  652. }
  653. func testNextOutboundMessageWhenClientClosedAndServerClosed() throws {
  654. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerOpen)
  655. // Send a message
  656. XCTAssertNoThrow(try stateMachine.send(message: [42, 42]))
  657. // Close server
  658. XCTAssertNoThrow(try stateMachine.receive(headers: .serverTrailers, endStream: true))
  659. // Close client
  660. XCTAssertNoThrow(try stateMachine.closeOutbound())
  661. // Even though we have enqueued a message, don't send it, because the server
  662. // is closed.
  663. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .noMoreMessages)
  664. }
  665. // - MARK: Next inbound message
  666. func testNextInboundMessageWhenServerIdle() {
  667. for targetState in [
  668. TargetStateMachineState.clientIdleServerIdle, .clientOpenServerIdle, .clientClosedServerIdle,
  669. ] {
  670. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  671. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  672. }
  673. }
  674. func testNextInboundMessageWhenClientOpenAndServerOpen() throws {
  675. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerOpen)
  676. let receivedBytes = ByteBuffer(bytes: [
  677. 0, // compression flag: unset
  678. 0, 0, 0, 2, // message length: 2 bytes
  679. 42, 42, // original message
  680. ])
  681. try stateMachine.receive(buffer: receivedBytes, endStream: false)
  682. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage([42, 42]))
  683. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  684. }
  685. func testNextInboundMessageWhenClientOpenAndServerOpen_WithCompression() throws {
  686. var stateMachine = self.makeClientStateMachine(
  687. targetState: .clientOpenServerOpen,
  688. compressionEnabled: true
  689. )
  690. let originalMessage = [UInt8]([42, 42, 43, 43])
  691. let receivedBytes = try self.frameMessage(originalMessage, compress: true)
  692. try stateMachine.receive(buffer: receivedBytes, endStream: false)
  693. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(originalMessage))
  694. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  695. }
  696. func testNextInboundMessageWhenClientOpenAndServerClosed() throws {
  697. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerOpen)
  698. let receivedBytes = ByteBuffer(bytes: [
  699. 0, // compression flag: unset
  700. 0, 0, 0, 2, // message length: 2 bytes
  701. 42, 42, // original message
  702. ])
  703. try stateMachine.receive(buffer: receivedBytes, endStream: false)
  704. // Close server
  705. XCTAssertNoThrow(try stateMachine.receive(headers: .serverTrailers, endStream: true))
  706. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage([42, 42]))
  707. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  708. }
  709. func testNextInboundMessageWhenClientClosedAndServerOpen() throws {
  710. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerOpen)
  711. let receivedBytes = ByteBuffer(bytes: [
  712. 0, // compression flag: unset
  713. 0, 0, 0, 2, // message length: 2 bytes
  714. 42, 42, // original message
  715. ])
  716. try stateMachine.receive(buffer: receivedBytes, endStream: false)
  717. // Close client
  718. XCTAssertNoThrow(try stateMachine.closeOutbound())
  719. // Even though the client is closed, because it received a message while open,
  720. // we must get the message now.
  721. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage([42, 42]))
  722. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  723. }
  724. func testNextInboundMessageWhenClientClosedAndServerClosed() throws {
  725. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerOpen)
  726. let receivedBytes = ByteBuffer(bytes: [
  727. 0, // compression flag: unset
  728. 0, 0, 0, 2, // message length: 2 bytes
  729. 42, 42, // original message
  730. ])
  731. try stateMachine.receive(buffer: receivedBytes, endStream: false)
  732. // Close server
  733. XCTAssertNoThrow(try stateMachine.receive(headers: .serverTrailers, endStream: true))
  734. // Close client
  735. XCTAssertNoThrow(try stateMachine.closeOutbound())
  736. // Even though the client is closed, because it received a message while open,
  737. // we must get the message now.
  738. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage([42, 42]))
  739. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  740. }
  741. // - MARK: Common paths
  742. func testNormalFlow() throws {
  743. var stateMachine = self.makeClientStateMachine(targetState: .clientIdleServerIdle)
  744. // Client sends metadata
  745. let clientInitialMetadata = try stateMachine.send(metadata: .init())
  746. XCTAssertEqual(
  747. clientInitialMetadata,
  748. [
  749. GRPCHTTP2Keys.path.rawValue: "test/test",
  750. GRPCHTTP2Keys.scheme.rawValue: "http",
  751. GRPCHTTP2Keys.method.rawValue: "POST",
  752. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  753. GRPCHTTP2Keys.te.rawValue: "trailers",
  754. GRPCHTTP2Keys.acceptEncoding.rawValue: "deflate",
  755. ]
  756. )
  757. // Server sends initial metadata
  758. let serverInitialHeadersAction = try stateMachine.receive(
  759. headers: .serverInitialMetadata,
  760. endStream: false
  761. )
  762. XCTAssertEqual(
  763. serverInitialHeadersAction,
  764. .receivedMetadata([
  765. ":status": "200",
  766. "content-type": "application/grpc",
  767. "grpc-accept-encoding": "deflate",
  768. ])
  769. )
  770. // Client sends messages
  771. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .awaitMoreMessages)
  772. let message = [UInt8]([1, 2, 3, 4])
  773. let framedMessage = try self.frameMessage(message, compress: false)
  774. try stateMachine.send(message: message)
  775. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .sendMessage(framedMessage))
  776. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .awaitMoreMessages)
  777. // Server sends response
  778. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  779. let firstResponseBytes = [UInt8]([5, 6, 7])
  780. let firstResponse = try self.frameMessage(firstResponseBytes, compress: false)
  781. let secondResponseBytes = [UInt8]([8, 9, 10])
  782. let secondResponse = try self.frameMessage(secondResponseBytes, compress: false)
  783. try stateMachine.receive(buffer: firstResponse, endStream: false)
  784. try stateMachine.receive(buffer: secondResponse, endStream: false)
  785. // Make sure messages have arrived
  786. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(firstResponseBytes))
  787. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(secondResponseBytes))
  788. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  789. // Client sends end
  790. XCTAssertNoThrow(try stateMachine.closeOutbound())
  791. // Server ends
  792. let metadataReceivedAction = try stateMachine.receive(
  793. headers: .serverTrailers,
  794. endStream: true
  795. )
  796. let receivedMetadata = {
  797. var m = Metadata(headers: .serverTrailers)
  798. m.removeAllValues(forKey: GRPCHTTP2Keys.grpcStatus.rawValue)
  799. m.removeAllValues(forKey: GRPCHTTP2Keys.grpcStatusMessage.rawValue)
  800. return m
  801. }()
  802. XCTAssertEqual(
  803. metadataReceivedAction,
  804. .receivedStatusAndMetadata(status: .init(code: .ok, message: ""), metadata: receivedMetadata)
  805. )
  806. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .noMoreMessages)
  807. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  808. }
  809. func testClientClosesBeforeServerOpens() throws {
  810. var stateMachine = self.makeClientStateMachine(targetState: .clientIdleServerIdle)
  811. // Client sends metadata
  812. let clientInitialMetadata = try stateMachine.send(metadata: .init())
  813. XCTAssertEqual(
  814. clientInitialMetadata,
  815. [
  816. GRPCHTTP2Keys.path.rawValue: "test/test",
  817. GRPCHTTP2Keys.scheme.rawValue: "http",
  818. GRPCHTTP2Keys.method.rawValue: "POST",
  819. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  820. GRPCHTTP2Keys.te.rawValue: "trailers",
  821. GRPCHTTP2Keys.acceptEncoding.rawValue: "deflate",
  822. ]
  823. )
  824. // Client sends messages and ends
  825. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .awaitMoreMessages)
  826. let message = [UInt8]([1, 2, 3, 4])
  827. let framedMessage = try self.frameMessage(message, compress: false)
  828. XCTAssertNoThrow(try stateMachine.send(message: message))
  829. XCTAssertNoThrow(try stateMachine.closeOutbound())
  830. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .sendMessage(framedMessage))
  831. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .noMoreMessages)
  832. // Server sends initial metadata
  833. let serverInitialHeadersAction = try stateMachine.receive(
  834. headers: .serverInitialMetadata,
  835. endStream: false
  836. )
  837. XCTAssertEqual(
  838. serverInitialHeadersAction,
  839. .receivedMetadata([
  840. ":status": "200",
  841. "content-type": "application/grpc",
  842. "grpc-accept-encoding": "deflate",
  843. ])
  844. )
  845. // Server sends response
  846. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  847. let firstResponseBytes = [UInt8]([5, 6, 7])
  848. let firstResponse = try self.frameMessage(firstResponseBytes, compress: false)
  849. let secondResponseBytes = [UInt8]([8, 9, 10])
  850. let secondResponse = try self.frameMessage(secondResponseBytes, compress: false)
  851. try stateMachine.receive(buffer: firstResponse, endStream: false)
  852. try stateMachine.receive(buffer: secondResponse, endStream: false)
  853. // Make sure messages have arrived
  854. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(firstResponseBytes))
  855. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(secondResponseBytes))
  856. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  857. // Server ends
  858. let metadataReceivedAction = try stateMachine.receive(
  859. headers: .serverTrailers,
  860. endStream: true
  861. )
  862. let receivedMetadata = {
  863. var m = Metadata(headers: .serverTrailers)
  864. m.removeAllValues(forKey: GRPCHTTP2Keys.grpcStatus.rawValue)
  865. m.removeAllValues(forKey: GRPCHTTP2Keys.grpcStatusMessage.rawValue)
  866. return m
  867. }()
  868. XCTAssertEqual(
  869. metadataReceivedAction,
  870. .receivedStatusAndMetadata(status: .init(code: .ok, message: ""), metadata: receivedMetadata)
  871. )
  872. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .noMoreMessages)
  873. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  874. }
  875. func testClientClosesBeforeServerResponds() throws {
  876. var stateMachine = self.makeClientStateMachine(targetState: .clientIdleServerIdle)
  877. // Client sends metadata
  878. let clientInitialMetadata = try stateMachine.send(metadata: .init())
  879. XCTAssertEqual(
  880. clientInitialMetadata,
  881. [
  882. GRPCHTTP2Keys.path.rawValue: "test/test",
  883. GRPCHTTP2Keys.scheme.rawValue: "http",
  884. GRPCHTTP2Keys.method.rawValue: "POST",
  885. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  886. GRPCHTTP2Keys.te.rawValue: "trailers",
  887. GRPCHTTP2Keys.acceptEncoding.rawValue: "deflate",
  888. ]
  889. )
  890. // Client sends messages
  891. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .awaitMoreMessages)
  892. let message = [UInt8]([1, 2, 3, 4])
  893. let framedMessage = try self.frameMessage(message, compress: false)
  894. try stateMachine.send(message: message)
  895. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .sendMessage(framedMessage))
  896. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .awaitMoreMessages)
  897. // Server sends initial metadata
  898. let serverInitialHeadersAction = try stateMachine.receive(
  899. headers: .serverInitialMetadata,
  900. endStream: false
  901. )
  902. XCTAssertEqual(
  903. serverInitialHeadersAction,
  904. .receivedMetadata([
  905. ":status": "200",
  906. "content-type": "application/grpc",
  907. "grpc-accept-encoding": "deflate",
  908. ])
  909. )
  910. // Client closes
  911. XCTAssertNoThrow(try stateMachine.closeOutbound())
  912. // Server sends response
  913. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  914. let firstResponseBytes = [UInt8]([5, 6, 7])
  915. let firstResponse = try self.frameMessage(firstResponseBytes, compress: false)
  916. let secondResponseBytes = [UInt8]([8, 9, 10])
  917. let secondResponse = try self.frameMessage(secondResponseBytes, compress: false)
  918. try stateMachine.receive(buffer: firstResponse, endStream: false)
  919. try stateMachine.receive(buffer: secondResponse, endStream: false)
  920. // Make sure messages have arrived
  921. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(firstResponseBytes))
  922. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(secondResponseBytes))
  923. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  924. // Server ends
  925. let metadataReceivedAction = try stateMachine.receive(
  926. headers: .serverTrailers,
  927. endStream: true
  928. )
  929. let receivedMetadata = {
  930. var m = Metadata(headers: .serverTrailers)
  931. m.removeAllValues(forKey: GRPCHTTP2Keys.grpcStatus.rawValue)
  932. m.removeAllValues(forKey: GRPCHTTP2Keys.grpcStatusMessage.rawValue)
  933. return m
  934. }()
  935. XCTAssertEqual(
  936. metadataReceivedAction,
  937. .receivedStatusAndMetadata(status: .init(code: .ok, message: ""), metadata: receivedMetadata)
  938. )
  939. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .noMoreMessages)
  940. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  941. }
  942. }
  943. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  944. final class GRPCStreamServerStateMachineTests: XCTestCase {
  945. private func makeServerStateMachine(
  946. targetState: TargetStateMachineState,
  947. compressionEnabled: Bool = false
  948. ) -> GRPCStreamStateMachine {
  949. var stateMachine = GRPCStreamStateMachine(
  950. configuration: .server(
  951. .init(
  952. scheme: .http,
  953. acceptedEncodings: [.deflate]
  954. )
  955. ),
  956. maximumPayloadSize: 100,
  957. skipAssertions: true
  958. )
  959. let clientMetadata: HPACKHeaders =
  960. compressionEnabled ? .clientInitialMetadataWithDeflateCompression : .clientInitialMetadata
  961. switch targetState {
  962. case .clientIdleServerIdle:
  963. break
  964. case .clientOpenServerIdle:
  965. // Open client
  966. XCTAssertNoThrow(try stateMachine.receive(headers: clientMetadata, endStream: false))
  967. case .clientOpenServerOpen:
  968. // Open client
  969. XCTAssertNoThrow(try stateMachine.receive(headers: clientMetadata, endStream: false))
  970. // Open server
  971. XCTAssertNoThrow(try stateMachine.send(metadata: Metadata(headers: .serverInitialMetadata)))
  972. case .clientOpenServerClosed:
  973. // Open client
  974. XCTAssertNoThrow(try stateMachine.receive(headers: clientMetadata, endStream: false))
  975. // Open server
  976. XCTAssertNoThrow(try stateMachine.send(metadata: Metadata(headers: .serverInitialMetadata)))
  977. // Close server
  978. XCTAssertNoThrow(
  979. try stateMachine.send(
  980. status: .init(code: .ok, message: ""),
  981. metadata: []
  982. )
  983. )
  984. case .clientClosedServerIdle:
  985. // Open client
  986. XCTAssertNoThrow(try stateMachine.receive(headers: clientMetadata, endStream: false))
  987. // Close client
  988. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: true))
  989. case .clientClosedServerOpen:
  990. // Open client
  991. XCTAssertNoThrow(try stateMachine.receive(headers: clientMetadata, endStream: false))
  992. // Open server
  993. XCTAssertNoThrow(try stateMachine.send(metadata: Metadata(headers: .serverInitialMetadata)))
  994. // Close client
  995. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: true))
  996. case .clientClosedServerClosed:
  997. // Open client
  998. XCTAssertNoThrow(try stateMachine.receive(headers: clientMetadata, endStream: false))
  999. // Open server
  1000. XCTAssertNoThrow(try stateMachine.send(metadata: Metadata(headers: .serverInitialMetadata)))
  1001. // Close client
  1002. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: true))
  1003. // Close server
  1004. XCTAssertNoThrow(
  1005. try stateMachine.send(
  1006. status: .init(code: .ok, message: ""),
  1007. metadata: []
  1008. )
  1009. )
  1010. }
  1011. return stateMachine
  1012. }
  1013. // - MARK: Send Metadata
  1014. func testSendMetadataWhenClientIdleAndServerIdle() throws {
  1015. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1016. XCTAssertThrowsError(
  1017. ofType: RPCError.self,
  1018. try stateMachine.send(metadata: .init())
  1019. ) { error in
  1020. XCTAssertEqual(error.code, .internalError)
  1021. XCTAssertEqual(
  1022. error.message,
  1023. "Client cannot be idle if server is sending initial metadata: it must have opened."
  1024. )
  1025. }
  1026. }
  1027. func testSendMetadataWhenClientOpenAndServerIdle() throws {
  1028. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerIdle)
  1029. XCTAssertNoThrow(try stateMachine.send(metadata: .init()))
  1030. }
  1031. func testSendMetadataWhenClientOpenAndServerOpen() throws {
  1032. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1033. // Try sending metadata again: should throw
  1034. XCTAssertThrowsError(
  1035. ofType: RPCError.self,
  1036. try stateMachine.send(metadata: .init())
  1037. ) { error in
  1038. XCTAssertEqual(error.code, .internalError)
  1039. XCTAssertEqual(error.message, "Server has already sent initial metadata.")
  1040. }
  1041. }
  1042. func testSendMetadataWhenClientOpenAndServerClosed() throws {
  1043. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerClosed)
  1044. // Try sending metadata again: should throw
  1045. XCTAssertThrowsError(ofType: RPCError.self, try stateMachine.send(metadata: .init())) { error in
  1046. XCTAssertEqual(error.code, .internalError)
  1047. XCTAssertEqual(error.message, "Server cannot send metadata if closed.")
  1048. }
  1049. }
  1050. func testSendMetadataWhenClientClosedAndServerIdle() throws {
  1051. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerIdle)
  1052. // We should be allowed to send initial metadata if client is closed:
  1053. // client may be finished sending request but may still be awaiting response.
  1054. XCTAssertNoThrow(try stateMachine.send(metadata: .init()))
  1055. }
  1056. func testSendMetadataWhenClientClosedAndServerOpen() throws {
  1057. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerOpen)
  1058. // Try sending metadata again: should throw
  1059. XCTAssertThrowsError(ofType: RPCError.self, try stateMachine.send(metadata: .init())) { error in
  1060. XCTAssertEqual(error.code, .internalError)
  1061. XCTAssertEqual(error.message, "Server has already sent initial metadata.")
  1062. }
  1063. }
  1064. func testSendMetadataWhenClientClosedAndServerClosed() throws {
  1065. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerClosed)
  1066. // Try sending metadata again: should throw
  1067. XCTAssertThrowsError(ofType: RPCError.self, try stateMachine.send(metadata: .init())) { error in
  1068. XCTAssertEqual(error.code, .internalError)
  1069. XCTAssertEqual(error.message, "Server cannot send metadata if closed.")
  1070. }
  1071. }
  1072. // - MARK: Send Message
  1073. func testSendMessageWhenClientIdleAndServerIdle() {
  1074. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1075. XCTAssertThrowsError(
  1076. ofType: RPCError.self,
  1077. try stateMachine.send(message: [])
  1078. ) { error in
  1079. XCTAssertEqual(error.code, .internalError)
  1080. XCTAssertEqual(
  1081. error.message,
  1082. "Server must have sent initial metadata before sending a message."
  1083. )
  1084. }
  1085. }
  1086. func testSendMessageWhenClientOpenAndServerIdle() {
  1087. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerIdle)
  1088. // Now send a message
  1089. XCTAssertThrowsError(
  1090. ofType: RPCError.self,
  1091. try stateMachine.send(message: [])
  1092. ) { error in
  1093. XCTAssertEqual(error.code, .internalError)
  1094. XCTAssertEqual(
  1095. error.message,
  1096. "Server must have sent initial metadata before sending a message."
  1097. )
  1098. }
  1099. }
  1100. func testSendMessageWhenClientOpenAndServerOpen() {
  1101. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1102. // Now send a message
  1103. XCTAssertNoThrow(try stateMachine.send(message: []))
  1104. }
  1105. func testSendMessageWhenClientOpenAndServerClosed() {
  1106. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerClosed)
  1107. // Try sending another message: it should fail
  1108. XCTAssertThrowsError(
  1109. ofType: RPCError.self,
  1110. try stateMachine.send(message: [])
  1111. ) { error in
  1112. XCTAssertEqual(error.code, .internalError)
  1113. XCTAssertEqual(error.message, "Server can't send a message if it's closed.")
  1114. }
  1115. }
  1116. func testSendMessageWhenClientClosedAndServerIdle() {
  1117. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerIdle)
  1118. XCTAssertThrowsError(
  1119. ofType: RPCError.self,
  1120. try stateMachine.send(message: [])
  1121. ) { error in
  1122. XCTAssertEqual(error.code, .internalError)
  1123. XCTAssertEqual(
  1124. error.message,
  1125. "Server must have sent initial metadata before sending a message."
  1126. )
  1127. }
  1128. }
  1129. func testSendMessageWhenClientClosedAndServerOpen() {
  1130. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerOpen)
  1131. // Try sending a message: even though client is closed, we should send it
  1132. // because it may be expecting a response.
  1133. XCTAssertNoThrow(try stateMachine.send(message: []))
  1134. }
  1135. func testSendMessageWhenClientClosedAndServerClosed() {
  1136. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerClosed)
  1137. // Try sending another message: it should fail
  1138. XCTAssertThrowsError(
  1139. ofType: RPCError.self,
  1140. try stateMachine.send(message: [])
  1141. ) { error in
  1142. XCTAssertEqual(error.code, .internalError)
  1143. XCTAssertEqual(error.message, "Server can't send a message if it's closed.")
  1144. }
  1145. }
  1146. // - MARK: Send Status and Trailers
  1147. func testSendStatusAndTrailersWhenClientIdle() {
  1148. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1149. XCTAssertThrowsError(
  1150. ofType: RPCError.self,
  1151. try stateMachine.send(
  1152. status: .init(code: .ok, message: ""),
  1153. metadata: .init()
  1154. )
  1155. ) { error in
  1156. XCTAssertEqual(error.code, .internalError)
  1157. XCTAssertEqual(error.message, "Server can't send status if client is idle.")
  1158. }
  1159. }
  1160. func testSendStatusAndTrailersWhenClientOpenAndServerIdle() throws {
  1161. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerIdle)
  1162. let trailers = try stateMachine.send(
  1163. status: .init(code: .unknown, message: "RPC unknown"),
  1164. metadata: .init()
  1165. )
  1166. // Make sure it's a trailers-only response: it must have :status header and content-type
  1167. XCTAssertEqual(
  1168. trailers,
  1169. [
  1170. ":status": "200",
  1171. "content-type": "application/grpc",
  1172. "grpc-status": "2",
  1173. "grpc-status-message": "RPC unknown",
  1174. ]
  1175. )
  1176. // Try sending another message: it should fail because server is now closed.
  1177. XCTAssertThrowsError(
  1178. ofType: RPCError.self,
  1179. try stateMachine.send(message: [])
  1180. ) { error in
  1181. XCTAssertEqual(error.code, .internalError)
  1182. XCTAssertEqual(error.message, "Server can't send a message if it's closed.")
  1183. }
  1184. }
  1185. func testSendStatusAndTrailersWhenClientOpenAndServerOpen() throws {
  1186. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1187. let trailers = try stateMachine.send(
  1188. status: .init(code: .ok, message: ""),
  1189. metadata: .init()
  1190. )
  1191. // Make sure it's NOT a trailers-only response, because the server was
  1192. // already open (so it sent initial metadata): it shouldn't have :status or content-type headers
  1193. XCTAssertEqual(trailers, ["grpc-status": "0"])
  1194. // Try sending another message: it should fail because server is now closed.
  1195. XCTAssertThrowsError(
  1196. ofType: RPCError.self,
  1197. try stateMachine.send(message: [])
  1198. ) { error in
  1199. XCTAssertEqual(error.code, .internalError)
  1200. XCTAssertEqual(error.message, "Server can't send a message if it's closed.")
  1201. }
  1202. }
  1203. func testSendStatusAndTrailersWhenClientOpenAndServerClosed() {
  1204. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerClosed)
  1205. XCTAssertThrowsError(
  1206. ofType: RPCError.self,
  1207. try stateMachine.send(
  1208. status: .init(code: .ok, message: ""),
  1209. metadata: .init()
  1210. )
  1211. ) { error in
  1212. XCTAssertEqual(error.code, .internalError)
  1213. XCTAssertEqual(error.message, "Server can't send anything if closed.")
  1214. }
  1215. }
  1216. func testSendStatusAndTrailersWhenClientClosedAndServerIdle() throws {
  1217. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerIdle)
  1218. let trailers = try stateMachine.send(
  1219. status: .init(code: .unknown, message: "RPC unknown"),
  1220. metadata: .init()
  1221. )
  1222. // Make sure it's a trailers-only response: it must have :status header and content-type
  1223. XCTAssertEqual(
  1224. trailers,
  1225. [
  1226. ":status": "200",
  1227. "content-type": "application/grpc",
  1228. "grpc-status": "2",
  1229. "grpc-status-message": "RPC unknown",
  1230. ]
  1231. )
  1232. // Try sending another message: it should fail because server is now closed.
  1233. XCTAssertThrowsError(
  1234. ofType: RPCError.self,
  1235. try stateMachine.send(message: [])
  1236. ) { error in
  1237. XCTAssertEqual(error.code, .internalError)
  1238. XCTAssertEqual(error.message, "Server can't send a message if it's closed.")
  1239. }
  1240. }
  1241. func testSendStatusAndTrailersWhenClientClosedAndServerOpen() throws {
  1242. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerOpen)
  1243. let trailers = try stateMachine.send(
  1244. status: .init(code: .ok, message: ""),
  1245. metadata: .init()
  1246. )
  1247. // Make sure it's NOT a trailers-only response, because the server was
  1248. // already open (so it sent initial metadata): it shouldn't have :status or content-type headers
  1249. XCTAssertEqual(trailers, ["grpc-status": "0"])
  1250. // Try sending another message: it should fail because server is now closed.
  1251. XCTAssertThrowsError(
  1252. ofType: RPCError.self,
  1253. try stateMachine.send(message: [])
  1254. ) { error in
  1255. XCTAssertEqual(error.code, .internalError)
  1256. XCTAssertEqual(error.message, "Server can't send a message if it's closed.")
  1257. }
  1258. }
  1259. func testSendStatusAndTrailersWhenClientClosedAndServerClosed() {
  1260. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerClosed)
  1261. XCTAssertThrowsError(
  1262. ofType: RPCError.self,
  1263. try stateMachine.send(
  1264. status: .init(code: .ok, message: ""),
  1265. metadata: .init()
  1266. )
  1267. ) { error in
  1268. XCTAssertEqual(error.code, .internalError)
  1269. XCTAssertEqual(error.message, "Server can't send anything if closed.")
  1270. }
  1271. }
  1272. // - MARK: Receive metadata
  1273. func testReceiveMetadataWhenClientIdleAndServerIdle() throws {
  1274. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1275. let action = try stateMachine.receive(headers: .clientInitialMetadata, endStream: false)
  1276. XCTAssertEqual(
  1277. action,
  1278. .receivedMetadata(Metadata(headers: .clientInitialMetadata))
  1279. )
  1280. }
  1281. func testReceiveMetadataWhenClientIdleAndServerIdle_WithEndStream() throws {
  1282. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1283. let action = try stateMachine.receive(headers: .clientInitialMetadata, endStream: true)
  1284. XCTAssertEqual(
  1285. action,
  1286. .receivedMetadata(Metadata(headers: .clientInitialMetadata))
  1287. )
  1288. }
  1289. func testReceiveMetadataWhenClientIdleAndServerIdle_MissingContentType() throws {
  1290. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1291. let action = try stateMachine.receive(
  1292. headers: .receivedWithoutContentType,
  1293. endStream: false
  1294. )
  1295. self.assertRejectedRPC(action) { trailers in
  1296. XCTAssertEqual(trailers.count, 1)
  1297. XCTAssertEqual(trailers.firstString(forKey: .status), "415")
  1298. }
  1299. }
  1300. func testReceiveMetadataWhenClientIdleAndServerIdle_InvalidContentType() throws {
  1301. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1302. let action = try stateMachine.receive(
  1303. headers: .receivedWithInvalidContentType,
  1304. endStream: false
  1305. )
  1306. self.assertRejectedRPC(action) { trailers in
  1307. XCTAssertEqual(trailers.count, 1)
  1308. XCTAssertEqual(trailers.firstString(forKey: .status), "415")
  1309. }
  1310. }
  1311. func testReceiveMetadataWhenClientIdleAndServerIdle_MissingPath() throws {
  1312. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1313. let action = try stateMachine.receive(
  1314. headers: .receivedWithoutEndpoint,
  1315. endStream: false
  1316. )
  1317. self.assertRejectedRPC(action) { trailers in
  1318. XCTAssertEqual(
  1319. trailers,
  1320. [
  1321. ":status": "200",
  1322. "content-type": "application/grpc",
  1323. "grpc-status": "12",
  1324. "grpc-status-message": "No :path header has been set.",
  1325. ]
  1326. )
  1327. }
  1328. }
  1329. func testReceiveMetadataWhenClientIdleAndServerIdle_MissingTE() throws {
  1330. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1331. let action = try stateMachine.receive(
  1332. headers: .receivedWithoutTE,
  1333. endStream: false
  1334. )
  1335. self.assertRejectedRPC(action) { trailers in
  1336. XCTAssertEqual(
  1337. trailers,
  1338. [
  1339. ":status": "200",
  1340. "content-type": "application/grpc",
  1341. "grpc-status": "3",
  1342. "grpc-status-message":
  1343. "\"te\" header is expected to be present and have a value of \"trailers\".",
  1344. ]
  1345. )
  1346. }
  1347. }
  1348. func testReceiveMetadataWhenClientIdleAndServerIdle_InvalidTE() throws {
  1349. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1350. let action = try stateMachine.receive(
  1351. headers: .receivedWithInvalidTE,
  1352. endStream: false
  1353. )
  1354. self.assertRejectedRPC(action) { trailers in
  1355. XCTAssertEqual(
  1356. trailers,
  1357. [
  1358. ":status": "200",
  1359. "content-type": "application/grpc",
  1360. "grpc-status": "3",
  1361. "grpc-status-message":
  1362. "\"te\" header is expected to be present and have a value of \"trailers\".",
  1363. ]
  1364. )
  1365. }
  1366. }
  1367. func testReceiveMetadataWhenClientIdleAndServerIdle_MissingMethod() throws {
  1368. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1369. let action = try stateMachine.receive(
  1370. headers: .receivedWithoutMethod,
  1371. endStream: false
  1372. )
  1373. self.assertRejectedRPC(action) { trailers in
  1374. XCTAssertEqual(
  1375. trailers,
  1376. [
  1377. ":status": "200",
  1378. "content-type": "application/grpc",
  1379. "grpc-status": "3",
  1380. "grpc-status-message":
  1381. ":method header is expected to be present and have a value of \"POST\".",
  1382. ]
  1383. )
  1384. }
  1385. }
  1386. func testReceiveMetadataWhenClientIdleAndServerIdle_InvalidMethod() throws {
  1387. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1388. let action = try stateMachine.receive(
  1389. headers: .receivedWithInvalidMethod,
  1390. endStream: false
  1391. )
  1392. self.assertRejectedRPC(action) { trailers in
  1393. XCTAssertEqual(
  1394. trailers,
  1395. [
  1396. ":status": "200",
  1397. "content-type": "application/grpc",
  1398. "grpc-status": "3",
  1399. "grpc-status-message":
  1400. ":method header is expected to be present and have a value of \"POST\".",
  1401. ]
  1402. )
  1403. }
  1404. }
  1405. func testReceiveMetadataWhenClientIdleAndServerIdle_MissingScheme() throws {
  1406. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1407. let action = try stateMachine.receive(
  1408. headers: .receivedWithoutScheme,
  1409. endStream: false
  1410. )
  1411. self.assertRejectedRPC(action) { trailers in
  1412. XCTAssertEqual(
  1413. trailers,
  1414. [
  1415. ":status": "200",
  1416. "content-type": "application/grpc",
  1417. "grpc-status": "3",
  1418. "grpc-status-message": ":scheme header must be present and one of \"http\" or \"https\".",
  1419. ]
  1420. )
  1421. }
  1422. }
  1423. func testReceiveMetadataWhenClientIdleAndServerIdle_InvalidScheme() throws {
  1424. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1425. let action = try stateMachine.receive(
  1426. headers: .receivedWithInvalidScheme,
  1427. endStream: false
  1428. )
  1429. self.assertRejectedRPC(action) { trailers in
  1430. XCTAssertEqual(
  1431. trailers,
  1432. [
  1433. ":status": "200",
  1434. "content-type": "application/grpc",
  1435. "grpc-status": "3",
  1436. "grpc-status-message": ":scheme header must be present and one of \"http\" or \"https\".",
  1437. ]
  1438. )
  1439. }
  1440. }
  1441. func testReceiveMetadataWhenClientIdleAndServerIdle_ServerUnsupportedEncoding() throws {
  1442. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1443. // Try opening client with a compression algorithm that is not accepted
  1444. // by the server.
  1445. let action = try stateMachine.receive(
  1446. headers: .clientInitialMetadataWithGzipCompression,
  1447. endStream: false
  1448. )
  1449. self.assertRejectedRPC(action) { trailers in
  1450. XCTAssertEqual(
  1451. trailers,
  1452. [
  1453. ":status": "200",
  1454. "content-type": "application/grpc",
  1455. "grpc-accept-encoding": "deflate",
  1456. "grpc-status": "12",
  1457. "grpc-status-message":
  1458. "gzip compression is not supported; supported algorithms are listed in grpc-accept-encoding",
  1459. ]
  1460. )
  1461. }
  1462. }
  1463. //TODO: add more encoding-related validation tests (for both client and server)
  1464. // and message encoding tests
  1465. func testReceiveMetadataWhenClientOpenAndServerIdle() throws {
  1466. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerIdle)
  1467. // Try receiving initial metadata again - should fail
  1468. XCTAssertThrowsError(
  1469. ofType: RPCError.self,
  1470. try stateMachine.receive(headers: .clientInitialMetadata, endStream: false)
  1471. ) { error in
  1472. XCTAssertEqual(error.code, .internalError)
  1473. XCTAssertEqual(error.message, "Client shouldn't have sent metadata twice.")
  1474. }
  1475. }
  1476. func testReceiveMetadataWhenClientOpenAndServerOpen() throws {
  1477. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1478. XCTAssertThrowsError(
  1479. ofType: RPCError.self,
  1480. try stateMachine.receive(headers: .clientInitialMetadata, endStream: false)
  1481. ) { error in
  1482. XCTAssertEqual(error.code, .internalError)
  1483. XCTAssertEqual(error.message, "Client shouldn't have sent metadata twice.")
  1484. }
  1485. }
  1486. func testReceiveMetadataWhenClientOpenAndServerClosed() {
  1487. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerClosed)
  1488. XCTAssertThrowsError(
  1489. ofType: RPCError.self,
  1490. try stateMachine.receive(headers: .clientInitialMetadata, endStream: false)
  1491. ) { error in
  1492. XCTAssertEqual(error.code, .internalError)
  1493. XCTAssertEqual(error.message, "Client shouldn't have sent metadata twice.")
  1494. }
  1495. }
  1496. func testReceiveMetadataWhenClientClosedAndServerIdle() {
  1497. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerIdle)
  1498. XCTAssertThrowsError(
  1499. ofType: RPCError.self,
  1500. try stateMachine.receive(headers: .clientInitialMetadata, endStream: false)
  1501. ) { error in
  1502. XCTAssertEqual(error.code, .internalError)
  1503. XCTAssertEqual(error.message, "Client can't have sent metadata if closed.")
  1504. }
  1505. }
  1506. func testReceiveMetadataWhenClientClosedAndServerOpen() {
  1507. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerOpen)
  1508. XCTAssertThrowsError(
  1509. ofType: RPCError.self,
  1510. try stateMachine.receive(headers: .clientInitialMetadata, endStream: false)
  1511. ) { error in
  1512. XCTAssertEqual(error.code, .internalError)
  1513. XCTAssertEqual(error.message, "Client can't have sent metadata if closed.")
  1514. }
  1515. }
  1516. func testReceiveMetadataWhenClientClosedAndServerClosed() {
  1517. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerClosed)
  1518. XCTAssertThrowsError(
  1519. ofType: RPCError.self,
  1520. try stateMachine.receive(headers: .clientInitialMetadata, endStream: false)
  1521. ) { error in
  1522. XCTAssertEqual(error.code, .internalError)
  1523. XCTAssertEqual(error.message, "Client can't have sent metadata if closed.")
  1524. }
  1525. }
  1526. // - MARK: Receive message
  1527. func testReceiveMessageWhenClientIdleAndServerIdle() {
  1528. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1529. XCTAssertThrowsError(
  1530. ofType: RPCError.self,
  1531. try stateMachine.receive(buffer: .init(), endStream: false)
  1532. ) { error in
  1533. XCTAssertEqual(error.code, .internalError)
  1534. XCTAssertEqual(error.message, "Can't have received a message if client is idle.")
  1535. }
  1536. }
  1537. func testReceiveMessageWhenClientOpenAndServerIdle() {
  1538. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerIdle)
  1539. // Receive messages successfully: the second one should close client.
  1540. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: false))
  1541. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: true))
  1542. // Verify client is now closed
  1543. XCTAssertThrowsError(
  1544. ofType: RPCError.self,
  1545. try stateMachine.receive(buffer: .init(), endStream: false)
  1546. ) { error in
  1547. XCTAssertEqual(error.code, .internalError)
  1548. XCTAssertEqual(error.message, "Client can't send a message if closed.")
  1549. }
  1550. }
  1551. func testReceiveMessageWhenClientOpenAndServerOpen() throws {
  1552. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1553. // Receive messages successfully: the second one should close client.
  1554. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: false))
  1555. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: true))
  1556. // Verify client is now closed
  1557. XCTAssertThrowsError(
  1558. ofType: RPCError.self,
  1559. try stateMachine.receive(buffer: .init(), endStream: false)
  1560. ) { error in
  1561. XCTAssertEqual(error.code, .internalError)
  1562. XCTAssertEqual(error.message, "Client can't send a message if closed.")
  1563. }
  1564. }
  1565. func testReceiveMessageWhenClientOpenAndServerClosed() {
  1566. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerClosed)
  1567. // Client is not done sending request, don't fail.
  1568. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: false))
  1569. }
  1570. func testReceiveMessageWhenClientClosedAndServerIdle() {
  1571. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerIdle)
  1572. XCTAssertThrowsError(
  1573. ofType: RPCError.self,
  1574. try stateMachine.receive(buffer: .init(), endStream: false)
  1575. ) { error in
  1576. XCTAssertEqual(error.code, .internalError)
  1577. XCTAssertEqual(error.message, "Client can't send a message if closed.")
  1578. }
  1579. }
  1580. func testReceiveMessageWhenClientClosedAndServerOpen() {
  1581. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerOpen)
  1582. XCTAssertThrowsError(
  1583. ofType: RPCError.self,
  1584. try stateMachine.receive(buffer: .init(), endStream: false)
  1585. ) { error in
  1586. XCTAssertEqual(error.code, .internalError)
  1587. XCTAssertEqual(error.message, "Client can't send a message if closed.")
  1588. }
  1589. }
  1590. func testReceiveMessageWhenClientClosedAndServerClosed() {
  1591. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerClosed)
  1592. XCTAssertThrowsError(
  1593. ofType: RPCError.self,
  1594. try stateMachine.receive(buffer: .init(), endStream: false)
  1595. ) { error in
  1596. XCTAssertEqual(error.code, .internalError)
  1597. XCTAssertEqual(error.message, "Client can't send a message if closed.")
  1598. }
  1599. }
  1600. // - MARK: Next outbound message
  1601. func testNextOutboundMessageWhenClientIdleAndServerIdle() {
  1602. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1603. XCTAssertThrowsError(
  1604. ofType: RPCError.self,
  1605. try stateMachine.nextOutboundMessage()
  1606. ) { error in
  1607. XCTAssertEqual(error.code, .internalError)
  1608. XCTAssertEqual(error.message, "Server is not open yet.")
  1609. }
  1610. }
  1611. func testNextOutboundMessageWhenClientOpenAndServerIdle() throws {
  1612. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerIdle)
  1613. XCTAssertThrowsError(
  1614. ofType: RPCError.self,
  1615. try stateMachine.nextOutboundMessage()
  1616. ) { error in
  1617. XCTAssertEqual(error.code, .internalError)
  1618. XCTAssertEqual(error.message, "Server is not open yet.")
  1619. }
  1620. }
  1621. func testNextOutboundMessageWhenClientOpenAndServerIdle_WithCompression() throws {
  1622. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerIdle)
  1623. XCTAssertThrowsError(
  1624. ofType: RPCError.self,
  1625. try stateMachine.nextOutboundMessage()
  1626. ) { error in
  1627. XCTAssertEqual(error.code, .internalError)
  1628. XCTAssertEqual(error.message, "Server is not open yet.")
  1629. }
  1630. }
  1631. func testNextOutboundMessageWhenClientOpenAndServerOpen() throws {
  1632. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1633. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .awaitMoreMessages)
  1634. XCTAssertNoThrow(try stateMachine.send(message: [42, 42]))
  1635. let response = try stateMachine.nextOutboundMessage()
  1636. let expectedBytes: [UInt8] = [
  1637. 0, // compression flag: unset
  1638. 0, 0, 0, 2, // message length: 2 bytes
  1639. 42, 42, // original message
  1640. ]
  1641. XCTAssertEqual(response, .sendMessage(ByteBuffer(bytes: expectedBytes)))
  1642. // And then make sure that nothing else is returned
  1643. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .awaitMoreMessages)
  1644. }
  1645. func testNextOutboundMessageWhenClientOpenAndServerOpen_WithCompression() throws {
  1646. var stateMachine = self.makeServerStateMachine(
  1647. targetState: .clientOpenServerOpen,
  1648. compressionEnabled: true
  1649. )
  1650. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .awaitMoreMessages)
  1651. let originalMessage = [UInt8]([42, 42, 43, 43])
  1652. XCTAssertNoThrow(try stateMachine.send(message: originalMessage))
  1653. let response = try stateMachine.nextOutboundMessage()
  1654. let framedMessage = try self.frameMessage(originalMessage, compress: true)
  1655. XCTAssertEqual(response, .sendMessage(framedMessage))
  1656. }
  1657. func testNextOutboundMessageWhenClientOpenAndServerClosed() throws {
  1658. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1659. // Send message and close server
  1660. XCTAssertNoThrow(try stateMachine.send(message: [42, 42]))
  1661. XCTAssertNoThrow(
  1662. try stateMachine.send(
  1663. status: .init(code: .ok, message: ""),
  1664. metadata: []
  1665. )
  1666. )
  1667. let response = try stateMachine.nextOutboundMessage()
  1668. let expectedBytes: [UInt8] = [
  1669. 0, // compression flag: unset
  1670. 0, 0, 0, 2, // message length: 2 bytes
  1671. 42, 42, // original message
  1672. ]
  1673. XCTAssertEqual(response, .sendMessage(ByteBuffer(bytes: expectedBytes)))
  1674. // And then make sure that nothing else is returned anymore
  1675. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .noMoreMessages)
  1676. }
  1677. func testNextOutboundMessageWhenClientClosedAndServerIdle() throws {
  1678. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerIdle)
  1679. XCTAssertThrowsError(
  1680. ofType: RPCError.self,
  1681. try stateMachine.nextOutboundMessage()
  1682. ) { error in
  1683. XCTAssertEqual(error.code, .internalError)
  1684. XCTAssertEqual(error.message, "Server is not open yet.")
  1685. }
  1686. }
  1687. func testNextOutboundMessageWhenClientClosedAndServerOpen() throws {
  1688. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1689. // Send a message
  1690. XCTAssertNoThrow(try stateMachine.send(message: [42, 42]))
  1691. // Close client
  1692. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: true))
  1693. // Send another message
  1694. XCTAssertNoThrow(try stateMachine.send(message: [43, 43]))
  1695. // Make sure that getting the next outbound message _does_ return the message
  1696. // we have enqueued.
  1697. let response = try stateMachine.nextOutboundMessage()
  1698. let expectedBytes: [UInt8] = [
  1699. 0, // compression flag: unset
  1700. 0, 0, 0, 2, // message length: 2 bytes
  1701. 42, 42, // original message
  1702. // End of first message - beginning of second
  1703. 0, // compression flag: unset
  1704. 0, 0, 0, 2, // message length: 2 bytes
  1705. 43, 43, // original message
  1706. ]
  1707. XCTAssertEqual(response, .sendMessage(ByteBuffer(bytes: expectedBytes)))
  1708. // And then make sure that nothing else is returned anymore
  1709. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .awaitMoreMessages)
  1710. }
  1711. func testNextOutboundMessageWhenClientClosedAndServerClosed() throws {
  1712. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerOpen)
  1713. // Send a message and close server
  1714. XCTAssertNoThrow(try stateMachine.send(message: [42, 42]))
  1715. XCTAssertNoThrow(
  1716. try stateMachine.send(
  1717. status: .init(code: .ok, message: ""),
  1718. metadata: []
  1719. )
  1720. )
  1721. // We have enqueued a message, make sure we return it even though server is closed,
  1722. // because we haven't yet drained all of the pending messages.
  1723. let response = try stateMachine.nextOutboundMessage()
  1724. let expectedBytes: [UInt8] = [
  1725. 0, // compression flag: unset
  1726. 0, 0, 0, 2, // message length: 2 bytes
  1727. 42, 42, // original message
  1728. ]
  1729. XCTAssertEqual(response, .sendMessage(ByteBuffer(bytes: expectedBytes)))
  1730. // And then make sure that nothing else is returned anymore
  1731. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .noMoreMessages)
  1732. }
  1733. // - MARK: Next inbound message
  1734. func testNextInboundMessageWhenClientIdleAndServerIdle() {
  1735. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1736. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  1737. }
  1738. func testNextInboundMessageWhenClientOpenAndServerIdle() {
  1739. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerIdle)
  1740. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  1741. }
  1742. func testNextInboundMessageWhenClientOpenAndServerOpen() throws {
  1743. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1744. let receivedBytes = ByteBuffer(bytes: [
  1745. 0, // compression flag: unset
  1746. 0, 0, 0, 2, // message length: 2 bytes
  1747. 42, 42, // original message
  1748. ])
  1749. try stateMachine.receive(buffer: receivedBytes, endStream: false)
  1750. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage([42, 42]))
  1751. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  1752. }
  1753. func testNextInboundMessageWhenClientOpenAndServerOpen_WithCompression() throws {
  1754. var stateMachine = self.makeServerStateMachine(
  1755. targetState: .clientOpenServerOpen,
  1756. compressionEnabled: true
  1757. )
  1758. let originalMessage = [UInt8]([42, 42, 43, 43])
  1759. let receivedBytes = try self.frameMessage(originalMessage, compress: true)
  1760. try stateMachine.receive(buffer: receivedBytes, endStream: false)
  1761. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(originalMessage))
  1762. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  1763. }
  1764. func testNextInboundMessageWhenClientOpenAndServerClosed() throws {
  1765. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1766. let receivedBytes = ByteBuffer(bytes: [
  1767. 0, // compression flag: unset
  1768. 0, 0, 0, 2, // message length: 2 bytes
  1769. 42, 42, // original message
  1770. ])
  1771. try stateMachine.receive(buffer: receivedBytes, endStream: false)
  1772. // Close server
  1773. XCTAssertNoThrow(
  1774. try stateMachine.send(
  1775. status: .init(code: .ok, message: ""),
  1776. metadata: []
  1777. )
  1778. )
  1779. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage([42, 42]))
  1780. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  1781. }
  1782. func testNextInboundMessageWhenClientClosedAndServerIdle() {
  1783. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerIdle)
  1784. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  1785. }
  1786. func testNextInboundMessageWhenClientClosedAndServerOpen() throws {
  1787. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1788. let receivedBytes = ByteBuffer(bytes: [
  1789. 0, // compression flag: unset
  1790. 0, 0, 0, 2, // message length: 2 bytes
  1791. 42, 42, // original message
  1792. ])
  1793. try stateMachine.receive(buffer: receivedBytes, endStream: false)
  1794. // Close client
  1795. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: true))
  1796. // Even though the client is closed, because the server received a message
  1797. // while it was still open, we must get the message now.
  1798. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage([42, 42]))
  1799. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  1800. }
  1801. func testNextInboundMessageWhenClientClosedAndServerClosed() throws {
  1802. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1803. let receivedBytes = ByteBuffer(bytes: [
  1804. 0, // compression flag: unset
  1805. 0, 0, 0, 2, // message length: 2 bytes
  1806. 42, 42, // original message
  1807. ])
  1808. try stateMachine.receive(buffer: receivedBytes, endStream: false)
  1809. // Close server
  1810. XCTAssertNoThrow(
  1811. try stateMachine.send(
  1812. status: .init(code: .ok, message: ""),
  1813. metadata: []
  1814. )
  1815. )
  1816. // Close client
  1817. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: true))
  1818. // Even though the client and server are closed, because the server received
  1819. // a message while the client was still open, we must get the message now.
  1820. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage([42, 42]))
  1821. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  1822. }
  1823. // - MARK: Common paths
  1824. func testNormalFlow() throws {
  1825. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1826. // Client sends metadata
  1827. let receiveMetadataAction = try stateMachine.receive(
  1828. headers: .clientInitialMetadata,
  1829. endStream: false
  1830. )
  1831. XCTAssertEqual(
  1832. receiveMetadataAction,
  1833. .receivedMetadata(Metadata(headers: .clientInitialMetadata))
  1834. )
  1835. // Server sends initial metadata
  1836. let sentInitialHeaders = try stateMachine.send(metadata: Metadata(headers: ["custom": "value"]))
  1837. XCTAssertEqual(
  1838. sentInitialHeaders,
  1839. [
  1840. ":status": "200",
  1841. "content-type": "application/grpc",
  1842. "grpc-accept-encoding": "deflate",
  1843. "custom": "value",
  1844. ]
  1845. )
  1846. // Client sends messages
  1847. let deframedMessage = [UInt8]([1, 2, 3, 4])
  1848. let completeMessage = try self.frameMessage(deframedMessage, compress: false)
  1849. // Split message into two parts to make sure the stitching together of the frames works well
  1850. let firstMessage = completeMessage.getSlice(at: 0, length: 4)!
  1851. let secondMessage = completeMessage.getSlice(at: 4, length: completeMessage.readableBytes - 4)!
  1852. try stateMachine.receive(buffer: firstMessage, endStream: false)
  1853. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  1854. try stateMachine.receive(buffer: secondMessage, endStream: false)
  1855. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(deframedMessage))
  1856. // Server sends response
  1857. let firstResponse = [UInt8]([5, 6, 7])
  1858. let secondResponse = [UInt8]([8, 9, 10])
  1859. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .awaitMoreMessages)
  1860. try stateMachine.send(message: firstResponse)
  1861. try stateMachine.send(message: secondResponse)
  1862. // Make sure messages are outbound
  1863. let framedMessages = try self.frameMessages([firstResponse, secondResponse], compress: false)
  1864. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .sendMessage(framedMessages))
  1865. // Client sends end
  1866. try stateMachine.receive(buffer: ByteBuffer(), endStream: true)
  1867. // Server ends
  1868. let response = try stateMachine.send(
  1869. status: .init(code: .ok, message: ""),
  1870. metadata: []
  1871. )
  1872. XCTAssertEqual(response, ["grpc-status": "0"])
  1873. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .noMoreMessages)
  1874. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  1875. }
  1876. func testClientClosesBeforeServerOpens() throws {
  1877. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1878. // Client sends metadata
  1879. let receiveMetadataAction = try stateMachine.receive(
  1880. headers: .clientInitialMetadata,
  1881. endStream: false
  1882. )
  1883. XCTAssertEqual(
  1884. receiveMetadataAction,
  1885. .receivedMetadata(Metadata(headers: .clientInitialMetadata))
  1886. )
  1887. // Client sends messages
  1888. let deframedMessage = [UInt8]([1, 2, 3, 4])
  1889. let completeMessage = try self.frameMessage(deframedMessage, compress: false)
  1890. // Split message into two parts to make sure the stitching together of the frames works well
  1891. let firstMessage = completeMessage.getSlice(at: 0, length: 4)!
  1892. let secondMessage = completeMessage.getSlice(at: 4, length: completeMessage.readableBytes - 4)!
  1893. try stateMachine.receive(buffer: firstMessage, endStream: false)
  1894. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  1895. try stateMachine.receive(buffer: secondMessage, endStream: false)
  1896. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(deframedMessage))
  1897. // Client sends end
  1898. try stateMachine.receive(buffer: ByteBuffer(), endStream: true)
  1899. // Server sends initial metadata
  1900. let sentInitialHeaders = try stateMachine.send(metadata: Metadata(headers: ["custom": "value"]))
  1901. XCTAssertEqual(
  1902. sentInitialHeaders,
  1903. [
  1904. "custom": "value",
  1905. ":status": "200",
  1906. "content-type": "application/grpc",
  1907. "grpc-accept-encoding": "deflate",
  1908. ]
  1909. )
  1910. // Server sends response
  1911. let firstResponse = [UInt8]([5, 6, 7])
  1912. let secondResponse = [UInt8]([8, 9, 10])
  1913. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .awaitMoreMessages)
  1914. try stateMachine.send(message: firstResponse)
  1915. try stateMachine.send(message: secondResponse)
  1916. // Make sure messages are outbound
  1917. let framedMessages = try self.frameMessages([firstResponse, secondResponse], compress: false)
  1918. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .sendMessage(framedMessages))
  1919. // Server ends
  1920. let response = try stateMachine.send(
  1921. status: .init(code: .ok, message: ""),
  1922. metadata: []
  1923. )
  1924. XCTAssertEqual(response, ["grpc-status": "0"])
  1925. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .noMoreMessages)
  1926. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  1927. }
  1928. func testClientClosesBeforeServerResponds() throws {
  1929. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1930. // Client sends metadata
  1931. let receiveMetadataAction = try stateMachine.receive(
  1932. headers: .clientInitialMetadata,
  1933. endStream: false
  1934. )
  1935. XCTAssertEqual(
  1936. receiveMetadataAction,
  1937. .receivedMetadata(Metadata(headers: .clientInitialMetadata))
  1938. )
  1939. // Client sends messages
  1940. let deframedMessage = [UInt8]([1, 2, 3, 4])
  1941. let completeMessage = try self.frameMessage(deframedMessage, compress: false)
  1942. // Split message into two parts to make sure the stitching together of the frames works well
  1943. let firstMessage = completeMessage.getSlice(at: 0, length: 4)!
  1944. let secondMessage = completeMessage.getSlice(at: 4, length: completeMessage.readableBytes - 4)!
  1945. try stateMachine.receive(buffer: firstMessage, endStream: false)
  1946. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  1947. try stateMachine.receive(buffer: secondMessage, endStream: false)
  1948. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(deframedMessage))
  1949. // Server sends initial metadata
  1950. let sentInitialHeaders = try stateMachine.send(metadata: Metadata(headers: ["custom": "value"]))
  1951. XCTAssertEqual(
  1952. sentInitialHeaders,
  1953. [
  1954. "custom": "value",
  1955. ":status": "200",
  1956. "content-type": "application/grpc",
  1957. "grpc-accept-encoding": "deflate",
  1958. ]
  1959. )
  1960. // Client sends end
  1961. try stateMachine.receive(buffer: ByteBuffer(), endStream: true)
  1962. // Server sends response
  1963. let firstResponse = [UInt8]([5, 6, 7])
  1964. let secondResponse = [UInt8]([8, 9, 10])
  1965. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .awaitMoreMessages)
  1966. try stateMachine.send(message: firstResponse)
  1967. try stateMachine.send(message: secondResponse)
  1968. // Make sure messages are outbound
  1969. let framedMessages = try self.frameMessages([firstResponse, secondResponse], compress: false)
  1970. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .sendMessage(framedMessages))
  1971. // Server ends
  1972. let response = try stateMachine.send(
  1973. status: .init(code: .ok, message: ""),
  1974. metadata: []
  1975. )
  1976. XCTAssertEqual(response, ["grpc-status": "0"])
  1977. XCTAssertEqual(try stateMachine.nextOutboundMessage(), .noMoreMessages)
  1978. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  1979. }
  1980. }
  1981. extension XCTestCase {
  1982. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  1983. func assertRejectedRPC(
  1984. _ action: GRPCStreamStateMachine.OnMetadataReceived,
  1985. expression: (HPACKHeaders) throws -> Void
  1986. ) rethrows {
  1987. guard case .rejectRPC(let trailers) = action else {
  1988. XCTFail("RPC should have been rejected.")
  1989. return
  1990. }
  1991. try expression(trailers)
  1992. }
  1993. func frameMessage(_ message: [UInt8], compress: Bool) throws -> ByteBuffer {
  1994. try frameMessages([message], compress: compress)
  1995. }
  1996. func frameMessages(_ messages: [[UInt8]], compress: Bool) throws -> ByteBuffer {
  1997. var framer = GRPCMessageFramer()
  1998. let compressor: Zlib.Compressor? = {
  1999. if compress {
  2000. return Zlib.Compressor(method: .deflate)
  2001. } else {
  2002. return nil
  2003. }
  2004. }()
  2005. defer { compressor?.end() }
  2006. for message in messages {
  2007. framer.append(message)
  2008. }
  2009. return try XCTUnwrap(framer.next(compressor: compressor))
  2010. }
  2011. }