GRPCStreamStateMachineTests.swift 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864
  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 NIOEmbedded
  19. import NIOHPACK
  20. import XCTest
  21. @testable import GRPCNIOTransportCore
  22. private enum TargetStateMachineState: CaseIterable {
  23. case clientIdleServerIdle
  24. case clientOpenServerIdle
  25. case clientOpenServerOpen
  26. case clientOpenServerClosed
  27. case clientClosedServerIdle
  28. case clientClosedServerOpen
  29. case clientClosedServerClosed
  30. }
  31. extension HPACKHeaders {
  32. // Client
  33. fileprivate static let clientInitialMetadata: Self = [
  34. GRPCHTTP2Keys.path.rawValue: "/test/test",
  35. GRPCHTTP2Keys.scheme.rawValue: "http",
  36. GRPCHTTP2Keys.method.rawValue: "POST",
  37. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  38. GRPCHTTP2Keys.te.rawValue: "trailers",
  39. ]
  40. fileprivate static let clientInitialMetadataWithDeflateCompression: Self = [
  41. GRPCHTTP2Keys.path.rawValue: "/test/test",
  42. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  43. GRPCHTTP2Keys.method.rawValue: "POST",
  44. GRPCHTTP2Keys.scheme.rawValue: "https",
  45. GRPCHTTP2Keys.te.rawValue: "trailers",
  46. GRPCHTTP2Keys.acceptEncoding.rawValue: "deflate",
  47. GRPCHTTP2Keys.encoding.rawValue: "deflate",
  48. ]
  49. fileprivate static let clientInitialMetadataWithGzipCompression: Self = [
  50. GRPCHTTP2Keys.path.rawValue: "/test/test",
  51. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  52. GRPCHTTP2Keys.method.rawValue: "POST",
  53. GRPCHTTP2Keys.scheme.rawValue: "https",
  54. GRPCHTTP2Keys.te.rawValue: "trailers",
  55. GRPCHTTP2Keys.acceptEncoding.rawValue: "gzip",
  56. GRPCHTTP2Keys.encoding.rawValue: "gzip",
  57. ]
  58. fileprivate static let receivedWithoutContentType: Self = [
  59. GRPCHTTP2Keys.path.rawValue: "/test/test"
  60. ]
  61. fileprivate static let receivedWithInvalidContentType: Self = [
  62. GRPCHTTP2Keys.path.rawValue: "/test/test",
  63. GRPCHTTP2Keys.contentType.rawValue: "invalid/invalid",
  64. ]
  65. fileprivate static let receivedWithInvalidPath: Self = [
  66. GRPCHTTP2Keys.path.rawValue: "someinvalidpath",
  67. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  68. ]
  69. fileprivate static let receivedWithoutEndpoint: Self = [
  70. GRPCHTTP2Keys.contentType.rawValue: "application/grpc"
  71. ]
  72. fileprivate static let receivedWithoutTE: Self = [
  73. GRPCHTTP2Keys.path.rawValue: "/test/test",
  74. GRPCHTTP2Keys.scheme.rawValue: "http",
  75. GRPCHTTP2Keys.method.rawValue: "POST",
  76. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  77. ]
  78. fileprivate static let receivedWithInvalidTE: Self = [
  79. GRPCHTTP2Keys.path.rawValue: "/test/test",
  80. GRPCHTTP2Keys.scheme.rawValue: "http",
  81. GRPCHTTP2Keys.method.rawValue: "POST",
  82. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  83. GRPCHTTP2Keys.te.rawValue: "invalidte",
  84. ]
  85. fileprivate static let receivedWithoutMethod: Self = [
  86. GRPCHTTP2Keys.path.rawValue: "/test/test",
  87. GRPCHTTP2Keys.scheme.rawValue: "http",
  88. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  89. GRPCHTTP2Keys.te.rawValue: "trailers",
  90. ]
  91. fileprivate static let receivedWithInvalidMethod: Self = [
  92. GRPCHTTP2Keys.path.rawValue: "/test/test",
  93. GRPCHTTP2Keys.scheme.rawValue: "http",
  94. GRPCHTTP2Keys.method.rawValue: "GET",
  95. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  96. GRPCHTTP2Keys.te.rawValue: "trailers",
  97. ]
  98. fileprivate static let receivedWithoutScheme: Self = [
  99. GRPCHTTP2Keys.path.rawValue: "/test/test",
  100. GRPCHTTP2Keys.method.rawValue: "POST",
  101. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  102. GRPCHTTP2Keys.te.rawValue: "trailers",
  103. ]
  104. fileprivate static let receivedWithInvalidScheme: Self = [
  105. GRPCHTTP2Keys.path.rawValue: "/test/test",
  106. GRPCHTTP2Keys.scheme.rawValue: "invalidscheme",
  107. GRPCHTTP2Keys.method.rawValue: "POST",
  108. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  109. GRPCHTTP2Keys.te.rawValue: "trailers",
  110. ]
  111. // Server
  112. fileprivate static let serverInitialMetadata: Self = [
  113. GRPCHTTP2Keys.status.rawValue: "200",
  114. GRPCHTTP2Keys.contentType.rawValue: ContentType.grpc.canonicalValue,
  115. ]
  116. fileprivate static let serverInitialMetadataWithDeflateCompression: Self = [
  117. GRPCHTTP2Keys.status.rawValue: "200",
  118. GRPCHTTP2Keys.contentType.rawValue: ContentType.grpc.canonicalValue,
  119. GRPCHTTP2Keys.encoding.rawValue: "deflate",
  120. ]
  121. fileprivate static let serverInitialMetadataWithGZIPCompression: Self = [
  122. GRPCHTTP2Keys.status.rawValue: "200",
  123. GRPCHTTP2Keys.contentType.rawValue: ContentType.grpc.canonicalValue,
  124. GRPCHTTP2Keys.encoding.rawValue: "gzip",
  125. ]
  126. fileprivate static let serverTrailers: Self = [
  127. GRPCHTTP2Keys.status.rawValue: "200",
  128. GRPCHTTP2Keys.contentType.rawValue: ContentType.grpc.canonicalValue,
  129. GRPCHTTP2Keys.grpcStatus.rawValue: "0",
  130. ]
  131. }
  132. @available(gRPCSwiftNIOTransport 2.0, *)
  133. final class GRPCStreamClientStateMachineTests: XCTestCase {
  134. private func makeClientStateMachine(
  135. targetState: TargetStateMachineState,
  136. compressionEnabled: Bool = false
  137. ) -> GRPCStreamStateMachine {
  138. var stateMachine = GRPCStreamStateMachine(
  139. configuration: .client(
  140. .init(
  141. methodDescriptor: .testTest,
  142. scheme: .http,
  143. authority: nil,
  144. outboundEncoding: compressionEnabled ? .deflate : .none,
  145. acceptedEncodings: [.deflate]
  146. )
  147. ),
  148. maxPayloadSize: 100,
  149. skipAssertions: true
  150. )
  151. let serverMetadata: HPACKHeaders =
  152. compressionEnabled ? .serverInitialMetadataWithDeflateCompression : .serverInitialMetadata
  153. switch targetState {
  154. case .clientIdleServerIdle:
  155. break
  156. case .clientOpenServerIdle:
  157. // Open client
  158. XCTAssertNoThrow(try stateMachine.send(metadata: []))
  159. case .clientOpenServerOpen:
  160. // Open client
  161. XCTAssertNoThrow(try stateMachine.send(metadata: []))
  162. // Open server
  163. XCTAssertNoThrow(try stateMachine.receive(headers: serverMetadata, endStream: false))
  164. case .clientOpenServerClosed:
  165. // Open client
  166. XCTAssertNoThrow(try stateMachine.send(metadata: []))
  167. // Open server
  168. XCTAssertNoThrow(try stateMachine.receive(headers: serverMetadata, endStream: false))
  169. // Close server
  170. XCTAssertNoThrow(try stateMachine.receive(headers: .serverTrailers, endStream: true))
  171. case .clientClosedServerIdle:
  172. // Open client
  173. XCTAssertNoThrow(try stateMachine.send(metadata: []))
  174. // Close client
  175. XCTAssertNoThrow(try stateMachine.closeOutbound())
  176. case .clientClosedServerOpen:
  177. // Open client
  178. XCTAssertNoThrow(try stateMachine.send(metadata: []))
  179. // Open server
  180. XCTAssertNoThrow(try stateMachine.receive(headers: serverMetadata, endStream: false))
  181. // Close client
  182. XCTAssertNoThrow(try stateMachine.closeOutbound())
  183. case .clientClosedServerClosed:
  184. // Open client
  185. XCTAssertNoThrow(try stateMachine.send(metadata: []))
  186. // Open server
  187. XCTAssertNoThrow(try stateMachine.receive(headers: serverMetadata, endStream: false))
  188. // Close client
  189. XCTAssertNoThrow(try stateMachine.closeOutbound())
  190. // Close server
  191. XCTAssertNoThrow(try stateMachine.receive(headers: .serverTrailers, endStream: true))
  192. }
  193. return stateMachine
  194. }
  195. // - MARK: Send Metadata
  196. func testSendMetadataWhenClientIdleAndServerIdle() throws {
  197. var stateMachine = self.makeClientStateMachine(targetState: .clientIdleServerIdle)
  198. XCTAssertNoThrow(try stateMachine.send(metadata: []))
  199. }
  200. func testSendMetadataWhenClientAlreadyOpen() throws {
  201. for targetState in [
  202. TargetStateMachineState.clientOpenServerIdle, .clientOpenServerOpen, .clientOpenServerClosed,
  203. ] {
  204. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  205. // Try sending metadata again: should throw
  206. XCTAssertThrowsError(
  207. ofType: GRPCStreamStateMachine.InvalidState.self,
  208. try stateMachine.send(metadata: .init())
  209. ) {
  210. error in
  211. XCTAssertEqual(error.message, "Client is already open: shouldn't be sending metadata.")
  212. }
  213. }
  214. }
  215. func testSendMetadataWhenClientAlreadyClosed() throws {
  216. for targetState in [
  217. TargetStateMachineState.clientClosedServerIdle, .clientClosedServerOpen,
  218. .clientClosedServerClosed,
  219. ] {
  220. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  221. // Try sending metadata again: should throw
  222. XCTAssertThrowsError(
  223. ofType: GRPCStreamStateMachine.InvalidState.self,
  224. try stateMachine.send(metadata: .init())
  225. ) {
  226. error in
  227. XCTAssertEqual(error.message, "Client is closed: can't send metadata.")
  228. }
  229. }
  230. }
  231. // - MARK: Send Message
  232. func testSendMessageWhenClientIdleAndServerIdle() {
  233. var stateMachine = self.makeClientStateMachine(targetState: .clientIdleServerIdle)
  234. // Try to send a message without opening (i.e. without sending initial metadata)
  235. XCTAssertThrowsError(
  236. ofType: GRPCStreamStateMachine.InvalidState.self,
  237. try stateMachine.send(message: ByteBuffer(), promise: nil)
  238. ) { error in
  239. XCTAssertEqual(error.message, "Client not yet open.")
  240. }
  241. }
  242. func testSendMessageWhenClientOpen() {
  243. for targetState in [
  244. TargetStateMachineState.clientOpenServerIdle, .clientOpenServerOpen, .clientOpenServerClosed,
  245. ] {
  246. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  247. // Now send a message
  248. XCTAssertNoThrow(try stateMachine.send(message: ByteBuffer(), promise: nil))
  249. }
  250. }
  251. func testSendMessageWhenClientClosed() {
  252. for targetState in [
  253. TargetStateMachineState.clientClosedServerIdle, .clientClosedServerOpen,
  254. .clientClosedServerClosed,
  255. ] {
  256. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  257. // Try sending another message: it should fail
  258. XCTAssertThrowsError(
  259. ofType: GRPCStreamStateMachine.InvalidState.self,
  260. try stateMachine.send(message: ByteBuffer(), promise: nil)
  261. ) { error in
  262. XCTAssertEqual(error.message, "Client is closed, cannot send a message.")
  263. }
  264. }
  265. }
  266. // - MARK: Send Status and Trailers
  267. func testSendStatusAndTrailers() {
  268. for targetState in TargetStateMachineState.allCases {
  269. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  270. // This operation is never allowed on the client.
  271. XCTAssertThrowsError(
  272. ofType: GRPCStreamStateMachine.InvalidState.self,
  273. try stateMachine.send(
  274. status: Status(code: .ok, message: ""),
  275. metadata: .init()
  276. )
  277. ) { error in
  278. XCTAssertEqual(error.message, "Client cannot send status and trailer.")
  279. }
  280. }
  281. }
  282. // - MARK: Receive initial metadata
  283. func testReceiveInitialMetadataWhenClientIdleAndServerIdle() {
  284. var stateMachine = self.makeClientStateMachine(targetState: .clientIdleServerIdle)
  285. XCTAssertThrowsError(
  286. ofType: GRPCStreamStateMachine.InvalidState.self,
  287. try stateMachine.receive(headers: .init(), endStream: false)
  288. ) { error in
  289. XCTAssertEqual(error.message, "Server cannot have sent metadata if the client is idle.")
  290. }
  291. }
  292. func testReceiveInvalidInitialMetadataWhenServerIdle() throws {
  293. for targetState in [
  294. TargetStateMachineState.clientOpenServerIdle, .clientClosedServerIdle,
  295. ] {
  296. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  297. // Receive metadata with unexpected non-200 status code
  298. let action = try stateMachine.receive(
  299. headers: [GRPCHTTP2Keys.status.rawValue: "300"],
  300. endStream: false
  301. )
  302. XCTAssertEqual(
  303. action,
  304. .receivedStatusAndMetadata_clientOnly(
  305. status: .init(code: .unknown, message: "Unexpected non-200 HTTP Status Code."),
  306. metadata: [":status": "300"]
  307. )
  308. )
  309. // Further attempts from the server to send messages to the client will simply be dropped.
  310. XCTAssertEqual(
  311. try stateMachine.receive(buffer: .init(), endStream: false),
  312. .doNothing
  313. )
  314. }
  315. }
  316. func testReceiveInitialMetadataWhenServerIdle_ClientUnsupportedEncoding() throws {
  317. // Create client with deflate compression enabled
  318. var stateMachine = self.makeClientStateMachine(
  319. targetState: .clientOpenServerIdle,
  320. compressionEnabled: true
  321. )
  322. // Try opening server with gzip compression, which client does not support.
  323. let action = try stateMachine.receive(
  324. headers: .serverInitialMetadataWithGZIPCompression,
  325. endStream: false
  326. )
  327. XCTAssertEqual(
  328. action,
  329. .receivedStatusAndMetadata_clientOnly(
  330. status: Status(
  331. code: .internalError,
  332. message:
  333. "The server picked a compression algorithm ('gzip') the client does not know about."
  334. ),
  335. metadata: [
  336. ":status": "200",
  337. "content-type": "application/grpc",
  338. "grpc-encoding": "gzip",
  339. ]
  340. )
  341. )
  342. }
  343. func testReceiveMessage_ClientCompressionEnabled() throws {
  344. // Enable deflate compression on client
  345. var stateMachine = self.makeClientStateMachine(
  346. targetState: .clientOpenServerOpen,
  347. compressionEnabled: true
  348. )
  349. let originalMessage = ByteBuffer(bytes: [42, 42, 43, 43])
  350. // Receiving uncompressed message should still work.
  351. let receivedUncompressedBytes = try self.frameMessage(originalMessage, compression: .none)
  352. XCTAssertNoThrow(try stateMachine.receive(buffer: receivedUncompressedBytes, endStream: false))
  353. var receivedAction = stateMachine.nextInboundMessage()
  354. switch receivedAction {
  355. case .noMoreMessages, .awaitMoreMessages:
  356. XCTFail("Should have received message")
  357. case .receiveMessage(let receivedMessaged):
  358. XCTAssertEqual(originalMessage, receivedMessaged)
  359. }
  360. // Receiving compressed message with deflate should work
  361. let receivedDeflateCompressedBytes = try self.frameMessage(
  362. originalMessage,
  363. compression: .deflate
  364. )
  365. XCTAssertNoThrow(
  366. try stateMachine.receive(buffer: receivedDeflateCompressedBytes, endStream: false)
  367. )
  368. receivedAction = stateMachine.nextInboundMessage()
  369. switch receivedAction {
  370. case .noMoreMessages, .awaitMoreMessages:
  371. XCTFail("Should have received message")
  372. case .receiveMessage(let receivedMessaged):
  373. XCTAssertEqual(originalMessage, receivedMessaged)
  374. }
  375. // Receiving compressed message with gzip (unsupported) should throw error
  376. let receivedGZIPCompressedBytes = try self.frameMessage(originalMessage, compression: .gzip)
  377. let action = try stateMachine.receive(buffer: receivedGZIPCompressedBytes, endStream: false)
  378. XCTAssertEqual(
  379. action,
  380. .endRPCAndForwardErrorStatus_clientOnly(
  381. Status(code: .internalError, message: "Failed to decode message")
  382. )
  383. )
  384. receivedAction = stateMachine.nextInboundMessage()
  385. switch receivedAction {
  386. case .awaitMoreMessages:
  387. ()
  388. case .noMoreMessages:
  389. XCTFail("Should be awaiting for more messages")
  390. case .receiveMessage:
  391. XCTFail("Should not have received message")
  392. }
  393. }
  394. func testReceiveInitialMetadataWhenServerIdle() throws {
  395. for targetState in [
  396. TargetStateMachineState.clientOpenServerIdle, .clientClosedServerIdle,
  397. ] {
  398. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  399. // Receive metadata = open server
  400. let action = try stateMachine.receive(
  401. headers: [
  402. GRPCHTTP2Keys.status.rawValue: "200",
  403. GRPCHTTP2Keys.contentType.rawValue: ContentType.grpc.canonicalValue,
  404. GRPCHTTP2Keys.encoding.rawValue: "deflate",
  405. "custom": "123",
  406. "custom-bin": Base64.encode(bytes: [42, 43, 44]),
  407. ],
  408. endStream: false
  409. )
  410. var expectedMetadata: Metadata = [
  411. ":status": "200",
  412. "content-type": "application/grpc",
  413. "grpc-encoding": "deflate",
  414. "custom": "123",
  415. ]
  416. expectedMetadata.addBinary([42, 43, 44], forKey: "custom-bin")
  417. XCTAssertEqual(action, .receivedMetadata(expectedMetadata, nil))
  418. }
  419. }
  420. func testReceiveInitialMetadataWhenServerOpen() throws {
  421. for targetState in [
  422. TargetStateMachineState.clientOpenServerOpen, .clientClosedServerOpen,
  423. ] {
  424. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  425. let action1 = try stateMachine.receive(
  426. headers: [
  427. GRPCHTTP2Keys.status.rawValue: "200",
  428. GRPCHTTP2Keys.contentType.rawValue: ContentType.grpc.canonicalValue,
  429. GRPCHTTP2Keys.encoding.rawValue: "deflate",
  430. "custom": "123",
  431. "custom-bin": Base64.encode(bytes: [42, 43, 44]),
  432. ],
  433. endStream: false
  434. )
  435. let expectedStatus = Status(code: .unknown, message: "No 'grpc-status' value in trailers")
  436. let expectedMetadata: Metadata = [
  437. ":status": "200",
  438. "content-type": "application/grpc",
  439. "grpc-encoding": "deflate",
  440. "custom": "123",
  441. "custom-bin": .binary([42, 43, 44]),
  442. ]
  443. XCTAssertEqual(
  444. action1,
  445. .receivedStatusAndMetadata_clientOnly(status: expectedStatus, metadata: expectedMetadata)
  446. )
  447. // Now make sure everything works well if we include grpc-status
  448. let action2 = try stateMachine.receive(
  449. headers: [
  450. GRPCHTTP2Keys.status.rawValue: "200",
  451. GRPCHTTP2Keys.grpcStatus.rawValue: String(Status.Code.ok.rawValue),
  452. GRPCHTTP2Keys.contentType.rawValue: ContentType.grpc.canonicalValue,
  453. GRPCHTTP2Keys.encoding.rawValue: "deflate",
  454. "custom": "123",
  455. "custom-bin": Base64.encode(bytes: [42, 43, 44]),
  456. ],
  457. endStream: false
  458. )
  459. XCTAssertEqual(
  460. action2,
  461. .receivedStatusAndMetadata_clientOnly(
  462. status: Status(code: .ok, message: ""),
  463. metadata: expectedMetadata
  464. )
  465. )
  466. }
  467. }
  468. func testReceiveInitialMetadataWhenServerClosed() {
  469. for targetState in [TargetStateMachineState.clientOpenServerClosed, .clientClosedServerClosed] {
  470. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  471. // We should not throw if the server sends metadata after it's been transitioned to close:
  472. // we should just drop these packages.
  473. XCTAssertNoThrow(try stateMachine.receive(headers: .init(), endStream: false))
  474. }
  475. }
  476. // - MARK: Receive end trailers
  477. func testReceiveEndTrailerWhenClientIdleAndServerIdle() {
  478. var stateMachine = self.makeClientStateMachine(targetState: .clientIdleServerIdle)
  479. // Receive an end trailer
  480. XCTAssertThrowsError(
  481. ofType: GRPCStreamStateMachine.InvalidState.self,
  482. try stateMachine.receive(headers: .init(), endStream: true)
  483. ) { error in
  484. XCTAssertEqual(error.message, "Server cannot have sent metadata if the client is idle.")
  485. }
  486. }
  487. func testReceiveEndTrailerWhenClientOpenAndServerIdle() throws {
  488. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerIdle)
  489. // Receive a trailers-only response
  490. let trailersOnlyResponse: HPACKHeaders = [
  491. GRPCHTTP2Keys.status.rawValue: "200",
  492. GRPCHTTP2Keys.contentType.rawValue: ContentType.grpc.canonicalValue,
  493. GRPCHTTP2Keys.grpcStatus.rawValue: String(Status.Code.internalError.rawValue),
  494. GRPCHTTP2Keys.grpcStatusMessage.rawValue: GRPCStatusMessageMarshaller.marshall(
  495. "Some, status, message"
  496. )!,
  497. "custom-key": "custom-value",
  498. ]
  499. let trailers = try stateMachine.receive(headers: trailersOnlyResponse, endStream: true)
  500. switch trailers {
  501. case .receivedStatusAndMetadata_clientOnly(let status, let metadata):
  502. XCTAssertEqual(status, Status(code: .internalError, message: "Some, status, message"))
  503. XCTAssertEqual(
  504. metadata,
  505. [
  506. ":status": "200",
  507. "content-type": "application/grpc",
  508. "custom-key": "custom-value",
  509. ]
  510. )
  511. case .receivedMetadata, .doNothing, .rejectRPC_serverOnly, .protocolViolation_serverOnly:
  512. XCTFail("Expected .receivedStatusAndMetadata")
  513. }
  514. }
  515. func testReceiveEndTrailerWhenServerOpen() throws {
  516. for targetState in [TargetStateMachineState.clientOpenServerOpen, .clientClosedServerOpen] {
  517. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  518. // Receive an end trailer
  519. let action = try stateMachine.receive(
  520. headers: [
  521. GRPCHTTP2Keys.status.rawValue: "200",
  522. GRPCHTTP2Keys.grpcStatus.rawValue: String(Status.Code.ok.rawValue),
  523. GRPCHTTP2Keys.contentType.rawValue: ContentType.grpc.canonicalValue,
  524. GRPCHTTP2Keys.encoding.rawValue: "deflate",
  525. "custom": "123",
  526. ],
  527. endStream: true
  528. )
  529. let expectedMetadata: Metadata = [
  530. ":status": "200",
  531. "content-type": "application/grpc",
  532. "grpc-encoding": "deflate",
  533. "custom": "123",
  534. ]
  535. XCTAssertEqual(
  536. action,
  537. .receivedStatusAndMetadata_clientOnly(
  538. status: .init(code: .ok, message: ""),
  539. metadata: expectedMetadata
  540. )
  541. )
  542. }
  543. }
  544. func testReceiveEndTrailerWhenClientOpenAndServerClosed() {
  545. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerClosed)
  546. // We should not throw if the server sends trailers after it's been transitioned to close:
  547. // we should just drop these packages.
  548. XCTAssertNoThrow(try stateMachine.receive(headers: .init(), endStream: true))
  549. }
  550. func testReceiveEndTrailerWhenClientClosedAndServerIdle() throws {
  551. var stateMachine = self.makeClientStateMachine(targetState: .clientClosedServerIdle)
  552. // Server sends a trailers-only response
  553. let trailersOnlyResponse: HPACKHeaders = [
  554. GRPCHTTP2Keys.status.rawValue: "200",
  555. GRPCHTTP2Keys.contentType.rawValue: ContentType.grpc.canonicalValue,
  556. GRPCHTTP2Keys.grpcStatus.rawValue: String(Status.Code.internalError.rawValue),
  557. GRPCHTTP2Keys.grpcStatusMessage.rawValue: GRPCStatusMessageMarshaller.marshall(
  558. "Some status message"
  559. )!,
  560. "custom-key": "custom-value",
  561. ]
  562. let trailers = try stateMachine.receive(headers: trailersOnlyResponse, endStream: true)
  563. switch trailers {
  564. case .receivedStatusAndMetadata_clientOnly(let status, let metadata):
  565. XCTAssertEqual(status, Status(code: .internalError, message: "Some status message"))
  566. XCTAssertEqual(
  567. metadata,
  568. [
  569. ":status": "200",
  570. "content-type": "application/grpc",
  571. "custom-key": "custom-value",
  572. ]
  573. )
  574. case .receivedMetadata, .doNothing, .rejectRPC_serverOnly, .protocolViolation_serverOnly:
  575. XCTFail("Expected .receivedStatusAndMetadata")
  576. }
  577. }
  578. func testReceiveEndTrailerWhenClientClosedAndServerClosed() {
  579. var stateMachine = self.makeClientStateMachine(targetState: .clientClosedServerClosed)
  580. // Close server again (endStream = true) and assert we don't throw.
  581. // This can happen if the previous close was caused by a grpc-status header
  582. // and then the server sends an empty frame with EOS set.
  583. XCTAssertEqual(try stateMachine.receive(headers: .init(), endStream: true), .doNothing)
  584. }
  585. // - MARK: Receive message
  586. func testReceiveMessageWhenClientIdleAndServerIdle() {
  587. var stateMachine = self.makeClientStateMachine(targetState: .clientIdleServerIdle)
  588. XCTAssertThrowsError(
  589. ofType: GRPCStreamStateMachine.InvalidState.self,
  590. try stateMachine.receive(buffer: .init(), endStream: false)
  591. ) { error in
  592. XCTAssertEqual(
  593. error.message,
  594. "Cannot have received anything from server if client is not yet open."
  595. )
  596. }
  597. }
  598. func testReceiveMessageWhenServerIdle() {
  599. for targetState in [TargetStateMachineState.clientOpenServerIdle, .clientClosedServerIdle] {
  600. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  601. XCTAssertThrowsError(
  602. ofType: GRPCStreamStateMachine.InvalidState.self,
  603. try stateMachine.receive(buffer: .init(), endStream: false)
  604. ) { error in
  605. XCTAssertEqual(
  606. error.message,
  607. "Server cannot have sent a message before sending the initial metadata."
  608. )
  609. }
  610. }
  611. }
  612. func testReceiveMessageWhenServerOpen() throws {
  613. for targetState in [TargetStateMachineState.clientOpenServerOpen, .clientClosedServerOpen] {
  614. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  615. XCTAssertEqual(
  616. try stateMachine.receive(buffer: .init(), endStream: false),
  617. .readInbound
  618. )
  619. XCTAssertEqual(
  620. try stateMachine.receive(buffer: .init(), endStream: true),
  621. .endRPCAndForwardErrorStatus_clientOnly(
  622. Status(
  623. code: .internalError,
  624. message: """
  625. Server sent EOS alongside a data frame, but server is only allowed \
  626. to close by sending status and trailers.
  627. """
  628. )
  629. )
  630. )
  631. }
  632. }
  633. func testReceiveMessageWhenServerClosed() throws {
  634. for targetState in [TargetStateMachineState.clientOpenServerClosed, .clientClosedServerClosed] {
  635. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  636. // We should drop the messages if we receive anything once the server's closed.
  637. XCTAssertEqual(
  638. try stateMachine.receive(buffer: .init(), endStream: false),
  639. .doNothing
  640. )
  641. }
  642. }
  643. // - MARK: Next outbound message
  644. func testNextOutboundMessageWhenClientIdleAndServerIdle() {
  645. var stateMachine = self.makeClientStateMachine(targetState: .clientIdleServerIdle)
  646. XCTAssertThrowsError(
  647. ofType: GRPCStreamStateMachine.InvalidState.self,
  648. try stateMachine.nextOutboundFrame()
  649. ) { error in
  650. XCTAssertEqual(error.message, "Client is not open yet.")
  651. }
  652. }
  653. func testNextOutboundMessageWhenClientOpenAndServerOpenOrIdle() throws {
  654. for targetState in [TargetStateMachineState.clientOpenServerIdle, .clientOpenServerOpen] {
  655. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  656. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .awaitMoreMessages)
  657. XCTAssertNoThrow(try stateMachine.send(message: ByteBuffer(bytes: [42, 42]), promise: nil))
  658. let expectedBytes: [UInt8] = [
  659. 0, // compression flag: unset
  660. 0, 0, 0, 2, // message length: 2 bytes
  661. 42, 42, // original message
  662. ]
  663. XCTAssertEqual(
  664. try stateMachine.nextOutboundFrame(),
  665. .sendFrame(frame: ByteBuffer(bytes: expectedBytes), promise: nil)
  666. )
  667. // And then make sure that nothing else is returned anymore
  668. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .awaitMoreMessages)
  669. }
  670. }
  671. func testNextOutboundMessageWhenClientOpenAndServerIdle_WithCompression() throws {
  672. var stateMachine = self.makeClientStateMachine(
  673. targetState: .clientOpenServerIdle,
  674. compressionEnabled: true
  675. )
  676. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .awaitMoreMessages)
  677. let originalMessage = ByteBuffer(bytes: [42, 42, 43, 43])
  678. XCTAssertNoThrow(try stateMachine.send(message: originalMessage, promise: nil))
  679. let request = try stateMachine.nextOutboundFrame()
  680. let framedMessage = try self.frameMessage(originalMessage, compression: .deflate)
  681. XCTAssertEqual(request, .sendFrame(frame: framedMessage, promise: nil))
  682. }
  683. func testNextOutboundMessageWhenClientOpenAndServerOpen_WithCompression() throws {
  684. var stateMachine = self.makeClientStateMachine(
  685. targetState: .clientOpenServerOpen,
  686. compressionEnabled: true
  687. )
  688. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .awaitMoreMessages)
  689. let originalMessage = ByteBuffer(bytes: [42, 42, 43, 43])
  690. XCTAssertNoThrow(try stateMachine.send(message: originalMessage, promise: nil))
  691. let request = try stateMachine.nextOutboundFrame()
  692. let framedMessage = try self.frameMessage(originalMessage, compression: .deflate)
  693. XCTAssertEqual(request, .sendFrame(frame: framedMessage, promise: nil))
  694. }
  695. func testNextOutboundMessageWhenClientOpenAndServerClosed() throws {
  696. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerClosed)
  697. // No more messages to send
  698. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .noMoreMessages)
  699. // Queue a message, but assert the action is .noMoreMessages nevertheless,
  700. // because the server is closed.
  701. XCTAssertNoThrow(try stateMachine.send(message: ByteBuffer(bytes: [42, 42]), promise: nil))
  702. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .noMoreMessages)
  703. }
  704. func testNextOutboundMessageWhenClientClosedAndServerIdle() throws {
  705. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerIdle)
  706. // Send a message and close client
  707. XCTAssertNoThrow(try stateMachine.send(message: ByteBuffer(bytes: [42, 42]), promise: nil))
  708. XCTAssertNoThrow(try stateMachine.closeOutbound())
  709. // Make sure that getting the next outbound message _does_ return the message
  710. // we have enqueued.
  711. let request = try stateMachine.nextOutboundFrame()
  712. let expectedBytes: [UInt8] = [
  713. 0, // compression flag: unset
  714. 0, 0, 0, 2, // message length: 2 bytes
  715. 42, 42, // original message
  716. ]
  717. XCTAssertEqual(request, .sendFrame(frame: ByteBuffer(bytes: expectedBytes), promise: nil))
  718. // And then make sure that nothing else is returned anymore
  719. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .noMoreMessages)
  720. }
  721. func testNextOutboundMessageWhenClientClosedAndServerOpen() throws {
  722. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerOpen)
  723. // Send a message and close client
  724. XCTAssertNoThrow(try stateMachine.send(message: ByteBuffer(bytes: [42, 42]), promise: nil))
  725. XCTAssertNoThrow(try stateMachine.closeOutbound())
  726. // Make sure that getting the next outbound message _does_ return the message
  727. // we have enqueued.
  728. let request = try stateMachine.nextOutboundFrame()
  729. let expectedBytes: [UInt8] = [
  730. 0, // compression flag: unset
  731. 0, 0, 0, 2, // message length: 2 bytes
  732. 42, 42, // original message
  733. ]
  734. XCTAssertEqual(request, .sendFrame(frame: ByteBuffer(bytes: expectedBytes), promise: nil))
  735. // And then make sure that nothing else is returned anymore
  736. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .noMoreMessages)
  737. }
  738. func testNextOutboundMessageWhenClientClosedAndServerClosed() throws {
  739. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerOpen)
  740. // Send a message
  741. XCTAssertNoThrow(try stateMachine.send(message: ByteBuffer(bytes: [42, 42]), promise: nil))
  742. // Close server
  743. XCTAssertNoThrow(try stateMachine.receive(headers: .serverTrailers, endStream: true))
  744. // Close client
  745. XCTAssertNoThrow(try stateMachine.closeOutbound())
  746. // Even though we have enqueued a message, don't send it, because the server
  747. // is closed.
  748. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .noMoreMessages)
  749. }
  750. // - MARK: Next inbound message
  751. func testNextInboundMessageWhenServerIdle() {
  752. for targetState in [
  753. TargetStateMachineState.clientIdleServerIdle, .clientOpenServerIdle, .clientClosedServerIdle,
  754. ] {
  755. var stateMachine = self.makeClientStateMachine(targetState: targetState)
  756. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  757. }
  758. }
  759. func testNextInboundMessageWhenClientOpenAndServerOpen() throws {
  760. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerOpen)
  761. let receivedBytes = ByteBuffer(bytes: [
  762. 0, // compression flag: unset
  763. 0, 0, 0, 2, // message length: 2 bytes
  764. 42, 42, // original message
  765. ])
  766. XCTAssertEqual(
  767. try stateMachine.receive(buffer: receivedBytes, endStream: false),
  768. .readInbound
  769. )
  770. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(ByteBuffer(bytes: [42, 42])))
  771. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  772. }
  773. func testNextInboundMessageWhenClientOpenAndServerOpen_WithCompression() throws {
  774. var stateMachine = self.makeClientStateMachine(
  775. targetState: .clientOpenServerOpen,
  776. compressionEnabled: true
  777. )
  778. let originalMessage = ByteBuffer(bytes: [42, 42, 43, 43])
  779. let receivedBytes = try self.frameMessage(originalMessage, compression: .deflate)
  780. XCTAssertEqual(
  781. try stateMachine.receive(buffer: receivedBytes, endStream: false),
  782. .readInbound
  783. )
  784. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(originalMessage))
  785. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  786. }
  787. func testNextInboundMessageWhenClientOpenAndServerClosed() throws {
  788. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerOpen)
  789. let receivedBytes = ByteBuffer(bytes: [
  790. 0, // compression flag: unset
  791. 0, 0, 0, 2, // message length: 2 bytes
  792. 42, 42, // original message
  793. ])
  794. XCTAssertEqual(
  795. try stateMachine.receive(buffer: receivedBytes, endStream: false),
  796. .readInbound
  797. )
  798. // Close server
  799. XCTAssertNoThrow(try stateMachine.receive(headers: .serverTrailers, endStream: true))
  800. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(ByteBuffer(bytes: [42, 42])))
  801. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  802. }
  803. func testNextInboundMessageWhenClientClosedAndServerOpen() throws {
  804. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerOpen)
  805. let receivedBytes = ByteBuffer(bytes: [
  806. 0, // compression flag: unset
  807. 0, 0, 0, 2, // message length: 2 bytes
  808. 42, 42, // original message
  809. ])
  810. XCTAssertEqual(
  811. try stateMachine.receive(buffer: receivedBytes, endStream: false),
  812. .readInbound
  813. )
  814. // Close client
  815. XCTAssertNoThrow(try stateMachine.closeOutbound())
  816. // Even though the client is closed, because it received a message while open,
  817. // we must get the message now.
  818. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(ByteBuffer(bytes: [42, 42])))
  819. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  820. }
  821. func testNextInboundMessageWhenClientClosedAndServerClosed() throws {
  822. var stateMachine = self.makeClientStateMachine(targetState: .clientOpenServerOpen)
  823. let receivedBytes = ByteBuffer(bytes: [
  824. 0, // compression flag: unset
  825. 0, 0, 0, 2, // message length: 2 bytes
  826. 42, 42, // original message
  827. ])
  828. XCTAssertEqual(
  829. try stateMachine.receive(buffer: receivedBytes, endStream: false),
  830. .readInbound
  831. )
  832. // Close server
  833. XCTAssertNoThrow(try stateMachine.receive(headers: .serverTrailers, endStream: true))
  834. // Close client
  835. XCTAssertNoThrow(try stateMachine.closeOutbound())
  836. // Even though the client is closed, because it received a message while open,
  837. // we must get the message now.
  838. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(ByteBuffer(bytes: [42, 42])))
  839. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  840. }
  841. // - MARK: Unexpected close
  842. func testUnexpectedCloseWhenServerIdleOrOpen() throws {
  843. let thrownError = RPCError(code: .deadlineExceeded, message: "Test error")
  844. let reasonAndExpectedStatusPairs = [
  845. (
  846. GRPCStreamStateMachine.UnexpectedInboundCloseReason.channelInactive,
  847. Status(code: .unavailable, message: "Stream unexpectedly closed.")
  848. ),
  849. (
  850. GRPCStreamStateMachine.UnexpectedInboundCloseReason.streamReset,
  851. Status(
  852. code: .unavailable,
  853. message: "Stream unexpectedly closed: a RST_STREAM frame was received."
  854. )
  855. ),
  856. (
  857. GRPCStreamStateMachine.UnexpectedInboundCloseReason.errorThrown(thrownError),
  858. Status(
  859. code: .unavailable,
  860. message: "Stream unexpectedly closed with error."
  861. )
  862. ),
  863. ]
  864. let states = [
  865. TargetStateMachineState.clientIdleServerIdle,
  866. .clientOpenServerIdle,
  867. .clientOpenServerOpen,
  868. .clientClosedServerIdle,
  869. .clientClosedServerOpen,
  870. ]
  871. for state in states {
  872. for (closeReason, expectedStatus) in reasonAndExpectedStatusPairs {
  873. var stateMachine = self.makeClientStateMachine(targetState: state)
  874. var action = stateMachine.unexpectedInboundClose(reason: closeReason)
  875. guard case .forwardStatus_clientOnly(let status) = action else {
  876. XCTFail("Should have been `fireError` but was `\(action)` (state: \(state)).")
  877. return
  878. }
  879. XCTAssertEqual(status, expectedStatus)
  880. // Calling unexpectedInboundClose again should return `doNothing` because
  881. // we're already closed.
  882. action = stateMachine.unexpectedInboundClose(reason: closeReason)
  883. guard case .doNothing = action else {
  884. XCTFail("Should have been `doNothing` but was `\(action)` (state: \(state)).")
  885. return
  886. }
  887. }
  888. }
  889. }
  890. func testUnexpectedCloseWhenServerClosed() throws {
  891. let closeReasons = [
  892. GRPCStreamStateMachine.UnexpectedInboundCloseReason.channelInactive,
  893. .streamReset,
  894. .errorThrown(RPCError(code: .deadlineExceeded, message: "Test error")),
  895. ]
  896. let states = [
  897. TargetStateMachineState.clientOpenServerClosed,
  898. .clientClosedServerClosed,
  899. ]
  900. for state in states {
  901. for closeReason in closeReasons {
  902. var stateMachine = self.makeClientStateMachine(targetState: state)
  903. var action = stateMachine.unexpectedInboundClose(reason: closeReason)
  904. guard case .doNothing = action else {
  905. XCTFail("Should have been `doNothing` but was `\(action)` (state: \(state)).")
  906. return
  907. }
  908. // Calling unexpectedInboundClose again should return `doNothing` again.
  909. action = stateMachine.unexpectedInboundClose(reason: closeReason)
  910. guard case .doNothing = action else {
  911. XCTFail("Should have been `doNothing` but was `\(action)` (state: \(state)).")
  912. return
  913. }
  914. }
  915. }
  916. }
  917. // - MARK: Common paths
  918. func testNormalFlow() throws {
  919. var stateMachine = self.makeClientStateMachine(targetState: .clientIdleServerIdle)
  920. // Client sends metadata
  921. let clientInitialMetadata = try stateMachine.send(metadata: .init())
  922. XCTAssertEqual(
  923. clientInitialMetadata,
  924. [
  925. GRPCHTTP2Keys.path.rawValue: "/test/test",
  926. GRPCHTTP2Keys.scheme.rawValue: "http",
  927. GRPCHTTP2Keys.method.rawValue: "POST",
  928. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  929. GRPCHTTP2Keys.te.rawValue: "trailers",
  930. GRPCHTTP2Keys.acceptEncoding.rawValue: "deflate",
  931. ]
  932. )
  933. // Server sends initial metadata
  934. let serverInitialHeadersAction = try stateMachine.receive(
  935. headers: .serverInitialMetadata,
  936. endStream: false
  937. )
  938. XCTAssertEqual(
  939. serverInitialHeadersAction,
  940. .receivedMetadata(
  941. [
  942. ":status": "200",
  943. "content-type": "application/grpc",
  944. ],
  945. nil
  946. )
  947. )
  948. // Client sends messages
  949. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .awaitMoreMessages)
  950. let message = ByteBuffer(bytes: [1, 2, 3, 4])
  951. let framedMessage = try self.frameMessage(message, compression: .none)
  952. try stateMachine.send(message: message, promise: nil)
  953. XCTAssertEqual(
  954. try stateMachine.nextOutboundFrame(),
  955. .sendFrame(frame: framedMessage, promise: nil)
  956. )
  957. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .awaitMoreMessages)
  958. // Server sends response
  959. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  960. let firstResponseBytes = ByteBuffer(bytes: [5, 6, 7])
  961. let firstResponse = try self.frameMessage(firstResponseBytes, compression: .none)
  962. let secondResponseBytes = ByteBuffer(bytes: [8, 9, 10])
  963. let secondResponse = try self.frameMessage(secondResponseBytes, compression: .none)
  964. XCTAssertEqual(
  965. try stateMachine.receive(buffer: firstResponse, endStream: false),
  966. .readInbound
  967. )
  968. XCTAssertEqual(
  969. try stateMachine.receive(buffer: secondResponse, endStream: false),
  970. .readInbound
  971. )
  972. // Make sure messages have arrived
  973. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(firstResponseBytes))
  974. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(secondResponseBytes))
  975. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  976. // Client sends end
  977. XCTAssertNoThrow(try stateMachine.closeOutbound())
  978. // Server ends
  979. let metadataReceivedAction = try stateMachine.receive(
  980. headers: .serverTrailers,
  981. endStream: true
  982. )
  983. let receivedMetadata = {
  984. var m = Metadata(headers: .serverTrailers)
  985. m.removeAllValues(forKey: GRPCHTTP2Keys.grpcStatus.rawValue)
  986. m.removeAllValues(forKey: GRPCHTTP2Keys.grpcStatusMessage.rawValue)
  987. return m
  988. }()
  989. XCTAssertEqual(
  990. metadataReceivedAction,
  991. .receivedStatusAndMetadata_clientOnly(
  992. status: .init(code: .ok, message: ""),
  993. metadata: receivedMetadata
  994. )
  995. )
  996. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .noMoreMessages)
  997. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  998. }
  999. func testClientClosesBeforeItCanOpen() throws {
  1000. var stateMachine = self.makeClientStateMachine(targetState: .clientIdleServerIdle)
  1001. XCTAssertNoThrow(try stateMachine.closeOutbound())
  1002. }
  1003. func testClientClosesBeforeServerOpens() throws {
  1004. var stateMachine = self.makeClientStateMachine(targetState: .clientIdleServerIdle)
  1005. // Client sends metadata
  1006. let clientInitialMetadata = try stateMachine.send(metadata: .init())
  1007. XCTAssertEqual(
  1008. clientInitialMetadata,
  1009. [
  1010. GRPCHTTP2Keys.path.rawValue: "/test/test",
  1011. GRPCHTTP2Keys.scheme.rawValue: "http",
  1012. GRPCHTTP2Keys.method.rawValue: "POST",
  1013. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  1014. GRPCHTTP2Keys.te.rawValue: "trailers",
  1015. GRPCHTTP2Keys.acceptEncoding.rawValue: "deflate",
  1016. ]
  1017. )
  1018. // Client sends messages and ends
  1019. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .awaitMoreMessages)
  1020. let message = ByteBuffer(bytes: [1, 2, 3, 4])
  1021. let framedMessage = try self.frameMessage(message, compression: .none)
  1022. XCTAssertNoThrow(try stateMachine.send(message: message, promise: nil))
  1023. XCTAssertNoThrow(try stateMachine.closeOutbound())
  1024. XCTAssertEqual(
  1025. try stateMachine.nextOutboundFrame(),
  1026. .sendFrame(frame: framedMessage, promise: nil)
  1027. )
  1028. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .noMoreMessages)
  1029. // Server sends initial metadata
  1030. let serverInitialHeadersAction = try stateMachine.receive(
  1031. headers: .serverInitialMetadata,
  1032. endStream: false
  1033. )
  1034. XCTAssertEqual(
  1035. serverInitialHeadersAction,
  1036. .receivedMetadata(
  1037. [
  1038. ":status": "200",
  1039. "content-type": "application/grpc",
  1040. ],
  1041. nil
  1042. )
  1043. )
  1044. // Server sends response
  1045. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  1046. let firstResponseBytes = ByteBuffer(bytes: [5, 6, 7])
  1047. let firstResponse = try self.frameMessage(firstResponseBytes, compression: .none)
  1048. let secondResponseBytes = ByteBuffer(bytes: [8, 9, 10])
  1049. let secondResponse = try self.frameMessage(secondResponseBytes, compression: .none)
  1050. XCTAssertEqual(
  1051. try stateMachine.receive(buffer: firstResponse, endStream: false),
  1052. .readInbound
  1053. )
  1054. XCTAssertEqual(
  1055. try stateMachine.receive(buffer: secondResponse, endStream: false),
  1056. .readInbound
  1057. )
  1058. // Make sure messages have arrived
  1059. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(firstResponseBytes))
  1060. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(secondResponseBytes))
  1061. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  1062. // Server ends
  1063. let metadataReceivedAction = try stateMachine.receive(
  1064. headers: .serverTrailers,
  1065. endStream: true
  1066. )
  1067. let receivedMetadata = {
  1068. var m = Metadata(headers: .serverTrailers)
  1069. m.removeAllValues(forKey: GRPCHTTP2Keys.grpcStatus.rawValue)
  1070. m.removeAllValues(forKey: GRPCHTTP2Keys.grpcStatusMessage.rawValue)
  1071. return m
  1072. }()
  1073. XCTAssertEqual(
  1074. metadataReceivedAction,
  1075. .receivedStatusAndMetadata_clientOnly(
  1076. status: .init(code: .ok, message: ""),
  1077. metadata: receivedMetadata
  1078. )
  1079. )
  1080. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .noMoreMessages)
  1081. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  1082. }
  1083. func testClientClosesBeforeServerResponds() throws {
  1084. var stateMachine = self.makeClientStateMachine(targetState: .clientIdleServerIdle)
  1085. // Client sends metadata
  1086. let clientInitialMetadata = try stateMachine.send(metadata: .init())
  1087. XCTAssertEqual(
  1088. clientInitialMetadata,
  1089. [
  1090. GRPCHTTP2Keys.path.rawValue: "/test/test",
  1091. GRPCHTTP2Keys.scheme.rawValue: "http",
  1092. GRPCHTTP2Keys.method.rawValue: "POST",
  1093. GRPCHTTP2Keys.contentType.rawValue: "application/grpc",
  1094. GRPCHTTP2Keys.te.rawValue: "trailers",
  1095. GRPCHTTP2Keys.acceptEncoding.rawValue: "deflate",
  1096. ]
  1097. )
  1098. // Client sends messages
  1099. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .awaitMoreMessages)
  1100. let message = ByteBuffer(bytes: [1, 2, 3, 4])
  1101. let framedMessage = try self.frameMessage(message, compression: .none)
  1102. try stateMachine.send(message: message, promise: nil)
  1103. XCTAssertEqual(
  1104. try stateMachine.nextOutboundFrame(),
  1105. .sendFrame(frame: framedMessage, promise: nil)
  1106. )
  1107. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .awaitMoreMessages)
  1108. // Server sends initial metadata
  1109. let serverInitialHeadersAction = try stateMachine.receive(
  1110. headers: .serverInitialMetadata,
  1111. endStream: false
  1112. )
  1113. XCTAssertEqual(
  1114. serverInitialHeadersAction,
  1115. .receivedMetadata(
  1116. [
  1117. ":status": "200",
  1118. "content-type": "application/grpc",
  1119. ],
  1120. nil
  1121. )
  1122. )
  1123. // Client closes
  1124. XCTAssertNoThrow(try stateMachine.closeOutbound())
  1125. // Server sends response
  1126. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  1127. let firstResponseBytes = ByteBuffer(bytes: [5, 6, 7])
  1128. let firstResponse = try self.frameMessage(firstResponseBytes, compression: .none)
  1129. let secondResponseBytes = ByteBuffer(bytes: [8, 9, 10])
  1130. let secondResponse = try self.frameMessage(secondResponseBytes, compression: .none)
  1131. XCTAssertEqual(
  1132. try stateMachine.receive(buffer: firstResponse, endStream: false),
  1133. .readInbound
  1134. )
  1135. XCTAssertEqual(
  1136. try stateMachine.receive(buffer: secondResponse, endStream: false),
  1137. .readInbound
  1138. )
  1139. // Make sure messages have arrived
  1140. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(firstResponseBytes))
  1141. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(secondResponseBytes))
  1142. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  1143. // Server ends
  1144. let metadataReceivedAction = try stateMachine.receive(
  1145. headers: .serverTrailers,
  1146. endStream: true
  1147. )
  1148. let receivedMetadata = {
  1149. var m = Metadata(headers: .serverTrailers)
  1150. m.removeAllValues(forKey: GRPCHTTP2Keys.grpcStatus.rawValue)
  1151. m.removeAllValues(forKey: GRPCHTTP2Keys.grpcStatusMessage.rawValue)
  1152. return m
  1153. }()
  1154. XCTAssertEqual(
  1155. metadataReceivedAction,
  1156. .receivedStatusAndMetadata_clientOnly(
  1157. status: .init(code: .ok, message: ""),
  1158. metadata: receivedMetadata
  1159. )
  1160. )
  1161. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .noMoreMessages)
  1162. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  1163. }
  1164. }
  1165. @available(gRPCSwiftNIOTransport 2.0, *)
  1166. final class GRPCStreamServerStateMachineTests: XCTestCase {
  1167. private func makeServerStateMachine(
  1168. targetState: TargetStateMachineState,
  1169. deflateCompressionEnabled: Bool = false
  1170. ) -> GRPCStreamStateMachine {
  1171. var stateMachine = GRPCStreamStateMachine(
  1172. configuration: .server(
  1173. .init(
  1174. scheme: .http,
  1175. acceptedEncodings: deflateCompressionEnabled ? [.deflate] : []
  1176. )
  1177. ),
  1178. maxPayloadSize: 100,
  1179. skipAssertions: true
  1180. )
  1181. let clientMetadata: HPACKHeaders =
  1182. deflateCompressionEnabled
  1183. ? .clientInitialMetadataWithDeflateCompression : .clientInitialMetadata
  1184. switch targetState {
  1185. case .clientIdleServerIdle:
  1186. break
  1187. case .clientOpenServerIdle:
  1188. // Open client
  1189. XCTAssertNoThrow(try stateMachine.receive(headers: clientMetadata, endStream: false))
  1190. case .clientOpenServerOpen:
  1191. // Open client
  1192. XCTAssertNoThrow(try stateMachine.receive(headers: clientMetadata, endStream: false))
  1193. // Open server
  1194. XCTAssertNoThrow(try stateMachine.send(metadata: Metadata(headers: .serverInitialMetadata)))
  1195. case .clientOpenServerClosed:
  1196. // Open client
  1197. XCTAssertNoThrow(try stateMachine.receive(headers: clientMetadata, endStream: false))
  1198. // Open server
  1199. XCTAssertNoThrow(try stateMachine.send(metadata: Metadata(headers: .serverInitialMetadata)))
  1200. // Close server
  1201. XCTAssertNoThrow(
  1202. try stateMachine.send(
  1203. status: .init(code: .ok, message: ""),
  1204. metadata: []
  1205. )
  1206. )
  1207. case .clientClosedServerIdle:
  1208. // Open client
  1209. XCTAssertNoThrow(try stateMachine.receive(headers: clientMetadata, endStream: false))
  1210. // Close client
  1211. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: true))
  1212. case .clientClosedServerOpen:
  1213. // Open client
  1214. XCTAssertNoThrow(try stateMachine.receive(headers: clientMetadata, endStream: false))
  1215. // Open server
  1216. XCTAssertNoThrow(try stateMachine.send(metadata: Metadata(headers: .serverInitialMetadata)))
  1217. // Close client
  1218. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: true))
  1219. case .clientClosedServerClosed:
  1220. // Open client
  1221. XCTAssertNoThrow(try stateMachine.receive(headers: clientMetadata, endStream: false))
  1222. // Open server
  1223. XCTAssertNoThrow(try stateMachine.send(metadata: Metadata(headers: .serverInitialMetadata)))
  1224. // Close client
  1225. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: true))
  1226. // Close server
  1227. XCTAssertNoThrow(
  1228. try stateMachine.send(
  1229. status: .init(code: .ok, message: ""),
  1230. metadata: []
  1231. )
  1232. )
  1233. }
  1234. return stateMachine
  1235. }
  1236. // - MARK: Send Metadata
  1237. func testSendMetadataWhenClientIdleAndServerIdle() throws {
  1238. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1239. XCTAssertThrowsError(
  1240. ofType: GRPCStreamStateMachine.InvalidState.self,
  1241. try stateMachine.send(metadata: .init())
  1242. ) { error in
  1243. XCTAssertEqual(
  1244. error.message,
  1245. "Client cannot be idle if server is sending initial metadata: it must have opened."
  1246. )
  1247. }
  1248. }
  1249. func testSendMetadataWhenClientOpenAndServerIdle() throws {
  1250. var stateMachine = self.makeServerStateMachine(
  1251. targetState: .clientOpenServerIdle,
  1252. deflateCompressionEnabled: false
  1253. )
  1254. XCTAssertEqual(
  1255. try stateMachine.send(metadata: .init()),
  1256. [
  1257. ":status": "200",
  1258. "content-type": "application/grpc",
  1259. ]
  1260. )
  1261. }
  1262. func testSendMetadataWhenClientOpenAndServerIdle_AndCompressionEnabled() {
  1263. // Enable deflate compression on server
  1264. var stateMachine = self.makeServerStateMachine(
  1265. targetState: .clientOpenServerIdle,
  1266. deflateCompressionEnabled: true
  1267. )
  1268. XCTAssertEqual(
  1269. try stateMachine.send(metadata: .init()),
  1270. [
  1271. ":status": "200",
  1272. "content-type": "application/grpc",
  1273. "grpc-encoding": "deflate",
  1274. ]
  1275. )
  1276. }
  1277. func testSendMetadataWhenClientOpenAndServerOpen() throws {
  1278. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1279. // Try sending metadata again: should throw
  1280. XCTAssertThrowsError(
  1281. ofType: GRPCStreamStateMachine.InvalidState.self,
  1282. try stateMachine.send(metadata: .init())
  1283. ) { error in
  1284. XCTAssertEqual(error.message, "Server has already sent initial metadata.")
  1285. }
  1286. }
  1287. func testSendMetadataWhenClientOpenAndServerClosed() throws {
  1288. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerClosed)
  1289. // Try sending metadata again: should throw
  1290. XCTAssertThrowsError(
  1291. ofType: GRPCStreamStateMachine.InvalidState.self,
  1292. try stateMachine.send(metadata: .init())
  1293. ) { error in
  1294. XCTAssertEqual(error.message, "Server cannot send metadata if closed.")
  1295. }
  1296. }
  1297. func testSendMetadataWhenClientClosedAndServerIdle() throws {
  1298. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerIdle)
  1299. // We should be allowed to send initial metadata if client is closed:
  1300. // client may be finished sending request but may still be awaiting response.
  1301. XCTAssertNoThrow(try stateMachine.send(metadata: .init()))
  1302. }
  1303. func testSendMetadataWhenClientClosedAndServerOpen() throws {
  1304. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerOpen)
  1305. // Try sending metadata again: should throw
  1306. XCTAssertThrowsError(
  1307. ofType: GRPCStreamStateMachine.InvalidState.self,
  1308. try stateMachine.send(metadata: .init())
  1309. ) { error in
  1310. XCTAssertEqual(error.message, "Server has already sent initial metadata.")
  1311. }
  1312. }
  1313. func testSendMetadataWhenClientClosedAndServerClosed() throws {
  1314. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerClosed)
  1315. // Try sending metadata again: should throw
  1316. XCTAssertThrowsError(
  1317. ofType: GRPCStreamStateMachine.InvalidState.self,
  1318. try stateMachine.send(metadata: .init())
  1319. ) { error in
  1320. XCTAssertEqual(error.message, "Server cannot send metadata if closed.")
  1321. }
  1322. }
  1323. // - MARK: Send Message
  1324. func testSendMessageWhenClientIdleAndServerIdle() {
  1325. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1326. XCTAssertThrowsError(
  1327. ofType: GRPCStreamStateMachine.InvalidState.self,
  1328. try stateMachine.send(message: ByteBuffer(), promise: nil)
  1329. ) { error in
  1330. XCTAssertEqual(
  1331. error.message,
  1332. "Server must have sent initial metadata before sending a message."
  1333. )
  1334. }
  1335. }
  1336. func testSendMessageWhenClientOpenAndServerIdle() {
  1337. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerIdle)
  1338. // Now send a message
  1339. XCTAssertThrowsError(
  1340. ofType: GRPCStreamStateMachine.InvalidState.self,
  1341. try stateMachine.send(message: ByteBuffer(), promise: nil)
  1342. ) { error in
  1343. XCTAssertEqual(
  1344. error.message,
  1345. "Server must have sent initial metadata before sending a message."
  1346. )
  1347. }
  1348. }
  1349. func testSendMessageWhenClientOpenAndServerOpen() {
  1350. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1351. // Now send a message
  1352. XCTAssertNoThrow(try stateMachine.send(message: ByteBuffer(), promise: nil))
  1353. }
  1354. func testSendMessageWhenClientOpenAndServerClosed() {
  1355. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerClosed)
  1356. // Try sending another message: it should fail
  1357. XCTAssertThrowsError(
  1358. ofType: GRPCStreamStateMachine.InvalidState.self,
  1359. try stateMachine.send(message: ByteBuffer(), promise: nil)
  1360. ) { error in
  1361. XCTAssertEqual(error.message, "Server can't send a message if it's closed.")
  1362. }
  1363. }
  1364. func testSendMessageWhenClientClosedAndServerIdle() {
  1365. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerIdle)
  1366. XCTAssertThrowsError(
  1367. ofType: GRPCStreamStateMachine.InvalidState.self,
  1368. try stateMachine.send(message: ByteBuffer(), promise: nil)
  1369. ) { error in
  1370. XCTAssertEqual(
  1371. error.message,
  1372. "Server must have sent initial metadata before sending a message."
  1373. )
  1374. }
  1375. }
  1376. func testSendMessageWhenClientClosedAndServerOpen() {
  1377. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerOpen)
  1378. // Try sending a message: even though client is closed, we should send it
  1379. // because it may be expecting a response.
  1380. XCTAssertNoThrow(try stateMachine.send(message: ByteBuffer(), promise: nil))
  1381. }
  1382. func testSendMessageWhenClientClosedAndServerClosed() {
  1383. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerClosed)
  1384. // Try sending another message: it should fail
  1385. XCTAssertThrowsError(
  1386. ofType: GRPCStreamStateMachine.InvalidState.self,
  1387. try stateMachine.send(message: ByteBuffer(), promise: nil)
  1388. ) { error in
  1389. XCTAssertEqual(error.message, "Server can't send a message if it's closed.")
  1390. }
  1391. }
  1392. // - MARK: Send Status and Trailers
  1393. func testSendStatusAndTrailersWhenClientIdle() {
  1394. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1395. XCTAssertThrowsError(
  1396. ofType: GRPCStreamStateMachine.InvalidState.self,
  1397. try stateMachine.send(
  1398. status: .init(code: .ok, message: ""),
  1399. metadata: .init()
  1400. )
  1401. ) { error in
  1402. XCTAssertEqual(error.message, "Server can't send status if client is idle.")
  1403. }
  1404. }
  1405. func testSendStatusAndTrailersWhenClientOpenAndServerIdle() throws {
  1406. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerIdle)
  1407. let trailers = try stateMachine.send(
  1408. status: .init(code: .unknown, message: "RPC unknown"),
  1409. metadata: .init()
  1410. )
  1411. // Make sure it's a trailers-only response: it must have :status header and content-type
  1412. XCTAssertEqual(
  1413. trailers,
  1414. [
  1415. ":status": "200",
  1416. "content-type": "application/grpc",
  1417. "grpc-status": "2",
  1418. "grpc-message": "RPC unknown",
  1419. ]
  1420. )
  1421. // Try sending another message: it should fail because server is now closed.
  1422. XCTAssertThrowsError(
  1423. ofType: GRPCStreamStateMachine.InvalidState.self,
  1424. try stateMachine.send(message: ByteBuffer(), promise: nil)
  1425. ) { error in
  1426. XCTAssertEqual(error.message, "Server can't send a message if it's closed.")
  1427. }
  1428. }
  1429. func testSendStatusAndTrailersWhenClientOpenAndServerOpen() throws {
  1430. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1431. let trailers = try stateMachine.send(
  1432. status: .init(code: .ok, message: ""),
  1433. metadata: .init()
  1434. )
  1435. // Make sure it's NOT a trailers-only response, because the server was
  1436. // already open (so it sent initial metadata): it shouldn't have :status or content-type headers
  1437. XCTAssertEqual(trailers, ["grpc-status": "0"])
  1438. // Try sending another message: it should fail because server is now closed.
  1439. XCTAssertThrowsError(
  1440. ofType: GRPCStreamStateMachine.InvalidState.self,
  1441. try stateMachine.send(message: ByteBuffer(), promise: nil)
  1442. ) { error in
  1443. XCTAssertEqual(error.message, "Server can't send a message if it's closed.")
  1444. }
  1445. }
  1446. func testSendStatusAndTrailersWhenClientOpenAndServerClosed() {
  1447. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerClosed)
  1448. XCTAssertThrowsError(
  1449. ofType: GRPCStreamStateMachine.InvalidState.self,
  1450. try stateMachine.send(
  1451. status: .init(code: .ok, message: ""),
  1452. metadata: .init()
  1453. )
  1454. ) { error in
  1455. XCTAssertEqual(error.message, "Server can't send anything if closed.")
  1456. }
  1457. }
  1458. func testSendStatusAndTrailersWhenClientClosedAndServerIdle() throws {
  1459. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerIdle)
  1460. let trailers = try stateMachine.send(
  1461. status: .init(code: .unknown, message: "RPC unknown"),
  1462. metadata: .init()
  1463. )
  1464. // Make sure it's a trailers-only response: it must have :status header and content-type
  1465. XCTAssertEqual(
  1466. trailers,
  1467. [
  1468. ":status": "200",
  1469. "content-type": "application/grpc",
  1470. "grpc-status": "2",
  1471. "grpc-message": "RPC unknown",
  1472. ]
  1473. )
  1474. // Try sending another message: it should fail because server is now closed.
  1475. XCTAssertThrowsError(
  1476. ofType: GRPCStreamStateMachine.InvalidState.self,
  1477. try stateMachine.send(message: ByteBuffer(), promise: nil)
  1478. ) { error in
  1479. XCTAssertEqual(error.message, "Server can't send a message if it's closed.")
  1480. }
  1481. }
  1482. func testSendStatusAndTrailersWhenClientClosedAndServerOpen() throws {
  1483. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerOpen)
  1484. let trailers = try stateMachine.send(
  1485. status: .init(code: .ok, message: ""),
  1486. metadata: .init()
  1487. )
  1488. // Make sure it's NOT a trailers-only response, because the server was
  1489. // already open (so it sent initial metadata): it shouldn't have :status or content-type headers
  1490. XCTAssertEqual(trailers, ["grpc-status": "0"])
  1491. // Try sending another message: it should fail because server is now closed.
  1492. XCTAssertThrowsError(
  1493. ofType: GRPCStreamStateMachine.InvalidState.self,
  1494. try stateMachine.send(message: ByteBuffer(), promise: nil)
  1495. ) { error in
  1496. XCTAssertEqual(error.message, "Server can't send a message if it's closed.")
  1497. }
  1498. }
  1499. func testSendStatusAndTrailersWhenClientClosedAndServerClosed() {
  1500. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerClosed)
  1501. XCTAssertThrowsError(
  1502. ofType: GRPCStreamStateMachine.InvalidState.self,
  1503. try stateMachine.send(
  1504. status: .init(code: .ok, message: ""),
  1505. metadata: .init()
  1506. )
  1507. ) { error in
  1508. XCTAssertEqual(error.message, "Server can't send anything if closed.")
  1509. }
  1510. }
  1511. // - MARK: Receive metadata
  1512. func testReceiveMetadataWhenClientIdleAndServerIdle() throws {
  1513. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1514. let action = try stateMachine.receive(headers: .clientInitialMetadata, endStream: false)
  1515. XCTAssertEqual(
  1516. action,
  1517. .receivedMetadata(
  1518. Metadata(headers: .clientInitialMetadata),
  1519. MethodDescriptor(path: "/test/test")
  1520. )
  1521. )
  1522. }
  1523. func testReceiveMetadataWhenClientIdleAndServerIdle_WithEndStream() throws {
  1524. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1525. let action = try stateMachine.receive(headers: .clientInitialMetadata, endStream: true)
  1526. XCTAssertEqual(
  1527. action,
  1528. .receivedMetadata(
  1529. Metadata(headers: .clientInitialMetadata),
  1530. MethodDescriptor(path: "/test/test")
  1531. )
  1532. )
  1533. }
  1534. func testReceiveMetadataWhenClientIdleAndServerIdle_MissingContentType() throws {
  1535. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1536. let action = try stateMachine.receive(
  1537. headers: .receivedWithoutContentType,
  1538. endStream: false
  1539. )
  1540. self.assertRejectedRPC(action) { trailers in
  1541. XCTAssertEqual(trailers.count, 1)
  1542. XCTAssertEqual(trailers.firstString(forKey: .status), "415")
  1543. }
  1544. }
  1545. func testReceiveMetadataWhenClientIdleAndServerIdle_InvalidContentType() throws {
  1546. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1547. let action = try stateMachine.receive(
  1548. headers: .receivedWithInvalidContentType,
  1549. endStream: false
  1550. )
  1551. self.assertRejectedRPC(action) { trailers in
  1552. XCTAssertEqual(trailers.count, 1)
  1553. XCTAssertEqual(trailers.firstString(forKey: .status), "415")
  1554. }
  1555. }
  1556. func testReceiveMetadataWhenClientIdleAndServerIdle_MissingPath() throws {
  1557. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1558. let action = try stateMachine.receive(
  1559. headers: .receivedWithoutEndpoint,
  1560. endStream: false
  1561. )
  1562. self.assertRejectedRPC(action) { trailers in
  1563. XCTAssertEqual(
  1564. trailers,
  1565. [
  1566. ":status": "200",
  1567. "content-type": "application/grpc",
  1568. "grpc-status": String(Status.Code.invalidArgument.rawValue),
  1569. "grpc-message": "No :path header has been set.",
  1570. ]
  1571. )
  1572. }
  1573. }
  1574. func testReceiveMetadataWhenClientIdleAndServerIdle_InvalidPath() throws {
  1575. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1576. let action = try stateMachine.receive(
  1577. headers: .receivedWithInvalidPath,
  1578. endStream: false
  1579. )
  1580. self.assertRejectedRPC(action) { trailers in
  1581. XCTAssertEqual(
  1582. trailers,
  1583. [
  1584. ":status": "200",
  1585. "content-type": "application/grpc",
  1586. "grpc-status": String(Status.Code.unimplemented.rawValue),
  1587. "grpc-message":
  1588. "The given :path (someinvalidpath) does not correspond to a valid method.",
  1589. ]
  1590. )
  1591. }
  1592. }
  1593. func testReceiveMetadataWhenClientIdleAndServerIdle_MissingTE() throws {
  1594. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1595. let action = try stateMachine.receive(
  1596. headers: .receivedWithoutTE,
  1597. endStream: false
  1598. )
  1599. let metadata: Metadata = [
  1600. ":path": "/test/test",
  1601. ":scheme": "http",
  1602. ":method": "POST",
  1603. "content-type": "application/grpc",
  1604. ]
  1605. XCTAssertEqual(action, .receivedMetadata(metadata, .testTest))
  1606. }
  1607. func testReceiveMetadataWhenClientIdleAndServerIdle_MissingMethod() throws {
  1608. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1609. let action = try stateMachine.receive(
  1610. headers: .receivedWithoutMethod,
  1611. endStream: false
  1612. )
  1613. self.assertRejectedRPC(action) { trailers in
  1614. XCTAssertEqual(
  1615. trailers,
  1616. [
  1617. ":status": "200",
  1618. "content-type": "application/grpc",
  1619. "grpc-status": "3",
  1620. "grpc-message":
  1621. ":method header is expected to be present and have a value of \"POST\".",
  1622. ]
  1623. )
  1624. }
  1625. }
  1626. func testReceiveMetadataWhenClientIdleAndServerIdle_InvalidMethod() throws {
  1627. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1628. let action = try stateMachine.receive(
  1629. headers: .receivedWithInvalidMethod,
  1630. endStream: false
  1631. )
  1632. self.assertRejectedRPC(action) { trailers in
  1633. XCTAssertEqual(
  1634. trailers,
  1635. [
  1636. ":status": "200",
  1637. "content-type": "application/grpc",
  1638. "grpc-status": "3",
  1639. "grpc-message":
  1640. ":method header is expected to be present and have a value of \"POST\".",
  1641. ]
  1642. )
  1643. }
  1644. }
  1645. func testReceiveMetadataWhenClientIdleAndServerIdle_MissingScheme() throws {
  1646. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1647. let action = try stateMachine.receive(
  1648. headers: .receivedWithoutScheme,
  1649. endStream: false
  1650. )
  1651. self.assertRejectedRPC(action) { trailers in
  1652. XCTAssertEqual(
  1653. trailers,
  1654. [
  1655. ":status": "200",
  1656. "content-type": "application/grpc",
  1657. "grpc-status": "3",
  1658. "grpc-message": ":scheme header must be present and one of \"http\" or \"https\".",
  1659. ]
  1660. )
  1661. }
  1662. }
  1663. func testReceiveMetadataWhenClientIdleAndServerIdle_InvalidScheme() throws {
  1664. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1665. let action = try stateMachine.receive(
  1666. headers: .receivedWithInvalidScheme,
  1667. endStream: false
  1668. )
  1669. self.assertRejectedRPC(action) { trailers in
  1670. XCTAssertEqual(
  1671. trailers,
  1672. [
  1673. ":status": "200",
  1674. "content-type": "application/grpc",
  1675. "grpc-status": "3",
  1676. "grpc-message": ":scheme header must be present and one of \"http\" or \"https\".",
  1677. ]
  1678. )
  1679. }
  1680. }
  1681. func testReceiveMetadataWhenClientIdleAndServerIdle_ServerUnsupportedEncoding() throws {
  1682. var stateMachine = self.makeServerStateMachine(
  1683. targetState: .clientIdleServerIdle,
  1684. deflateCompressionEnabled: true
  1685. )
  1686. // Try opening client with a compression algorithm that is not accepted
  1687. // by the server.
  1688. let action = try stateMachine.receive(
  1689. headers: .clientInitialMetadataWithGzipCompression,
  1690. endStream: false
  1691. )
  1692. self.assertRejectedRPC(action) { trailers in
  1693. let expected: HPACKHeaders = [
  1694. ":status": "200",
  1695. "content-type": "application/grpc",
  1696. "grpc-status": "12",
  1697. "grpc-message":
  1698. "gzip compression is not supported; supported algorithms are listed in grpc-accept-encoding",
  1699. "grpc-accept-encoding": "deflate",
  1700. "grpc-accept-encoding": "identity",
  1701. ]
  1702. XCTAssertEqual(expected.count, trailers.count, "Expected \(expected) but got \(trailers)")
  1703. for header in trailers {
  1704. XCTAssertTrue(
  1705. expected.contains { name, value, _ in
  1706. header.name == name && header.value == header.value
  1707. }
  1708. )
  1709. }
  1710. }
  1711. }
  1712. func testReceiveMetadataWhenClientOpenAndServerIdle() throws {
  1713. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerIdle)
  1714. // Try receiving initial metadata again - should be a protocol violation
  1715. let action = try stateMachine.receive(headers: .clientInitialMetadata, endStream: false)
  1716. XCTAssertEqual(action, .protocolViolation_serverOnly)
  1717. }
  1718. func testReceiveMetadataWhenClientOpenAndServerOpen() throws {
  1719. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1720. let action = try stateMachine.receive(headers: .clientInitialMetadata, endStream: false)
  1721. XCTAssertEqual(action, .protocolViolation_serverOnly)
  1722. }
  1723. func testReceiveMetadataWhenClientOpenAndServerClosed() throws {
  1724. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerClosed)
  1725. let action = try stateMachine.receive(headers: .clientInitialMetadata, endStream: false)
  1726. XCTAssertEqual(action, .protocolViolation_serverOnly)
  1727. }
  1728. func testReceiveMetadataWhenClientClosedAndServerIdle() {
  1729. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerIdle)
  1730. XCTAssertThrowsError(
  1731. ofType: GRPCStreamStateMachine.InvalidState.self,
  1732. try stateMachine.receive(headers: .clientInitialMetadata, endStream: false)
  1733. ) { error in
  1734. XCTAssertEqual(error.message, "Client can't have sent metadata if closed.")
  1735. }
  1736. }
  1737. func testReceiveMetadataWhenClientClosedAndServerOpen() {
  1738. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerOpen)
  1739. XCTAssertThrowsError(
  1740. ofType: GRPCStreamStateMachine.InvalidState.self,
  1741. try stateMachine.receive(headers: .clientInitialMetadata, endStream: false)
  1742. ) { error in
  1743. XCTAssertEqual(error.message, "Client can't have sent metadata if closed.")
  1744. }
  1745. }
  1746. func testReceiveMetadataWhenClientClosedAndServerClosed() {
  1747. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerClosed)
  1748. XCTAssertThrowsError(
  1749. ofType: GRPCStreamStateMachine.InvalidState.self,
  1750. try stateMachine.receive(headers: .clientInitialMetadata, endStream: false)
  1751. ) { error in
  1752. XCTAssertEqual(error.message, "Client can't have sent metadata if closed.")
  1753. }
  1754. }
  1755. // - MARK: Receive message
  1756. func testReceiveMessageWhenClientIdleAndServerIdle() {
  1757. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1758. XCTAssertThrowsError(
  1759. ofType: GRPCStreamStateMachine.InvalidState.self,
  1760. try stateMachine.receive(buffer: .init(), endStream: false)
  1761. ) { error in
  1762. XCTAssertEqual(error.message, "Can't have received a message if client is idle.")
  1763. }
  1764. }
  1765. func testReceiveMessageWhenClientOpenAndServerIdle() {
  1766. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerIdle)
  1767. // Receive messages successfully: the second one should close client.
  1768. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: false))
  1769. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: true))
  1770. // Verify client is now closed
  1771. XCTAssertThrowsError(
  1772. ofType: GRPCStreamStateMachine.InvalidState.self,
  1773. try stateMachine.receive(buffer: .init(), endStream: false)
  1774. ) { error in
  1775. XCTAssertEqual(error.message, "Client can't send a message if closed.")
  1776. }
  1777. }
  1778. func testReceiveMessageWhenClientOpenAndServerOpen() throws {
  1779. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1780. // Receive messages successfully: the second one should close client.
  1781. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: false))
  1782. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: true))
  1783. // Verify client is now closed
  1784. XCTAssertThrowsError(
  1785. ofType: GRPCStreamStateMachine.InvalidState.self,
  1786. try stateMachine.receive(buffer: .init(), endStream: false)
  1787. ) { error in
  1788. XCTAssertEqual(error.message, "Client can't send a message if closed.")
  1789. }
  1790. }
  1791. func testReceiveMessage_ServerCompressionEnabled() throws {
  1792. // Enable deflate compression on server
  1793. var stateMachine = self.makeServerStateMachine(
  1794. targetState: .clientOpenServerOpen,
  1795. deflateCompressionEnabled: true
  1796. )
  1797. let originalMessage = ByteBuffer(bytes: [42, 42, 43, 43])
  1798. // Receiving uncompressed message should still work.
  1799. let receivedUncompressedBytes = try self.frameMessage(originalMessage, compression: .none)
  1800. XCTAssertNoThrow(try stateMachine.receive(buffer: receivedUncompressedBytes, endStream: false))
  1801. var receivedAction = stateMachine.nextInboundMessage()
  1802. switch receivedAction {
  1803. case .noMoreMessages, .awaitMoreMessages:
  1804. XCTFail("Should have received message")
  1805. case .receiveMessage(let receivedMessaged):
  1806. XCTAssertEqual(originalMessage, receivedMessaged)
  1807. }
  1808. // Receiving compressed message with deflate should work
  1809. let receivedDeflateCompressedBytes = try self.frameMessage(
  1810. originalMessage,
  1811. compression: .deflate
  1812. )
  1813. XCTAssertNoThrow(
  1814. try stateMachine.receive(buffer: receivedDeflateCompressedBytes, endStream: false)
  1815. )
  1816. receivedAction = stateMachine.nextInboundMessage()
  1817. switch receivedAction {
  1818. case .noMoreMessages, .awaitMoreMessages:
  1819. XCTFail("Should have received message")
  1820. case .receiveMessage(let receivedMessaged):
  1821. XCTAssertEqual(originalMessage, receivedMessaged)
  1822. }
  1823. // Receiving compressed message with gzip (unsupported) should throw error
  1824. let receivedGZIPCompressedBytes = try self.frameMessage(originalMessage, compression: .gzip)
  1825. let action = try stateMachine.receive(buffer: receivedGZIPCompressedBytes, endStream: false)
  1826. XCTAssertEqual(
  1827. action,
  1828. .forwardErrorAndClose_serverOnly(
  1829. RPCError(code: .internalError, message: "Failed to decode message")
  1830. )
  1831. )
  1832. receivedAction = stateMachine.nextInboundMessage()
  1833. switch receivedAction {
  1834. case .awaitMoreMessages:
  1835. ()
  1836. case .noMoreMessages:
  1837. XCTFail("Should be awaiting for more messages")
  1838. case .receiveMessage:
  1839. XCTFail("Should not have received message")
  1840. }
  1841. }
  1842. func testReceiveMessageWhenClientOpenAndServerClosed() {
  1843. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerClosed)
  1844. // Client is not done sending request, don't fail.
  1845. XCTAssertEqual(try stateMachine.receive(buffer: ByteBuffer(), endStream: false), .doNothing)
  1846. }
  1847. func testReceiveMessageWhenClientClosedAndServerIdle() {
  1848. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerIdle)
  1849. XCTAssertThrowsError(
  1850. ofType: GRPCStreamStateMachine.InvalidState.self,
  1851. try stateMachine.receive(buffer: .init(), endStream: false)
  1852. ) { error in
  1853. XCTAssertEqual(error.message, "Client can't send a message if closed.")
  1854. }
  1855. }
  1856. func testReceiveMessageWhenClientClosedAndServerOpen() {
  1857. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerOpen)
  1858. XCTAssertThrowsError(
  1859. ofType: GRPCStreamStateMachine.InvalidState.self,
  1860. try stateMachine.receive(buffer: .init(), endStream: false)
  1861. ) { error in
  1862. XCTAssertEqual(error.message, "Client can't send a message if closed.")
  1863. }
  1864. }
  1865. func testReceiveMessageWhenClientClosedAndServerClosed() {
  1866. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerClosed)
  1867. XCTAssertThrowsError(
  1868. ofType: GRPCStreamStateMachine.InvalidState.self,
  1869. try stateMachine.receive(buffer: .init(), endStream: false)
  1870. ) { error in
  1871. XCTAssertEqual(error.message, "Client can't send a message if closed.")
  1872. }
  1873. }
  1874. // - MARK: Next outbound message
  1875. func testNextOutboundMessageWhenClientIdleAndServerIdle() {
  1876. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  1877. XCTAssertThrowsError(
  1878. ofType: GRPCStreamStateMachine.InvalidState.self,
  1879. try stateMachine.nextOutboundFrame()
  1880. ) { error in
  1881. XCTAssertEqual(error.message, "Server is not open yet.")
  1882. }
  1883. }
  1884. func testNextOutboundMessageWhenClientOpenAndServerIdle() throws {
  1885. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerIdle)
  1886. XCTAssertThrowsError(
  1887. ofType: GRPCStreamStateMachine.InvalidState.self,
  1888. try stateMachine.nextOutboundFrame()
  1889. ) { error in
  1890. XCTAssertEqual(error.message, "Server is not open yet.")
  1891. }
  1892. }
  1893. func testNextOutboundMessageWhenClientOpenAndServerIdle_WithCompression() throws {
  1894. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerIdle)
  1895. XCTAssertThrowsError(
  1896. ofType: GRPCStreamStateMachine.InvalidState.self,
  1897. try stateMachine.nextOutboundFrame()
  1898. ) { error in
  1899. XCTAssertEqual(error.message, "Server is not open yet.")
  1900. }
  1901. }
  1902. func testNextOutboundMessageWhenClientOpenAndServerOpen() throws {
  1903. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1904. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .awaitMoreMessages)
  1905. XCTAssertNoThrow(try stateMachine.send(message: ByteBuffer(bytes: [42, 42]), promise: nil))
  1906. let response = try stateMachine.nextOutboundFrame()
  1907. let expectedBytes: [UInt8] = [
  1908. 0, // compression flag: unset
  1909. 0, 0, 0, 2, // message length: 2 bytes
  1910. 42, 42, // original message
  1911. ]
  1912. XCTAssertEqual(response, .sendFrame(frame: ByteBuffer(bytes: expectedBytes), promise: nil))
  1913. // And then make sure that nothing else is returned
  1914. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .awaitMoreMessages)
  1915. }
  1916. func testNextOutboundMessageWhenClientOpenAndServerOpen_WithCompression() throws {
  1917. var stateMachine = self.makeServerStateMachine(
  1918. targetState: .clientOpenServerOpen,
  1919. deflateCompressionEnabled: true
  1920. )
  1921. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .awaitMoreMessages)
  1922. let originalMessage = ByteBuffer(bytes: [42, 42, 43, 43])
  1923. XCTAssertNoThrow(try stateMachine.send(message: originalMessage, promise: nil))
  1924. let response = try stateMachine.nextOutboundFrame()
  1925. let framedMessage = try self.frameMessage(originalMessage, compression: .deflate)
  1926. XCTAssertEqual(response, .sendFrame(frame: framedMessage, promise: nil))
  1927. }
  1928. func testNextOutboundMessageWhenClientOpenAndServerClosed() throws {
  1929. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1930. // Send message and close server
  1931. XCTAssertNoThrow(try stateMachine.send(message: ByteBuffer(bytes: [42, 42]), promise: nil))
  1932. XCTAssertNoThrow(
  1933. try stateMachine.send(
  1934. status: .init(code: .ok, message: ""),
  1935. metadata: []
  1936. )
  1937. )
  1938. let response = try stateMachine.nextOutboundFrame()
  1939. let expectedBytes: [UInt8] = [
  1940. 0, // compression flag: unset
  1941. 0, 0, 0, 2, // message length: 2 bytes
  1942. 42, 42, // original message
  1943. ]
  1944. XCTAssertEqual(response, .sendFrame(frame: ByteBuffer(bytes: expectedBytes), promise: nil))
  1945. // And then make sure that nothing else is returned anymore
  1946. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .noMoreMessages)
  1947. }
  1948. func testNextOutboundMessageWhenClientClosedAndServerIdle() throws {
  1949. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerIdle)
  1950. XCTAssertThrowsError(
  1951. ofType: GRPCStreamStateMachine.InvalidState.self,
  1952. try stateMachine.nextOutboundFrame()
  1953. ) { error in
  1954. XCTAssertEqual(error.message, "Server is not open yet.")
  1955. }
  1956. }
  1957. func testNextOutboundMessageWhenClientClosedAndServerOpen() throws {
  1958. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  1959. // Send a message
  1960. XCTAssertNoThrow(try stateMachine.send(message: ByteBuffer(bytes: [42, 42]), promise: nil))
  1961. // Close client
  1962. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: true))
  1963. // Send another message
  1964. XCTAssertNoThrow(try stateMachine.send(message: ByteBuffer(bytes: [43, 43]), promise: nil))
  1965. // Make sure that getting the next outbound message _does_ return the message
  1966. // we have enqueued.
  1967. let response = try stateMachine.nextOutboundFrame()
  1968. let expectedBytes: [UInt8] = [
  1969. 0, // compression flag: unset
  1970. 0, 0, 0, 2, // message length: 2 bytes
  1971. 42, 42, // original message
  1972. // End of first message - beginning of second
  1973. 0, // compression flag: unset
  1974. 0, 0, 0, 2, // message length: 2 bytes
  1975. 43, 43, // original message
  1976. ]
  1977. XCTAssertEqual(response, .sendFrame(frame: ByteBuffer(bytes: expectedBytes), promise: nil))
  1978. // And then make sure that nothing else is returned anymore
  1979. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .awaitMoreMessages)
  1980. }
  1981. func testNextOutboundMessageWhenClientClosedAndServerClosed() throws {
  1982. var stateMachine = self.makeServerStateMachine(targetState: .clientClosedServerOpen)
  1983. // Send a message and close server
  1984. XCTAssertNoThrow(try stateMachine.send(message: ByteBuffer(bytes: [42, 42]), promise: nil))
  1985. XCTAssertNoThrow(
  1986. try stateMachine.send(
  1987. status: .init(code: .ok, message: ""),
  1988. metadata: []
  1989. )
  1990. )
  1991. // We have enqueued a message, make sure we return it even though server is closed,
  1992. // because we haven't yet drained all of the pending messages.
  1993. let response = try stateMachine.nextOutboundFrame()
  1994. let expectedBytes: [UInt8] = [
  1995. 0, // compression flag: unset
  1996. 0, 0, 0, 2, // message length: 2 bytes
  1997. 42, 42, // original message
  1998. ]
  1999. XCTAssertEqual(response, .sendFrame(frame: ByteBuffer(bytes: expectedBytes), promise: nil))
  2000. // And then make sure that nothing else is returned anymore
  2001. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .noMoreMessages)
  2002. }
  2003. // - MARK: Next inbound message
  2004. func testNextInboundMessageWhenClientIdleAndServerIdle() {
  2005. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  2006. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  2007. }
  2008. func testNextInboundMessageWhenClientOpenAndServerIdle() {
  2009. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerIdle)
  2010. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  2011. }
  2012. func testNextInboundMessageWhenClientOpenAndServerOpen() throws {
  2013. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  2014. let receivedBytes = ByteBuffer(bytes: [
  2015. 0, // compression flag: unset
  2016. 0, 0, 0, 2, // message length: 2 bytes
  2017. 42, 42, // original message
  2018. ])
  2019. XCTAssertEqual(
  2020. try stateMachine.receive(buffer: receivedBytes, endStream: false),
  2021. .readInbound
  2022. )
  2023. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(ByteBuffer(bytes: [42, 42])))
  2024. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  2025. }
  2026. func testNextInboundMessageWhenClientOpenAndServerOpen_WithCompression() throws {
  2027. var stateMachine = self.makeServerStateMachine(
  2028. targetState: .clientOpenServerOpen,
  2029. deflateCompressionEnabled: true
  2030. )
  2031. let originalMessage = ByteBuffer(bytes: [42, 42, 43, 43])
  2032. let receivedBytes = try self.frameMessage(originalMessage, compression: .deflate)
  2033. XCTAssertEqual(
  2034. try stateMachine.receive(buffer: receivedBytes, endStream: false),
  2035. .readInbound
  2036. )
  2037. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(originalMessage))
  2038. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  2039. }
  2040. func testNextInboundMessageWhenClientOpenAndServerClosed() throws {
  2041. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  2042. let receivedBytes = ByteBuffer(bytes: [
  2043. 0, // compression flag: unset
  2044. 0, 0, 0, 2, // message length: 2 bytes
  2045. 42, 42, // original message
  2046. ])
  2047. XCTAssertEqual(
  2048. try stateMachine.receive(buffer: receivedBytes, endStream: false),
  2049. .readInbound
  2050. )
  2051. // Close server
  2052. XCTAssertNoThrow(
  2053. try stateMachine.send(
  2054. status: .init(code: .ok, message: ""),
  2055. metadata: []
  2056. )
  2057. )
  2058. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  2059. }
  2060. func testNextInboundMessageWhenClientClosedAndServerIdle() throws {
  2061. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerIdle)
  2062. let action = try stateMachine.receive(
  2063. buffer: ByteBuffer(repeating: 0, count: 5),
  2064. endStream: true
  2065. )
  2066. XCTAssertEqual(action, .readInbound)
  2067. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(ByteBuffer()))
  2068. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  2069. }
  2070. func testNextInboundMessageWhenClientClosedAndServerOpen() throws {
  2071. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  2072. let receivedBytes = ByteBuffer(bytes: [
  2073. 0, // compression flag: unset
  2074. 0, 0, 0, 2, // message length: 2 bytes
  2075. 42, 42, // original message
  2076. ])
  2077. XCTAssertEqual(
  2078. try stateMachine.receive(buffer: receivedBytes, endStream: false),
  2079. .readInbound
  2080. )
  2081. // Close client
  2082. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: true))
  2083. // Even though the client is closed, because the server received a message
  2084. // while it was still open, we must get the message now.
  2085. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(ByteBuffer(bytes: [42, 42])))
  2086. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  2087. }
  2088. func testNextInboundMessageWhenClientClosedAndServerClosed() throws {
  2089. var stateMachine = self.makeServerStateMachine(targetState: .clientOpenServerOpen)
  2090. let receivedBytes = ByteBuffer(bytes: [
  2091. 0, // compression flag: unset
  2092. 0, 0, 0, 2, // message length: 2 bytes
  2093. 42, 42, // original message
  2094. ])
  2095. XCTAssertEqual(
  2096. try stateMachine.receive(buffer: receivedBytes, endStream: false),
  2097. .readInbound
  2098. )
  2099. // Close server
  2100. XCTAssertNoThrow(
  2101. try stateMachine.send(
  2102. status: .init(code: .ok, message: ""),
  2103. metadata: []
  2104. )
  2105. )
  2106. // Close client
  2107. XCTAssertNoThrow(try stateMachine.receive(buffer: .init(), endStream: true))
  2108. // The server is closed, the message should be dropped.
  2109. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  2110. }
  2111. // - MARK: Unexpected close
  2112. func testUnexpectedCloseWhenClientIdleOrOpen() throws {
  2113. let reasonAndExpectedErrorPairs = [
  2114. (
  2115. GRPCStreamStateMachine.UnexpectedInboundCloseReason.channelInactive,
  2116. RPCError(code: .unavailable, message: "Stream unexpectedly closed.")
  2117. ),
  2118. (
  2119. GRPCStreamStateMachine.UnexpectedInboundCloseReason.streamReset,
  2120. RPCError(
  2121. code: .unavailable,
  2122. message: "Stream unexpectedly closed: a RST_STREAM frame was received."
  2123. )
  2124. ),
  2125. (
  2126. GRPCStreamStateMachine.UnexpectedInboundCloseReason.errorThrown(
  2127. RPCError(code: .deadlineExceeded, message: "Test error")
  2128. ),
  2129. RPCError(code: .deadlineExceeded, message: "Test error")
  2130. ),
  2131. ]
  2132. let states = [
  2133. TargetStateMachineState.clientIdleServerIdle,
  2134. .clientOpenServerIdle,
  2135. .clientOpenServerOpen,
  2136. .clientOpenServerClosed,
  2137. ]
  2138. for state in states {
  2139. for (closeReason, expectedError) in reasonAndExpectedErrorPairs {
  2140. var stateMachine = self.makeServerStateMachine(targetState: state)
  2141. var action = stateMachine.unexpectedInboundClose(reason: closeReason)
  2142. guard case .fireError_serverOnly(let error) = action else {
  2143. XCTFail("Should have been `fireError` but was `\(action)` (state: \(state)).")
  2144. return
  2145. }
  2146. XCTAssertEqual(error as? RPCError, expectedError)
  2147. // Calling unexpectedInboundClose again should return `doNothing` because
  2148. // we're already closed.
  2149. action = stateMachine.unexpectedInboundClose(reason: closeReason)
  2150. guard case .doNothing = action else {
  2151. XCTFail("Should have been `doNothing` but was `\(action)` (state: \(state)).")
  2152. return
  2153. }
  2154. }
  2155. }
  2156. }
  2157. func testUnexpectedCloseWhenClientClosed() throws {
  2158. let closeReasons = [
  2159. GRPCStreamStateMachine.UnexpectedInboundCloseReason.channelInactive,
  2160. .streamReset,
  2161. .errorThrown(RPCError(code: .deadlineExceeded, message: "Test error")),
  2162. ]
  2163. let states = [
  2164. TargetStateMachineState.clientClosedServerIdle,
  2165. .clientClosedServerOpen,
  2166. .clientClosedServerClosed,
  2167. ]
  2168. for state in states {
  2169. for closeReason in closeReasons {
  2170. var stateMachine = self.makeServerStateMachine(targetState: state)
  2171. var action = stateMachine.unexpectedInboundClose(reason: closeReason)
  2172. guard case .doNothing = action else {
  2173. XCTFail("Should have been `doNothing` but was `\(action)` (state: \(state)).")
  2174. return
  2175. }
  2176. // Calling unexpectedInboundClose again should return `doNothing` again.
  2177. action = stateMachine.unexpectedInboundClose(reason: closeReason)
  2178. guard case .doNothing = action else {
  2179. XCTFail("Should have been `doNothing` but was `\(action)` (state: \(state)).")
  2180. return
  2181. }
  2182. }
  2183. }
  2184. }
  2185. // - MARK: Common paths
  2186. func testNormalFlow() throws {
  2187. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  2188. // Client sends metadata
  2189. let receiveMetadataAction = try stateMachine.receive(
  2190. headers: .clientInitialMetadata,
  2191. endStream: false
  2192. )
  2193. XCTAssertEqual(
  2194. receiveMetadataAction,
  2195. .receivedMetadata(
  2196. Metadata(headers: .clientInitialMetadata),
  2197. MethodDescriptor(path: "/test/test")
  2198. )
  2199. )
  2200. // Server sends initial metadata
  2201. let sentInitialHeaders = try stateMachine.send(metadata: Metadata(headers: ["custom": "value"]))
  2202. XCTAssertEqual(
  2203. sentInitialHeaders,
  2204. [
  2205. ":status": "200",
  2206. "content-type": "application/grpc",
  2207. "custom": "value",
  2208. ]
  2209. )
  2210. // Client sends messages
  2211. let deframedMessage = ByteBuffer(bytes: [1, 2, 3, 4])
  2212. let completeMessage = try self.frameMessage(deframedMessage, compression: .none)
  2213. // Split message into two parts to make sure the stitching together of the frames works well
  2214. let firstMessage = completeMessage.getSlice(at: 0, length: 4)!
  2215. let secondMessage = completeMessage.getSlice(at: 4, length: completeMessage.readableBytes - 4)!
  2216. XCTAssertEqual(
  2217. try stateMachine.receive(buffer: firstMessage, endStream: false),
  2218. .readInbound
  2219. )
  2220. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  2221. XCTAssertEqual(
  2222. try stateMachine.receive(buffer: secondMessage, endStream: false),
  2223. .readInbound
  2224. )
  2225. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(deframedMessage))
  2226. // Server sends response
  2227. let eventLoop = EmbeddedEventLoop()
  2228. let firstPromise = eventLoop.makePromise(of: Void.self)
  2229. let secondPromise = eventLoop.makePromise(of: Void.self)
  2230. let firstResponse = ByteBuffer(bytes: [5, 6, 7])
  2231. let secondResponse = ByteBuffer(bytes: [8, 9, 10])
  2232. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .awaitMoreMessages)
  2233. try stateMachine.send(message: firstResponse, promise: firstPromise)
  2234. try stateMachine.send(message: secondResponse, promise: secondPromise)
  2235. // Make sure messages are outbound
  2236. let framedMessages = try self.frameMessages(
  2237. [firstResponse, secondResponse],
  2238. compression: .none
  2239. )
  2240. guard
  2241. case .sendFrame(let nextOutboundByteBuffer, let nextOutboundPromise) =
  2242. try stateMachine.nextOutboundFrame()
  2243. else {
  2244. XCTFail("Should have received .sendMessage")
  2245. return
  2246. }
  2247. XCTAssertEqual(nextOutboundByteBuffer, framedMessages)
  2248. XCTAssertTrue(firstPromise.futureResult === nextOutboundPromise?.futureResult)
  2249. // Make sure that the promises associated with each sent message are chained
  2250. // together: when succeeding the one returned by the state machine on
  2251. // `nextOutboundMessage()`, the others should also be succeeded.
  2252. firstPromise.succeed()
  2253. try secondPromise.futureResult.assertSuccess().wait()
  2254. // Client sends end
  2255. XCTAssertEqual(
  2256. try stateMachine.receive(buffer: ByteBuffer(), endStream: true),
  2257. .readInbound
  2258. )
  2259. // Server ends
  2260. let response = try stateMachine.send(
  2261. status: .init(code: .ok, message: ""),
  2262. metadata: []
  2263. )
  2264. XCTAssertEqual(response, ["grpc-status": "0"])
  2265. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .noMoreMessages)
  2266. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  2267. }
  2268. func testClientClosesBeforeServerOpens() throws {
  2269. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  2270. // Client sends metadata
  2271. let receiveMetadataAction = try stateMachine.receive(
  2272. headers: .clientInitialMetadata,
  2273. endStream: false
  2274. )
  2275. XCTAssertEqual(
  2276. receiveMetadataAction,
  2277. .receivedMetadata(
  2278. Metadata(headers: .clientInitialMetadata),
  2279. MethodDescriptor(path: "/test/test")
  2280. )
  2281. )
  2282. // Client sends messages
  2283. let deframedMessage = ByteBuffer(bytes: [1, 2, 3, 4])
  2284. let completeMessage = try self.frameMessage(deframedMessage, compression: .none)
  2285. // Split message into two parts to make sure the stitching together of the frames works well
  2286. let firstMessage = completeMessage.getSlice(at: 0, length: 4)!
  2287. let secondMessage = completeMessage.getSlice(at: 4, length: completeMessage.readableBytes - 4)!
  2288. XCTAssertEqual(
  2289. try stateMachine.receive(buffer: firstMessage, endStream: false),
  2290. .readInbound
  2291. )
  2292. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  2293. XCTAssertEqual(
  2294. try stateMachine.receive(buffer: secondMessage, endStream: false),
  2295. .readInbound
  2296. )
  2297. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(deframedMessage))
  2298. // Client sends end
  2299. XCTAssertEqual(
  2300. try stateMachine.receive(buffer: ByteBuffer(), endStream: true),
  2301. .readInbound
  2302. )
  2303. // Server sends initial metadata
  2304. let sentInitialHeaders = try stateMachine.send(metadata: Metadata(headers: ["custom": "value"]))
  2305. XCTAssertEqual(
  2306. sentInitialHeaders,
  2307. [
  2308. "custom": "value",
  2309. ":status": "200",
  2310. "content-type": "application/grpc",
  2311. ]
  2312. )
  2313. // Server sends response
  2314. let firstResponse = ByteBuffer(bytes: [5, 6, 7])
  2315. let secondResponse = ByteBuffer(bytes: [8, 9, 10])
  2316. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .awaitMoreMessages)
  2317. try stateMachine.send(message: firstResponse, promise: nil)
  2318. try stateMachine.send(message: secondResponse, promise: nil)
  2319. // Make sure messages are outbound
  2320. let framedMessages = try self.frameMessages(
  2321. [firstResponse, secondResponse],
  2322. compression: .none
  2323. )
  2324. XCTAssertEqual(
  2325. try stateMachine.nextOutboundFrame(),
  2326. .sendFrame(frame: framedMessages, promise: nil)
  2327. )
  2328. // Server ends
  2329. let response = try stateMachine.send(
  2330. status: .init(code: .ok, message: ""),
  2331. metadata: []
  2332. )
  2333. XCTAssertEqual(response, ["grpc-status": "0"])
  2334. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .noMoreMessages)
  2335. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  2336. }
  2337. func testClientClosesBeforeServerResponds() throws {
  2338. var stateMachine = self.makeServerStateMachine(targetState: .clientIdleServerIdle)
  2339. // Client sends metadata
  2340. let receiveMetadataAction = try stateMachine.receive(
  2341. headers: .clientInitialMetadata,
  2342. endStream: false
  2343. )
  2344. XCTAssertEqual(
  2345. receiveMetadataAction,
  2346. .receivedMetadata(
  2347. Metadata(headers: .clientInitialMetadata),
  2348. MethodDescriptor(path: "/test/test")
  2349. )
  2350. )
  2351. // Client sends messages
  2352. let deframedMessage = ByteBuffer(bytes: [1, 2, 3, 4])
  2353. let completeMessage = try self.frameMessage(deframedMessage, compression: .none)
  2354. // Split message into two parts to make sure the stitching together of the frames works well
  2355. let firstMessage = completeMessage.getSlice(at: 0, length: 4)!
  2356. let secondMessage = completeMessage.getSlice(at: 4, length: completeMessage.readableBytes - 4)!
  2357. XCTAssertEqual(
  2358. try stateMachine.receive(buffer: firstMessage, endStream: false),
  2359. .readInbound
  2360. )
  2361. XCTAssertEqual(stateMachine.nextInboundMessage(), .awaitMoreMessages)
  2362. XCTAssertEqual(
  2363. try stateMachine.receive(buffer: secondMessage, endStream: false),
  2364. .readInbound
  2365. )
  2366. XCTAssertEqual(stateMachine.nextInboundMessage(), .receiveMessage(deframedMessage))
  2367. // Server sends initial metadata
  2368. let sentInitialHeaders = try stateMachine.send(metadata: Metadata(headers: ["custom": "value"]))
  2369. XCTAssertEqual(
  2370. sentInitialHeaders,
  2371. [
  2372. "custom": "value",
  2373. ":status": "200",
  2374. "content-type": "application/grpc",
  2375. ]
  2376. )
  2377. // Client sends end
  2378. XCTAssertEqual(
  2379. try stateMachine.receive(buffer: ByteBuffer(), endStream: true),
  2380. .readInbound
  2381. )
  2382. // Server sends response
  2383. let firstResponse = ByteBuffer(bytes: [5, 6, 7])
  2384. let secondResponse = ByteBuffer(bytes: [8, 9, 10])
  2385. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .awaitMoreMessages)
  2386. try stateMachine.send(message: firstResponse, promise: nil)
  2387. try stateMachine.send(message: secondResponse, promise: nil)
  2388. // Make sure messages are outbound
  2389. let framedMessages = try self.frameMessages(
  2390. [firstResponse, secondResponse],
  2391. compression: .none
  2392. )
  2393. XCTAssertEqual(
  2394. try stateMachine.nextOutboundFrame(),
  2395. .sendFrame(frame: framedMessages, promise: nil)
  2396. )
  2397. // Server ends
  2398. let response = try stateMachine.send(
  2399. status: .init(code: .ok, message: ""),
  2400. metadata: []
  2401. )
  2402. XCTAssertEqual(response, ["grpc-status": "0"])
  2403. XCTAssertEqual(try stateMachine.nextOutboundFrame(), .noMoreMessages)
  2404. XCTAssertEqual(stateMachine.nextInboundMessage(), .noMoreMessages)
  2405. }
  2406. }
  2407. @available(gRPCSwiftNIOTransport 2.0, *)
  2408. extension XCTestCase {
  2409. func assertRejectedRPC(
  2410. _ action: GRPCStreamStateMachine.OnMetadataReceived,
  2411. expression: (HPACKHeaders) throws -> Void
  2412. ) rethrows {
  2413. guard case .rejectRPC_serverOnly(let trailers) = action else {
  2414. XCTFail("RPC should have been rejected.")
  2415. return
  2416. }
  2417. try expression(trailers)
  2418. }
  2419. func frameMessage(_ message: ByteBuffer, compression: CompressionAlgorithm) throws -> ByteBuffer {
  2420. try frameMessages([message], compression: compression)
  2421. }
  2422. func frameMessages(
  2423. _ messages: [ByteBuffer],
  2424. compression: CompressionAlgorithm
  2425. ) throws -> ByteBuffer {
  2426. var framer = GRPCMessageFramer()
  2427. let compressor: Zlib.Compressor? = {
  2428. switch compression {
  2429. case .deflate:
  2430. return Zlib.Compressor(method: .deflate)
  2431. case .gzip:
  2432. return Zlib.Compressor(method: .gzip)
  2433. default:
  2434. return nil
  2435. }
  2436. }()
  2437. defer { compressor?.end() }
  2438. for message in messages {
  2439. framer.append(message, promise: nil)
  2440. }
  2441. return try XCTUnwrap(framer.next(compressor: compressor)).bytes
  2442. }
  2443. }
  2444. @available(gRPCSwiftNIOTransport 2.0, *)
  2445. extension GRPCStreamStateMachine.OnNextOutboundFrame {
  2446. static func == (
  2447. lhs: GRPCStreamStateMachine.OnNextOutboundFrame,
  2448. rhs: GRPCStreamStateMachine.OnNextOutboundFrame
  2449. ) -> Bool {
  2450. switch (lhs, rhs) {
  2451. case (.noMoreMessages, .noMoreMessages):
  2452. return true
  2453. case (.awaitMoreMessages, .awaitMoreMessages):
  2454. return true
  2455. case (.sendFrame(let lhsMessage, _), .sendFrame(let rhsMessage, _)):
  2456. // Note that we're not comparing the EventLoopPromises here, as they're
  2457. // not Equatable. This is fine though, since we only use this in tests.
  2458. return lhsMessage == rhsMessage
  2459. default:
  2460. return false
  2461. }
  2462. }
  2463. }
  2464. @available(gRPCSwiftNIOTransport 2.0, *)
  2465. extension GRPCStreamStateMachine.OnNextOutboundFrame: Equatable {}