Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions server/messengers/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
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<void> {
Expand Down
3 changes: 2 additions & 1 deletion server/messengers/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,8 @@ export function createMessengerHost(deps: MessengerHostDeps) {
let update: Record<string, unknown>;
try { update = JSON.parse(Buffer.concat(chunks).toString("utf8")) as Record<string, unknown>; }
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;
}
Expand Down
33 changes: 31 additions & 2 deletions server/messengers/telegram.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async function until<T>(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-"));
Expand All @@ -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" };
Expand All @@ -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()! }),
Expand Down Expand Up @@ -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<void>((resolve) => door.listen(0, "127.0.0.1", resolve));
cleanups.push(() => new Promise<void>((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);
Expand Down
5 changes: 4 additions & 1 deletion server/messengers/telegram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading