Spaces:
Sleeping

arena / server.js
jtoeps's picture
Claude Opus 4.8
beyblade arena: docker space (server + 4 claude handlers, in-memory telemetry)
9abf5bb
Raw History Blame Contribute Delete
7.52 kB
// server.js β€” Beyblade Arena (#003) as a Hugging Face Docker Space.
// Zero dependencies. Serves index.html and runs the Vercel-style handlers
// (beyblade, writers-room, card, voice) behind a tiny req/res shim, so the
// handlers stay the same as the ones on funderdevelopment.com. The two KV-backed
// telemetry endpoints (ping/stats) are reimplemented in-memory here β€” HF has no
// Vercel KV, so counts reset on every rebuild and after an idle sleep. Gameplay
// never depends on them; ping is fire-and-forget and the page ignores failures.
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = Number(process.env.PORT) || 7860; // must match app_port in README.md
const PAGE = fs.readFileSync(path.join(__dirname, 'index.html'));
// Claude-spending routes. Each handler only needs ANTHROPIC_API_KEY.
const ROUTES = {
'/api/beyblade': require('./beyblade.js'),
'/api/writers-room': require('./writers-room.js'),
'/api/card': require('./card.js'),
'/api/voice': require('./voice.js'),
};
// ── spend guards ─────────────────────────────────────────────────────────
// The Space is public and every ROUTES call spends real Claude tokens. A full
// best-of-3 match is call-heavy (kits + voices + cards + per-collision dialogue
// + promos + epitaphs), so these are much roomier than meiosis's β€” roomy for a
// person mid-match, still stingy for a script. Over a limit the API answers 429
// and the page drops into its own offline fallback β€” nothing breaks. ping/stats
// are free and bypass these.
const PER_IP_LIMIT = Number(process.env.BEYBLADE_PER_IP_LIMIT) || 300; // calls per 15 min
const PER_IP_WINDOW_MS = 15 * 60 * 1000;
const DAILY_CAP = Number(process.env.BEYBLADE_DAILY_CAP) || 8000; // calls per UTC day, everyone
const MAX_BODY_BYTES = 64 * 1024;
const MAX_STRING = 4000; // writers-room prompts + voice extracts run long; don't truncate them
const hits = new Map(); // ip β†’ { count, windowStart }
let day = new Date().toISOString().slice(0, 10);
let dayCount = 0;
function overLimit(ip) {
const today = new Date().toISOString().slice(0, 10);
if (today !== day) { day = today; dayCount = 0; }
if (dayCount >= DAILY_CAP) return 'daily cap';
const now = Date.now();
const h = hits.get(ip);
if (!h || now - h.windowStart > PER_IP_WINDOW_MS) {
hits.set(ip, { count: 1, windowStart: now });
} else if (h.count >= PER_IP_LIMIT) {
return 'per-ip limit';
} else {
h.count++;
}
dayCount++;
return null;
}
setInterval(() => {
const cutoff = Date.now() - PER_IP_WINDOW_MS;
for (const [ip, h] of hits) if (h.windowStart < cutoff) hits.delete(ip);
}, PER_IP_WINDOW_MS).unref();
// ── telemetry (in-memory; resets on rebuild/sleep) ─────────────────────────
const ALLOWED_EVENTS = new Set([
'arena_launch', 'wiki_loaded', 'share_clicked', 'burst', 'continue_clicked',
'epitaph_shown', 'card_generated', 'card_shared', 'chat_copied',
]);
const counters = Object.create(null);
// ── helpers ──────────────────────────────────────────────────────────────
function clientIp(req) {
const fwd = req.headers['x-forwarded-for'];
return (fwd ? String(fwd).split(',')[0] : req.socket.remoteAddress || '').trim();
}
// Vercel gives handlers res.status(n).json(obj); plain Node doesn't.
function shim(res) {
res.status = code => { res.statusCode = code; return res; };
res.json = obj => {
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify(obj));
};
return res;
}
function clamp(value) {
if (typeof value === 'string') return value.slice(0, MAX_STRING);
if (Array.isArray(value)) return value.slice(0, 8).map(clamp);
if (value && typeof value === 'object') {
const out = {};
for (const k of Object.keys(value)) out[k] = clamp(value[k]);
return out;
}
return value;
}
function readBody(req) {
return new Promise((resolve, reject) => {
let size = 0;
const chunks = [];
req.on('data', chunk => {
size += chunk.length;
if (size > MAX_BODY_BYTES) {
req.removeAllListeners('data');
req.resume();
reject(new Error('too large'));
return;
}
chunks.push(chunk);
});
req.on('end', () => {
try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')); }
catch (_) { resolve({}); }
});
req.on('error', reject);
});
}
// ── server ───────────────────────────────────────────────────────────────
const server = http.createServer(async (req, res) => {
shim(res);
const url = new URL(req.url, 'http://local');
// the page
if ((req.method === 'GET' || req.method === 'HEAD') && (url.pathname === '/' || url.pathname === '/index.html')) {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache' });
return res.end(req.method === 'HEAD' ? undefined : PAGE);
}
// telemetry β€” free, no spend guard
if (url.pathname === '/api/ping') {
if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' });
let body = {};
try { body = await readBody(req); } catch (_) {}
const event = body && body.event;
if (!event || !ALLOWED_EVENTS.has(event)) return res.status(400).json({ error: 'unknown event' });
counters[event] = (counters[event] || 0) + 1;
return res.status(200).json({ ok: true, stored: true });
}
if (url.pathname === '/api/stats') {
const events = {};
for (const e of ALLOWED_EVENTS) events[e] = counters[e] || 0;
return res.status(200).json({
timestamp: new Date().toISOString(),
events,
total_interactions: Object.values(events).reduce((a, b) => a + b, 0),
note: 'in-memory; resets on Space rebuild/sleep',
});
}
// claude-spending routes
const handler = ROUTES[url.pathname];
if (!handler) {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
return res.end('dead channel');
}
if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' });
const ip = clientIp(req);
const blocked = overLimit(ip);
if (blocked) {
console.warn(`${url.pathname} 429 (${blocked})`);
return res.status(429).json({ error: 'the arena is catching its breath β€” try again soon', fallback_used: true, text: null });
}
try {
req.body = clamp(await readBody(req));
} catch (_) {
res.setHeader('Connection', 'close');
return res.status(413).json({ error: 'payload too large' });
}
const started = Date.now();
try {
await handler(req, res);
} catch (err) {
console.error(`${url.pathname} crashed:`, err);
if (!res.headersSent) res.status(500).json({ error: 'internal error', fallback_used: true, text: null });
}
console.log(`${url.pathname} ${res.statusCode} ${Date.now() - started}ms Β· ${dayCount}/${DAILY_CAP} today`);
});
server.listen(PORT, () => {
const key = process.env.ANTHROPIC_API_KEY ? 'set' : 'MISSING β€” page will fly solo until you add the secret';
console.log(`beyblade arena up on :${PORT} Β· claude key: ${key}`);
});