Skip to content

Commit fb6c5a5

Browse files
committed
fix(whatsapp): persist durable inbound delivery
1 parent 67c56f3 commit fb6c5a5

6 files changed

Lines changed: 914 additions & 102 deletions
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
import type { WAMessage } from "baileys";
2+
import { afterEach, describe, expect, it, vi } from "vitest";
3+
4+
type StoredMessage = {
5+
key?: {
6+
id?: string;
7+
remoteJid?: string;
8+
participant?: string;
9+
fromMe?: boolean;
10+
};
11+
messageTimestamp?: number;
12+
message?: {
13+
conversation?: string;
14+
};
15+
};
16+
17+
type StoredRecord = {
18+
id: string;
19+
accountId: string;
20+
upsertType: "notify" | "append";
21+
message: StoredMessage;
22+
receivedAt: number;
23+
};
24+
25+
type TestStore = {
26+
pending: StoredRecord[];
27+
completed: Record<string, number | { completedAt: number }>;
28+
};
29+
30+
function cloneStore(store: TestStore): TestStore {
31+
return structuredClone(store);
32+
}
33+
34+
function makeMessage(id: string): WAMessage {
35+
return {
36+
key: {
37+
id,
38+
remoteJid: "[email protected]",
39+
fromMe: false,
40+
},
41+
messageTimestamp: 1_779_434_000,
42+
message: { conversation: `body ${id}` },
43+
} as unknown as WAMessage;
44+
}
45+
46+
describe("durable inbound queue", () => {
47+
afterEach(() => {
48+
vi.doUnmock("openclaw/plugin-sdk/file-lock");
49+
vi.doUnmock("openclaw/plugin-sdk/json-store");
50+
vi.resetModules();
51+
});
52+
53+
it("serializes overlapping accept and complete writes against one store", async () => {
54+
vi.resetModules();
55+
let store: TestStore = { pending: [], completed: {} };
56+
let overlapPhase = false;
57+
let overlapWrites = 0;
58+
let releaseFirstOverlapWrite!: () => void;
59+
let resolveFirstOverlapWriteBlocked!: () => void;
60+
const firstOverlapWriteBlocked = new Promise<void>((resolve) => {
61+
resolveFirstOverlapWriteBlocked = resolve;
62+
});
63+
const firstOverlapWriteCanContinue = new Promise<void>((resolve) => {
64+
releaseFirstOverlapWrite = resolve;
65+
});
66+
67+
vi.doMock("openclaw/plugin-sdk/file-lock", () => ({
68+
withFileLock: async (_filePath: string, _options: unknown, fn: () => Promise<unknown>) =>
69+
await fn(),
70+
}));
71+
vi.doMock("openclaw/plugin-sdk/json-store", () => ({
72+
readJsonFileWithFallback: vi.fn(async () => ({ value: cloneStore(store), exists: true })),
73+
writeJsonFileAtomically: vi.fn(async (_filePath: string, value: unknown) => {
74+
if (overlapPhase) {
75+
overlapWrites += 1;
76+
if (overlapWrites === 1) {
77+
resolveFirstOverlapWriteBlocked();
78+
await firstOverlapWriteCanContinue;
79+
}
80+
}
81+
store = cloneStore(value as TestStore);
82+
}),
83+
}));
84+
85+
const {
86+
acceptDurableInboundMessage,
87+
completeDurableInboundMessage,
88+
loadPendingDurableInboundMessages,
89+
} = await import("./durable-queue.js");
90+
91+
const oldAccepted = await acceptDurableInboundMessage({
92+
authDir: "/tmp/openclaw-durable-inbound-test",
93+
accountId: "acct",
94+
upsertType: "notify",
95+
message: makeMessage("old"),
96+
});
97+
expect(oldAccepted.kind).toBe("accepted");
98+
if (oldAccepted.kind !== "accepted") {
99+
throw new Error("old message should be accepted");
100+
}
101+
102+
overlapPhase = true;
103+
const acceptNew = acceptDurableInboundMessage({
104+
authDir: "/tmp/openclaw-durable-inbound-test",
105+
accountId: "acct",
106+
upsertType: "notify",
107+
message: makeMessage("new"),
108+
});
109+
await firstOverlapWriteBlocked;
110+
const completeOld = completeDurableInboundMessage({
111+
authDir: "/tmp/openclaw-durable-inbound-test",
112+
record: oldAccepted.record,
113+
});
114+
await new Promise((resolve) => setImmediate(resolve));
115+
releaseFirstOverlapWrite();
116+
await Promise.all([acceptNew, completeOld]);
117+
118+
const pending = await loadPendingDurableInboundMessages({
119+
authDir: "/tmp/openclaw-durable-inbound-test",
120+
accountId: "acct",
121+
});
122+
expect(pending.map((record) => record.message.key?.id)).toEqual(["new"]);
123+
expect(store.pending.map((record) => record.message.key?.id)).toEqual(["new"]);
124+
expect(Object.keys(store.completed)).toHaveLength(1);
125+
});
126+
});
Lines changed: 255 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,255 @@
1+
import { createHash } from "node:crypto";
2+
import path from "node:path";
3+
import type { WAMessage } from "baileys";
4+
import { withFileLock } from "openclaw/plugin-sdk/file-lock";
5+
import { readJsonFileWithFallback, writeJsonFileAtomically } from "openclaw/plugin-sdk/json-store";
6+
import { BufferJSON } from "../session.runtime.js";
7+
8+
const STORE_FILE = "inbound-queue.json";
9+
const LOCK_OPTIONS = {
10+
retries: { retries: 6, factor: 1.35, minTimeout: 8, maxTimeout: 180 },
11+
stale: 60_000,
12+
};
13+
// `withFileLock` is process-local re-entrant; serialize same-file store cycles here.
14+
const storeOperationQueues = new Map<string, Promise<unknown>>();
15+
16+
export type DurableInboundUpsertType = "notify" | "append";
17+
18+
export type DurableInboundRecord = {
19+
id: string;
20+
accountId: string;
21+
upsertType: DurableInboundUpsertType;
22+
message: WAMessage;
23+
receivedAt: number;
24+
};
25+
26+
export type DurableInboundReadReceiptTarget = {
27+
id: string;
28+
remoteJid: string;
29+
participantJid?: string;
30+
isSelfChat: boolean;
31+
};
32+
33+
type DurableInboundCompletedEntry =
34+
| number
35+
| {
36+
completedAt: number;
37+
readReceiptTarget?: DurableInboundReadReceiptTarget;
38+
};
39+
40+
type QueueStore = {
41+
pending: DurableInboundRecord[];
42+
completed: Record<string, DurableInboundCompletedEntry>;
43+
};
44+
45+
export type DurableInboundAcceptResult =
46+
| { kind: "accepted"; record: DurableInboundRecord }
47+
| { kind: "duplicate"; id: string; readReceiptTarget?: DurableInboundReadReceiptTarget }
48+
| { kind: "untracked" };
49+
50+
function isRecordObject(value: unknown): value is Record<string, unknown> {
51+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
52+
}
53+
54+
function trimNonEmpty(value: string | null | undefined): string | null {
55+
return value?.trim() || null;
56+
}
57+
58+
function durableId(params: {
59+
accountId: string;
60+
remoteJid?: string | null;
61+
messageId?: string | null;
62+
participantJid?: string | null;
63+
}): string | null {
64+
const accountId = trimNonEmpty(params.accountId);
65+
const remoteJid = trimNonEmpty(params.remoteJid);
66+
const messageId = trimNonEmpty(params.messageId);
67+
if (!accountId || !remoteJid || !messageId || messageId === "unknown") {
68+
return null;
69+
}
70+
return createHash("sha256")
71+
.update([accountId, remoteJid, messageId, trimNonEmpty(params.participantJid) ?? ""].join("\0"))
72+
.digest("hex");
73+
}
74+
75+
function coerceMessageTimestamp(raw: unknown): number | undefined {
76+
if (raw == null) {
77+
return undefined;
78+
}
79+
if (typeof raw === "object" && typeof (raw as { toNumber?: unknown }).toNumber === "function") {
80+
const value = Number((raw as { toNumber: () => unknown }).toNumber());
81+
return Number.isFinite(value) ? value : undefined;
82+
}
83+
if (isRecordObject(raw) && typeof raw.low === "number" && typeof raw.high === "number") {
84+
const low = raw.unsigned === true ? raw.low >>> 0 : raw.low;
85+
const high = raw.unsigned === true ? raw.high >>> 0 : raw.high;
86+
const value = low + high * 0x100000000;
87+
return Number.isSafeInteger(value) ? value : undefined;
88+
}
89+
const value = Number(raw);
90+
return Number.isFinite(value) ? value : undefined;
91+
}
92+
93+
function prepareMessage(message: WAMessage): WAMessage {
94+
const messageTimestamp = coerceMessageTimestamp(message.messageTimestamp);
95+
const storable = messageTimestamp === undefined ? message : { ...message, messageTimestamp };
96+
return JSON.parse(JSON.stringify(storable, BufferJSON.replacer)) as WAMessage;
97+
}
98+
99+
function reviveMessage(message: WAMessage): WAMessage {
100+
const revived = JSON.parse(JSON.stringify(message), BufferJSON.reviver) as WAMessage;
101+
const messageTimestamp = coerceMessageTimestamp(revived.messageTimestamp);
102+
return messageTimestamp === undefined ? revived : { ...revived, messageTimestamp };
103+
}
104+
105+
async function readStore(filePath: string): Promise<QueueStore> {
106+
const { value } = await readJsonFileWithFallback<unknown>(filePath, null);
107+
if (!isRecordObject(value)) {
108+
return { pending: [], completed: {} };
109+
}
110+
const pending = Array.isArray(value.pending) ? (value.pending as DurableInboundRecord[]) : [];
111+
return {
112+
pending: pending
113+
.filter((record) => isRecordObject(record.message))
114+
.map((record) => Object.assign({}, record, { message: reviveMessage(record.message) })),
115+
completed: isRecordObject(value.completed)
116+
? (value.completed as Record<string, DurableInboundCompletedEntry>)
117+
: {},
118+
};
119+
}
120+
121+
function completedEntryTime(entry: DurableInboundCompletedEntry): number {
122+
return typeof entry === "number" ? entry : entry.completedAt;
123+
}
124+
125+
function pruneCompleted(
126+
completed: Record<string, DurableInboundCompletedEntry>,
127+
): Record<string, DurableInboundCompletedEntry> {
128+
return Object.fromEntries(
129+
Object.entries(completed)
130+
.toSorted(([, a], [, b]) => completedEntryTime(b) - completedEntryTime(a))
131+
.slice(0, 10_000),
132+
);
133+
}
134+
135+
function enqueueStoreOperation<T>(filePath: string, fn: () => Promise<T>): Promise<T> {
136+
const previous = storeOperationQueues.get(filePath) ?? Promise.resolve();
137+
const next = previous.then(fn, fn);
138+
storeOperationQueues.set(filePath, next);
139+
next
140+
.finally(() => {
141+
if (storeOperationQueues.get(filePath) === next) {
142+
storeOperationQueues.delete(filePath);
143+
}
144+
})
145+
.catch(() => {});
146+
return next;
147+
}
148+
149+
async function updateStore<T>(
150+
authDir: string,
151+
fn: (store: QueueStore, now: number, filePath: string) => Promise<T>,
152+
) {
153+
const filePath = path.join(authDir, STORE_FILE);
154+
return await enqueueStoreOperation(filePath, () =>
155+
withFileLock(filePath, LOCK_OPTIONS, async () => {
156+
const now = Date.now();
157+
const store = await readStore(filePath);
158+
store.completed = pruneCompleted(store.completed);
159+
return await fn(store, now, filePath);
160+
}),
161+
);
162+
}
163+
164+
export async function acceptDurableInboundMessage(params: {
165+
authDir: string;
166+
accountId: string;
167+
upsertType: DurableInboundUpsertType;
168+
message: WAMessage;
169+
receivedAt?: number;
170+
}): Promise<DurableInboundAcceptResult> {
171+
const messageId = params.message.key?.id ?? undefined;
172+
const remoteJid = params.message.key?.remoteJid ?? undefined;
173+
const participantJid = params.message.key?.participant ?? undefined;
174+
const id = durableId({ accountId: params.accountId, remoteJid, messageId, participantJid });
175+
if (!id || !remoteJid || !messageId) {
176+
return { kind: "untracked" };
177+
}
178+
return await updateStore(params.authDir, async (store, now, filePath) => {
179+
const completed = store.completed[id];
180+
if (completed !== undefined) {
181+
return {
182+
kind: "duplicate",
183+
id,
184+
readReceiptTarget: typeof completed === "number" ? undefined : completed.readReceiptTarget,
185+
};
186+
}
187+
const pending = store.pending.find((record) => record.id === id);
188+
if (pending) {
189+
return { kind: "accepted", record: pending };
190+
}
191+
const record: DurableInboundRecord = {
192+
id,
193+
accountId: params.accountId,
194+
upsertType: params.upsertType,
195+
message: prepareMessage(params.message),
196+
receivedAt: params.receivedAt ?? now,
197+
};
198+
await writeJsonFileAtomically(filePath, {
199+
...store,
200+
pending: [...store.pending, record],
201+
});
202+
return { kind: "accepted", record: { ...record, message: params.message } };
203+
});
204+
}
205+
206+
export async function loadPendingDurableInboundMessages(params: {
207+
authDir: string;
208+
accountId: string;
209+
}): Promise<DurableInboundRecord[]> {
210+
return await updateStore(params.authDir, async (store) =>
211+
store.pending
212+
.filter(
213+
(record) =>
214+
record.accountId === params.accountId && store.completed[record.id] === undefined,
215+
)
216+
.toSorted((a, b) => a.receivedAt - b.receivedAt || a.id.localeCompare(b.id)),
217+
);
218+
}
219+
220+
export async function completeDurableInboundMessage(params: {
221+
authDir: string;
222+
record: DurableInboundRecord;
223+
readReceiptTarget?: DurableInboundReadReceiptTarget;
224+
}): Promise<void> {
225+
await updateStore(params.authDir, async (store, now, filePath) => {
226+
const completedEntry: DurableInboundCompletedEntry = params.readReceiptTarget
227+
? { completedAt: now, readReceiptTarget: params.readReceiptTarget }
228+
: now;
229+
await writeJsonFileAtomically(filePath, {
230+
...store,
231+
pending: store.pending.filter((record) => record.id !== params.record.id),
232+
completed: pruneCompleted({ ...store.completed, [params.record.id]: completedEntry }),
233+
});
234+
});
235+
}
236+
237+
export async function recordDurableInboundRetry(params: {
238+
authDir: string;
239+
record: DurableInboundRecord;
240+
}): Promise<void> {
241+
await updateStore(params.authDir, async (store, _now, filePath) => {
242+
if (store.completed[params.record.id] !== undefined) {
243+
return;
244+
}
245+
const current = store.pending.find((record) => record.id === params.record.id) ?? params.record;
246+
const next = {
247+
...current,
248+
message: prepareMessage(current.message),
249+
};
250+
await writeJsonFileAtomically(filePath, {
251+
...store,
252+
pending: [next, ...store.pending.filter((record) => record.id !== next.id)],
253+
});
254+
});
255+
}

0 commit comments

Comments
 (0)