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

app.ts

101 lines3.8 KB

1import { Hono } from "hono"
2import { createRealtime, rawSql } from "@neon/realtime/server"
3import { z } from "zod"
4​
5import { teamIdToName } from "../shared/teams.js"
6import type { runtimeConfig } from "./config.js"
7import {
8 buildIdentityCookieHeader,
9 createIdentityCookie,
10 generatePlayerId,
11 generateTeamId,
12 parseIdentityCookie,
13} from "./lib/identity-cookie.js"
14import { BOARD_QUERY, GAME_QUERY, GameStore } from "./store.js"
15​
16/** Builds the stateless HTTP API around a host-managed Postgres pool. */
17export function createApp(config: ReturnType<typeof runtimeConfig>, store: GameStore) {
18 const issuer = createRealtime({ secret: config.secret, db: config.databaseName })
19 const app = new Hono()
20​
21 // Identity, quota and short-lived query capabilities must not be cached.
22 app.use("/api/*", async (c, next) => {
23 c.header("Cache-Control", "no-store")
24 await next()
25 })
26​
27 /**
28 * GET /api/health
29 * Reports that the API is running. Database setup is a separate deployment step.
30 */
31 app.get("/api/health", (c) => c.json({ ok: true }))
32​
33 /**
34 * GET /api/team
35 * Returns the player's identity and team from their signed cookie. A missing or
36 * invalid cookie creates a new player, random team and HTTP-only identity cookie.
37 */
38 app.get("/api/team", async (c) => {
39 let identity = await parseIdentityCookie(c.req.header("cookie"), config.identitySecret)
40 if (!identity) {
41 identity = { playerId: generatePlayerId(), teamId: generateTeamId() }
42 c.header(
43 "Set-Cookie",
44 buildIdentityCookieHeader(
45 await createIdentityCookie(identity.playerId, identity.teamId, config.identitySecret),
46 process.env.NODE_ENV === "production",
47 ),
48 )
49 }
50 return c.json({ ...identity, team: teamIdToName(identity.teamId) })
51 })
52​
53 /**
54 * GET /api/quota
55 * Returns the signed player's available lines and seconds until the next refill.
56 * This is a read-only projection; missing or invalid identity returns 401.
57 */
58 app.get("/api/quota", async (c) => {
59 const identity = await parseIdentityCookie(c.req.header("cookie"), config.identitySecret)
60 if (!identity) return c.json({ ok: false, code: "NO_IDENTITY" }, 401)
61 return c.json({ ok: true, ...(await store.quota(identity.playerId)) })
62 })
63​
64 /**
65 * GET /api/realtime
66 * Issues short-lived capabilities for the fixed board and reset-generation
67 * queries, together with the WebSocket URL and current game start timestamp.
68 * Browsers connect directly to Realtime; the signing secret stays on the server.
69 */
70 app.get("/api/realtime", async (c) => {
71 const game = await store.game()
72 const query = await issuer.seal({ query: rawSql(BOARD_QUERY, [1]) })
73 const gameQuery = await issuer.seal({ query: rawSql(GAME_QUERY, [1]) })
74 return c.json({ query, gameQuery, startedAt: game.started_at, url: config.realtimeUrl })
75 })
76​
77 /**
78 * POST /api/draw
79 * Accepts { edgeId } for the player/team verified from their signed cookie.
80 * Postgres validates and applies the move atomically in one function call.
81 * Success follows commit and includes the transaction ID for Realtime confirmation;
82 * rejected moves return the store's HTTP status and error code.
83 */
84 app.post("/api/draw", async (c) => {
85 const identity = await parseIdentityCookie(c.req.header("cookie"), config.identitySecret)
86 if (!identity) return c.json({ ok: false, code: "NO_IDENTITY" }, 401)
87 const parsed = z
88 .object({ edgeId: z.number().int().min(0) })
89 .safeParse(await c.req.json().catch(() => null))
90 if (!parsed.success) return c.json({ ok: false, code: "INVALID_REQUEST" }, 400)
91 const { status, ...result } = await store.draw(identity, parsed.data.edgeId)
92 return c.json(result, status)
93 })
94​
95 app.onError((error, c) => {
96 console.error(error)
97 return c.json({ ok: false, code: "DATABASE_ERROR" }, 503)
98 })
99​
100 return app