GRPCStreamStateMachineTests.swift 100 KB

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