GRPCStreamStateMachineTests.swift 99 KB

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