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