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
4 changes: 4 additions & 0 deletions apps/api/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
# running app, and by scripts/test-env.cjs for tests.
DATABASE_URL="postgresql://fintrack:fintrack@localhost:5432/fintrack?schema=public"
DIRECT_URL="postgresql://fintrack:fintrack@localhost:5432/fintrack?schema=public"
# In production behind a transaction pooler (e.g. Supabase, port 6543), append
# ?pgbouncer=true&connection_limit=1 to DATABASE_URL — Prisma must skip prepared
# statements or pooled requests fail with `prepared statement "sN" does not exist`.
# Keep DIRECT_URL on a direct connection (port 5432, no flag) for migrations.
REDIS_URL="redis://localhost:6379"

# Secrets & tokens
Expand Down
27 changes: 23 additions & 4 deletions apps/bot/src/services/apiClient.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { config } from "../config.js";
import { logger } from "../lib/logger.js";
import {
type TokenPair,
deleteTokens,
getTokens,
hasTokens,
setTokens,
Expand Down Expand Up @@ -47,6 +47,21 @@ async function exchangeTokens(
return data;
}

// Dedupe concurrent re-exchanges per user: a burst of 401s would otherwise fire
// one exchange each and blow the API's exchange rate limit (10 / 15 min).
const inflightExchange = new Map<number, Promise<TokenPair>>();

function exchangeOnce(telegramId: number, name: string): Promise<TokenPair> {
let inflight = inflightExchange.get(telegramId);
if (!inflight) {
inflight = exchangeTokens(telegramId, name).finally(() => {
inflightExchange.delete(telegramId);
});
inflightExchange.set(telegramId, inflight);
}
return inflight;
}

async function apiFetch(
method: string,
path: string,
Expand All @@ -67,14 +82,18 @@ async function apiFetch(

if (res.status === 401 && tokens && !retried) {
try {
await exchangeTokens(telegramId, tokens.name);
} catch {
await deleteTokens(telegramId);
await exchangeOnce(telegramId, tokens.name);
} catch (err) {
logger.warn({ err, path }, "token re-exchange failed");
return res;
}
return apiFetch(method, path, telegramId, body, true);
}

if (!res.ok) {
logger.warn({ status: res.status, method, path }, "api request failed");
}

return res;
}

Expand Down
Loading