|
| 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