Skip to content

Commit f7fb490

Browse files
fix(zalo): journal polled updates before dispatch
The Zalo Bot API consumes each polled update on response (getUpdates has no offset or confirm parameter), so a crash or restart between the poll response and dispatch completion permanently loses the message. Route polling through the same durable ingress the webhook transport uses (#110630), including durable-after-stop admission for the shutdown race, while keeping current ready/recovering status and partial-delivery recovery behavior. PR #110803
1 parent 38e0ae6 commit f7fb490

7 files changed

Lines changed: 435 additions & 42 deletions

‎extensions/zalo/src/monitor.image.polling.test-support.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
import {
1414
getUpdatesMock,
1515
getZaloRuntimeMock,
16+
installLifecycleIngressState,
1617
loadCachedLifecycleMonitorModule,
1718
resetLifecycleTestState,
1819
sendMessageMock,
@@ -32,6 +33,7 @@ describe("Zalo polling image handling", () => {
3233
beforeEach(async () => {
3334
await resetLifecycleTestState();
3435
getZaloRuntimeMock.mockReturnValue(core);
36+
await installLifecycleIngressState();
3537
});
3638

3739
afterAll(async () => {

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,9 @@ async function startLifecycleMonitor(
8080

8181
describe("monitorZaloProvider lifecycle", () => {
8282
beforeEach(async () => {
83+
// Warm the lazy ingress module so polling startup settles within the
84+
// lifecycle settle helpers (and within fake-timer advancement).
85+
await import("./webhook-spool.js");
8386
const createdDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-zalo-monitor-"));
8487
testStateDir = await fs.realpath(createdDir);
8588
previousStateDir = process.env.OPENCLAW_STATE_DIR;
@@ -181,11 +184,16 @@ describe("monitorZaloProvider lifecycle", () => {
181184
lastError: expect.stringContaining("zalo poll transport failed"),
182185
});
183186
expect(getUpdatesMock).toHaveBeenCalledTimes(1);
184-
expect(vi.getTimerCount()).toBe(1);
187+
// Backoff sleep plus the durable-ingress drain pump; the exact count is an
188+
// implementation detail, while the post-abort zero below is the contract.
189+
expect(vi.getTimerCount()).toBeGreaterThan(0);
185190

186191
abort.abort();
187192
await run;
188193

194+
// The ingress queue opened the shared state DB; its WAL maintenance
195+
// interval is process-level and clears when the DB handle closes.
196+
closeOpenClawStateDatabaseForTest();
189197
expect(vi.getTimerCount()).toBe(0);
190198
await vi.advanceTimersByTimeAsync(5_000);
191199
expect(getUpdatesMock).toHaveBeenCalledTimes(1);
Lines changed: 350 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,350 @@
1+
// Zalo tests cover the durable ingress journal on the polling transport.
2+
import fs from "node:fs/promises";
3+
import os from "node:os";
4+
import path from "node:path";
5+
import {
6+
closeOpenClawStateDatabaseForTest,
7+
createChannelIngressQueueForTests,
8+
} from "openclaw/plugin-sdk/plugin-state-test-runtime";
9+
import {
10+
createEmptyPluginRegistry,
11+
createRuntimeEnv,
12+
setActivePluginRegistry,
13+
} from "openclaw/plugin-sdk/plugin-test-runtime";
14+
import {
15+
afterAll,
16+
afterEach,
17+
beforeAll,
18+
beforeEach,
19+
describe,
20+
expect,
21+
it,
22+
vi,
23+
type Mock,
24+
} from "vitest";
25+
import type { ResolvedZaloAccount } from "./accounts.js";
26+
import type { ZaloUpdate } from "./api.js";
27+
import type { OpenClawConfig, PluginRuntime } from "./runtime-api.js";
28+
import {
29+
createImageLifecycleCore,
30+
createLifecycleMonitorSetup,
31+
createTextUpdate,
32+
settleAsyncWork,
33+
} from "./test-support/lifecycle-test-support.js";
34+
import {
35+
getUpdatesMock,
36+
getZaloRuntimeMock,
37+
loadCachedLifecycleMonitorModule,
38+
resetLifecycleTestState,
39+
} from "./test-support/monitor-mocks-test-support.js";
40+
import {
41+
waitForZaloWebhookVerdict,
42+
type ZaloWebhookTestPayload,
43+
} from "./webhook-spool.test-support.js";
44+
45+
type ZaloPollingTestQueue = Parameters<typeof waitForZaloWebhookVerdict>[0];
46+
47+
type DispatchReplyOptions = {
48+
replyOptions?: {
49+
turnAdoptionLifecycle?: { onAdopted: () => Promise<void> };
50+
};
51+
};
52+
53+
function createDeferred() {
54+
let resolve!: () => void;
55+
let reject!: (reason?: unknown) => void;
56+
const promise = new Promise<void>((res, rej) => {
57+
resolve = res;
58+
reject = rej;
59+
});
60+
return { promise, resolve, reject };
61+
}
62+
63+
async function startPollingMonitor(setup: {
64+
account: ResolvedZaloAccount;
65+
config: OpenClawConfig;
66+
}) {
67+
const { monitorZaloProvider } = await loadCachedLifecycleMonitorModule("zalo-polling-ingress");
68+
const abort = new AbortController();
69+
const runtime = createRuntimeEnv();
70+
const run = monitorZaloProvider({
71+
token: "zalo-token", // pragma: allowlist secret
72+
account: setup.account,
73+
config: setup.config,
74+
runtime,
75+
abortSignal: abort.signal,
76+
});
77+
return { abort, run, runtime };
78+
}
79+
80+
describe("Zalo polling durable ingress", () => {
81+
const { core } = createImageLifecycleCore();
82+
const dispatchMock = core.channel.reply
83+
.dispatchReplyWithBufferedBlockDispatcher as unknown as Mock;
84+
let stateDir: string | undefined;
85+
let queue: ZaloPollingTestQueue;
86+
87+
beforeAll(async () => {
88+
// Install module mocks first, then warm the lazy ingress module so monitor
89+
// startup does not pay module load inside the tests.
90+
await loadCachedLifecycleMonitorModule("zalo-polling-ingress");
91+
await import("./webhook-spool.js");
92+
});
93+
94+
beforeEach(async () => {
95+
await resetLifecycleTestState();
96+
const createdDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-zalo-poll-ingress-"));
97+
stateDir = await fs.realpath(createdDir);
98+
process.env.OPENCLAW_STATE_DIR = stateDir;
99+
queue = createChannelIngressQueueForTests<ZaloWebhookTestPayload>({
100+
channelId: "zalo",
101+
accountId: "default",
102+
stateDir,
103+
});
104+
core.state.openChannelIngressQueue = ((_options: { accountId?: string }) =>
105+
queue) as unknown as PluginRuntime["state"]["openChannelIngressQueue"];
106+
getZaloRuntimeMock.mockReturnValue(core);
107+
setActivePluginRegistry(createEmptyPluginRegistry());
108+
});
109+
110+
afterAll(async () => {
111+
await resetLifecycleTestState();
112+
});
113+
114+
afterEach(async () => {
115+
dispatchMock.mockReset();
116+
await resetLifecycleTestState();
117+
closeOpenClawStateDatabaseForTest();
118+
if (stateDir) {
119+
await fs.rm(stateDir, { recursive: true, force: true });
120+
stateDir = undefined;
121+
}
122+
delete process.env.OPENCLAW_STATE_DIR;
123+
});
124+
125+
it("journals a polled update durably before dispatch and tombstones it after adoption", async () => {
126+
const update = createTextUpdate({
127+
messageId: "poll-journal-1",
128+
userId: "user-1",
129+
userName: "User One",
130+
chatId: "dm-chat-1",
131+
});
132+
getUpdatesMock
133+
.mockResolvedValueOnce({ ok: true, result: update as ZaloUpdate })
134+
.mockImplementation(() => new Promise(() => {}));
135+
136+
const dispatchStarted = createDeferred();
137+
const dispatchGate = createDeferred();
138+
let durableIdsAtDispatch: string[] = [];
139+
dispatchMock.mockImplementation(async ({ replyOptions }: DispatchReplyOptions) => {
140+
// The update must be durable before the agent turn starts.
141+
const [claims, pending] = await Promise.all([queue.listClaims(), queue.listPending()]);
142+
durableIdsAtDispatch = [...claims, ...pending].map((record) => record.id);
143+
dispatchStarted.resolve();
144+
await dispatchGate.promise;
145+
await replyOptions?.turnAdoptionLifecycle?.onAdopted();
146+
});
147+
148+
const { abort, run } = await startPollingMonitor(
149+
createLifecycleMonitorSetup({ accountId: "default", dmPolicy: "open", webhookUrl: "" }),
150+
);
151+
152+
await dispatchStarted.promise;
153+
expect(durableIdsAtDispatch).toEqual(["poll-journal-1"]);
154+
155+
dispatchGate.resolve();
156+
await waitForZaloWebhookVerdict(queue, "poll-journal-1", "completed");
157+
expect(dispatchMock).toHaveBeenCalledTimes(1);
158+
159+
abort.abort();
160+
await run;
161+
});
162+
163+
it("dedupes a re-polled update after completion", async () => {
164+
const update = createTextUpdate({
165+
messageId: "poll-dedupe-1",
166+
userId: "user-1",
167+
userName: "User One",
168+
chatId: "dm-chat-1",
169+
});
170+
dispatchMock.mockImplementation(async ({ replyOptions }: DispatchReplyOptions) => {
171+
await replyOptions?.turnAdoptionLifecycle?.onAdopted();
172+
});
173+
getUpdatesMock
174+
.mockResolvedValueOnce({ ok: true, result: update as ZaloUpdate })
175+
// Simulate a Bot API redelivery of the same consumed update.
176+
.mockResolvedValueOnce({ ok: true, result: update as ZaloUpdate })
177+
.mockImplementation(() => new Promise(() => {}));
178+
179+
const { abort, run } = await startPollingMonitor(
180+
createLifecycleMonitorSetup({ accountId: "default", dmPolicy: "open", webhookUrl: "" }),
181+
);
182+
183+
// Wait for the monitor's own admission before probing the row: the verdict
184+
// probe enqueues, so it must never win the race against the polled admission.
185+
await vi.waitFor(() => {
186+
expect(dispatchMock).toHaveBeenCalledTimes(1);
187+
});
188+
await waitForZaloWebhookVerdict(queue, "poll-dedupe-1", "completed");
189+
await vi.waitFor(() => {
190+
expect(getUpdatesMock.mock.calls.length).toBeGreaterThanOrEqual(3);
191+
});
192+
await settleAsyncWork();
193+
expect(dispatchMock).toHaveBeenCalledTimes(1);
194+
195+
abort.abort();
196+
await run;
197+
});
198+
199+
it("replays a journaled update exactly once after a crash between poll and dispatch", async () => {
200+
const update = createTextUpdate({
201+
messageId: "poll-restart-1",
202+
userId: "user-1",
203+
userName: "User One",
204+
chatId: "dm-chat-1",
205+
});
206+
const dispatchStarted = createDeferred();
207+
const crashDispatch = createDeferred();
208+
// First attempt dies mid-dispatch: the process is killed before a verdict.
209+
dispatchMock.mockImplementationOnce(async () => {
210+
dispatchStarted.resolve();
211+
await crashDispatch.promise;
212+
});
213+
getUpdatesMock
214+
.mockResolvedValueOnce({ ok: true, result: update as ZaloUpdate })
215+
.mockImplementation(() => new Promise(() => {}));
216+
217+
const setup = createLifecycleMonitorSetup({
218+
accountId: "default",
219+
dmPolicy: "open",
220+
webhookUrl: "",
221+
});
222+
const first = await startPollingMonitor(setup);
223+
224+
await dispatchStarted.promise;
225+
// Crash while the delivery is in flight; the journaled row must survive the
226+
// stop either as a dead-owner claim or as a released retry.
227+
first.abort.abort();
228+
crashDispatch.reject(new Error("simulated process crash"));
229+
await first.run;
230+
231+
const [crashClaims, crashPending] = await Promise.all([
232+
queue.listClaims(),
233+
queue.listPending(),
234+
]);
235+
expect([...crashClaims, ...crashPending].map((record) => record.id)).toEqual([
236+
"poll-restart-1",
237+
]);
238+
239+
// Restart: a fresh monitor recovers the unfinished row and replays it.
240+
dispatchMock.mockImplementation(async ({ replyOptions }: DispatchReplyOptions) => {
241+
await replyOptions?.turnAdoptionLifecycle?.onAdopted();
242+
});
243+
getUpdatesMock.mockReset();
244+
getUpdatesMock
245+
// The Bot API re-serves the consumed update once more after the restart.
246+
.mockResolvedValueOnce({ ok: true, result: update as ZaloUpdate })
247+
.mockImplementation(() => new Promise(() => {}));
248+
249+
const second = await startPollingMonitor(setup);
250+
251+
await waitForZaloWebhookVerdict(queue, "poll-restart-1", "completed");
252+
await vi.waitFor(() => {
253+
expect(getUpdatesMock.mock.calls.length).toBeGreaterThanOrEqual(2);
254+
});
255+
await settleAsyncWork();
256+
// Exactly one successful dispatch across crash + replay + redelivery.
257+
expect(dispatchMock).toHaveBeenCalledTimes(2);
258+
259+
second.abort.abort();
260+
await second.run;
261+
});
262+
263+
it("journals a polled update on the abort path with durable-after-stop admission", async () => {
264+
const updateA = createTextUpdate({
265+
messageId: "poll-abort-a",
266+
userId: "user-1",
267+
userName: "User One",
268+
chatId: "dm-chat-1",
269+
});
270+
const updateB = createTextUpdate({
271+
messageId: "poll-abort-b",
272+
userId: "user-1",
273+
userName: "User One",
274+
chatId: "dm-chat-1",
275+
});
276+
277+
// First update completes normally so the poll loop advances to the next
278+
// getUpdates call, which stays in-flight past shutdown.
279+
dispatchMock.mockImplementation(async ({ replyOptions }: DispatchReplyOptions) => {
280+
await replyOptions?.turnAdoptionLifecycle?.onAdopted();
281+
});
282+
283+
const latePoll = createDeferred();
284+
getUpdatesMock
285+
.mockResolvedValueOnce({ ok: true, result: updateA as ZaloUpdate })
286+
.mockImplementationOnce(() =>
287+
latePoll.promise.then(() => ({ ok: true, result: updateB as ZaloUpdate })),
288+
)
289+
.mockImplementation(() => new Promise(() => {}));
290+
291+
const { abort, run } = await startPollingMonitor(
292+
createLifecycleMonitorSetup({ accountId: "default", dmPolicy: "open", webhookUrl: "" }),
293+
);
294+
295+
// Wait for the first update to complete so the next poll is in-flight on
296+
// getUpdates when abort fires.
297+
await vi.waitFor(() => {
298+
expect(dispatchMock).toHaveBeenCalledTimes(1);
299+
});
300+
await waitForZaloWebhookVerdict(queue, "poll-abort-a", "completed");
301+
302+
// Abort while the second getUpdates is in-flight; the monitor shuts down
303+
// before the poll response arrives.
304+
abort.abort();
305+
await run;
306+
307+
// Release the in-flight poll after the monitor has fully shut down.
308+
latePoll.resolve();
309+
310+
// With durable-after-stop admission the abort branch must persist the
311+
// consumed update into the durable ingress queue even after stop.
312+
await vi.waitFor(async () => {
313+
const [claims, pending] = await Promise.all([queue.listClaims(), queue.listPending()]);
314+
const ids = [...claims, ...pending].map((record) => record.id);
315+
expect(ids).toContain("poll-abort-b");
316+
});
317+
});
318+
319+
it("dead-letters an authentication failure from dispatch without retry", async () => {
320+
const update = createTextUpdate({
321+
messageId: "poll-deadletter-1",
322+
userId: "user-1",
323+
userName: "User One",
324+
chatId: "dm-chat-1",
325+
});
326+
const { ZaloApiError } = await import("./api.js");
327+
dispatchMock.mockImplementation(async () => {
328+
throw new ZaloApiError("Unauthorized", 401, "Unauthorized");
329+
});
330+
getUpdatesMock
331+
.mockResolvedValueOnce({ ok: true, result: update as ZaloUpdate })
332+
.mockImplementation(() => new Promise(() => {}));
333+
334+
const { abort, run, runtime } = await startPollingMonitor(
335+
createLifecycleMonitorSetup({ accountId: "default", dmPolicy: "open", webhookUrl: "" }),
336+
);
337+
338+
// Wait for the monitor's own admission before probing the row (see dedupe test).
339+
await vi.waitFor(() => {
340+
expect(dispatchMock).toHaveBeenCalledTimes(1);
341+
});
342+
await waitForZaloWebhookVerdict(queue, "poll-deadletter-1", "failed");
343+
await settleAsyncWork();
344+
expect(dispatchMock).toHaveBeenCalledTimes(1);
345+
expect(runtime.error).toHaveBeenCalledWith(expect.stringContaining("authentication-failed"));
346+
347+
abort.abort();
348+
await run;
349+
});
350+
});

0 commit comments

Comments
 (0)