@@ -216,16 +216,25 @@ function delayedBodyStream(
216216 } ;
217217}
218218const wsMockState = vi . hoisted ( ( ) => ( {
219- behavior : "close" as "close" | "open" | "error" | "message" | "unexpected-response" ,
219+ behavior : "close" as
220+ | "close"
221+ | "open"
222+ | "error"
223+ | "message"
224+ | "buffered-message"
225+ | "pending"
226+ | "unexpected-response" ,
220227 urls : [ ] as string [ ] ,
221228 options : [ ] as Array < { maxPayload ?: number ; handshakeTimeout ?: number } | undefined > ,
229+ terminations : 0 ,
222230} ) ) ;
223231
224232beforeEach ( ( ) => {
225233 vi . spyOn ( fetchModule , "resolveFetch" ) . mockReturnValue ( mockFetch as unknown as typeof fetch ) ;
226234 wsMockState . behavior = "close" ;
227235 wsMockState . urls = [ ] ;
228236 wsMockState . options = [ ] ;
237+ wsMockState . terminations = 0 ;
229238} ) ;
230239
231240function requireFetchCall ( index = 0 ) : [ RequestInfo | URL , RequestInit ] {
@@ -266,6 +275,7 @@ function expectMockLogNotContains(mock: ReturnType<typeof vi.fn>, expected: stri
266275vi . mock ( "ws" , ( ) => ( {
267276 default : class MockWebSocket {
268277 private handlers = new Map < string , Array < ( ...args : unknown [ ] ) => void > > ( ) ;
278+ private bufferedMessageFlushed = false ;
269279
270280 constructor ( url : string | URL , options ?: { maxPayload ?: number ; handshakeTimeout ?: number } ) {
271281 wsMockState . urls . push ( String ( url ) ) ;
@@ -281,6 +291,11 @@ vi.mock("ws", () => ({
281291 } else if ( wsMockState . behavior === "message" ) {
282292 this . emit ( "message" , Buffer . from ( '{"envelope":{"timestamp":1}}' ) ) ;
283293 this . emit ( "close" , 1000 , Buffer . from ( "done" ) ) ;
294+ } else if ( wsMockState . behavior === "buffered-message" ) {
295+ this . emit ( "open" ) ;
296+ this . emit ( "message" , Buffer . from ( '{"envelope":{"timestamp":1}}' ) ) ;
297+ } else if ( wsMockState . behavior === "pending" ) {
298+ // Keep the opening handshake unresolved until shutdown closes it.
284299 } else {
285300 this . emit ( "close" , 1000 , Buffer . from ( "done" ) ) ;
286301 }
@@ -306,10 +321,17 @@ vi.mock("ws", () => ({
306321 }
307322
308323 close ( ) {
324+ if ( wsMockState . behavior === "buffered-message" && ! this . bufferedMessageFlushed ) {
325+ this . bufferedMessageFlushed = true ;
326+ // ws flushes already-buffered receiver frames before its final close event.
327+ this . emit ( "message" , Buffer . from ( '{"envelope":{"timestamp":2}}' ) ) ;
328+ }
309329 this . emit ( "close" , 1000 , Buffer . from ( "done" ) ) ;
310330 }
311331
312- terminate ( ) { }
332+ terminate ( ) {
333+ wsMockState . terminations += 1 ;
334+ }
313335
314336 private emit ( event : string , ...args : unknown [ ] ) {
315337 for ( const handler of this . handlers . get ( event ) ?? [ ] ) {
@@ -1625,6 +1647,150 @@ describe("streamContainerEvents", () => {
16251647 expect ( removeEventListener ) . toHaveBeenCalledWith ( "abort" , abortHandler ) ;
16261648 } ) ;
16271649
1650+ it ( "drains accepted and socket-buffered receive events before resolving shutdown" , async ( ) => {
1651+ wsMockState . behavior = "buffered-message" ;
1652+ const abort = new AbortController ( ) ;
1653+ const removeEventListener = vi . spyOn ( abort . signal , "removeEventListener" ) ;
1654+ let releaseFirst ! : ( ) => void ;
1655+ const firstDelivery = new Promise < void > ( ( resolve ) => {
1656+ releaseFirst = resolve ;
1657+ } ) ;
1658+ let markFirstStarted ! : ( ) => void ;
1659+ const firstStarted = new Promise < void > ( ( resolve ) => {
1660+ markFirstStarted = resolve ;
1661+ } ) ;
1662+ const timestamps : number [ ] = [ ] ;
1663+ const stream = streamContainerEvents ( {
1664+ baseUrl : "http://localhost:8080" ,
1665+ abortSignal : abort . signal ,
1666+ timeoutMs : 0 ,
1667+ onEvent : async ( event ) => {
1668+ timestamps . push ( event . envelope ?. timestamp ?? 0 ) ;
1669+ if ( timestamps . length === 1 ) {
1670+ markFirstStarted ( ) ;
1671+ await firstDelivery ;
1672+ }
1673+ } ,
1674+ } ) ;
1675+ let settled = false ;
1676+ void stream . then ( ( ) => {
1677+ settled = true ;
1678+ } ) ;
1679+
1680+ await firstStarted ;
1681+ abort . abort ( ) ;
1682+ const settledBeforeDrain = await Promise . race ( [
1683+ stream . then ( ( ) => true ) ,
1684+ new Promise < boolean > ( ( resolve ) => {
1685+ setTimeout ( ( ) => resolve ( false ) , 10 ) ;
1686+ } ) ,
1687+ ] ) ;
1688+ expect ( settledBeforeDrain ) . toBe ( false ) ;
1689+ expect ( settled ) . toBe ( false ) ;
1690+
1691+ releaseFirst ( ) ;
1692+ await expect ( stream ) . resolves . toBeUndefined ( ) ;
1693+ expect ( timestamps ) . toEqual ( [ 1 , 2 ] ) ;
1694+ expect ( removeEventListener ) . toHaveBeenCalledWith ( "abort" , expect . any ( Function ) ) ;
1695+ expect ( wsMockState . terminations ) . toBe ( 0 ) ;
1696+ } ) ;
1697+
1698+ it ( "propagates a receive-handler failure that settles during shutdown" , async ( ) => {
1699+ wsMockState . behavior = "buffered-message" ;
1700+ const abort = new AbortController ( ) ;
1701+ const appendError = new Error ( "durable append failed during shutdown" ) ;
1702+ let rejectDelivery ! : ( error : Error ) => void ;
1703+ const delivery = new Promise < void > ( ( _resolve , reject ) => {
1704+ rejectDelivery = reject ;
1705+ } ) ;
1706+ let markFirstStarted ! : ( ) => void ;
1707+ const firstStarted = new Promise < void > ( ( resolve ) => {
1708+ markFirstStarted = resolve ;
1709+ } ) ;
1710+ const stream = streamContainerEvents ( {
1711+ baseUrl : "http://localhost:8080" ,
1712+ abortSignal : abort . signal ,
1713+ onEvent : async ( ) => {
1714+ markFirstStarted ( ) ;
1715+ await delivery ;
1716+ } ,
1717+ } ) ;
1718+
1719+ await firstStarted ;
1720+ abort . abort ( ) ;
1721+ rejectDelivery ( appendError ) ;
1722+ await expect ( stream ) . rejects . toBe ( appendError ) ;
1723+ expect ( wsMockState . terminations ) . toBe ( 0 ) ;
1724+ } ) ;
1725+
1726+ it ( "bounds a stalled shutdown drain and records the accepted-message loss risk" , async ( ) => {
1727+ vi . useFakeTimers ( ) ;
1728+ try {
1729+ wsMockState . behavior = "buffered-message" ;
1730+ const abort = new AbortController ( ) ;
1731+ const error = vi . fn ( ) ;
1732+ let settled = false ;
1733+ const stream = streamContainerEvents ( {
1734+ baseUrl : "http://localhost:8080" ,
1735+ abortSignal : abort . signal ,
1736+ timeoutMs : 0 ,
1737+ onEvent : async ( ) => await new Promise < void > ( ( ) => { } ) ,
1738+ logger : { error } ,
1739+ } ) . then ( ( ) => {
1740+ settled = true ;
1741+ } ) ;
1742+
1743+ await vi . advanceTimersByTimeAsync ( 0 ) ;
1744+ abort . abort ( ) ;
1745+ await vi . advanceTimersByTimeAsync ( 1_499 ) ;
1746+ expect ( settled ) . toBe ( false ) ;
1747+ expect ( error ) . not . toHaveBeenCalled ( ) ;
1748+
1749+ await vi . advanceTimersByTimeAsync ( 1 ) ;
1750+ await expect ( stream ) . resolves . toBeUndefined ( ) ;
1751+ expect ( error ) . toHaveBeenCalledWith ( expect . stringMatching ( / r e c e i v e e v e n t s .* m a y b e l o s t / i) ) ;
1752+ expect ( wsMockState . terminations ) . toBe ( 1 ) ;
1753+ expect ( vi . getTimerCount ( ) ) . toBe ( 0 ) ;
1754+ } finally {
1755+ vi . useRealTimers ( ) ;
1756+ }
1757+ } ) ;
1758+
1759+ it ( "closes immediately when aborted before the opening handshake completes" , async ( ) => {
1760+ wsMockState . behavior = "pending" ;
1761+ const abort = new AbortController ( ) ;
1762+ const removeEventListener = vi . spyOn ( abort . signal , "removeEventListener" ) ;
1763+ const stream = streamContainerEvents ( {
1764+ baseUrl : "http://localhost:8080" ,
1765+ abortSignal : abort . signal ,
1766+ onEvent : vi . fn ( ) ,
1767+ } ) ;
1768+
1769+ abort . abort ( ) ;
1770+ await expect ( stream ) . resolves . toBeUndefined ( ) ;
1771+ expect ( removeEventListener ) . toHaveBeenCalledWith ( "abort" , expect . any ( Function ) ) ;
1772+ expect ( wsMockState . terminations ) . toBe ( 0 ) ;
1773+ } ) ;
1774+
1775+ it ( "handles an already-aborted signal without leaving its connection pending" , async ( ) => {
1776+ wsMockState . behavior = "pending" ;
1777+ const abort = new AbortController ( ) ;
1778+ abort . abort ( ) ;
1779+ const result = await Promise . race ( [
1780+ streamContainerEvents ( {
1781+ baseUrl : "http://localhost:8080" ,
1782+ abortSignal : abort . signal ,
1783+ onEvent : vi . fn ( ) ,
1784+ } ) . then ( ( ) => "closed" ) ,
1785+ new Promise < string > ( ( resolve ) => {
1786+ setTimeout ( ( ) => resolve ( "still pending" ) , 25 ) ;
1787+ } ) ,
1788+ ] ) ;
1789+
1790+ expect ( result ) . toBe ( "closed" ) ;
1791+ expect ( wsMockState . terminations ) . toBe ( 0 ) ;
1792+ } ) ;
1793+
16281794 it ( "propagates receive-handler failures to the stream" , async ( ) => {
16291795 wsMockState . behavior = "message" ;
16301796 const appendError = new Error ( "durable append failed" ) ;
0 commit comments