Skip to content

Commit 4928819

Browse files
fix(zalo): journal polled inbound updates across restarts
1 parent 00eb33f commit 4928819

9 files changed

Lines changed: 672 additions & 326 deletions
Lines changed: 245 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,245 @@
1+
// Zalo tests cover durable ingress journaling, replay, and dedupe.
2+
import { mkdtemp, realpath, rm } from "node:fs/promises";
3+
import os from "node:os";
4+
import path from "node:path";
5+
import { createChannelIngressQueueForTests } from "openclaw/plugin-sdk/plugin-state-test-runtime";
6+
import { afterEach, describe, expect, it, vi } from "vitest";
7+
import type { ZaloUpdate } from "./api.js";
8+
import {
9+
createZaloIngressSpool,
10+
type ZaloIngressSpool,
11+
type ZaloIngressTurnLifecycle,
12+
} from "./monitor-ingress.js";
13+
14+
type ZaloIngressPayload = {
15+
version: 1;
16+
receivedAt: number;
17+
update: ZaloUpdate;
18+
};
19+
20+
type ZaloIngressDispatch = (
21+
update: ZaloUpdate,
22+
lifecycle: ZaloIngressTurnLifecycle,
23+
) => Promise<void>;
24+
25+
const stateDirs: string[] = [];
26+
const disposers: Array<() => void> = [];
27+
28+
async function createStateDir(): Promise<string> {
29+
const created = await mkdtemp(path.join(os.tmpdir(), "openclaw-zalo-ingress-"));
30+
const resolved = await realpath(created);
31+
stateDirs.push(resolved);
32+
return resolved;
33+
}
34+
35+
function createQueue(stateDir: string) {
36+
return createChannelIngressQueueForTests<ZaloIngressPayload>({
37+
channelId: "zalo",
38+
accountId: "default",
39+
stateDir,
40+
});
41+
}
42+
43+
function createTextUpdate(params?: { messageId?: string; chatId?: string; userId?: string }) {
44+
return {
45+
event_name: "message.text.received",
46+
message: {
47+
message_id: params?.messageId ?? "msg-1",
48+
from: { id: params?.userId ?? "user-1", name: "Test User" },
49+
chat: { id: params?.chatId ?? "chat-1", chat_type: "PRIVATE" as const },
50+
date: 1_774_080_000,
51+
text: "hello from zalo",
52+
},
53+
} satisfies ZaloUpdate;
54+
}
55+
56+
function createSpool(params: {
57+
stateDir: string;
58+
dispatch: ZaloIngressDispatch;
59+
retryPolicy?: Parameters<typeof createZaloIngressSpool>[0]["retryPolicy"];
60+
}): ZaloIngressSpool {
61+
const spool = createZaloIngressSpool({
62+
accountId: "default",
63+
abortSignal: new AbortController().signal,
64+
queue: createQueue(params.stateDir),
65+
dispatch: params.dispatch,
66+
...(params.retryPolicy ? { retryPolicy: params.retryPolicy } : {}),
67+
});
68+
disposers.push(spool.dispose);
69+
return spool;
70+
}
71+
72+
async function drainSpool(spool: ZaloIngressSpool): Promise<void> {
73+
await spool.drainOnce();
74+
await spool.waitForIdle();
75+
}
76+
77+
afterEach(async () => {
78+
for (const dispose of disposers.splice(0).toReversed()) {
79+
dispose();
80+
}
81+
for (const stateDir of stateDirs.splice(0).toReversed()) {
82+
await rm(stateDir, { recursive: true, force: true });
83+
}
84+
});
85+
86+
describe("createZaloIngressSpool", () => {
87+
it("replays a journaled update after a crash before dispatch", async () => {
88+
// Loss window: the Bot API consumes the update on response, then the process
89+
// dies before processUpdate runs. The journaled row must survive and replay.
90+
const stateDir = await createStateDir();
91+
const crashed = createSpool({
92+
stateDir,
93+
dispatch: vi.fn<ZaloIngressDispatch>(async () => {
94+
throw new Error("must never dispatch before the crash");
95+
}),
96+
});
97+
await crashed.enqueue(createTextUpdate({ messageId: "msg-crash-window" }));
98+
crashed.dispose();
99+
100+
const dispatch = vi.fn<ZaloIngressDispatch>(async (_update, lifecycle) => {
101+
await lifecycle.onAdopted();
102+
});
103+
const recovered = createSpool({ stateDir, dispatch });
104+
await drainSpool(recovered);
105+
106+
expect(dispatch).toHaveBeenCalledOnce();
107+
expect(dispatch.mock.calls[0]?.[0].message?.message_id).toBe("msg-crash-window");
108+
});
109+
110+
it("tombstones after dispatch so a redelivered update never dispatches twice", async () => {
111+
const stateDir = await createStateDir();
112+
const dispatch = vi.fn<ZaloIngressDispatch>(async (_update, lifecycle) => {
113+
await lifecycle.onAdopted();
114+
});
115+
const spool = createSpool({ stateDir, dispatch });
116+
117+
expect(await spool.enqueue(createTextUpdate())).toEqual({ kind: "accepted" });
118+
await drainSpool(spool);
119+
expect(await spool.enqueue(createTextUpdate())).toEqual({ kind: "duplicate" });
120+
await drainSpool(spool);
121+
122+
expect(dispatch).toHaveBeenCalledOnce();
123+
});
124+
125+
it("completes at dispatch return when the turn never adopts", async () => {
126+
// Sticker/unsupported events and pre-dispatch drops (unauthorized, empty text)
127+
// never reach the turn lifecycle; they must still tombstone at dispatch return.
128+
const stateDir = await createStateDir();
129+
const dispatch = vi.fn<ZaloIngressDispatch>(async () => undefined);
130+
const spool = createSpool({ stateDir, dispatch });
131+
132+
await spool.enqueue(createTextUpdate());
133+
await drainSpool(spool);
134+
expect(await spool.enqueue(createTextUpdate())).toEqual({ kind: "duplicate" });
135+
136+
expect(dispatch).toHaveBeenCalledOnce();
137+
});
138+
139+
it("retries a failed dispatch instead of dropping the update", async () => {
140+
const stateDir = await createStateDir();
141+
let attempts = 0;
142+
const dispatch = vi.fn<ZaloIngressDispatch>(async () => {
143+
attempts += 1;
144+
if (attempts === 1) {
145+
throw new Error("dispatch boom");
146+
}
147+
});
148+
const spool = createSpool({
149+
stateDir,
150+
dispatch,
151+
retryPolicy: { baseMs: 1, maxMs: 5 },
152+
});
153+
154+
await spool.enqueue(createTextUpdate());
155+
await drainSpool(spool);
156+
expect(dispatch).toHaveBeenCalledOnce();
157+
158+
await vi.waitFor(async () => {
159+
await spool.drainOnce();
160+
await spool.waitForIdle();
161+
expect(dispatch).toHaveBeenCalledTimes(2);
162+
});
163+
expect(await spool.enqueue(createTextUpdate())).toEqual({ kind: "duplicate" });
164+
});
165+
166+
it("dead-letters a permanently invalid payload instead of retrying forever", async () => {
167+
const stateDir = await createStateDir();
168+
const queue = createQueue(stateDir);
169+
const dispatch = vi.fn<ZaloIngressDispatch>(async () => undefined);
170+
const spool = createSpool({ stateDir, dispatch });
171+
172+
const eventId = JSON.stringify(["chat-1", "user-1", "msg-corrupt"]);
173+
await queue.enqueue(
174+
eventId,
175+
{
176+
version: 99,
177+
receivedAt: Date.now(),
178+
update: createTextUpdate(),
179+
} as unknown as ZaloIngressPayload,
180+
{ receivedAt: Date.now(), laneKey: "chat:chat-1" },
181+
);
182+
await drainSpool(spool);
183+
184+
expect(dispatch).not.toHaveBeenCalled();
185+
expect(await queue.listPending()).toEqual([]);
186+
});
187+
188+
it("ignores updates that cannot be journaled", async () => {
189+
const stateDir = await createStateDir();
190+
const queue = createQueue(stateDir);
191+
const dispatch = vi.fn<ZaloIngressDispatch>(async () => undefined);
192+
const spool = createZaloIngressSpool({
193+
accountId: "default",
194+
abortSignal: new AbortController().signal,
195+
queue,
196+
dispatch,
197+
});
198+
disposers.push(spool.dispose);
199+
200+
expect(await spool.enqueue({ event_name: "message.text.received" })).toEqual({
201+
kind: "ignored",
202+
});
203+
expect(await queue.listPending()).toEqual([]);
204+
expect(dispatch).not.toHaveBeenCalled();
205+
});
206+
207+
it("keeps the same message id in different chats distinct", async () => {
208+
const stateDir = await createStateDir();
209+
const queue = createQueue(stateDir);
210+
const dispatch = vi.fn<ZaloIngressDispatch>(async () => undefined);
211+
const spool = createZaloIngressSpool({
212+
accountId: "default",
213+
abortSignal: new AbortController().signal,
214+
queue,
215+
dispatch,
216+
});
217+
disposers.push(spool.dispose);
218+
219+
expect(await spool.enqueue(createTextUpdate({ chatId: "chat-a" }))).toEqual({
220+
kind: "accepted",
221+
});
222+
expect(await spool.enqueue(createTextUpdate({ chatId: "chat-b" }))).toEqual({
223+
kind: "accepted",
224+
});
225+
expect(await queue.listPending()).toHaveLength(2);
226+
});
227+
228+
it("serializes one lane per chat", async () => {
229+
const stateDir = await createStateDir();
230+
const queue = createQueue(stateDir);
231+
const spool = createZaloIngressSpool({
232+
accountId: "default",
233+
abortSignal: new AbortController().signal,
234+
queue,
235+
dispatch: vi.fn<ZaloIngressDispatch>(async () => undefined),
236+
});
237+
disposers.push(spool.dispose);
238+
239+
await spool.enqueue(createTextUpdate({ chatId: "group-9", messageId: "msg-lane" }));
240+
241+
expect(await queue.listPending()).toEqual([
242+
expect.objectContaining({ laneKey: "chat:group-9" }),
243+
]);
244+
});
245+
});
Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
// Zalo plugin module owns durable ingress enqueue + drain for inbound updates.
2+
import {
3+
bindIngressLifecycleToReplyOptions,
4+
createChannelIngressDrain,
5+
DEFAULT_INGRESS_RETRY_DEAD_LETTER_MIN_AGE_MS,
6+
DEFAULT_INGRESS_RETRY_MAX_ATTEMPTS,
7+
type ChannelIngressQueue,
8+
} from "openclaw/plugin-sdk/channel-outbound";
9+
import { sleepWithAbort } from "openclaw/plugin-sdk/runtime-env";
10+
import type { ZaloUpdate } from "./api.js";
11+
import { getZaloRuntime } from "./runtime.js";
12+
13+
const ZALO_INGRESS_PAYLOAD_VERSION = 1;
14+
// Tombstones dominate the retired 5-minute in-memory webhook replay guard.
15+
const ZALO_INGRESS_COMPLETED_TTL_MS = 30 * 24 * 60 * 60 * 1000;
16+
const ZALO_INGRESS_COMPLETED_MAX_ENTRIES = 20_000;
17+
const ZALO_INGRESS_FAILED_TTL_MS = 30 * 24 * 60 * 60 * 1000;
18+
const ZALO_INGRESS_FAILED_MAX_ENTRIES = 1_000;
19+
// Short backoff against transient SQLite contention before failing closed.
20+
const ZALO_INGRESS_ENQUEUE_RETRY_DELAYS_MS = [250, 750] as const;
21+
22+
type ZaloIngressPayload = {
23+
version: typeof ZALO_INGRESS_PAYLOAD_VERSION;
24+
receivedAt: number;
25+
update: ZaloUpdate;
26+
};
27+
28+
/** Turn adoption lifecycle the drain binds into the channel turn (adoption tombstones the claim). */
29+
export type ZaloIngressTurnLifecycle = ReturnType<
30+
typeof bindIngressLifecycleToReplyOptions
31+
>["turnAdoptionLifecycle"];
32+
33+
export type ZaloIngressEnqueueResult =
34+
| { kind: "accepted" }
35+
| { kind: "duplicate" }
36+
| { kind: "ignored" };
37+
38+
class ZaloIngressPermanentError extends Error {}
39+
40+
function parseZaloIngressPayload(payload: ZaloIngressPayload): ZaloUpdate {
41+
if (payload.version !== ZALO_INGRESS_PAYLOAD_VERSION || !payload.update.message) {
42+
throw new ZaloIngressPermanentError("Zalo ingress payload is invalid.");
43+
}
44+
return payload.update;
45+
}
46+
47+
/** Stable dedupe id + serialized lane for one delivered update; null when it cannot be journaled. */
48+
function resolveZaloUpdateIngressFacts(update: ZaloUpdate): {
49+
eventId: string;
50+
laneKey: string;
51+
} | null {
52+
const message = update.message;
53+
const messageId = message?.message_id?.trim();
54+
if (!message || !messageId) {
55+
return null;
56+
}
57+
// JSON encoding keeps ids unambiguous when chat/sender values contain separators.
58+
return {
59+
eventId: JSON.stringify([message.chat.id, message.from.id, messageId]),
60+
laneKey: `chat:${message.chat.id}`,
61+
};
62+
}
63+
64+
export function createZaloIngressSpool(params: {
65+
accountId: string;
66+
abortSignal: AbortSignal;
67+
queue?: ChannelIngressQueue<ZaloIngressPayload>;
68+
retryPolicy?: {
69+
maxAttempts?: number;
70+
deadLetterMinAgeMs?: number;
71+
baseMs?: number;
72+
maxMs?: number;
73+
};
74+
onLog?: (message: string) => void;
75+
dispatch: (update: ZaloUpdate, lifecycle: ZaloIngressTurnLifecycle) => Promise<void>;
76+
}) {
77+
const queue =
78+
params.queue ??
79+
getZaloRuntime().state.openChannelIngressQueue<ZaloIngressPayload>({
80+
accountId: params.accountId,
81+
});
82+
const drain = createChannelIngressDrain<ZaloIngressPayload>({
83+
queue,
84+
abortSignal: params.abortSignal,
85+
retryPolicy: {
86+
maxAttempts: DEFAULT_INGRESS_RETRY_MAX_ATTEMPTS,
87+
deadLetterMinAgeMs: DEFAULT_INGRESS_RETRY_DEAD_LETTER_MIN_AGE_MS,
88+
...params.retryPolicy,
89+
},
90+
resolveNonRetryableFailure: (error) =>
91+
error instanceof ZaloIngressPermanentError
92+
? { reason: "invalid-payload", message: error.message }
93+
: null,
94+
...(params.onLog ? { onLog: params.onLog } : {}),
95+
dispatchClaimedEvent: async (record, lifecycle) => {
96+
const update = parseZaloIngressPayload(record.payload);
97+
await params.dispatch(
98+
update,
99+
bindIngressLifecycleToReplyOptions(lifecycle).turnAdoptionLifecycle,
100+
);
101+
},
102+
});
103+
104+
return {
105+
/** Journal one update durably before dispatch; the Bot API consumes updates on response. */
106+
enqueue: async (update: ZaloUpdate): Promise<ZaloIngressEnqueueResult> => {
107+
const facts = resolveZaloUpdateIngressFacts(update);
108+
if (!facts) {
109+
// Updates without a message are no-ops downstream; a message without the
110+
// contract-required message_id can be neither deduped nor replayed.
111+
if (update.message) {
112+
params.onLog?.("zalo ingress: dropping update with message but no message_id");
113+
}
114+
return { kind: "ignored" };
115+
}
116+
const receivedAt = Date.now();
117+
await queue.prune({
118+
completedTtlMs: ZALO_INGRESS_COMPLETED_TTL_MS,
119+
completedMaxEntries: ZALO_INGRESS_COMPLETED_MAX_ENTRIES,
120+
failedTtlMs: ZALO_INGRESS_FAILED_TTL_MS,
121+
failedMaxEntries: ZALO_INGRESS_FAILED_MAX_ENTRIES,
122+
});
123+
let lastError: unknown;
124+
for (let attempt = 0; ; attempt += 1) {
125+
try {
126+
const result = await queue.enqueue(
127+
facts.eventId,
128+
{ version: ZALO_INGRESS_PAYLOAD_VERSION, receivedAt, update },
129+
{ receivedAt, laneKey: facts.laneKey },
130+
);
131+
return result.kind === "accepted" ? { kind: "accepted" } : { kind: "duplicate" };
132+
} catch (error) {
133+
lastError = error;
134+
const delay = ZALO_INGRESS_ENQUEUE_RETRY_DELAYS_MS[attempt];
135+
if (delay === undefined || params.abortSignal.aborted) {
136+
break;
137+
}
138+
await sleepWithAbort(delay, params.abortSignal).catch(() => undefined);
139+
}
140+
}
141+
// Fail closed: dispatching an unjournaled update would bypass dedupe and die with the process.
142+
throw lastError;
143+
},
144+
drainOnce: async () => {
145+
await drain.drainOnce();
146+
},
147+
waitForIdle: drain.waitForIdle,
148+
dispose: () => drain.dispose(),
149+
};
150+
}
151+
152+
export type ZaloIngressSpool = ReturnType<typeof createZaloIngressSpool>;

0 commit comments

Comments
 (0)