Public: anyone can read this; the crew can change it.
Migrated from github.com/amirmushichge/pixel-plays
metrics to quantitatively produce better games. which games are played the mo… #46
Check · Review · Land · Live done — Landed and live in production.
quill/pixel-plays:quill/43-metrics-to-quantitatively-produce-better → main 2 commits fork 6 threads · 6 unresolved
README.md +4 −1
| @@ -38,7 +38,10 @@ node serve.mjs | ||
| 38 | 38 | |
| 39 | 39 | Then open http://127.0.0.1:5300/. `PORT` and `HOST` override the port and address; `bun serve.mjs` works the same. Any static file server works, and the site deploys as plain static files. |
| 40 | 40 | |
| 41 | On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. The app keeps no state, so it does not need `FORGE_APP_DATA`. `bun test` checks that the server answers every game page and track. | |
| 41 | On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is only the play counts, under `FORGE_APP_DATA`. `bun test` checks that the server answers every game page and track. | |
| 42 | ||
| 43 | ## Plays | |
| 44 | `/stats/` ranks the games by how much they are played, and `/api/stats` returns the same rows as JSON. Each game page reports three anonymous events to `POST /api/play` (an Origin check against browser cross-site posts, which a script can still forge, so the endpoint is also limited as below): the page opened, the first tap or key press (a play), and the seconds the page stayed visible after that. Only totals per game are kept, with no ids or cookies, in `plays.json` under `FORGE_APP_DATA` (in memory when it is unset). `stats.mjs` holds the counting; it needs no dependency, so the file is plain JSON rather than SQLite, which would tie the server to Bun. Limits: 60 events a minute per client address (the socket address, never a header) and 600 a minute per game, answered with 429; a play is refused unless an open is ahead of it and time unless plays can account for it (at most 3600 s each), so forged events cannot show a ratio real ones never could. They cannot stop someone slowly inflating a game within those bounds, so treat the numbers as a guide. Counts are flushed to disk on SIGTERM. Not recorded yet: a finished round, since each game ends in its own way. | |
| 42 | 45 | |
| 43 | 46 | ## Add a game |
| 44 | 47 | Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules })`, set `window.PP_SCENE`, load `../engine.js`, then add the game to `GAMES` in `shell.js` with a one-line `blurb`; the home page lists every `GAMES` entry (a static fallback list for no-JS is kept in sync by `serve.test.mjs`, so add the matching `<li>` to `index.html` too). The page needs a `#mute` button. Put its background track at `<id>/<id>.mp3`, or set `music: false` on its `GAMES` entry when it has none (Stone Skip, Kite Hill, Paper Route, Harbour Crane, Pizza Toss, Sled Run, Pottery Wheel, Row Home, Orchard, Lighthouse, Market Scale, Window Washer and Domino Run play on their own sound effects). Rules that need testing go in a plain script with a `.test.mjs` beside it, as in `kite-hill/model.js`. |
index.html +1 −1
| @@ -44,7 +44,7 @@ footer a { display: inline; padding: 0; font-weight: inherit; text-decoration: u | ||
| 44 | 44 | <li><a href="market-scale/">Market Scale</a><span>Weigh fruit onto a hanging pan scale to match each order: exact scores 3, within 50 g scores 1</span><span>Game forged by the crew</span></li> |
| 45 | 45 | <li><a href="domino-run/">Domino Run</a><span>Set out a line of 20 dominoes along a chalk path and tip the first: a gap too wide stops the chain, too close topples one early, ring the bell for 10 plus 1 per domino left</span><span>Game forged by the crew</span></li> |
| 46 | 46 | </ul> |
| 47 | <footer>Concept by <a href="https://x.com/awwbhi2">abhi</a>. Game by <a href="https://x.com/AmirMushich">AmirMushich</a>. Visual reference for the style: shawn.'s <a href="https://x.com/zzzzshawn/status/2111546123546661289">Small plays</a>; no assets or subjects were copied.</footer> | |
| 47 | <footer>Concept by <a href="https://x.com/awwbhi2">abhi</a>. Game by <a href="https://x.com/AmirMushich">AmirMushich</a>. Visual reference for the style: shawn.'s <a href="https://x.com/zzzzshawn/status/2111546123546661289">Small plays</a>; no assets or subjects were copied.<br><a href="stats/">Most played</a></footer> | |
| 48 | 48 | </main> |
| 49 | 49 | <script src="shell.js"></script> |
| 50 | 50 | <script> |
limits.mjs added +21
| @@ -0,0 +1,21 @@ | ||
| 1 | // Fixed-window rate limits for the play counter: one per client address, one per game. | |
| 2 | const WINDOW_MS = 60_000; | |
| 3 | ||
| 4 | // allow(key) is true while key has made fewer than max calls in the current window; at most maxKeys windows are tracked | |
| 5 | export function createLimiter({ max, maxKeys = 1000, now = Date.now }) { | |
| 6 | const windows = new Map(); | |
| 7 | return function allow(key) { | |
| 8 | const t = now(); | |
| 9 | let w = windows.get(key); | |
| 10 | if (w && t - w.start >= WINDOW_MS) { windows.delete(key); w = undefined; } | |
| 11 | if (!w) { | |
| 12 | if (windows.size >= maxKeys) { | |
| 13 | for (const [k, v] of windows) if (t - v.start >= WINDOW_MS) windows.delete(k); | |
| 14 | if (windows.size >= maxKeys) return false; | |
| 15 | } | |
| 16 | w = { start: t, n: 0 }; | |
| 17 | windows.set(key, w); | |
| 18 | } | |
| 19 | return ++w.n <= max; | |
| 20 | }; | |
| 21 | } |
limits.test.mjs added +18
| @@ -0,0 +1,18 @@ | ||
| 1 | import { test, expect } from 'bun:test'; | |
| 2 | import { createLimiter } from './limits.mjs'; | |
| 3 | ||
| 4 | test('allows max per window per key, then again in the next window', () => { | |
| 5 | let t = 0; | |
| 6 | const allow = createLimiter({ max: 2, now: () => t }); | |
| 7 | expect([allow('a'), allow('a'), allow('a'), allow('b')]).toEqual([true, true, false, true]); | |
| 8 | t = 60_000; | |
| 9 | expect(allow('a')).toBe(true); | |
| 10 | }); | |
| 11 | ||
| 12 | test('a full key table refuses new keys until windows expire', () => { | |
| 13 | let t = 0; | |
| 14 | const allow = createLimiter({ max: 5, maxKeys: 2, now: () => t }); | |
| 15 | expect([allow('a'), allow('b'), allow('c'), allow('a')]).toEqual([true, true, false, true]); | |
| 16 | t = 60_000; | |
| 17 | expect(allow('c')).toBe(true); | |
| 18 | }); |
serve.mjs +49 −1
| @@ -2,12 +2,50 @@ import { createServer } from 'node:http'; | ||
| 2 | 2 | import { readFile, stat } from 'node:fs/promises'; |
| 3 | 3 | import { extname, join, normalize, sep } from 'node:path'; |
| 4 | 4 | import { fileURLToPath } from 'node:url'; |
| 5 | import { createLimiter } from './limits.mjs'; | |
| 6 | import { createStats, renderStats } from './stats.mjs'; | |
| 5 | 7 | |
| 6 | 8 | const root = fileURLToPath(new URL('.', import.meta.url)); |
| 7 | 9 | const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.css': 'text/css', '.png': 'image/png', '.mp3': 'audio/mpeg' }; |
| 8 | 10 | const port = process.env.PORT ? Number(process.env.PORT) : 5300; |
| 9 | 11 | const host = process.env.HOST || '127.0.0.1'; |
| 10 | 12 | |
| 13 | const titles = {}; | |
| 14 | const ids = []; | |
| 15 | // the games are listed once, in shell.js; read them from there instead of repeating the list | |
| 16 | for (const m of (await readFile(join(root, 'shell.js'), 'utf8')).matchAll(/\{ id: '([a-z-]+)', title: '([^']+)'/g)) { ids.push(m[1]); titles[m[1]] = m[2]; } | |
| 17 | export const stats = createStats(ids, process.env.FORGE_APP_DATA); | |
| 18 | const security = { 'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer' }; | |
| 19 | // the stats page runs no script, so it can say so; the games keep what they had | |
| 20 | const lockedDown = { ...security, 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'" }; | |
| 21 | ||
| 22 | function sameOrigin(req) { | |
| 23 | try { return new URL(req.headers.origin).host === req.headers.host; } catch { return false; } | |
| 24 | } | |
| 25 | ||
| 26 | // keyed by the socket address, never a header; the per-game ceiling holds even when a proxy puts everyone on one address | |
outdated
No rate limit, and the Origin check is the only gate, so a scripted client can send any count. Add a per- |
||
| 27 | const perClient = createLimiter({ max: 60 }); | |
| 28 | const perGame = createLimiter({ max: 600 }); | |
| 29 | const MAX_BODY = 256; | |
outdated
This counts characters of the decoded string, not bytes read. Sum |
||
| 30 | ||
| 31 | async function recordPlay(req, res) { | |
| 32 | if (!sameOrigin(req)) return res.writeHead(403).end(); | |
| 33 | if (!perClient(req.socket.remoteAddress ?? '')) return res.writeHead(429, { 'retry-after': '60' }).end(); | |
| 34 | const chunks = []; | |
| 35 | let size = 0; | |
| 36 | for await (const chunk of req) { | |
| 37 | size += chunk.length; | |
| 38 | if (size > MAX_BODY) return res.writeHead(413).end(); | |
| 39 | chunks.push(chunk); | |
| 40 | } | |
| 41 | let body; | |
| 42 | try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return res.writeHead(400).end(); } | |
| 43 | if (!body || typeof body !== 'object' || typeof body.game !== 'string') return res.writeHead(400).end(); | |
| 44 | if (!perGame(body.game)) return res.writeHead(429, { 'retry-after': '60' }).end(); | |
| 45 | if (!stats.record(body.game, body.event, body.seconds)) return res.writeHead(400).end(); | |
| 46 | res.writeHead(204, security).end(); | |
| 47 | } | |
| 48 | ||
| 11 | 49 | export const server = createServer(async (req, res) => { |
| 12 | 50 | let path; |
| 13 | 51 | try { |
| @@ -15,15 +53,25 @@ export const server = createServer(async (req, res) => { | ||
| 15 | 53 | } catch { |
| 16 | 54 | return res.writeHead(400).end('bad request'); |
| 17 | 55 | } |
| 56 | if (path === '/api/play') return req.method === 'POST' ? recordPlay(req, res) : res.writeHead(405, { allow: 'POST' }).end(); | |
| 57 | if (path === '/api/stats' || path === '/stats' || path === '/stats/') { | |
| 58 | if (req.method !== 'GET' && req.method !== 'HEAD') return res.writeHead(405, { allow: 'GET, HEAD' }).end(); | |
| 59 | const json = path === '/api/stats'; | |
| 60 | const body = json ? JSON.stringify(stats.snapshot()) : renderStats(stats.snapshot(), titles); | |
| 61 | res.writeHead(200, { 'content-type': json ? 'application/json' : 'text/html; charset=utf-8', 'cache-control': 'no-store', ...lockedDown }); | |
| 62 | return res.end(req.method === 'HEAD' ? undefined : body); | |
| 63 | } | |
| 18 | 64 | const target = join(root, path.endsWith(sep) || path === sep ? join(path, 'index.html') : path); |
| 19 | 65 | if (!target.startsWith(root)) return res.writeHead(403).end(); |
| 20 | 66 | try { |
| 21 | 67 | // a game folder without its trailing slash: redirect like vercel.json's trailingSlash, so relative assets resolve |
| 22 | 68 | if ((await stat(target)).isDirectory()) return res.writeHead(308, { location: path + '/' }).end(); |
| 23 | 69 | const body = await readFile(target); |
| 24 | res.writeHead(200, { 'content-length': body.length, 'content-type': types[extname(target)] || 'application/octet-stream', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer' }); | |
| 70 | res.writeHead(200, { 'content-length': body.length, 'content-type': types[extname(target)] || 'application/octet-stream', 'cache-control': 'no-store', ...security }); | |
| 25 | 71 | res.end(body); |
| 26 | 72 | } catch { |
| 27 | 73 | res.writeHead(404).end('not found'); |
| 28 | 74 | } |
| 29 | 75 | }).listen(port, host); |
| 76 | ||
| 77 | for (const sig of ['SIGTERM', 'SIGINT']) process.on(sig, () => { stats.flush(); process.exit(0); }); |
serve.test.mjs +56
| @@ -155,3 +155,59 @@ test('Domino Run and its rules script are served without a track', async () => { | ||
| 155 | 155 | expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8'); |
| 156 | 156 | expect((await fetch(base + '/domino-run/chain.js')).status).toBe(200); |
| 157 | 157 | }); |
| 158 | ||
| 159 | const post = (body, headers = { origin: base }) => fetch(base + '/api/play', { method: 'POST', body: typeof body === 'string' ? body : JSON.stringify(body), headers }); | |
| 160 | ||
| 161 | test('plays are counted from the same origin and show on the stats page and JSON', async () => { | |
| 162 | const before = (await (await fetch(base + '/api/stats')).json()).find(r => r.id === 'domino-run'); | |
| 163 | expect((await post({ game: 'domino-run', event: 'open' })).status).toBe(204); | |
| 164 | expect((await post({ game: 'domino-run', event: 'play' })).status).toBe(204); | |
| 165 | expect((await post({ game: 'domino-run', event: 'time', seconds: 20 })).status).toBe(204); | |
| 166 | const after = (await (await fetch(base + '/api/stats')).json()).find(r => r.id === 'domino-run'); | |
| 167 | expect(after.open).toBe(before.open + 1); | |
| 168 | expect(after.play).toBe(before.play + 1); | |
| 169 | expect(after.seconds).toBe(before.seconds + 20); | |
| 170 | const page = await fetch(base + '/stats/'); | |
| 171 | expect(page.status).toBe(200); | |
| 172 | expect(page.headers.get('content-security-policy')).toContain("default-src 'none'"); | |
| 173 | expect(await page.text()).toContain('Domino Run'); | |
| 174 | }); | |
| 175 | ||
| 176 | test('plays from another origin, with no origin, or malformed are refused', async () => { | |
| 177 | const ok = { game: 'balote', event: 'open' }; | |
| 178 | expect((await post(ok, { origin: 'http://evil.example' })).status).toBe(403); | |
| 179 | expect((await post(ok, {})).status).toBe(403); | |
| 180 | expect((await post('not json')).status).toBe(400); | |
| 181 | expect((await post({ game: 'nope', event: 'open' })).status).toBe(400); | |
| 182 | expect((await post({ game: 'balote', event: 'time', seconds: 'x' })).status).toBe(400); | |
| 183 | expect((await post('x'.repeat(1000))).status).toBe(413); | |
| 184 | expect((await fetch(base + '/api/play')).status).toBe(405); | |
| 185 | }); | |
| 186 | ||
| 187 | test('home links to the stats page', async () => { | |
| 188 | expect(await (await fetch(base + '/')).text()).toContain('href="stats/"'); | |
| 189 | }); | |
| 190 | ||
| 191 | test('/api/stats lists exactly the games shell.js lists', async () => { | |
| 192 | globalThis.window = globalThis; | |
| 193 | let games; | |
| 194 | try { | |
| 195 | await import('./shell.js?ids'); | |
| 196 | games = window.PixelPlays.GAMES; | |
| 197 | } finally { | |
| 198 | delete globalThis.window; | |
| 199 | delete globalThis.PixelPlays; | |
| 200 | } | |
| 201 | const listed = (await (await fetch(base + '/api/stats')).json()).map(r => r.id).sort(); | |
| 202 | expect(listed).toEqual(games.map(g => g.id).sort()); | |
| 203 | }); | |
| 204 | ||
| 205 | test('a body over 256 bytes is refused by bytes, not characters', async () => { | |
| 206 | expect((await post(JSON.stringify({ game: 'balote', event: 'open', pad: 'é'.repeat(130) }))).status).toBe(413); | |
| 207 | }); | |
| 208 | ||
| 209 | test('a client that posts too often gets 429', async () => { | |
| 210 | let last = 0; | |
| 211 | for (let i = 0; i < 70 && last !== 429; i++) last = (await post({ game: 'orchard', event: 'open' })).status; | |
| 212 | expect(last).toBe(429); | |
| 213 | }); |
shell.js +27
| @@ -147,6 +147,33 @@ window.PixelPlays = (() => { | ||
| 147 | 147 | |
| 148 | 148 | document.body.append(menu, open, dialog, credits); |
| 149 | 149 | if (game.music !== false) startMusic(id); |
| 150 | track(id); | |
| 151 | } | |
| 152 | // anonymous counts for the plays page: the page opened, the first tap or key press, and the seconds it stayed visible after that | |
| 153 | function track(id) { | |
| 154 | const send = body => { | |
| 155 | try { fetch('../api/play', { method: 'POST', body: JSON.stringify({ game: id, ...body }), keepalive: true }).catch(() => {}); } catch {} | |
| 156 | }; | |
| 157 | let played = false, since = 0; | |
| 158 | const lap = () => { | |
|
||
| 159 | if (!played || !since) return; | |
| 160 | const seconds = Math.min(3600, Math.round((Date.now() - since) / 1000)); | |
| 161 | since = 0; | |
| 162 | if (seconds >= 1) send({ event: 'time', seconds }); | |
| 163 | }; | |
| 164 | send({ event: 'open' }); | |
| 165 | for (const kind of ['pointerdown', 'keydown']) { | |
| 166 | document.addEventListener(kind, () => { | |
| 167 | if (played) return; | |
| 168 | played = true; since = Date.now(); | |
| 169 | send({ event: 'play' }); | |
| 170 | }); | |
| 171 | } | |
| 172 | document.addEventListener('visibilitychange', () => { | |
| 173 | if (document.hidden) lap(); | |
| 174 | else if (played) since = Date.now(); | |
| 175 | }); | |
| 176 | window.addEventListener?.('pagehide', lap); | |
| 150 | 177 | } |
| 151 | 178 | // each game loops <id>/<id>.mp3 from the first gesture, because browsers block sound before one. |
| 152 | 179 | // The game's own sound button mutes it too. |
shell.test.mjs +48 −4
| @@ -6,19 +6,23 @@ const element = () => ({ | ||
| 6 | 6 | append(...n) { this.children.push(...n); }, addEventListener() {}, setAttribute() {}, showModal() {}, close() {}, |
| 7 | 7 | }); |
| 8 | 8 | const SAVED = ['window', 'document', 'Audio', 'PixelPlays']; |
| 9 | let audios, byId; | |
| 9 | const realFetch = globalThis.fetch; | |
| 10 | let audios, byId, sent, listeners; | |
| 10 | 11 | // stubs live only while a test runs, so they never leak into the server tests in the same process |
| 11 | 12 | function stub() { |
| 12 | audios = []; byId = {}; | |
| 13 | audios = []; byId = {}; sent = []; listeners = {}; | |
| 14 | globalThis.fetch = (url, init) => { sent.push([url, JSON.parse(init.body)]); return Promise.resolve(); }; | |
| 13 | 15 | globalThis.window = globalThis; |
| 16 | window.addEventListener = (k, f) => { (window.addEventListener.calls[k] ??= []).push(f); }; | |
| 17 | window.addEventListener.calls = {}; | |
| 14 | 18 | globalThis.Audio = class { constructor(src) { this.src = src; audios.push(src); } play() { return Promise.resolve(); } pause() {} }; |
| 15 | 19 | globalThis.document = { |
| 16 | head: element(), body: element(), hidden: false, addEventListener() {}, | |
| 20 | head: element(), body: element(), hidden: false, addEventListener(k, f) { (listeners[k] ??= []).push(f); }, | |
| 17 | 21 | createElement: () => element(), |
| 18 | 22 | getElementById: id => (byId[id] ??= element()), |
| 19 | 23 | }; |
| 20 | 24 | } |
| 21 | function unstub() { for (const k of SAVED) delete globalThis[k]; } | |
| 25 | function unstub() { globalThis.fetch = realFetch; for (const k of SAVED) delete globalThis[k]; } | |
| 22 | 26 | function guarded(fn) { return async () => { stub(); try { await fn(); } finally { unstub(); } }; } |
| 23 | 27 | let loads = 0; |
| 24 | 28 | async function mount(id) { |
| @@ -51,3 +55,43 @@ test('forged games credit the engine, not the game, to AmirMushich', guarded(asy | ||
| 51 | 55 | expect(t).not.toContain('Game by'); |
| 52 | 56 | expect(text(await mount('balote'))).toContain('Game by'); |
| 53 | 57 | })); |
| 58 | ||
| 59 | test('a game reports its open, its first gesture once, and nothing identifying', guarded(async () => { | |
| 60 | await mount('orchard'); | |
| 61 | expect(sent).toEqual([['../api/play', { game: 'orchard', event: 'open' }]]); | |
| 62 | const gesture = listeners.pointerdown.at(-1); gesture(); gesture(); | |
| 63 | expect(sent.filter(([, b]) => b.event === 'play')).toEqual([['../api/play', { game: 'orchard', event: 'play' }]]); | |
| 64 | })); | |
| 65 | ||
| 66 | test('time is sent when the page is hidden after a play, resumes on return, clamps, and skips under a second', guarded(async () => { | |
| 67 | let now = 1_000_000; | |
| 68 | const realNow = Date.now; | |
| 69 | Date.now = () => now; | |
| 70 | try { | |
| 71 | await mount('orchard'); | |
| 72 | const hide = () => { document.hidden = true; for (const f of listeners.visibilitychange) f(); }; | |
| 73 | const show = () => { document.hidden = false; for (const f of listeners.visibilitychange) f(); }; | |
| 74 | const times = () => sent.filter(([, b]) => b.event === 'time').map(([, b]) => b.seconds); | |
| 75 | hide(); | |
| 76 | expect(times()).toEqual([]); // no play yet | |
| 77 | show(); | |
| 78 | listeners.pointerdown.at(-1)(); | |
| 79 | now += 12_400; | |
| 80 | hide(); | |
| 81 | expect(times()).toEqual([12]); | |
| 82 | hide(); | |
| 83 | expect(times()).toEqual([12]); // already counted | |
| 84 | show(); | |
| 85 | now += 400; | |
| 86 | hide(); | |
| 87 | expect(times()).toEqual([12]); // under a second | |
| 88 | show(); | |
| 89 | now += 5000 * 1000; | |
| 90 | hide(); | |
| 91 | expect(times()).toEqual([12, 3600]); | |
| 92 | show(); | |
| 93 | now += 3000; | |
| 94 | for (const f of window.addEventListener.calls.pagehide) f(); | |
| 95 | expect(times()).toEqual([12, 3600, 3]); | |
| 96 | } finally { Date.now = realNow; } | |
| 97 | })); |
stats.mjs added +99
| @@ -0,0 +1,99 @@ | ||
| 1 | // Anonymous play counts per game: no ids, no cookies, only totals. Persisted as one JSON file under FORGE_APP_DATA. | |
| 2 | import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; | |
| 3 | import { join } from 'node:path'; | |
| 4 | ||
| 5 | export const EVENTS = ['open', 'play', 'time']; | |
| 6 | const MAX_SECONDS = 3600; | |
| 7 | const empty = () => ({ open: 0, play: 0, seconds: 0 }); | |
| 8 | ||
| 9 | // dir: where to persist (undefined keeps counts in memory); ids: the games that may be counted | |
| 10 | export function createStats(ids, dir) { | |
| 11 | const file = dir ? join(dir, 'plays.json') : null; | |
| 12 | const counts = new Map(ids.map(id => [id, empty()])); | |
| 13 | if (file) { | |
| 14 | try { | |
| 15 | const saved = JSON.parse(readFileSync(file, 'utf8')); | |
| 16 | for (const [id, c] of Object.entries(saved)) { | |
| 17 | const row = counts.get(id); | |
| 18 | if (row) for (const k of Object.keys(row)) if (Number.isSafeInteger(c?.[k]) && c[k] >= 0) row[k] = c[k]; | |
| 19 | } | |
| 20 | } catch {} | |
| 21 | } | |
| 22 | let timer = null; | |
| 23 | const flush = () => { | |
| 24 | if (timer) clearTimeout(timer); | |
| 25 | timer = null; | |
| 26 | if (!file) return; | |
| 27 | try { | |
| 28 | mkdirSync(dir, { recursive: true }); | |
| 29 | writeFileSync(file + '.tmp', JSON.stringify(Object.fromEntries(counts))); | |
| 30 | renameSync(file + '.tmp', file); | |
| 31 | } catch {} | |
| 32 | }; | |
| 33 | // returns false when the input is not a known game and event | |
| 34 | function record(game, event, seconds) { | |
| 35 | const row = counts.get(game); | |
| 36 | if (!row || !EVENTS.includes(event)) return false; | |
| 37 | // totals stay consistent: a play follows an open, and time follows plays, so forged events cannot show a ratio a real one never could | |
| 38 | if (event === 'time') { | |
| 39 | if (!Number.isInteger(seconds) || seconds < 1 || seconds > MAX_SECONDS) return false; | |
outdated
Refuse |
||
| 40 | if (row.seconds + seconds > row.play * MAX_SECONDS) return false; | |
outdated
|
||
| 41 | row.seconds += seconds; | |
| 42 | } else { | |
| 43 | if (event === 'play' && row.play + 1 > row.open) return false; | |
| 44 | row[event]++; | |
| 45 | } | |
| 46 | if (!timer) { | |
| 47 | timer = setTimeout(flush, 1000); | |
| 48 | timer.unref(); | |
| 49 | } | |
| 50 | return true; | |
| 51 | } | |
| 52 | // rows ranked by plays, then opens; playRate is plays per open, avgSeconds is time per play | |
| 53 | function snapshot() { | |
| 54 | return [...counts].map(([id, c]) => ({ | |
| 55 | id, ...c, | |
| 56 | playRate: c.open ? Math.round(1000 * c.play / c.open) / 10 : 0, | |
| 57 | avgSeconds: c.play ? Math.round(c.seconds / c.play) : 0, | |
| 58 | })).sort((a, b) => b.play - a.play || b.open - a.open || a.id.localeCompare(b.id)); | |
| 59 | } | |
| 60 | return { record, snapshot, flush }; | |
| 61 | } | |
| 62 | ||
| 63 | const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]); | |
| 64 | ||
| 65 | export function renderStats(rows, titles) { | |
| 66 | const body = rows.map((r, i) => `<tr><td>${i + 1}</td><th scope="row"><a href="../${esc(r.id)}/">${esc(titles[r.id] ?? r.id)}</a></th><td>${r.play}</td><td>${r.open}</td><td>${r.playRate}%</td><td>${r.avgSeconds}s</td></tr>`).join('\n'); | |
| 67 | return `<!doctype html> | |
| 68 | <html lang="en"> | |
| 69 | <head> | |
| 70 | <meta charset="utf-8"> | |
| 71 | <meta name="viewport" content="width=device-width, initial-scale=1"> | |
| 72 | <title>Plays · Pixel Plays</title> | |
| 73 | <style> | |
| 74 | body { margin: 0; background: #fff; color: #1c1b19; font: 16px/1.5 system-ui, sans-serif; } | |
| 75 | main { max-width: 44rem; margin: 0 auto; padding: 8vh 20px 48px; } | |
| 76 | h1 { font-size: 1.5rem; margin: 0 0 .25em; } | |
| 77 | p { margin: 0 0 2rem; color: #8b877f; } | |
| 78 | table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; } | |
| 79 | th, td { padding: 10px 8px; border-top: 1px solid #e6e3dc; text-align: right; } | |
| 80 | th[scope=row], thead th:nth-child(2) { text-align: left; } | |
| 81 | thead th { color: #8b877f; font-weight: 400; font-size: .875rem; } | |
| 82 | a { color: inherit; text-underline-offset: 3px; } | |
| 83 | </style> | |
| 84 | </head> | |
| 85 | <body> | |
| 86 | <main> | |
| 87 | <h1>Plays</h1> | |
| 88 | <p>Anonymous totals per game, most played first. A play is the first tap or key press on a page; the play rate is plays per page open; the time is average seconds the page was visible per play.</p> | |
| 89 | <table> | |
| 90 | <thead><tr><th>#</th><th>Game</th><th>Plays</th><th>Opens</th><th>Play rate</th><th>Time</th></tr></thead> | |
| 91 | <tbody> | |
| 92 | ${body} | |
| 93 | </tbody> | |
| 94 | </table> | |
| 95 | <p><a href="../">All games</a></p> | |
| 96 | </main> | |
| 97 | </body> | |
| 98 | </html>`; | |
| 99 | } |
stats.test.mjs added +58
| @@ -0,0 +1,58 @@ | ||
| 1 | import { test, expect } from 'bun:test'; | |
| 2 | import { mkdtempSync, readFileSync } from 'node:fs'; | |
| 3 | import { join } from 'node:path'; | |
| 4 | import { createStats, renderStats } from './stats.mjs'; | |
| 5 | ||
| 6 | test('counts opens, plays and seconds per known game only', () => { | |
| 7 | const s = createStats(['a', 'b']); | |
| 8 | expect(s.record('a', 'open')).toBe(true); | |
| 9 | expect(s.record('a', 'play')).toBe(true); | |
| 10 | expect(s.record('a', 'time', 30)).toBe(true); | |
| 11 | expect(s.record('zzz', 'open')).toBe(false); | |
| 12 | expect(s.record('a', 'bogus')).toBe(false); | |
| 13 | expect(s.record('a', 'time', -1)).toBe(false); | |
| 14 | expect(s.record('a', 'time', 99999)).toBe(false); | |
| 15 | expect(s.record('a', 'time', 1.5)).toBe(false); | |
| 16 | expect(s.record('__proto__', 'open')).toBe(false); | |
| 17 | expect(s.snapshot().find(r => r.id === 'a')).toMatchObject({ open: 1, play: 1, seconds: 30, playRate: 100, avgSeconds: 30 }); | |
| 18 | }); | |
| 19 | ||
| 20 | test('ranks by plays, then opens', () => { | |
| 21 | const s = createStats(['a', 'b', 'c']); | |
| 22 | for (const g of ['b', 'b', 'c', 'a']) s.record(g, 'open'); | |
| 23 | s.record('b', 'play'); s.record('b', 'play'); s.record('c', 'play'); | |
| 24 | expect(s.snapshot().map(r => r.id)).toEqual(['b', 'c', 'a']); | |
| 25 | }); | |
| 26 | ||
| 27 | test('persists under the data directory and reloads', () => { | |
| 28 | const dir = mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'stats-')); | |
| 29 | const s = createStats(['a'], dir); | |
| 30 | s.record('a', 'open'); s.record('a', 'open'); s.record('a', 'play'); s.record('a', 'play'); | |
| 31 | s.flush(); | |
| 32 | expect(JSON.parse(readFileSync(join(dir, 'plays.json'), 'utf8')).a.play).toBe(2); | |
| 33 | expect(createStats(['a'], dir).snapshot()[0].play).toBe(2); | |
| 34 | }); | |
| 35 | ||
| 36 | test('the page escapes titles', () => { | |
| 37 | const html = renderStats([{ id: 'a', open: 1, play: 1, seconds: 0, playRate: 100, avgSeconds: 0 }], { a: '<script>x</script>' }); | |
| 38 | expect(html).not.toContain('<script>'); | |
| 39 | expect(html).toContain('<script>'); | |
| 40 | }); | |
| 41 | ||
| 42 | test('refuses a play with no open ahead of it', () => { | |
| 43 | const s = createStats(['a']); | |
| 44 | expect(s.record('a', 'play')).toBe(false); | |
| 45 | s.record('a', 'open'); | |
| 46 | expect(s.record('a', 'play')).toBe(true); | |
| 47 | expect(s.record('a', 'play')).toBe(false); | |
| 48 | expect(s.snapshot()[0]).toMatchObject({ open: 1, play: 1, playRate: 100 }); | |
| 49 | }); | |
| 50 | ||
| 51 | test('refuses time that the plays cannot account for', () => { | |
| 52 | const s = createStats(['a']); | |
| 53 | expect(s.record('a', 'time', 1)).toBe(false); | |
| 54 | s.record('a', 'open'); s.record('a', 'play'); | |
| 55 | expect(s.record('a', 'time', 3600)).toBe(true); | |
| 56 | expect(s.record('a', 'time', 1)).toBe(false); | |
| 57 | expect(s.snapshot()[0].seconds).toBe(3600); | |
| 58 | }); |
The countable ids come from a regex over shell.js source. Add a test that
/api/statsids equalPixelPlaysGAMES ids, so a differently formatted entry fails loudly (point 5).