GRPCStreamStateMachineTests.swift 100 KB

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