Files
wikideck/server/wikimedia/cache.ts
T
claudeanderic dbb89ce9c5 Night 2: 40-card Magic-style duel, PvP with owned decks, polite Wikimedia client, Android mining (#23)
Night 2 (2026-11-17), from the `claude/wikideck` fork's `night/2026-11-17` branch. It follows Night 1 (#22).

## What's in it
- **Duel engine** (fork #72, #80): 40-card decks of cards you own, Notability/Citations, keywords, effects T1–T12, Connected, a hidden-information-safe `viewFor`/`logFor`, and replay. Balance v1 tuning (#84) gives the first player about 51%.
- **Card profiles** (#70, #82): Figure, Location, Event, Institution or Doctrine, plus stats, keywords and rules text, all derived from real article data. Templates only.
- **Design and story** (#66, #69, #83): DUEL_DESIGN.md, plus the match log and the encyclopedic "Battle of X (2026)" recap.
- **PvP** (#74, #77, #81, #76, #85):
  - The server checks ownership, and 40-card eligibility is enforced.
  - Modes: Classic (ranked), Draft and Trending.
  - Invites, quick match, Elo, a ladder and recap pages. Online matches render on the duel board.
- **Duel board UI** (#79): MTG-style card faces and combat declaration, built for 360 px first.
- **Polite Wikimedia client** (#73, #75): throttled, cached and identified requests, the mint-path fix, and a prefetch pool.
- **Android mining** (#78): native RandomX, as a sideload build. The emulator mined a testnet block.
- **Testnet ops** (#67, #68).

PR numbers refer to `claude/wikideck`.

## Status
- **Tests:** 423, of which 422 pass, 0 fail and 1 is skipped. The build is OK (`node:24-alpine`, `--network none`).
- **Testnet:** running this commit (036489c) on r350.
- **Untouched:** no changes to `server/testnet/consensus.ts`, `randomx.ts`, `native/` or the mainnet compose.
- **Review:** night-review reviewed fork #66–#79. #80–#85 came from the agents' unfinished branches and were not reviewed.
- **Known gaps:**
  - The PvP end-to-end test hasn't been run (it needs two eom.dev accounts).
  - Bot matches aren't reachable from Play.
  - Card identity pre-bake hasn't been done.
  - The RandomX verifier latch (`server/testnet/randomx.ts:140`) is still open.

This PR is for Eric to merge.

🤖 Generated with [Claude Code](https://claude.com/claude-code)Reviewed-on: #23

Co-authored-by: Claude <claude@eom.dev>
2026-11-18 18:12:24 +00:00

75 lines
3.5 KiB
TypeScript

/**
* On-disk HTTP cache for off-chain Wikimedia reads (`$WIKIDECK_DATA_DIR/wikimedia-cache.sqlite`).
* It stores the raw body with its ETag / Last-Modified so stale entries can be revalidated with
* conditional requests. Mint-path requests never use it (see client.ts).
*/
import { DatabaseSync } from 'node:sqlite';
export type StoredEntry = {
status: number; body: Buffer; contentType: string; etag: string | null; lastModified: string | null;
expiresAt: number; storedAt: number;
};
export type CacheEntry = StoredEntry & { toResponse(): Response };
/** Canonical key: origin + path + sorted query, without `maxlag` (it changes only error behaviour). */
export function cacheKey(url: URL): string {
const params = [...url.searchParams].filter(([name]) => name !== 'maxlag')
.sort(([a, x], [b, y]) => a < b ? -1 : a > b ? 1 : x < y ? -1 : x > y ? 1 : 0);
return `${url.origin}${url.pathname}?${new URLSearchParams(params).toString()}`;
}
function withResponse(entry: StoredEntry): CacheEntry {
return { ...entry, toResponse: () => new Response(new Uint8Array(entry.body), { status: entry.status,
headers: { 'Content-Type': entry.contentType, 'Content-Length': String(entry.body.byteLength),
...(entry.etag ? { ETag: entry.etag } : {}) } }) };
}
type Row = { status: number; body: Uint8Array; content_type: string; etag: string | null;
last_modified: string | null; expires_at: number; stored_at: number };
export class WikimediaCache {
private readonly db: DatabaseSync;
private readonly maxRows: number;
private writes = 0;
/** `path` may be ':memory:' (tests). */
constructor(path: string, options: { maxRows?: number } = {}) {
this.maxRows = options.maxRows ?? 100_000;
this.db = new DatabaseSync(path);
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;
CREATE TABLE IF NOT EXISTS http_cache (key TEXT PRIMARY KEY, status INTEGER NOT NULL, body BLOB NOT NULL,
content_type TEXT NOT NULL, etag TEXT, last_modified TEXT, expires_at INTEGER NOT NULL, stored_at INTEGER NOT NULL);
CREATE INDEX IF NOT EXISTS http_cache_stored ON http_cache(stored_at);`);
}
get(key: string): CacheEntry | undefined {
const row = this.db.prepare('SELECT * FROM http_cache WHERE key = ?').get(key) as Row | undefined;
if (!row) return undefined;
return withResponse({ status: row.status, body: Buffer.from(row.body), contentType: row.content_type,
etag: row.etag, lastModified: row.last_modified, expiresAt: row.expires_at, storedAt: row.stored_at });
}
put(key: string, entry: StoredEntry): CacheEntry {
this.db.prepare(`INSERT OR REPLACE INTO http_cache (key, status, body, content_type, etag, last_modified, expires_at, stored_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(key, entry.status, entry.body, entry.contentType, entry.etag,
entry.lastModified, entry.expiresAt, entry.storedAt);
if (++this.writes % 500 === 0) this.prune();
return withResponse(entry);
}
touch(key: string, expiresAt: number): void {
this.db.prepare('UPDATE http_cache SET expires_at = ? WHERE key = ?').run(expiresAt, key);
}
delete(key: string): void { this.db.prepare('DELETE FROM http_cache WHERE key = ?').run(key); }
size(): number { return (this.db.prepare('SELECT COUNT(*) AS n FROM http_cache').get() as { n: number }).n; }
prune(): void {
this.db.prepare(`DELETE FROM http_cache WHERE key IN (SELECT key FROM http_cache ORDER BY stored_at DESC LIMIT -1 OFFSET ?)`)
.run(this.maxRows);
}
close(): void { this.db.close(); }
}