Skip to content

Commit 50ec557

Browse files
Alix-007RomneyDa
andauthored
fix(synology-chat): prevent duplicate messages after ambiguous failures (#119539)
* fix(synology-chat): avoid ambiguous send replays * fix(synology-chat): classify aggregate send failures * test(synology-chat): trim retry loopback proof --------- Co-authored-by: Dallin Romney <[email protected]>
1 parent 1de7c78 commit 50ec557

3 files changed

Lines changed: 196 additions & 18 deletions

File tree

‎extensions/synology-chat/src/client.loopback.test.ts‎

Lines changed: 107 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,13 @@ import { resolveLegacyWebhookNameToChatUserId, sendMessage } from "./client.js";
66

77
const 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
});

‎extensions/synology-chat/src/client.test.ts‎

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,14 @@ function mockFailureResponse(statusCode = 500) {
106106
mockResponse(statusCode, "error");
107107
}
108108

109+
function mockRequestErrorOnce(error: Error) {
110+
vi.mocked(https.request).mockImplementationOnce((() => {
111+
const req = createMockRequestEmitter();
112+
process.nextTick(() => req.emit("error", error));
113+
return req;
114+
}) as MockRequestHandler);
115+
}
116+
109117
function installFakeTimerHarness() {
110118
beforeAll(async () => {
111119
({ sendMessage, sendFileUrl, resolveLegacyWebhookNameToChatUserId } =
@@ -159,22 +167,56 @@ describe("sendMessage", () => {
159167
expect(result).toBe(true);
160168
});
161169

162-
it("returns false on server error after retries", async () => {
170+
it("returns false on server error without replaying", async () => {
163171
mockFailureResponse(500);
164172
const result = await settleTimers(sendMessage("https://nas.example.com/incoming", "Hello"));
165173
expect(result).toBe(false);
174+
expect(vi.mocked(https.request)).toHaveBeenCalledOnce();
175+
});
176+
177+
it("does not replay a mixed aggregate with an ambiguous transport leaf", async () => {
178+
const mixedError = Object.assign(
179+
new AggregateError([
180+
Object.assign(new Error("connect refused"), { code: "ECONNREFUSED" }),
181+
Object.assign(new Error("connection reset after write"), { code: "ECONNRESET" }),
182+
]),
183+
{ code: "ECONNREFUSED" },
184+
);
185+
mockRequestErrorOnce(mixedError);
186+
187+
const result = await settleTimers(sendMessage("https://nas.example.com/incoming", "Hello"));
188+
189+
expect(result).toBe(false);
190+
expect(vi.mocked(https.request)).toHaveBeenCalledOnce();
191+
});
192+
193+
it("retries when every aggregate transport leaf is pre-connect", async () => {
194+
mockSuccessResponse();
195+
const aggregateError = Object.assign(
196+
new AggregateError([
197+
Object.assign(new Error("connect refused"), { code: "ECONNREFUSED" }),
198+
Object.assign(new Error("host not found"), { code: "ENOTFOUND" }),
199+
]),
200+
{ code: "ECONNREFUSED" },
201+
);
202+
mockRequestErrorOnce(new TypeError("fetch failed", { cause: aggregateError }));
203+
204+
const result = await settleTimers(sendMessage("https://nas.example.com/incoming", "Hello"));
205+
206+
expect(result).toBe(true);
207+
expect(vi.mocked(https.request)).toHaveBeenCalledTimes(2);
166208
});
167209

168210
it.each([
169211
{ name: "Synology error envelope", body: { success: false, error: { code: 105 } } },
170212
{ name: "unrelated malformed response fields", body: { success: false, data: null } },
171-
])("retries an HTTP-successful webhook rejection ($name)", async ({ body }) => {
213+
])("does not replay an HTTP-successful webhook rejection ($name)", async ({ body }) => {
172214
mockResponse(200, JSON.stringify(body));
173215

174216
const result = await settleTimers(sendMessage("https://nas.example.com/incoming", "Hello"));
175217

176218
expect(result).toBe(false);
177-
expect(vi.mocked(https.request)).toHaveBeenCalledTimes(3);
219+
expect(vi.mocked(https.request)).toHaveBeenCalledOnce();
178220
});
179221

180222
it.each([

‎extensions/synology-chat/src/client.ts‎

Lines changed: 44 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@
55

66
import * as http from "node:http";
77
import * as https from "node:https";
8+
import { collectErrorGraphCandidates, extractErrorCode } from "openclaw/plugin-sdk/error-runtime";
89
import { safeParseJsonWithSchema, safeParseWithSchema } from "openclaw/plugin-sdk/extension-shared";
910
import { parseStrictNonNegativeInteger } from "openclaw/plugin-sdk/number-runtime";
1011
import { readByteStreamWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
12+
import { classifyTransientNetworkErrorCode } from "openclaw/plugin-sdk/retry-runtime";
1113
import { sleep } from "openclaw/plugin-sdk/runtime-env";
1214
import {
1315
formatErrorMessage,
@@ -28,6 +30,42 @@ const POST_REQUEST_TIMEOUT_MS = 30_000;
2830
let lastSendTime = 0;
2931
let sendQueue: Promise<void> = Promise.resolve();
3032

33+
const UNPROVEN_TRANSPORT_ERROR_BRANCH = "unproven transport error branch";
34+
35+
function nestedTransportErrorCandidates(current: Record<string, unknown>): unknown[] {
36+
const aggregateBranches = Array.isArray(current.errors)
37+
? current.errors.map((branch) => branch ?? UNPROVEN_TRANSPORT_ERROR_BRANCH)
38+
: [];
39+
const wrappers = [current.cause, current.original, current.error, current.reason].filter(
40+
(candidate) => candidate !== undefined && candidate !== null,
41+
);
42+
return [...aggregateBranches, ...wrappers];
43+
}
44+
45+
function isProvenPreConnectFailure(error: unknown): boolean {
46+
let foundPreConnectLeaf = false;
47+
for (const candidate of collectErrorGraphCandidates(error, nestedTransportErrorCandidates)) {
48+
const classification = classifyTransientNetworkErrorCode(extractErrorCode(candidate));
49+
const nested =
50+
candidate && typeof candidate === "object"
51+
? nestedTransportErrorCandidates(candidate as Record<string, unknown>)
52+
: [];
53+
// A webhook POST is safe to replay only when every terminal transport branch
54+
// proves it failed before connect; aggregate summary codes cannot hide a reset.
55+
if (nested.length > 0) {
56+
if (classification === "ambiguous") {
57+
return false;
58+
}
59+
continue;
60+
}
61+
if (classification !== "pre-connect") {
62+
return false;
63+
}
64+
foundPreConnectLeaf = true;
65+
}
66+
return foundPreConnectLeaf;
67+
}
68+
3169
// --- Chat user_id resolution ---
3270
// Synology Chat uses two different user_id spaces:
3371
// - Outgoing webhook user_id: per-integration sequential ID (e.g. 1)
@@ -120,19 +158,19 @@ async function sendMessageChunk(
120158
// The @mention is optional but user_ids is mandatory
121159
const body = buildWebhookBody({ text }, userId);
122160

123-
// Retry with exponential backoff (3 attempts, 300ms base)
161+
// A webhook POST is non-idempotent. Retry only when the transport proves the
162+
// request never connected; replaying an ambiguous failure can duplicate a message.
124163
const maxRetries = 3;
125164
const baseDelay = 300;
126165

127166
for (let attempt = 0; attempt < maxRetries; attempt++) {
128167
try {
129168
await waitForSendSlot();
130-
const ok = await doPost(incomingUrl, body, allowInsecureSsl);
131-
if (ok) {
132-
return true;
169+
return await doPost(incomingUrl, body, allowInsecureSsl);
170+
} catch (error) {
171+
if (!isProvenPreConnectFailure(error)) {
172+
return false;
133173
}
134-
} catch {
135-
// will retry
136174
}
137175

138176
if (attempt < maxRetries - 1) {

0 commit comments

Comments
 (0)