Open History to see the last commit
1# 1 Million Boxes specification
2
3This describes the implemented application. Postgres is authoritative for the
4board, box claims, team scores, completion and player quotas. Neon Realtime
5supplies snapshots and incremental changes to browser clients.
6
7## Game rules
8
9There is one game, `game_id = 1`, with 1,000×1,000 boxes and 2,002,000 edges.
10Players draw any available edge without turn order. The team that draws a box's
11fourth edge claims it. One edge can complete two boxes.
12
13| Team ID | Team | Packed owner |
14| ------- | ------ | ------------ |
15| 0 | Red | 1 |
16| 1 | Blue | 2 |
17| 2 | Green | 3 |
18| 3 | Yellow | 4 |
19
20Packed owner `0` means empty. Team scores count claimed boxes. The default
21`board_complete` mode ends when all one million boxes are claimed; the highest
22score wins, with ties allowed. `shared/game-config.ts` also supports
23`first_to_score`, with a target of 1,000 boxes. Changing that mode requires
24restarting the API and rebuilding the frontend together.
25
26## Identity and quota
27
28`GET /api/team` assigns a UUID and a random team on the first visit. A valid
29existing identity is reused. The HTTP-only `boxes_identity` cookie contains
30`playerId.teamId.signature`; the signature is an HMAC-SHA256 truncated to 32
31hexadecimal characters. The cookie has `Path=/`, `SameSite=Lax` and a one-year
32lifetime, plus `Secure` when `NODE_ENV=production`.
33
34The API verifies the cookie before quota reads and draws. Request bodies cannot
35choose the player, team or rules. This is anonymous demo identity, not an account
36system: clearing cookies creates a new identity.
37
38Each player has a persistent token bucket:
39
40- Capacity and starting balance: eight lines.
41- Refill: one line every 3,000 milliseconds, capped at eight.
42- Accepted move cost: one line.
43- Completing one box grants two lines; completing two grants four, capped at eight.
44- Draw validation allows 500 milliseconds of refill timing leeway.
45
46Refills are calculated lazily from timestamps. Draw enforcement uses the Postgres
47clock after waiting for move locks. `GET /api/quota` projects the stored quota
48using the API clock without leeway; it is a read-only display value. Browser
49quota is optimistic and reconciled with API responses. Quota rows remain until
50the administrative reset; there is no background refill or cleanup task.
51
52## Coordinates and tile encoding
53
54Horizontal edge `(x,y)` has ID `y*1000+x`, where `0≤x<1000`, `0≤y≤1000`.
55Vertical edge `(x,y)` has ID `1,001,000+y*1001+x`, where `0≤x≤1000`, `0≤y<1000`.
56Box `(x,y)` has ID `y*1000+x`, where both coordinates are below 1000.
57
58The board is divided into 125×125 tiles of 8×8 boxes. Tile IDs are row-major:
59`floor(y/8)*125+floor(x/8)`. Every edge is stored exactly once:
60
611. Edge owner slots 0–63 are the boxes' top edges, in row-major order.
622. Slots 64–127 are their left edges, in row-major order.
633. Tiles in the bottom row append eight outer bottom edges.
644. Tiles in the right column append eight outer right edges, after bottom edges
65 if both boundaries apply.
66
67Box owner slots 0–63 are also row-major. Each owner uses three bits, least
68significant bit first, continuing across byte boundaries. `shared/tiles.ts` and
69the SQL helpers implement the same codec.
70
71| Tile | Edge bytes | Box bytes | Total packed bytes |
72| ------------------------ | ---------- | --------- | ------------------ |
73| Interior | 48 | 24 | 72 |
74| Bottom or right boundary | 51 | 24 | 75 |
75| Bottom-right corner | 54 | 24 | 78 |
76
77The full board contains 15,625 tiles and 1,125,750 packed owner bytes. Box owners
78are explicitly stored, so an unordered snapshot cannot change who claimed a box.
79
80## Database schema
81
82`server/schema.sql` creates three tables:
83
84| Table | Key | Stored state |
85| --------------- | --------------------- | --------------------------------------------------------------------------------------------------- |
86| `games` | `game_id` | `started_at` reset generation in epoch milliseconds, `edges_placed`, four team `scores`, `complete` |
87| `board_tiles` | `(game_id,tile_id)` | Monotonic `revision`, packed `edges bytea`, packed `boxes bytea` |
88| `player_quotas` | `(game_id,player_id)` | `tokens`, `last_refill_at`, `last_seen_at` in epoch milliseconds |
89
90`pnpm db:init` installs the schema and functions, inserts a missing game, and seeds
91missing empty tiles in a transaction. It preserves an existing board. This is
92idempotent initialization, not a versioned migration system. Board dimensions
93and tile size are fixed by both schema constraints and initialization SQL;
94changing them requires coordinated schema and application changes.
95
96The API keeps a connection pool, configuration and capability issuer in memory.
97It has no authoritative board, score, player session or quota cache. API
98instances sharing the same database and signing secrets use the same game state.
99Neon Realtime maintains its query graphs, subscriptions and proxy connections.
100
101## Draw transaction
102
103The API executes one autocommit statement:
104
105```sql
106SELECT boxes_draw($1::uuid, $2::integer, $3::integer, $4::jsonb) AS result;
107```
108
109The arguments are verified player identity, team ID, edge ID and server-supplied
110rules. `server/draw.sql` performs the whole move inside Postgres:
111
1121. Validate the edge and identity, then compute adjacent boxes and all edges
113 required to check them.
1142. Acquire `FOR KEY SHARE` on the game row to coordinate with reset.
1153. Insert a missing quota row and lock it with `FOR UPDATE`. Concurrent first
116 moves by one player therefore share one bucket.
1174. Deduplicate required tiles and lock them with `ORDER BY tile_id FOR UPDATE`.
118 Checks across tile edges and corners include neighboring tiles, up to four.
1195. Refill quota using the database clock after lock waits. Reject a complete
120 game, an occupied edge or an exhausted quota.
1216. Deduct the cost, set the edge, and check both adjacent boxes against the
122 locked buffers. Set explicit box owners and apply claim bonuses.
1237. Write each dirty tile once and increase its revision. Update player quota.
1248. Atomically increment current game counters and recheck completion. A move
125 that loses a race with game completion is rolled back.
1269. Return the claim count, quota and top-level transaction ID.
127
128Moves that overlap in their required tiles serialize. Other tiles can be checked
129and updated concurrently. The final score/counter write still takes a short
130shared game-row lock. No application-to-database round trips occur while the
131function holds move locks.
132
133Expected rejection uses a PL/pgSQL exception subtransaction to undo every move
134write, including a newly created quota row, before returning an error result.
135Unexpected SQL errors abort the statement. The Node driver resolves the query
136after autocommit completes, so HTTP success is sent only after commit.
137
138## HTTP API
139
140All `/api/*` responses use `Cache-Control: no-store`.
141
142| Route | Purpose |
143| ------------------- | ------------------------------------------------------------------------------ |
144| `GET /api/health` | Returns `{ok:true}` when the API is running |
145| `GET /api/team` | Returns `{playerId,teamId,team}` and sets identity if needed |
146| `GET /api/quota` | Returns `{ok:true,quotaRemaining,refillIn}` for a verified identity |
147| `GET /api/realtime` | Returns `{url,query,gameQuery,startedAt}` with sealed fixed-query capabilities |
148| `POST /api/draw` | Accepts `{edgeId}` and executes the move |
149
150`refillIn` is seconds until the next refill, or zero at full quota. A successful
151draw returns `{ok:true,txid,boxesClaimed,quotaRemaining,refillIn}` with status 200;
152`txid` is a decimal string. Expected failures return `{ok:false,code}` with
153quota fields when the move reached quota validation:
154
155| Status | Code | Meaning |
156| ------ | ----------------- | --------------------------------------- |
157| 400 | `INVALID_REQUEST` | Malformed JSON or an invalid edge field |
158| 400 | `INVALID_EDGE` | Edge outside the board |
159| 401 | `NO_IDENTITY` | Missing or invalid signed identity |
160| 409 | `EDGE_TAKEN` | Edge already owned |
161| 410 | `GAME_COMPLETE` | Game ended before this move committed |
162| 429 | `QUOTA_EXHAUSTED` | No line available |
163| 503 | `DATABASE_ERROR` | An unexpected server/database error |
164
165## Neon Realtime and browser state
166
167The application subscribes directly to the authoritative board. There is no
168separate change log, REST snapshot handoff or query sharding.
169
170### Shared queries
171
172All browsers subscribe to these two queries with parameter `[1]`:
173
174```sql
175SELECT tile_id, revision, edges, boxes FROM board_tiles WHERE game_id = $1;
176SELECT started_at FROM games WHERE game_id = $1;
177```
178
179The board query is an unordered projection of primary-keyed tile rows. It needs
180no `ORDER BY`, `LIMIT`, joins or aggregates. Every viewer uses the same query
181and parameter. Parameterized query families share engine query graphs, and
182matching parameters share the query variant; the Realtime proxy fans out
183publications to subscribed connections. Sending data to each browser still
184costs bandwidth and serialization work. Initial snapshots are obtained for
185joining subscriptions; the application does not maintain a shared snapshot cache.
186
187The metadata query contains only the reset generation. Team scores and edge
188counts in the UI are derived from explicit tile owners, avoiding a live aggregate
189query.
190
191### Capabilities and recovery
192
193`GET /api/realtime` returns sealed board and metadata query capabilities, the
194WebSocket URL and the current `startedAt`. The API issuer uses the database name
195from `DATABASE_URL`, so sealed queries address the same database as writes.
196The signing secret stays on the API server. The API seals only these fixed
197queries and does not accept browser SQL. Browsers connect directly to the
198configured Neon Realtime endpoint.
199
200`QueryRefreshController` renews both capabilities through the same bootstrap
201endpoint, using the SDK's expiration scheduling. The SDK defaults to
20260-second capabilities. Subscription errors and exhausted renewals close the
203connection and obtain fresh capabilities and snapshots after a 1.5-second delay.
204This also handles terminal `upstream_rejected` responses after a service restart
205or a bulk board reset. The hook checks the game generation during bootstrap as
206well as through the metadata query.
207
208### Browser state and rendering
209
210`src/hooks/useBoardRealtime.ts` subscribes with `materialize:false`. The app
211handles `onReset` and `onBatch` directly rather than retaining a second complete
212materialized board in the SDK. `bytea` fields arrive as `Uint8Array`;
213`shared/tiles.ts` decodes their owners.
214
215The browser console logs bootstrap duration, the subscribe call, connection
216readiness, admission and snapshot start/completion for each subscription (`s1`
217is the board, `s2` is game metadata). `Game state loaded` reports milliseconds
218from subscribe to the complete snapshot and to state installation, plus the
219installation duration. A separate entry measures the wait for the first canvas
220render after installation. Incremental update sizes are grouped once per second.
221
222Sizes use decimal kB (1,000 bytes): `packedKB` counts decoded owner bytes;
223`protocolRowsKB` counts those rows' protocol v1 JSON, including opaque row keys
224and base64 wrappers. The SDK exposes decoded rows rather than transport frames,
225so this count excludes message envelopes, row separators, control messages,
226WebSocket/TCP overhead and compression. It must not be read as an exact network
227traffic measurement. No row contents or query capabilities are logged.
228
229A reset must contain exactly 15,625 tiles and installs them into a fresh
230`GameState`. Incremental upserts replace the changed tile owners. A removed tile
231or invalid tile causes reconnection. Box ownership is explicitly stored and does
232not depend on tile delivery order.
233
234The board canvas backing store follows the device pixel ratio. Cached grid and
235dot tiles are keyed by zoom bucket and display density, with geometry kept in
236CSS pixels. Bitmap box fills use nearest-neighbour sampling only within their
237own draw calls; grid and dot textures retain smooth antialiasing.
238The minimap also matches its responsive CSS size at device pixel density and
239redraws its bitmap and viewport outline when resized.
240
241Edge picking covers the full line segment and its endpoints, selecting the
242nearest line where hit areas overlap. Mouse and touch retain separate hit widths
243and minimum zoom levels.
244
245Local moves play a short synthesized pencil scratch after passing client checks.
246The draw response plays a rising chime when it confirms one or two box claims.
247Snapshots and other players' moves stay silent. Web Audio starts lazily from a
248draw gesture; the sound toggle above the zoom controls persists its preference in local storage
249and immediately silences scheduled sounds. Sound is enabled by default and
250audio failures do not affect gameplay.
251
252`pnpm simulate` adds synthetic play through `GameStore.draw()` and the normal
253Postgres draw function. Bots use distinct identities, four teams and real quotas;
254no board reset or direct packed-state writes are needed. An unpaced run seeds
255visible patches, while a target move rate generates a finite stream of committed
256Realtime updates. The script accepts `DATABASE_URL` or `--local` to select the
257running local development database, and exits cleanly on Ctrl+C.
258The separate `--complete` mode bulk-seeds to a requested percentage of completed
259boxes. It takes the exclusive game lock, installs current tiles in the shared
260rule oracle, applies randomly ordered free edges, and commits changed packed
261tiles and matching counters in one transaction. Existing owners, player quotas
262and `started_at` are preserved; the result arrives as one Realtime transaction.
263
264Rendering uses typed arrays and canvas with pan, zoom, a minimap and batched
265`requestAnimationFrame` updates. Snapshot hydration avoids move animations;
266incremental edge changes generate brief minimap animations. Personal box count
267is browser-local, credited from successful draw responses and persisted in
268localStorage; it is not a database leaderboard.
269
270Mouse players draw with a team-coloured pencil cursor and an eight-segment move
271dial. The next segment fills continuously towards the browser's server-aligned
272refill deadline; spending, refills and bonuses update the same optimistic quota
273state. Spending removes a segment immediately, while refills and bonuses fill
274segments smoothly. A spend followed by a box bonus keeps the number element
275and refill sweep stable, without restarting their animation for each count. The pencil tip is the pointer hotspot, and the dial flips near board
276edges. Pointer movement updates only the overlay transform. Native cursor
277hiding remains enabled across the mouse-capable board, independently of
278movement frames; controls retain their normal cursor. Accepted mouse clicks
279animate the pencil tip along the selected edge and back to the pointer in 260ms,
280while the moves dial stays at the pointer and the write proceeds immediately.
281The same animation clock reveals the canvas edge behind the pencil, clipping
282its existing hand-drawn path so its shape stays unchanged. Only the active
283edge’s small surrounding strip is repainted per frame. Early Realtime
284confirmation updates ownership without bypassing the reveal; cancellation
285restores the full current edge immediately.
286Taken edges and attempts without moves do not trigger a stroke. Moving the
287pointer, leaving the board or zooming cancels the stroke; touch and reduced-motion
288users retain immediate drawing without the pencil animation. The same dial
289appears slightly larger in the bottom-left when the pencil cursor is hidden,
290including on touch devices, and remains available to assistive technology.
291
292Controls use consistent 1px rounded borders, raised edges and subtle press
293feedback. Team
294badges and score chips keep the original team colours; score chips echo claimed
295boxes, and the minimap has a labelled frame. The UI keeps the Inter font and
296Neon accent without changing board rendering or the original logo.
297
298The board fills the area below the header. The move dial and learn-more link
299float over its bottom edge without a footer bar; gaps between controls still
300accept drawing input. The minimap and vertical zoom buttons share the moves
301dial’s bottom alignment on wider screens. On narrow screens the learn-more
302link stays at the bottom alongside the minimap and zoom buttons, with the fixed
303moves dial above it. The link keeps this position when the dial follows the
304mouse cursor.
305
306A blocked draw shows “Out of moves! Recharging...” and briefly shakes the cursor
307or fixed move dial; repeated attempts restart the shake. The prompt clears when
308a move refills. Reduced-motion preferences disable shakes and the refill sweep
309and shorten other feedback animations.
310
311### Write confirmation
312
313After a successful draw, the browser calls `awaitTxId(txid, 15000)` on its board
314subscription. This ties move confirmation to the shared live query. If
315confirmation times out, the client reconnects and reports that the move was
316saved. It keeps the server's quota result and does not resend or undo the move.
317
318## Initial payload
319
320The complete board's 1,125,750 packed owner bytes become 1,501,000 bytes of
321base64 owner strings. Tile sizes and boundary encoding are described above.
322
323In the public JSON protocol, a binary cell is represented as
324`{"base64":"..."}`. Scalar cell values are strings, which the SDK parses into
325their declared types. Rows also carry an opaque 64-character row ID, column
326names, revisions and publication framing. The base64 total alone therefore
327understates the initial query payload.
328
329A full-size synthetic probe measured 3,527,299 JSON application bytes
330(approximately 3.36 MiB) for 15,625 rows. That probe omitted the 750 binary bytes
331for outer boundary edges and used slightly different column names. The current
332board should be budgeted at roughly 3.5 MB of initial application data, rather
333than the 1.5 MB of base64 values. Revisions, protocol versions and framing can
334change the exact number. WebSocket, TCP and TLS overhead are additional.
335
336This board fits the 16 MiB initial-query budget of the engine version used for
337the demo. That limit is an engine setting/version detail, not a promise about
338every Neon deployment. The app uses one board query; fixed shards would add
339complexity without helping this board's current snapshot size.
340
341## Update traffic and capacity
342
343An upsert transmits the whole projected tile. A normal move changes one tile;
344a cross-boundary claim can change two. Up to four tiles may be locked for
345validation even though fewer are written. Multiple row changes can be batched
346by the protocol.
347
348An earlier one-subscriber synthetic probe measured approximately 505 application
349bytes per tile update, including publication framing. At one changed tile per
350accepted move, this gives the following rough bandwidth estimates:
351
352| Accepted moves/second | Per viewer | Across 1,000 viewers |
353| --------------------- | ---------- | -------------------- |
354| 10 | 5 KB/s | 5 MB/s |
355| 100 | 50 KB/s | 50 MB/s |
356
357These are arithmetic estimates, not measured capacity results. They omit extra
358claim tiles, transport overhead, simultaneous joins and slow-client recovery.
359The query graph can be shared while egress still grows with viewers. Qualification
360should measure sustained moves, concurrent joins, proxy CPU and bandwidth before
361changing this design.
362
363## Reset and operation
364
365`pnpm db:reset` is an administrative operation against the configured database.
366It takes `FOR UPDATE` on the game row, waits for active moves, then atomically
367clears tile owners, increments tile revisions, deletes quotas, resets counters
368and advances `started_at` monotonically. There is no public reset endpoint or
369automatic reset after completion.
370
371The metadata subscription and reconnect bootstrap both check `started_at`.
372A changed generation clears browser quota/personal-score caches and reloads the
373page. The signed player/team cookie is retained. Previous games and individual
374moves are not archived.
375
376Vercel serves the static frontend and routes `/api/*` to `api/index.ts`, which
377creates the shared Hono application from `server/app.ts`. The Node.js function
378reuses a five-connection Postgres pool against Neon's pooled endpoint; Vercel
379Fluid compute manages idle connections. It runs in `iad1` by default, with a
38030-second request limit. No schema initialization runs on a function cold start.
381
382`pnpm db:init` uses `DATABASE_URL_UNPOOLED` (falling back to `DATABASE_URL`) to
383install the schema, draw function and missing tiles before deployment. It
384preserves existing play. Neither the local API nor the Vercel function runs
385schema setup on startup. Disposable test and local fixture launchers run the
386setup script once before starting the API, against their own database.
387Host environment variables take priority over `.env.local`, then `.env`.
388
389Use the Neon connection details described in [README.md](README.md), a common
390origin for frontend and REST routes, and HTTPS with `NODE_ENV=production` for
391secure cookies. `neon.ts` declares `preview.realtime.allowedOrigins`, enabling
392Realtime for the branch and allowing local development plus the deployed game.
393`pnpm exec neon config plan` reviews the policy; `pnpm exec neon deploy` applies
394it. `pnpm exec neon env pull` writes `NEON_REALTIME_URL` and
395`NEON_REALTIME_SECRET` alongside the Postgres URLs. The application accepts the
396previous `REALTIME_PUBLIC_URL` / `REALTIME_SECRET` names as fallbacks for existing
397hosts. The signing and
398identity secrets stay in Vercel's server environment; the browser receives only
399short-lived query capabilities and the public WebSocket URL.
400
401## Verification
402
403Unit tests cover tile ownership, packing and unordered hydration. The disposable
404full-stack suite exercises the actual Postgres extension, Realtime proxy, SDK
405and API: snapshots, duplicates, quota refills, single and double claims, tile
406and reset locks, rollback, transaction confirmation, capability renewal,
407proxy restart and reset recovery. Browser tests cover independent players,
408canvas draws, mobile layouts and rendered recovery.
409
410See [CONTRIBUTING.md](CONTRIBUTING.md) for commands and fixture requirements.