Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(club): stop a cold tips stream replaying its backlog, and keep the leaderboard answering under DB pressure

nirholas6a73bb9fd0fb
diff --git a/api/club/leaderboard.js b/api/club/leaderboard.js
index 28c209be8..a1b461c2b 100644
--- a/api/club/leaderboard.js
+++ b/api/club/leaderboard.js
@@ -4,98 +4,107 @@
// Returns one row per dancer in the club_dancer_wallets registry (even if
// they have zero tips) so the UI stays stable as new dancers get added.
//
-// `window` is a strict whitelist — never user-injected SQL. Each branch is a
-// distinct tagged template so the underlying Neon HTTP client parameterizes
-// the interval literal safely.
+// `window` is a strict whitelist, never user-injected SQL. Each entry in
+// QUERIES is its own tagged template so the underlying Neon HTTP client
+// parameterizes the interval literal safely.
-import { sql } from '../_lib/db.js';
-import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { sql, isDbUnavailableError, isDbCapacityError } from '../_lib/db.js';
+import { cacheWrap } from '../_lib/cache.js';
+import { cors, json, method, wrap, error, serverError } from '../_lib/http.js';
+
+// Every open /club tab re-polls this on a 30s cadence and each window is a full
+// aggregate over club_tips (hundreds of thousands of rows, ~1s on the week
+// window), so the result is memoized. A room of viewers then costs one aggregate
+// per window per interval instead of one per viewer, and the staleness stays far
+// shorter than the poll cadence it feeds.
+const CACHE_TTL_S = 15;
+
+const QUERIES = {
+ hour: () => sql`
+ select
+ d.dancer,
+ d.display_name,
+ coalesce(sum(t.amount_atomics), 0)::text as total_atomics,
+ count(t.*)::int as tip_count,
+ coalesce(sum(case when t.paid_at is null then t.amount_atomics else 0 end), 0)::text as unpaid_atomics
+ from club_dancer_wallets d
+ left join club_tips t
+ on t.dancer = d.dancer and t.created_at >= now() - interval '1 hour'
+ group by d.dancer, d.display_name
+ order by coalesce(sum(t.amount_atomics), 0) desc, d.dancer asc
+ `,
+ day: () => sql`
+ select
+ d.dancer,
+ d.display_name,
+ coalesce(sum(t.amount_atomics), 0)::text as total_atomics,
+ count(t.*)::int as tip_count,
+ coalesce(sum(case when t.paid_at is null then t.amount_atomics else 0 end), 0)::text as unpaid_atomics
+ from club_dancer_wallets d
+ left join club_tips t
+ on t.dancer = d.dancer and t.created_at >= now() - interval '24 hours'
+ group by d.dancer, d.display_name
+ order by coalesce(sum(t.amount_atomics), 0) desc, d.dancer asc
+ `,
+ week: () => sql`
+ select
+ d.dancer,
+ d.display_name,
+ coalesce(sum(t.amount_atomics), 0)::text as total_atomics,
+ count(t.*)::int as tip_count,
+ coalesce(sum(case when t.paid_at is null then t.amount_atomics else 0 end), 0)::text as unpaid_atomics
+ from club_dancer_wallets d
+ left join club_tips t
+ on t.dancer = d.dancer and t.created_at >= now() - interval '7 days'
+ group by d.dancer, d.display_name
+ order by coalesce(sum(t.amount_atomics), 0) desc, d.dancer asc
+ `,
+ all: () => sql`
+ select
+ d.dancer,
+ d.display_name,
+ coalesce(sum(t.amount_atomics), 0)::text as total_atomics,
+ count(t.*)::int as tip_count,
+ coalesce(sum(case when t.paid_at is null then t.amount_atomics else 0 end), 0)::text as unpaid_atomics
+ from club_dancer_wallets d
+ left join club_tips t on t.dancer = d.dancer
+ group by d.dancer, d.display_name
+ order by coalesce(sum(t.amount_atomics), 0) desc, d.dancer asc
+ `,
+};
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
if (!method(req, res, ['GET'])) return;
const window = (req.query?.window || 'all').toString();
+ const run = QUERIES[window];
+ if (!run) {
+ return error(res, 400, 'bad_window', 'window must be hour|day|week|all');
+ }
+
let rows;
try {
- rows = await runForWindow(window);
+ rows = await cacheWrap(`club:leaderboard:${window}`, CACHE_TTL_S, run);
} catch (err) {
// Surface the Postgres error code so schema drift is diagnosable from
// logs alone: 42703 = column not found, 42P01 = undefined table.
- // `detail` carries the offending identifier when Neon provides it.
- console.error(
- '[club/leaderboard]',
- 'window=' + window,
- 'code=' + (err?.code || 'none'),
- err?.detail || err?.message || err,
- );
- return error(res, 500, 'db_error', 'Failed to load leaderboard');
- }
- if (rows === null) {
- return error(res, 400, 'bad_window', 'window must be hour|day|week|all');
+ // `detail` carries the offending identifier when Neon provides it. A
+ // database outage is skipped here: it is not schema drift, and one line per
+ // poll per open tab is exactly the flood serverError() throttles for us.
+ if (!isDbUnavailableError(err) && !isDbCapacityError(err)) {
+ console.error(
+ '[club/leaderboard]',
+ 'window=' + window,
+ 'code=' + (err?.code || 'none'),
+ err?.detail || err?.message || err,
+ );
+ }
+ // serverError rather than a hardcoded 500: it coerces an outage or a full
+ // branch to 503 + Retry-After with a single deduped ops alert, so a Neon
+ // blip degrades quietly instead of alerting once per polling tab.
+ return serverError(res, 500, 'db_error', err);
}
return json(res, 200, { window, rows });
});
-
-async function runForWindow(window) {
- switch (window) {
- case 'hour':
- return sql`
- select
- d.dancer,
- d.display_name,
- coalesce(sum(t.amount_atomics), 0)::text as total_atomics,
- count(t.*)::int as tip_count,
- coalesce(sum(case when t.paid_at is null then t.amount_atomics else 0 end), 0)::text as unpaid_atomics
- from club_dancer_wallets d
- left join club_tips t
- on t.dancer = d.dancer and t.created_at >= now() - interval '1 hour'
- group by d.dancer, d.display_name
- order by coalesce(sum(t.amount_atomics), 0) desc, d.dancer asc
- `;
- case 'day':
- return sql`
- select
- d.dancer,
- d.display_name,
- coalesce(sum(t.amount_atomics), 0)::text as total_atomics,
- count(t.*)::int as tip_count,
- coalesce(sum(case when t.paid_at is null then t.amount_atomics else 0 end), 0)::text as unpaid_atomics
- from club_dancer_wallets d
- left join club_tips t
- on t.dancer = d.dancer and t.created_at >= now() - interval '24 hours'
- group by d.dancer, d.display_name
- order by coalesce(sum(t.amount_atomics), 0) desc, d.dancer asc
- `;
- case 'week':
- return sql`
- select
- d.dancer,
- d.display_name,
- coalesce(sum(t.amount_atomics), 0)::text as total_atomics,
- count(t.*)::int as tip_count,
- coalesce(sum(case when t.paid_at is null then t.amount_atomics else 0 end), 0)::text as unpaid_atomics
- from club_dancer_wallets d
- left join club_tips t
- on t.dancer = d.dancer and t.created_at >= now() - interval '7 days'
- group by d.dancer, d.display_name
- order by coalesce(sum(t.amount_atomics), 0) desc, d.dancer asc
- `;
- case 'all':
- return sql`
- select
- d.dancer,
- d.display_name,
- coalesce(sum(t.amount_atomics), 0)::text as total_atomics,
- count(t.*)::int as tip_count,
- coalesce(sum(case when t.paid_at is null then t.amount_atomics else 0 end), 0)::text as unpaid_atomics
- from club_dancer_wallets d
- left join club_tips t on t.dancer = d.dancer
- group by d.dancer, d.display_name
- order by coalesce(sum(t.amount_atomics), 0) desc, d.dancer asc
- `;
- default:
- return null;
- }
-}
diff --git a/api/club/tips-stream.js b/api/club/tips-stream.js
index 61288ebf4..6b2fc22b2 100644
--- a/api/club/tips-stream.js
+++ b/api/club/tips-stream.js
@@ -84,24 +84,48 @@ async function runSharedPoll() {
}
function ensureSharedPoll() {
- if (!pollTimer) {
- pollTimer = setTimeout(runSharedPoll, POLL_MS_MIN);
- }
+ if (pollTimer) return;
+ // Cold start: the loop stopped when the last listener left, so the cursor is
+ // pinned to that moment. Rewind it to now before the first tick, or a room
+ // that went quiet for a while replays everything banked during the gap (up to
+ // MAX_ROWS_PER_TICK of it) into the first viewer back as if it were live.
+ // Resetting idleTicks with it also puts that viewer on the fast cadence
+ // instead of the 5s one the previous idle ramp had settled into.
+ sharedCursor = new Date();
+ sharedCursorId = '';
+ idleTicks = 0;
+ pollTimer = setTimeout(runSharedPoll, POLL_MS_MIN);
}
+const SSE_HEADERS = {
+ 'Content-Type': 'text/event-stream; charset=utf-8',
+ 'Cache-Control': 'no-cache, no-transform',
+ 'Connection': 'keep-alive',
+ // Critical: Vercel's edge gateway buffers responses by default; without
+ // this header SSE frames are held until the function returns, defeating the stream.
+ 'X-Accel-Buffering': 'no',
+};
+
// ── Per-connection handler ────────────────────────────────────────────────────
export default async function handleTipsStream(req, res) {
+ // Capture the verb before method() normalizes a HEAD probe to GET for dispatch.
+ const isHead = (req.method || 'GET').toUpperCase() === 'HEAD';
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
- res.writeHead(200, {
- 'Content-Type': 'text/event-stream; charset=utf-8',
- 'Cache-Control': 'no-cache, no-transform',
- 'Connection': 'keep-alive',
- // Critical: Vercel's edge gateway buffers responses by default; without
- // this header SSE frames are held until the function returns, defeating the stream.
- 'X-Accel-Buffering': 'no',
- });
+ // A HEAD asks for the headers this GET would answer with, not the stream
+ // itself, and a HEAD response can never carry a body anyway. Answer and end.
+ // Opening a real stream for one (api/ops/health.js probes this endpoint that
+ // way on every sweep) registered a listener that nothing would ever close, so
+ // each probe parked a client slot and a heartbeat timer until the 275s
+ // graceful shutdown finally reclaimed them.
+ if (isHead) {
+ res.writeHead(200, SSE_HEADERS);
+ res.end();
+ return;
+ }
+
+ res.writeHead(200, SSE_HEADERS);
let closed = false;
const send = (event, data) => {
diff --git a/tests/api/club-leaderboard.test.js b/tests/api/club-leaderboard.test.js
index 7ad6a9ce9..8225218e6 100644
--- a/tests/api/club-leaderboard.test.js
+++ b/tests/api/club-leaderboard.test.js
@@ -12,6 +12,14 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
const sqlMock = vi.fn();
vi.mock('../../api/_lib/db.js', () => ({ sql: sqlMock, isDbUnavailableError: () => false, isDbCapacityError: () => false }));
+// The handler memoizes each window through cacheWrap. Run it as a pass-through
+// here so every case below still exercises the query it names, and assert the
+// key + TTL it was called with separately.
+const cacheWrapMock = vi.fn(async (_key, _ttl, fn) => fn());
+vi.mock('../../api/_lib/cache.js', () => ({ cacheWrap: (...args) => cacheWrapMock(...args) }));
+
+vi.mock('../../api/_lib/alerts.js', () => ({ sendOpsAlert: vi.fn() }));
+
vi.mock('../../api/_lib/env.js', () => ({
env: { APP_ORIGIN: 'http://localhost:3000' },
}));
@@ -65,6 +73,7 @@ const sampleRows = [
beforeEach(() => {
sqlMock.mockReset();
sqlMock.mockResolvedValue(sampleRows);
+ cacheWrapMock.mockClear();
});
describe('GET /api/club/leaderboard', () => {
@@ -114,6 +123,21 @@ describe('GET /api/club/leaderboard', () => {
expect(body.window).toBe('day');
});
+ it('memoizes each window under its own cache key and TTL', async () => {
+ await invoke({ query: { window: 'day' } });
+ expect(cacheWrapMock).toHaveBeenCalledOnce();
+ const [key, ttl] = cacheWrapMock.mock.calls[0];
+ expect(key).toBe('club:leaderboard:day');
+ // A TTL well under the 30s client poll cadence, so the widget still moves.
+ expect(ttl).toBeGreaterThan(0);
+ expect(ttl).toBeLessThan(30);
+ });
+
+ it('never reaches the cache for an unknown window', async () => {
+ await invoke({ query: { window: 'forever' } });
+ expect(cacheWrapMock).not.toHaveBeenCalled();
+ });
+
it('returns 500 db_error and logs the Postgres code when the query throws', async () => {
const pgErr = Object.assign(new Error('column t.paid_at does not exist'), {
code: '42703',