@@ -6,13 +6,13 @@ import { resolveLegacyWebhookNameToChatUserId, sendMessage } from "./client.js";
66
77const USER_LIST_RESPONSE_MAX_BYTES = 1 * 1024 * 1024 ;
88
9- describe ( "Synology Chat user_list loopback" , ( ) => {
9+ describe ( "Synology Chat client loopback" , ( ) => {
1010 let server : http . Server | undefined ;
1111
12- async function listenLoopback ( handler : http . RequestListener ) : Promise < number > {
12+ async function listenLoopback ( handler : http . RequestListener , port = 0 ) : Promise < number > {
1313 server = http . createServer ( handler ) ;
1414 server . on ( "clientError" , ( _err , socket ) => socket . destroy ( ) ) ;
15- server . listen ( 0 , "127.0.0.1" ) ;
15+ server . listen ( port , "127.0.0.1" ) ;
1616 await once ( server , "listening" ) ;
1717 const address = server . address ( ) ;
1818 if ( ! address || typeof address === "string" ) {
@@ -21,6 +21,20 @@ describe("Synology Chat user_list loopback", () => {
2121 return address . port ;
2222 }
2323
24+ async function reserveLoopbackPort ( ) : Promise < number > {
25+ const reservation = http . createServer ( ) ;
26+ reservation . listen ( 0 , "127.0.0.1" ) ;
27+ await once ( reservation , "listening" ) ;
28+ const address = reservation . address ( ) ;
29+ if ( ! address || typeof address === "string" ) {
30+ throw new Error ( "expected reserved loopback address" ) ;
31+ }
32+ await new Promise < void > ( ( resolve , reject ) => {
33+ reservation . close ( ( err ) => ( err ? reject ( err ) : resolve ( ) ) ) ;
34+ } ) ;
35+ return address . port ;
36+ }
37+
2438 afterEach ( async ( ) => {
2539 vi . restoreAllMocks ( ) ;
2640 if ( server ) {
@@ -32,6 +46,89 @@ describe("Synology Chat user_list loopback", () => {
3246 }
3347 } ) ;
3448
49+ it ( "retries once when a real connection refusal occurs before the listener starts" , async ( ) => {
50+ const port = await reserveLoopbackPort ( ) ;
51+ const nativeSetTimeout = globalThis . setTimeout ;
52+ let releaseRetry : ( ( ) => void ) | undefined ;
53+ let markRetryScheduled ! : ( ) => void ;
54+ const retryScheduled = new Promise < void > ( ( resolve ) => {
55+ markRetryScheduled = resolve ;
56+ } ) ;
57+ const timeoutSpy = vi . spyOn ( globalThis , "setTimeout" ) ;
58+ timeoutSpy . mockImplementation ( ( (
59+ callback : ( ...args : unknown [ ] ) => void ,
60+ delay ?: number ,
61+ ...args : unknown [ ]
62+ ) => {
63+ if ( delay === 300 && releaseRetry === undefined ) {
64+ const heldTimer = nativeSetTimeout ( ( ) => { } , 10_000 ) ;
65+ heldTimer . unref ?.( ) ;
66+ releaseRetry = ( ) => {
67+ clearTimeout ( heldTimer ) ;
68+ callback ( ...args ) ;
69+ } ;
70+ markRetryScheduled ( ) ;
71+ return heldTimer ;
72+ }
73+ return nativeSetTimeout ( callback , delay , ...args ) ;
74+ } ) as typeof setTimeout ) ;
75+
76+ const incomingUrl = `http://127.0.0.1:${ port } /webapi/entry.cgi` ;
77+ const send = sendMessage ( incomingUrl , "retry after refusal" ) ;
78+ const firstOutcome = await Promise . race ( [
79+ retryScheduled . then ( ( ) => "retry-scheduled" as const ) ,
80+ send . then ( ( sendResult ) => ( { sendResult } ) ) ,
81+ ] ) ;
82+ expect ( firstOutcome ) . toBe ( "retry-scheduled" ) ;
83+
84+ let receivedRequests = 0 ;
85+ await listenLoopback ( ( req , res ) => {
86+ receivedRequests += 1 ;
87+ req . resume ( ) ;
88+ req . on ( "end" , ( ) => {
89+ res . writeHead ( 200 , { "Content-Type" : "application/json" } ) ;
90+ res . end ( JSON . stringify ( { success : true } ) ) ;
91+ } ) ;
92+ } , port ) ;
93+ if ( ! releaseRetry ) {
94+ throw new Error ( "expected pre-connect retry backoff" ) ;
95+ }
96+ releaseRetry ( ) ;
97+
98+ await expect ( send ) . resolves . toBe ( true ) ;
99+ expect ( receivedRequests ) . toBe ( 1 ) ;
100+ expect ( timeoutSpy . mock . calls . filter ( ( [ , delay ] ) => delay === 300 ) ) . toHaveLength ( 1 ) ;
101+ console . log (
102+ `[synology webhook retry proof] preconnect_refusal=true retry_scheduled=true server_received=${ receivedRequests } outcome=success` ,
103+ ) ;
104+ } ) ;
105+
106+ it ( "does not replay after the server receives the upload and disconnects" , async ( ) => {
107+ let requestCount = 0 ;
108+ let uploadedBody = "" ;
109+ const port = await listenLoopback ( ( req , res ) => {
110+ requestCount += 1 ;
111+ req . setEncoding ( "utf8" ) ;
112+ req . on ( "data" , ( chunk : string ) => {
113+ uploadedBody += chunk ;
114+ } ) ;
115+ req . on ( "end" , ( ) => {
116+ res . destroy ( ) ;
117+ } ) ;
118+ } ) ;
119+ const incomingUrl = `http://127.0.0.1:${ port } /webapi/entry.cgi` ;
120+
121+ await expect ( sendMessage ( incomingUrl , "post-upload disconnect" ) ) . resolves . toBe ( false ) ;
122+
123+ expect ( requestCount ) . toBe ( 1 ) ;
124+ expect ( new URLSearchParams ( uploadedBody ) . get ( "payload" ) ) . toBe (
125+ JSON . stringify ( { text : "post-upload disconnect" } ) ,
126+ ) ;
127+ console . log (
128+ `[synology webhook retry proof] server_received=${ requestCount } disconnect_after_upload=true replayed=${ requestCount > 1 } outcome=not_sent` ,
129+ ) ;
130+ } ) ;
131+
35132 it ( "delivers authenticated text and media without inventing platform message ids" , async ( ) => {
36133 const receivedPayloads : Array < Record < string , unknown > > = [ ] ;
37134 const port = await listenLoopback ( ( req , res ) => {
@@ -188,7 +285,7 @@ describe("Synology Chat user_list loopback", () => {
188285 await expect (
189286 synologyChatPlugin . outbound . sendText ( { cfg, text : "rejected" , to : "42" } ) ,
190287 ) . rejects . toThrow ( "Failed to send message to Synology Chat" ) ;
191- expect ( rejectedRequests ) . toBe ( 3 ) ;
288+ expect ( rejectedRequests ) . toBe ( 1 ) ;
192289
193290 await expect (
194291 synologyChatPlugin . outbound . sendMedia ( {
@@ -197,7 +294,7 @@ describe("Synology Chat user_list loopback", () => {
197294 to : "42" ,
198295 } ) ,
199296 ) . rejects . toThrow ( "Failed to send media to Synology Chat" ) ;
200- expect ( rejectedRequests ) . toBe ( 4 ) ;
297+ expect ( rejectedRequests ) . toBe ( 2 ) ;
201298 } ) ;
202299
203300 it ( "rejects private file URLs before contacting the authenticated webhook" , async ( ) => {
@@ -344,7 +441,7 @@ describe("Synology Chat user_list loopback", () => {
344441 expect ( elapsedMs ) . toBeLessThan ( timeoutMs + 1_500 ) ;
345442 } ) ;
346443
347- it ( "bounds a dripping chatbot response with a wall-clock deadline " , async ( ) => {
444+ it ( "does not replay a code-less wall-clock timeout from a dripping chatbot response " , async ( ) => {
348445 let requestCount = 0 ;
349446 const port = await listenLoopback ( ( _req , res ) => {
350447 requestCount += 1 ;
@@ -380,9 +477,10 @@ describe("Synology Chat user_list loopback", () => {
380477 await expect ( sendMessage ( incomingUrl , "hello" ) ) . resolves . toBe ( false ) ;
381478 const elapsedMs = performance . now ( ) - startedAt ;
382479
383- expect ( requestCount ) . toBe ( 3 ) ;
480+ expect ( requestCount ) . toBe ( 1 ) ;
384481 expect ( timeoutSpy ) . toHaveBeenCalledWith ( expect . any ( Function ) , 30_000 ) ;
385- expect ( elapsedMs ) . toBeGreaterThanOrEqual ( timeoutMs * 3 - 100 ) ;
386- expect ( elapsedMs ) . toBeLessThan ( 3_500 ) ;
482+ expect ( timeoutSpy . mock . calls . filter ( ( [ , delay ] ) => delay === 30_000 ) ) . toHaveLength ( 1 ) ;
483+ expect ( elapsedMs ) . toBeGreaterThanOrEqual ( timeoutMs - 50 ) ;
484+ expect ( elapsedMs ) . toBeLessThan ( timeoutMs + 1_500 ) ;
387485 } ) ;
388486} ) ;
0 commit comments