Skip to content
Source
Sign inSign up
samwillis/one-million-boxes
Open History to see the last commit

store.ts

167 lines6.0 KB

1import { readFile } from "node:fs/promises"
2import type { Pool } from "pg"
3import { TILE_COUNT, TILE_SIZE } from "../shared/tiles.js"
4import { isValidEdgeId } from "../shared/edge-math.js"
5import {
6 FIRST_TO_SCORE_TARGET,
7 GAME_END_MODE,
8 GRID_WIDTH,
9 GRID_HEIGHT,
10 MAX_QUOTA,
11 QUOTA_REFILL_INTERVAL_MS,
12 QUOTA_TIMING_LEEWAY_MS,
13 QUOTA_BONUS_SINGLE,
14 QUOTA_BONUS_DOUBLE,
15} from "../shared/game-config.js"
16import type { Identity } from "./lib/identity-cookie.js"
17​
18export const BOARD_QUERY =
19 "SELECT tile_id, revision, edges, boxes FROM board_tiles WHERE game_id = $1"
20export const GAME_QUERY = "SELECT started_at FROM games WHERE game_id = $1"
21​
22// Supplied by the server, never taken from the HTTP request.
23const DRAW_RULES = {
24 width: GRID_WIDTH,
25 height: GRID_HEIGHT,
26 tileSize: TILE_SIZE,
27 maxQuota: MAX_QUOTA,
28 refillIntervalMs: QUOTA_REFILL_INTERVAL_MS,
29 leewayMs: QUOTA_TIMING_LEEWAY_MS,
30 bonusSingle: QUOTA_BONUS_SINGLE,
31 bonusDouble: QUOTA_BONUS_DOUBLE,
32 endMode: GAME_END_MODE,
33 scoreTarget: FIRST_TO_SCORE_TARGET,
35​
36export interface DrawResult {
37 status: 200 | 400 | 409 | 410 | 429
38 ok: boolean
39 code?: string
40 txid?: string
41 boxesClaimed?: number
42 quotaRemaining?: number
43 refillIn?: number
45​
46type QuotaRow = { tokens: number; last_refill_at: string }
47​
48export function refillQuota(row: QuotaRow | undefined, now: number, leeway = 0) {
49 // Read-only projection for /api/quota. boxes_draw independently enforces the
50 // same rules using Postgres's clock after it has acquired the move locks.
51 if (!row) return { tokens: MAX_QUOTA, lastRefillAt: now }
52 const previous = Number(row.last_refill_at)
53 const refills = Math.max(0, Math.floor((now - previous + leeway) / QUOTA_REFILL_INTERVAL_MS))
54 const tokens = Math.min(MAX_QUOTA, row.tokens + refills)
55 return {
56 tokens,
57 lastRefillAt: tokens === MAX_QUOTA ? now : previous + refills * QUOTA_REFILL_INTERVAL_MS,
58 }
60​
61export class GameStore {
62 constructor(readonly pool: Pool) {}
63​
64 async initialize(): Promise<void> {
65 // Install the schema/functions and seed missing tiles without resetting an
66 // existing game. Run via db:init, outside the application startup and request paths.
67 const db = await this.pool.connect()
68 try {
69 await db.query("BEGIN")
70 await db.query(await readFile(new URL("./schema.sql", import.meta.url), "utf8"))
71 await db.query(await readFile(new URL("./draw.sql", import.meta.url), "utf8"))
72 await db.query(
73 "INSERT INTO games(game_id, started_at) VALUES(1, $1) ON CONFLICT DO NOTHING",
74 [Date.now()],
75 )
76 await db.query("SELECT game_id FROM games WHERE game_id = 1 FOR UPDATE")
77 // Capacity can change while developing game rules. Clamp existing buckets
78 // and replace their constraint atomically, after excluding active draws.
79 await db.query("UPDATE player_quotas SET tokens = $1 WHERE tokens > $1", [MAX_QUOTA])
80 await db.query(
81 "ALTER TABLE player_quotas DROP CONSTRAINT IF EXISTS player_quotas_tokens_check",
82 )
83 await db.query(
84 `ALTER TABLE player_quotas ADD CONSTRAINT player_quotas_tokens_check CHECK (tokens BETWEEN 0 AND ${MAX_QUOTA})`,
85 )
86 await db.query(
87 `INSERT INTO board_tiles(game_id, tile_id, edges, boxes)
88 SELECT 1, n, decode(repeat('00', 48 + CASE WHEN n / 125 = 124 THEN 3 ELSE 0 END
89 + CASE WHEN n % 125 = 124 THEN 3 ELSE 0 END), 'hex'), decode(repeat('00', 24), 'hex')
90 FROM generate_series(0, $1::integer - 1) AS n ON CONFLICT DO NOTHING`,
91 [TILE_COUNT],
92 )
93 await db.query("COMMIT")
94 } catch (error) {
95 await db.query("ROLLBACK")
96 throw error
97 } finally {
98 db.release()
99 }
100 }
101​
102 async game() {
103 const {
104 rows: [row],
105 } = await this.pool.query("SELECT * FROM games WHERE game_id = 1")
106 return { ...row, started_at: Number(row.started_at) }
107 }
108​
109 async quota(playerId: string) {
110 const {
111 rows: [row],
112 } = await this.pool.query<QuotaRow>(
113 "SELECT tokens, last_refill_at FROM player_quotas WHERE game_id = 1 AND player_id = $1",
114 [playerId],
115 )
116 const now = Date.now(),
117 quota = refillQuota(row, now)
118 return this.quotaResponse(quota, now)
119 }
120​
121 private quotaResponse(quota: { tokens: number; lastRefillAt: number }, now: number) {
122 return {
123 quotaRemaining: quota.tokens,
124 refillIn:
125 quota.tokens === MAX_QUOTA
126 ? 0
127 : Math.max(0, (QUOTA_REFILL_INTERVAL_MS - (now - quota.lastRefillAt)) / 1000),
128 }
129 }
130​
131 async draw(identity: Identity, edgeId: number): Promise<DrawResult> {
132 if (!isValidEdgeId(edgeId)) return { ok: false, code: "INVALID_EDGE", status: 400 }
133 // One autocommit statement: query resolution follows commit/ReadyForQuery,
134 // so no application round trips occur between acquiring and releasing locks.
135 const {
136 rows: [{ result }],
137 } = await this.pool.query<{ result: DrawResult }>(
138 "SELECT boxes_draw($1::uuid, $2::integer, $3::integer, $4::jsonb) AS result",
139 [identity.playerId, identity.teamId, edgeId, DRAW_RULES],
140 )
141 return result
142 }
143​
144 async reset(): Promise<void> {
145 // Administrative operation: the exclusive game lock waits for all moves'
146 // compatible KEY SHARE locks before clearing tiles and quotas together.
147 const db = await this.pool.connect()
148 try {
149 await db.query("BEGIN")
150 await db.query("SELECT game_id FROM games WHERE game_id = 1 FOR UPDATE")
151 await db.query(
152 "UPDATE games SET started_at = GREATEST(started_at + 1, $1), edges_placed = 0, scores = ARRAY[0,0,0,0], complete = false WHERE game_id = 1",
153 [Date.now()],
154 )
155 await db.query(
156 "UPDATE board_tiles SET edges = decode(repeat('00', octet_length(edges)), 'hex'), boxes = decode(repeat('00', 24), 'hex'), revision = revision + 1 WHERE game_id = 1",
157 )
158 await db.query("DELETE FROM player_quotas WHERE game_id = 1")
159 await db.query("COMMIT")
160 } catch (error) {
161 await db.query("ROLLBACK")
162 throw error
163 } finally {
164 db.release()
165 }
166 }