From ba65163a83dfe2dd9f752a58f1bedff3be32a466 Mon Sep 17 00:00:00 2001 From: Pranav Gawai Date: Sun, 29 Nov 2026 14:38:27 +0530 Subject: [PATCH] fix(telegram): retry chat updates after handling failures --- server/messengers/bridge.ts | 7 +++++-- server/messengers/host.ts | 3 ++- server/messengers/telegram.test.ts | 33 ++++++++++++++++++++++++++++-- server/messengers/telegram.ts | 5 ++++- 4 files changed, 42 insertions(+), 6 deletions(-) diff --git a/server/messengers/bridge.ts b/server/messengers/bridge.ts index be745c80e2..a506b28708 100644 --- a/server/messengers/bridge.ts +++ b/server/messengers/bridge.ts @@ -482,11 +482,14 @@ export function createMessengerBridge(deps: MessengerBridgeDeps) { /** Messages from one bot's account are handled one at a time, in order. */ receive(message: InboundMessage): Promise { const lane = generationKey(message.botId, message.platform); - const task = (inbound.get(lane) ?? Promise.resolve()).then(() => handle(message)); + const task = (inbound.get(lane) ?? Promise.resolve()).then(() => handle(message)).catch((error: unknown) => { + seen.delete(messengerSendId(message.platform, message.botId, message.chatId, message.messageId)); + throw error; + }); const tail = task.catch(() => log("A chat app message could not be handled.")); inbound.set(lane, tail); void tail.then(() => { if (inbound.get(lane) === tail) inbound.delete(lane); }); - return tail; + return task; }, /** A tap on a card's button; only the paired owner's answer reaches the card. */ choose(choice: InboundChoice): Promise { diff --git a/server/messengers/host.ts b/server/messengers/host.ts index 443613c469..00ce8d2829 100644 --- a/server/messengers/host.ts +++ b/server/messengers/host.ts @@ -440,7 +440,8 @@ export function createMessengerHost(deps: MessengerHostDeps) { let update: Record; try { update = JSON.parse(Buffer.concat(chunks).toString("utf8")) as Record; } catch { hookAnswer(res, 400); return true; } - try { await telegramUpdate(match[1]!, update); } catch { log("A Telegram update could not be handled."); } + try { await telegramUpdate(match[1]!, update); } + catch { log("A Telegram update could not be handled."); hookAnswer(res, 500); return true; } hookAnswer(res, 200); return true; } diff --git a/server/messengers/telegram.test.ts b/server/messengers/telegram.test.ts index c07b73a77a..bc35896319 100644 --- a/server/messengers/telegram.test.ts +++ b/server/messengers/telegram.test.ts @@ -28,7 +28,7 @@ async function until(read: () => T | undefined | null | false, ms = 8_000): P interface Sent { botId: string; threadId: string; text: string; sendId: string; outside: boolean; person: { name: string } } -async function fixture(options: { dataDir?: string; fake?: FakeTelegram; hookBase?: string } = {}) { +async function fixture(options: { dataDir?: string; fake?: FakeTelegram; hookBase?: string; failThreadOnce?: boolean } = {}) { const fake = options.fake ?? await startFakeTelegram({ token: TOKEN }); if (!options.fake) cleanups.push(() => fake.close()); const dataDir = options.dataDir ?? mkdtempSync(join(tmpdir(), "dusk-messengers-")); @@ -39,6 +39,7 @@ async function fixture(options: { dataDir?: string; fake?: FakeTelegram; hookBas const sent: Sent[] = []; const answers: Array<{ threadId: string; requestId: string; reply: { behavior: string; message?: string } }> = []; let threadCount = 0; + let failThread = options.failThreadOnce ?? false; const compacted: Array<{ botId: string; threadId: string; focus: string }> = []; const left: string[] = []; const state: { compactOutcome: "started" | "busy" | "failed" } = { compactOutcome: "started" }; @@ -49,7 +50,7 @@ async function fixture(options: { dataDir?: string; fake?: FakeTelegram; hookBas bot: (id) => (id === "bot-nova" ? { id, name: "Nova" } : null), onStoreChange: (listener) => { listeners.add(listener); return () => listeners.delete(listener); }, messages: (threadId) => threads.get(threadId) ?? [], - createThread: (_botId, title) => { const id = `thread-${++threadCount}`; threads.set(id, []); titles.set(id, title); return id; }, + createThread: (_botId, title) => { if (failThread) { failThread = false; throw new Error("temporary store failure"); } const id = `thread-${++threadCount}`; threads.set(id, []); titles.set(id, title); return id; }, threadExists: (_botId, threadId) => threads.has(threadId), saveAttachment: async (_bytes, name, mime) => ({ path: `/attachments/${name}`, kind: mime.startsWith("image/") ? "image" : "file", name }), readAttachment: (path) => ({ bytes: Buffer.from("png-bytes"), mime: "image/png", name: path.split("/").pop()! }), @@ -96,6 +97,34 @@ async function claimed() { } describe("Telegram chat channel", () => { + it("retries a polling update after a temporary conversation-store failure", async () => { + const f = await fixture({ failThreadOnce: true }); + const status = await f.host.connect("bot-nova", "telegram", TOKEN); + f.fake.message({ from: OWNER, text: `/start ${status.pairCode}` }); + await until(() => f.host.status("bot-nova").platforms[0]!.owner); + const update = f.fake.message({ from: OWNER, text: "please keep this" }); + expect((await until(() => f.sent[0])).text).toBe("please keep this"); + expect(f.fake.sent("getUpdates").filter((call) => Number(call.params.offset) === update.update_id)).toHaveLength(2); + }); + + it("asks Telegram to retry a webhook update after a temporary conversation-store failure", async () => { + const fake = await startFakeTelegram({ token: TOKEN }); + cleanups.push(() => fake.close()); + const f = await fixture({ fake, hookBase: "https://home.example.test", failThreadOnce: true }); + const door = createServer((req, res) => { void f.host.door(req, res, new URL(req.url ?? "/", "http://x")); }); + await new Promise((resolve) => door.listen(0, "127.0.0.1", resolve)); + cleanups.push(() => new Promise((resolve) => door.close(() => resolve()))); + const status = await f.host.connect("bot-nova", "telegram", TOKEN); + const url = `http://127.0.0.1:${(door.address() as AddressInfo).port}/hooks/telegram/bot-nova`; + const post = (update: unknown) => fetch(url, { method: "POST", headers: { "x-telegram-bot-api-secret-token": fake.webhook().secret }, body: JSON.stringify(update) }); + const claim = { update_id: 1, message: { message_id: 5, from: OWNER, chat: { id: OWNER.id, type: "private" }, text: `/start ${status.pairCode}` } }; + expect((await post(claim)).status).toBe(200); + const update = { update_id: 2, message: { message_id: 6, from: OWNER, chat: { id: OWNER.id, type: "private" }, text: "please keep this" } }; + expect((await post(update)).status).toBe(500); + expect((await post(update)).status).toBe(200); + expect(f.sent.map((one) => one.text)).toEqual(["please keep this"]); + }); + it("connects with a token, pairs the owner through the start link and refuses a stranger", async () => { const f = await fixture(); const status = await f.host.connect("bot-nova", "telegram", TOKEN); diff --git a/server/messengers/telegram.ts b/server/messengers/telegram.ts index 52e84eff62..8558549e8d 100644 --- a/server/messengers/telegram.ts +++ b/server/messengers/telegram.ts @@ -258,12 +258,15 @@ export function createTelegramPoller(deps: TelegramPollerDeps) { } failures = 0; deps.onState("online"); + let failed = false; for (const update of Array.isArray(updates) ? updates : []) { if (!running) return; const id = Number(update.update_id); - try { await deps.onUpdate(update); } catch { deps.log?.("A Telegram update could not be handled."); } + try { await deps.onUpdate(update); } + catch { deps.log?.("A Telegram update could not be handled."); failed = true; break; } if (Number.isSafeInteger(id)) deps.setOffset(id + 1); } + if (failed) await sleep(2_000); } } return {