perf(telegram): cache forum metadata lookup

This commit is contained in:
Ayaan Zaidi
2026-04-23 14:08:11 +05:30
parent c22a21759b
commit 50e6c0a3b2
2 changed files with 25 additions and 4 deletions

View File

@@ -52,13 +52,26 @@ describe("resolveTelegramForumFlag", () => {
const getChat = vi.fn(async () => ({ is_forum: true }));
await expect(
resolveTelegramForumFlag({
chatId: -100123,
chatId: -100789,
chatType: "supergroup",
isGroup: true,
getChat,
}),
).resolves.toBe(true);
expect(getChat).toHaveBeenCalledWith(-100123);
expect(getChat).toHaveBeenCalledWith(-100789);
});
it("reuses resolved forum metadata for later supergroup updates", async () => {
const getChat = vi.fn(async () => ({ is_forum: true }));
const params = {
chatId: -100456,
chatType: "supergroup" as const,
isGroup: true,
getChat,
};
await expect(resolveTelegramForumFlag(params)).resolves.toBe(true);
await expect(resolveTelegramForumFlag(params)).resolves.toBe(true);
expect(getChat).toHaveBeenCalledTimes(1);
});
it("returns false when forum lookup is unavailable", async () => {
@@ -67,7 +80,7 @@ describe("resolveTelegramForumFlag", () => {
});
await expect(
resolveTelegramForumFlag({
chatId: -100123,
chatId: -100999,
chatType: "supergroup",
isGroup: true,
getChat,

View File

@@ -40,6 +40,7 @@ export {
};
const TELEGRAM_GENERAL_TOPIC_ID = 1;
const telegramForumFlagByChatId = new Map<string, boolean>();
function hadUnsafeTelegramText(raw: unknown, sanitized: string): boolean {
return typeof raw === "string" && raw.trim().length > 0 && sanitized.trim().length === 0;
@@ -71,8 +72,15 @@ export async function resolveTelegramForumFlag(params: {
if (!params.isGroup || params.chatType !== "supergroup" || !params.getChat) {
return false;
}
const cacheKey = String(params.chatId);
const cached = telegramForumFlagByChatId.get(cacheKey);
if (cached !== undefined) {
return cached;
}
try {
return extractTelegramForumFlag(await params.getChat(params.chatId)) === true;
const resolved = extractTelegramForumFlag(await params.getChat(params.chatId)) === true;
telegramForumFlagByChatId.set(cacheKey, resolved);
return resolved;
} catch {
return false;
}