Files
wikideck/server/game/trends.ts
T

59 lines
2.6 KiB
TypeScript

/**
* Live pageview trends for `trending` modes, read from cache only at match time.
* Wikipedia egress is shared and rate-limited, so lookups never happen in a request path:
* unknown pages are queued and fetched one at a time, slowly, through the node's existing
* enrichment cache. Until a page is warm, its cards simply get no trend bonus.
*/
import type { LiveCardData } from '../../shared/game/modes.ts';
type Source = (pageId: number) => Promise<{ pageviews: { trendPercent: number | null } }>;
export class TrendCache {
private readonly values = new Map<number, { trend: number | null; at: number }>();
private readonly queue: number[] = [];
private readonly queued = new Set<number>();
private timer: ReturnType<typeof setInterval> | undefined;
private busy = false;
private readonly source: Source;
private readonly options: { intervalMs?: number; ttlMs?: number; maxEntries?: number; now?: () => number };
constructor(source: Source, options: { intervalMs?: number; ttlMs?: number; maxEntries?: number; now?: () => number } = {}) {
this.source = source; this.options = options;
}
/** Cache-only lookup; schedules a background fetch when missing or stale. */
get(pageId: number): LiveCardData | null {
const v = this.values.get(pageId);
const now = (this.options.now ?? Date.now)();
if (!v || now - v.at > (this.options.ttlMs ?? 6 * 3600_000)) this.enqueue(pageId);
return v ? { trendPercent: v.trend } : null;
}
enqueue(pageId: number): void {
if (!Number.isSafeInteger(pageId) || pageId <= 0 || this.queued.has(pageId) || this.queue.length >= 256) return;
this.queued.add(pageId); this.queue.push(pageId);
}
start(): void {
if (this.timer) return;
this.timer = setInterval(() => void this.step(), this.options.intervalMs ?? 20_000);
this.timer.unref();
}
stop(): void { if (this.timer) clearInterval(this.timer); this.timer = undefined; }
/** Fetch at most one page. Exposed for tests. */
async step(): Promise<void> {
if (this.busy) return;
const pageId = this.queue.shift();
if (pageId === undefined) return;
this.busy = true;
try {
const data = await this.source(pageId);
const trend = data.pageviews.trendPercent;
this.values.set(pageId, { trend: typeof trend === 'number' && Number.isFinite(trend) ? trend : null, at: (this.options.now ?? Date.now)() });
while (this.values.size > (this.options.maxEntries ?? 512)) this.values.delete(this.values.keys().next().value!);
} catch { /* Leave it cold; it is re-queued on a later lookup. */ }
finally { this.queued.delete(pageId); this.busy = false; }
}
}