Skip to content

Commit 0ac69b9

Browse files
authored
fix(zalo): prevent webhook message loss after acknowledgment (#110630)
* fix(zalo): adopt durable ingress drain with ack gated on raw-envelope append OA webhooks acked before detached processing behind a 5-minute in-memory guard, and Zalo does not retry (silent loss). Raw webhook JSON now appends durably (event_id = Bot API message.message_id, lane per chat.id) before the 200; failed appends answer 400/500 so nothing acks unpersisted. Dispatch runs through the core drain with serialized admissions across append backoff, deferred claims held through shutdown until adoption, retry/dead-letter classification, and 30d/20k tombstones replacing the deleted 5min/5k guard after its parity test. Webhook and polling transports stay mutually exclusive; no twin scenario exists across the four received-event types. Autoreview scanner false-positive on deleted-line token field references; full manual review performed (ack ordering, dual-transport exclusivity, eleven-test matrix). Part of the #109657 fleet program (wave 3). * refactor(zalo): keep webhook runtime exports private * test(zalo): use managed temp directories
1 parent 3131492 commit 0ac69b9

10 files changed

Lines changed: 1083 additions & 517 deletions

‎docs/channels/zalo.md‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -60,13 +60,13 @@ This page covers **Zalo Bot Creator / Marketplace bots**. **Zalo Official Accoun
6060

6161
## Limits
6262

63-
| Limit | Value |
64-
| ------------------------------ | ----------------------------------------------------------------------------- |
65-
| Outbound text chunk size | 2000 characters (Zalo API limit) |
66-
| Media size (inbound/outbound) | `channels.zalo.mediaMaxMb`, default `5` MB |
67-
| Webhook request body | 1 MB, 30s read timeout |
68-
| Webhook rate limit | 120 requests / 60s per path+client IP, then HTTP 429 |
69-
| Webhook duplicate-event window | 5 minutes (keyed on path + account + event name + chat + sender + message id) |
63+
| Limit | Value |
64+
| ----------------------------- | ------------------------------------------------------------------------ |
65+
| Outbound text chunk size | 2000 characters (Zalo API limit) |
66+
| Media size (inbound/outbound) | `channels.zalo.mediaMaxMb`, default `5` MB |
67+
| Webhook request body | 1 MB, 30s read timeout |
68+
| Webhook rate limit | 120 requests / 60s per path+client IP, then HTTP 429 |
69+
| Webhook replay tombstones | 30 days, up to 20,000 completed events per account (keyed by message id) |
7070

7171
## Access control
7272

@@ -97,6 +97,7 @@ Group chats are supported by the plugin (`chatTypes: ["direct", "group"]`) and g
9797
- Zalo sends events with an `X-Bot-Api-Secret-Token` header, checked with a constant-time comparison.
9898
- Gateway HTTP handles webhook requests at `channels.zalo.webhookPath` (defaults to the webhook URL's path).
9999
- Requests must use `Content-Type: application/json` (or a `+json` media type).
100+
- HTTP 200 is returned only after the raw event is durably stored; storage failures return HTTP 500.
100101
- getUpdates polling and webhook are mutually exclusive per Zalo API docs.
101102

102103
## Supported message types

‎extensions/zalo/src/monitor.lifecycle.test.ts‎

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,26 @@
11
// Zalo tests cover monitor.lifecycle plugin behavior.
2+
import fs from "node:fs/promises";
3+
import os from "node:os";
4+
import path from "node:path";
5+
import { createPluginRuntimeMock } from "openclaw/plugin-sdk/channel-test-helpers";
6+
import {
7+
closeOpenClawStateDatabaseForTest,
8+
createChannelIngressQueueForTests,
9+
} from "openclaw/plugin-sdk/plugin-state-test-runtime";
210
import {
311
createEmptyPluginRegistry,
412
createRuntimeEnv,
513
setActivePluginRegistry,
614
} from "openclaw/plugin-sdk/plugin-test-runtime";
7-
import { afterEach, describe, expect, it, vi } from "vitest";
8-
import type { OpenClawConfig } from "../runtime-api.js";
15+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
16+
import type { OpenClawConfig, PluginRuntime } from "../runtime-api.js";
917
import type { ResolvedZaloAccount } from "./accounts.js";
1018

1119
const getWebhookInfoMock = vi.fn(async () => ({ ok: true, result: { url: "" } }));
1220
const deleteWebhookMock = vi.fn(async () => ({ ok: true, result: { url: "" } }));
1321
const getUpdatesMock = vi.fn(() => new Promise(() => {}));
1422
const setWebhookMock = vi.fn(async () => ({ ok: true, result: { url: "" } }));
23+
const getZaloRuntimeMock = vi.hoisted(() => vi.fn());
1524

1625
vi.mock("./api.js", async () => {
1726
const actual = await vi.importActual<typeof import("./api.js")>("./api.js");
@@ -25,11 +34,7 @@ vi.mock("./api.js", async () => {
2534
});
2635

2736
vi.mock("./runtime.js", () => ({
28-
getZaloRuntime: () => ({
29-
logging: {
30-
shouldLogVerbose: () => false,
31-
},
32-
}),
37+
getZaloRuntime: getZaloRuntimeMock,
3338
}));
3439

3540
const TEST_ACCOUNT = {
@@ -38,6 +43,8 @@ const TEST_ACCOUNT = {
3843
} as unknown as ResolvedZaloAccount;
3944

4045
const TEST_CONFIG = {} as OpenClawConfig;
46+
let testStateDir: string | undefined;
47+
let previousStateDir: string | undefined;
4148

4249
async function settleLifecycleWork(): Promise<void> {
4350
for (let i = 0; i < 6; i += 1) {
@@ -70,11 +77,37 @@ async function startLifecycleMonitor(
7077
}
7178

7279
describe("monitorZaloProvider lifecycle", () => {
73-
afterEach(() => {
80+
beforeEach(async () => {
81+
const createdDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-zalo-monitor-"));
82+
testStateDir = await fs.realpath(createdDir);
83+
previousStateDir = process.env.OPENCLAW_STATE_DIR;
84+
process.env.OPENCLAW_STATE_DIR = testStateDir;
85+
const core = createPluginRuntimeMock();
86+
core.state.openChannelIngressQueue = (<T>(options: { accountId?: string }) =>
87+
createChannelIngressQueueForTests<T>({
88+
channelId: "zalo",
89+
accountId: options.accountId ?? "default",
90+
stateDir: testStateDir,
91+
})) as PluginRuntime["state"]["openChannelIngressQueue"];
92+
getZaloRuntimeMock.mockReturnValue(core);
93+
});
94+
95+
afterEach(async () => {
7496
vi.clearAllMocks();
7597
getUpdatesMock.mockReset();
7698
getUpdatesMock.mockImplementation(() => new Promise(() => {}));
7799
setActivePluginRegistry(createEmptyPluginRegistry());
100+
closeOpenClawStateDatabaseForTest();
101+
if (testStateDir) {
102+
await fs.rm(testStateDir, { recursive: true, force: true });
103+
testStateDir = undefined;
104+
}
105+
if (previousStateDir === undefined) {
106+
delete process.env.OPENCLAW_STATE_DIR;
107+
} else {
108+
process.env.OPENCLAW_STATE_DIR = previousStateDir;
109+
previousStateDir = undefined;
110+
}
78111
});
79112

80113
it("stays alive in polling mode until abort", async () => {
@@ -184,6 +217,7 @@ describe("monitorZaloProvider lifecycle", () => {
184217
resolveSetWebhookCalled = resolve;
185218
});
186219
setWebhookMock.mockImplementationOnce(async () => {
220+
expect(registry.httpRoutes).toHaveLength(2);
187221
resolveSetWebhookCalled?.();
188222
return { ok: true, result: { url: "" } };
189223
});

‎extensions/zalo/src/monitor.reply-once.lifecycle.test-support.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,8 @@ describe("Zalo reply-once lifecycle", () => {
7272

7373
it("routes one accepted webhook event to one visible reply across duplicate replay", async () => {
7474
dispatchReplyWithBufferedBlockDispatcherMock.mockImplementation(
75-
async ({ dispatcherOptions }) => {
75+
async ({ dispatcherOptions, replyOptions }) => {
76+
await replyOptions.turnAdoptionLifecycle?.onAdopted();
7677
await dispatcherOptions.deliver({ text: "zalo reply once" });
7778
},
7879
);
@@ -132,8 +133,10 @@ describe("Zalo reply-once lifecycle", () => {
132133
it("does not emit a second visible reply when replay arrives after a post-send failure", async () => {
133134
let dispatchAttempts = 0;
134135
dispatchReplyWithBufferedBlockDispatcherMock.mockImplementation(
135-
async ({ dispatcherOptions }) => {
136+
async ({ dispatcherOptions, replyOptions }) => {
136137
dispatchAttempts += 1;
138+
expect(replyOptions.turnAdoptionLifecycle).toBeDefined();
139+
await replyOptions.turnAdoptionLifecycle?.onAdopted();
137140
await dispatcherOptions.deliver({ text: "zalo reply after failure" });
138141
if (dispatchAttempts === 1) {
139142
throw new Error("post-send failure");
@@ -173,9 +176,7 @@ describe("Zalo reply-once lifecycle", () => {
173176

174177
expect(dispatchReplyWithBufferedBlockDispatcherMock).toHaveBeenCalledTimes(1);
175178
expect(sendMessageMock).toHaveBeenCalledTimes(1);
176-
expect(monitor.runtime.error).toHaveBeenCalledWith(
177-
"[acct-zalo-lifecycle] Zalo webhook failed: Error: post-send failure",
178-
);
179+
expect(monitor.runtime.error).not.toHaveBeenCalled();
179180
} finally {
180181
await monitor.stop();
181182
}

‎extensions/zalo/src/monitor.ts‎

Lines changed: 78 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,10 @@ import {
88
import { resolveStableChannelMessageIngress } from "openclaw/plugin-sdk/channel-ingress-runtime";
99
import { createChannelPairingController } from "openclaw/plugin-sdk/channel-pairing";
1010
import type { MarkdownTableMode, OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
11-
import { createLazyRuntimeModule } from "openclaw/plugin-sdk/lazy-runtime";
11+
import {
12+
createLazyRuntimeModule,
13+
createLazyRuntimeNamedExport,
14+
} from "openclaw/plugin-sdk/lazy-runtime";
1215
import {
1316
deliverTextOrMediaReply,
1417
resolveSendableOutboundReplyParts,
@@ -48,6 +51,7 @@ import {
4851
} from "./outbound-media.js";
4952
import { resolveZaloProxyFetch } from "./proxy.js";
5053
import { getZaloRuntime } from "./runtime.js";
54+
import type { ZaloWebhookIngressLifecycle } from "./webhook-spool.js";
5155

5256
/** Default idle timeout for Zalo inbound photo downloads (30 seconds). */
5357
const ZALO_MEDIA_READ_IDLE_TIMEOUT_MS = 30_000;
@@ -88,6 +92,7 @@ type ZaloProcessingContext = {
8892
webhookPath?: string;
8993
statusSink?: ZaloStatusSink;
9094
fetcher?: ZaloFetch;
95+
turnAdoptionLifecycle?: ZaloWebhookIngressLifecycle;
9196
};
9297

9398
type ZaloPollingLoopParams = ZaloProcessingContext & {
@@ -106,7 +111,18 @@ function resolveZaloTimestampMs(date: number | undefined): number | undefined {
106111
return date >= UNIX_MILLISECONDS_THRESHOLD ? date : date * 1000;
107112
}
108113

109-
const loadZaloWebhookModule = createLazyRuntimeModule(() => import("./monitor.webhook.js"));
114+
const loadZaloWebhookRuntime = createLazyRuntimeNamedExport(
115+
() => import("./monitor.webhook.js"),
116+
"zaloWebhookRuntime",
117+
);
118+
const loadZaloWebhookIngressRuntime = createLazyRuntimeNamedExport(
119+
() => import("./webhook-spool.js"),
120+
"zaloWebhookIngressRuntime",
121+
);
122+
const loadZaloWebhookModule = createLazyRuntimeModule(async () => ({
123+
...(await loadZaloWebhookRuntime()),
124+
...(await loadZaloWebhookIngressRuntime()),
125+
}));
110126

111127
function releaseSharedHostedMediaRouteRef(routePath: string): void {
112128
const current = hostedMediaRouteRefs.get(routePath);
@@ -210,22 +226,7 @@ async function handleZaloWebhookRequest(
210226
): Promise<boolean> {
211227
const { handleZaloWebhookRequest: handleZaloWebhookRequestInternal } =
212228
await loadZaloWebhookModule();
213-
return await handleZaloWebhookRequestInternal(req, res, async ({ update, target }) => {
214-
await processUpdate({
215-
update,
216-
token: target.token,
217-
account: target.account,
218-
config: target.config,
219-
runtime: target.runtime,
220-
core: target.core as ZaloCoreRuntime,
221-
mediaMaxMb: target.mediaMaxMb,
222-
canHostMedia: target.canHostMedia,
223-
webhookUrl: target.webhookUrl,
224-
webhookPath: target.webhookPath,
225-
statusSink: target.statusSink,
226-
fetcher: target.fetcher,
227-
});
228-
});
229+
return await handleZaloWebhookRequestInternal(req, res);
229230
}
230231

231232
function startPollingLoop(params: ZaloPollingLoopParams) {
@@ -313,6 +314,7 @@ async function processUpdate(params: ZaloUpdateProcessingParams): Promise<void>
313314
webhookPath: params.webhookPath,
314315
statusSink,
315316
fetcher,
317+
turnAdoptionLifecycle: params.turnAdoptionLifecycle,
316318
};
317319
if (!message) {
318320
return undefined;
@@ -725,6 +727,9 @@ async function processMessageWithPipeline(params: ZaloMessagePipelineParams): Pr
725727
runtime.error?.(`zalo: failed updating session meta: ${String(err)}`);
726728
},
727729
},
730+
...(params.turnAdoptionLifecycle
731+
? { turnAdoptionLifecycle: params.turnAdoptionLifecycle }
732+
: {}),
728733
});
729734
}
730735

@@ -840,6 +845,7 @@ export async function monitorZaloProvider(options: ZaloMonitorOptions): Promise<
840845

841846
let stopped = false;
842847
const stopHandlers: Array<() => void> = [];
848+
const asyncStopHandlers: Array<() => Promise<void>> = [];
843849
let cleanupWebhook: (() => Promise<void>) | undefined;
844850

845851
const stop = () => {
@@ -874,7 +880,7 @@ export async function monitorZaloProvider(options: ZaloMonitorOptions): Promise<
874880
}
875881

876882
if (useWebhook) {
877-
const { registerZaloWebhookTarget } = await loadZaloWebhookModule();
883+
const { createZaloWebhookIngress, registerZaloWebhookTarget } = await loadZaloWebhookModule();
878884
if (!effectiveWebhookUrl || !webhookSecret) {
879885
throw new Error("Zalo webhookUrl and webhookSecret are required for webhook mode");
880886
}
@@ -893,43 +899,38 @@ export async function monitorZaloProvider(options: ZaloMonitorOptions): Promise<
893899
runtime.log?.(
894900
`[${account.accountId}] Zalo configuring webhook path=${path} target=${describeWebhookTarget(effectiveWebhookUrl)}`,
895901
);
896-
await setWebhook(token, { url: effectiveWebhookUrl, secret_token: webhookSecret }, fetcher);
897-
let webhookCleanupPromise: Promise<void> | undefined;
898-
cleanupWebhook = async () => {
899-
if (!webhookCleanupPromise) {
900-
webhookCleanupPromise = (async () => {
901-
runtime.log?.(`[${account.accountId}] Zalo stopping; deleting webhook`);
902-
try {
903-
await deleteWebhook(token, fetcher, WEBHOOK_CLEANUP_TIMEOUT_MS);
904-
runtime.log?.(`[${account.accountId}] Zalo webhook deleted`);
905-
} catch (err) {
906-
const detail =
907-
err instanceof Error && err.name === "AbortError"
908-
? `timed out after ${String(WEBHOOK_CLEANUP_TIMEOUT_MS)}ms`
909-
: formatZaloError(err);
910-
runtime.error?.(`[${account.accountId}] Zalo webhook delete failed: ${detail}`);
911-
}
912-
})();
913-
}
914-
await webhookCleanupPromise;
915-
};
916-
runtime.log?.(`[${account.accountId}] Zalo webhook registered path=${path}`);
917-
902+
const ingress = createZaloWebhookIngress({
903+
accountId: account.accountId,
904+
runtime,
905+
deliver: async (update, turnAdoptionLifecycle) => {
906+
statusSink?.({ lastInboundAt: Date.now() });
907+
await processUpdate({
908+
update,
909+
token,
910+
account,
911+
config,
912+
runtime,
913+
core,
914+
mediaMaxMb: effectiveMediaMaxMb,
915+
canHostMedia,
916+
webhookUrl: effectiveWebhookUrl,
917+
webhookPath: path,
918+
statusSink,
919+
fetcher,
920+
turnAdoptionLifecycle,
921+
});
922+
},
923+
});
924+
ingress.start();
925+
asyncStopHandlers.push(ingress.stop);
918926
const unregister = registerZaloWebhookTarget(
919927
{
920-
token,
921928
account,
922929
config,
923930
runtime,
924-
core,
925931
path,
926-
webhookUrl: effectiveWebhookUrl,
927-
webhookPath: path,
928932
secret: webhookSecret,
929-
statusSink: (patch) => statusSink?.(patch),
930-
mediaMaxMb: effectiveMediaMaxMb,
931-
canHostMedia,
932-
fetcher,
933+
acceptWebhook: ingress.accept,
933934
},
934935
{
935936
route: {
@@ -951,6 +952,31 @@ export async function monitorZaloProvider(options: ZaloMonitorOptions): Promise<
951952
},
952953
);
953954
stopHandlers.push(unregister);
955+
await setWebhook(
956+
token,
957+
{ url: effectiveWebhookUrl, secret_token: webhookSecret }, // pragma: allowlist secret
958+
fetcher,
959+
);
960+
let webhookCleanupPromise: Promise<void> | undefined;
961+
cleanupWebhook = async () => {
962+
if (!webhookCleanupPromise) {
963+
webhookCleanupPromise = (async () => {
964+
runtime.log?.(`[${account.accountId}] Zalo stopping; deleting webhook`);
965+
try {
966+
await deleteWebhook(token, fetcher, WEBHOOK_CLEANUP_TIMEOUT_MS);
967+
runtime.log?.(`[${account.accountId}] Zalo webhook deleted`);
968+
} catch (err) {
969+
const detail =
970+
err instanceof Error && err.name === "AbortError"
971+
? `timed out after ${String(WEBHOOK_CLEANUP_TIMEOUT_MS)}ms`
972+
: formatZaloError(err);
973+
runtime.error?.(`[${account.accountId}] Zalo webhook delete failed: ${detail}`);
974+
}
975+
})();
976+
}
977+
await webhookCleanupPromise;
978+
};
979+
runtime.log?.(`[${account.accountId}] Zalo webhook registered path=${path}`);
954980
await waitForAbortSignal(abortSignal);
955981
return;
956982
}
@@ -1012,6 +1038,9 @@ export async function monitorZaloProvider(options: ZaloMonitorOptions): Promise<
10121038
abortSignal.removeEventListener("abort", stopOnAbort);
10131039
await cleanupWebhook?.();
10141040
stop();
1041+
for (const stopAsync of asyncStopHandlers) {
1042+
await stopAsync();
1043+
}
10151044
runtime.log?.(`[${account.accountId}] Zalo provider stopped mode=${mode}`);
10161045
}
10171046
}

0 commit comments

Comments
 (0)