GRPCStreamStateMachineTests.swift 100 KB

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