Skip to content
Source
Sign inSign up
samwillis/neonbricks
Open History to see the last commit

app.ts

524 lines17.3 KB

1import { Hono } from "hono";
2import { cors } from "hono/cors";
3import { bodyLimit } from "hono/body-limit";
4import { z } from "zod";
5import { randomUUID } from "node:crypto";
6import { waitUntil } from "@neon/functions";
7import { parseTriggerDelivery } from "@neon/functions/triggers";
8import { pool, transaction } from "./db";
9import {
10 authenticate,
11 DomainError,
12 lockAccess,
13 newSession,
14 type Identity,
15} from "./auth";
16import { createWorld, joinWorld, insertPart } from "./worlds";
17import { execute, reconnectParts } from "./commands";
18import {
19 realtime,
20 sceneQuery,
21 presenceQuery,
22 historyQuery,
23 memberQuery,
24} from "./live";
25import { starter } from "../shared/starter";
26import { validPart, collision } from "../shared/geometry";
27import { WORLD_LIMIT, HEIGHT_LIMIT, UNIT } from "../shared/types";
28import {
29 aiAvailable,
30 aiConfiguration,
31 AI_BUILDER_VERSION,
32 createGeneration,
33 getGeneration,
34 listGenerations,
35 conversationQuery,
36 runGeneration,
37 cancelGeneration,
38 acceptGeneration,
39 generationQuery,
40 expireGenerations,
41 dispatchGeneration,
42 reconcileGenerations,
43} from "./ai";
44const origins = (
45 process.env.ALLOWED_ORIGINS ||
46 "http://localhost:5173,http://127.0.0.1:5173,http://localhost:4173,http://127.0.0.1:4173"
47).split(",");
48const app = new Hono<{ Variables: { identity: Identity } }>();
49app.use("*", async (c, next) => {
50 c.header("Cache-Control", "no-store");
51 const started = performance.now();
52 await next();
53 c.header(
54 "Server-Timing",
55 `app;dur=${(performance.now() - started).toFixed(2)}`,
56 );
57});
58app.use(
59 "*",
60 cors({
61 origin: (o) => (origins.includes(o) ? o : undefined),
62 allowHeaders: ["Authorization", "Content-Type"],
63 allowMethods: ["GET", "POST", "DELETE", "OPTIONS"],
64 maxAge: 3600,
65 }),
66);
67app.use("*", bodyLimit({ maxSize: 128 * 1024 }));
68app.get("/api/health", (c) =>
69 c.json({
70 ok: true,
71 backend: "Neon Functions",
72 realtime: !!process.env.REALTIME_SECRET,
73 ai: aiAvailable(),
74 aiBuilder: AI_BUILDER_VERSION,
75 }),
76);
77const position = z.object({
78 x: z.number().int(),
79 y: z.number().int(),
80 z: z.number().int(),
81});
82const preview = z.object({
83 key: z.string().max(64),
84 color: z.string().regex(/^#[\da-f]{6}$/i),
85 position,
86 rotation: z.number().int().min(0).max(3),
87});
88const edit = z.object({
89 operationId: z.uuid(),
90 generation: z.number().int().positive(),
91 action: z.enum(["edit", "undo", "redo"]),
92 target: z.uuid().optional(),
93 changes: z
94 .array(
95 z.object({
96 id: z.uuid(),
97 expected: z.number().int().positive().optional(),
98 key: z.string().max(64).optional(),
99 color: z
100 .string()
101 .regex(/^#[\da-f]{6}$/i)
102 .optional(),
103 position: position.optional(),
104 rotation: z.number().int().min(0).max(3).optional(),
105 deleted: z.boolean().optional(),
106 }),
107 )
108 .max(100)
109 .optional(),
110 connections: z
111 .array(z.object({ id: z.uuid(), revision: z.number().int().positive() }))
112 .max(5000)
113 .optional(),
114});
115app.post("/api/session", async (c) => {
116 const input = z
117 .object({
118 name: z.string().trim().min(1).max(24),
119 color: z.string().regex(/^#[\da-f]{6}$/i),
120 })
121 .parse(await c.req.json());
122 return c.json(await newSession(input.name, input.color), 201);
123});
124app.post("/api/cleanup", async (c) => {
125 const delivery = await parseTriggerDelivery(c.req.raw);
126 if (!delivery.ok) return c.json({ error: "Trigger delivery required" }, 401);
127 await expireGenerations();
128 const result = await transaction(async (client) => {
129 const closed = await client.query(
130 "UPDATE worlds SET status='closed',generation=generation+1 WHERE status='open' AND expires_at<clock_timestamp() RETURNING id",
131 );
132 const expired = await client.query(
133 "UPDATE guest_sessions SET revoked=1 WHERE revoked=0 AND (expires_at<clock_timestamp() OR absolute_expiry<clock_timestamp()) RETURNING id",
134 );
135 const r = await client.query(
136 "DELETE FROM viewer_sessions WHERE expires_at<clock_timestamp()-interval '5 minutes'",
137 );
138 return {
139 removed: r.rowCount,
140 closed: closed.rowCount,
141 revoked: expired.rowCount,
142 };
143 });
144 return c.json(result);
145});
146app.post("/api/ai/reconcile", async (c) => {
147 const delivery = await parseTriggerDelivery(c.req.raw);
148 if (!delivery.ok || delivery.invocation.type !== "schedule")
149 return c.json({ error: "Scheduled trigger delivery required" }, 401);
150 await reconcileGenerations();
151 return c.json({ ok: true });
152});
153app.use("/api/*", async (c, next) => {
154 c.set("identity", await authenticate(c.req.header("authorization")));
155 await next();
156});
157app.post("/api/session/renew", async (c) => {
158 const a = c.get("identity");
159 const { rows } = await pool.query(
160 "UPDATE guest_sessions SET expires_at=LEAST(absolute_expiry,clock_timestamp()+interval '30 minutes') WHERE id=$1 AND guest=$2 AND revoked=0 AND expires_at>clock_timestamp() AND absolute_expiry>clock_timestamp() RETURNING expires_at",
161 [a.session, a.guest],
162 );
163 if (!rows[0]) throw new DomainError("Session expired", 401);
164 return c.json({ expiresAt: rows[0].expires_at, serverTime: Date.now() });
165});
166app.post("/api/profile", async (c) => {
167 const input = z
168 .object({
169 name: z.string().trim().min(1).max(24),
170 color: z.string().regex(/^#[\da-f]{6}$/i),
171 })
172 .parse(await c.req.json());
173 await pool.query("UPDATE guests SET name=$2,color=$3 WHERE id=$1", [
174 c.get("identity").guest,
175 input.name,
176 input.color,
177 ]);
178 return c.json({ ok: true });
179});
180app.post("/api/session/revoke", async (c) => {
181 const a = c.get("identity");
182 await pool.query(
183 "UPDATE guest_sessions SET revoked=1 WHERE id=$1 AND guest=$2",
184 [a.session, a.guest],
185 );
186 return c.json({ ok: true });
187});
188app.post("/api/worlds", async (c) => {
189 const input = z
190 .object({
191 title: z.string().trim().min(1).max(64),
192 starter: z.enum(["rover", "empty"]),
193 })
194 .parse(await c.req.json());
195 return c.json(
196 await createWorld(
197 input.title,
198 c.get("identity").guest,
199 input.starter === "rover",
200 ),
201 201,
202 );
203});
204app.get("/api/ai/config", (c) => c.json(aiConfiguration()));
205app.post("/api/ai/generations", async (c) => {
206 const input = z
207 .object({
208 id: z.uuid(),
209 prompt: z.string().trim().min(3).max(1200),
210 source: z.uuid().optional(),
211 target: z.uuid().optional(),
212 newWorld: z.boolean().optional(),
213 })
214 .refine(
215 (v) => !v.newWorld || (!v.target && !v.source),
216 "Choose a new or existing workshop",
217 )
218 .parse(await c.req.json());
219 const generation = await createGeneration(c.get("identity"), input);
220 if (generation.status === "queued")
221 waitUntil(
222 dispatchGeneration(generation.id).catch((error) =>
223 console.error(
224 "[ai-dispatch]",
225 generation.id,
226 error instanceof Error ? error.name : "Error",
227 ),
228 ),
229 );
230 return c.json(generation, 201);
231});
232app.get("/api/ai/generations/:id", async (c) =>
233 c.json(
234 await getGeneration(c.get("identity"), z.uuid().parse(c.req.param("id"))),
235 ),
236);
237app.get("/api/worlds/:world/ai", async (c) =>
238 c.json(
239 await listGenerations(
240 c.get("identity"),
241 z.uuid().parse(c.req.param("world")),
242 ),
243 ),
244);
245app.get("/api/ai/generations/:id/live", async (c) => {
246 const a = c.get("identity"),
247 id = z.uuid().parse(c.req.param("id"));
248 await getGeneration(a, id);
249 return c.json(await realtime().seal({ query: generationQuery(a, id) }));
250});
251app.post("/api/ai/generations/:id/run", async (c) =>
252 c.json(
253 await runGeneration(c.get("identity"), z.uuid().parse(c.req.param("id"))),
254 ),
255);
256app.post("/api/ai/generations/:id/cancel", async (c) =>
257 c.json(
258 await cancelGeneration(
259 c.get("identity"),
260 z.uuid().parse(c.req.param("id")),
261 ),
262 ),
263);
264app.post("/api/ai/generations/:id/accept", async (c) =>
265 c.json(
266 await acceptGeneration(
267 c.get("identity"),
268 z.uuid().parse(c.req.param("id")),
269 ),
270 ),
271);
272app.post("/api/worlds/:slug/join", async (c) =>
273 c.json(await joinWorld(c.get("identity"), c.req.param("slug"))),
274);
275app.get("/api/worlds/:world/live/:kind", async (c) => {
276 const a = c.get("identity"),
277 world = z.uuid().parse(c.req.param("world"));
278 await transaction(async (client) => lockAccess(client, a, world, false));
279 const kind = c.req.param("kind");
280 if (kind === "scene")
281 return c.json(await realtime().seal({ query: sceneQuery(world, a) }));
282 if (kind === "presence")
283 return c.json(await realtime().seal({ query: presenceQuery(world, a) }));
284 if (kind === "member")
285 return c.json(await realtime().seal({ query: memberQuery(world, a) }));
286 if (kind === "history")
287 return c.json(await realtime().seal({ query: historyQuery(world, a) }));
288 if (kind === "ai")
289 return c.json(
290 await realtime().seal({ query: conversationQuery(a, world) }),
291 );
292 throw new DomainError("Unknown query", 404);
293});
294app.post("/api/worlds/:world/edit", async (c) =>
295 c.json(
296 await execute(
297 c.get("identity"),
298 z.uuid().parse(c.req.param("world")),
299 edit.parse(await c.req.json()),
300 ),
301 ),
302);
303app.get("/api/worlds/:world/history", async (c) => {
304 const a = c.get("identity"),
305 world = z.uuid().parse(c.req.param("world"));
306 await transaction((client) => lockAccess(client, a, world, false));
307 const { rows } = await pool.query(
308 "SELECT h.undo,h.redo,h.generation=w.generation AS current FROM guest_world_history h JOIN worlds w ON w.id=h.world WHERE h.world=$1 AND h.guest=$2",
309 [world, a.guest],
310 );
311 const h = rows[0];
312 return c.json({
313 undo: h?.current ? h.undo.at(-1)?.id || null : null,
314 redo: h?.current ? h.redo.at(-1)?.id || null : null,
315 });
316});
317app.get("/api/worlds/:world/operations/:operation", async (c) => {
318 const a = c.get("identity"),
319 world = z.uuid().parse(c.req.param("world"));
320 await transaction((client) => lockAccess(client, a, world, false));
321 const { rows } = await pool.query(
322 "SELECT receipt FROM build_operations WHERE world=$1 AND guest=$2 AND id=$3",
323 [world, a.guest, z.uuid().parse(c.req.param("operation"))],
324 );
325 if (!rows[0]) throw new DomainError("Operation not found", 404);
326 return c.json(rows[0].receipt);
327});
328app.post("/api/worlds/:world/presence", async (c) => {
329 const a = c.get("identity"),
330 world = z.uuid().parse(c.req.param("world"));
331 const v = z
332 .object({
333 viewer: z.uuid(),
334 sequence: z.number().int().min(1).max(2147483647),
335 generation: z.number().int().positive(),
336 selection: z.array(z.uuid()).max(100),
337 preview: preview.nullable(),
338 // Optional for clients loaded before the cursor feature was deployed.
339 cursor: z
340 .object({
341 x: z
342 .number()
343 .min(-WORLD_LIMIT - UNIT)
344 .max(WORLD_LIMIT + UNIT),
345 y: z
346 .number()
347 .min(-UNIT)
348 .max(HEIGHT_LIMIT + UNIT),
349 z: z
350 .number()
351 .min(-WORLD_LIMIT - UNIT)
352 .max(WORLD_LIMIT + UNIT),
353 })
354 .nullable()
355 .optional(),
356 sample: z.boolean(),
357 })
358 .parse(await c.req.json());
359 return c.json(
360 await transaction(async (client) => {
361 const w = await lockAccess(client, a, world, false);
362 if (w.generation !== v.generation || w.status !== "open")
363 throw new DomainError("Workshop changed");
364 const r = await client.query(
365 "UPDATE viewer_sessions SET sequence=$5,selection=$6,preview=CASE WHEN $8 THEN $7::jsonb ELSE preview END,preview_at=CASE WHEN $8 THEN clock_timestamp() ELSE preview_at END,cursor=CASE WHEN $8 AND $11 THEN $10::jsonb ELSE cursor END,cursor_at=CASE WHEN $8 AND $11 THEN clock_timestamp() ELSE cursor_at END,generation=$9,expires_at=clock_timestamp()+interval '30 seconds' WHERE id=$1 AND world=$2 AND guest=$3 AND session=$4 AND sequence<$5 RETURNING id",
366 [
367 v.viewer,
368 world,
369 a.guest,
370 a.session,
371 v.sequence,
372 JSON.stringify(v.selection),
373 JSON.stringify(v.preview),
374 v.sample,
375 v.generation,
376 JSON.stringify(v.cursor ?? null),
377 v.cursor !== undefined,
378 ],
379 );
380 if (!r.rowCount) {
381 const exists = await client.query(
382 "SELECT id FROM viewer_sessions WHERE id=$1 AND world=$2 AND guest=$3 AND session=$4",
383 [v.viewer, world, a.guest, a.session],
384 );
385 if (!exists.rowCount)
386 throw new DomainError("Viewer expired. Rejoin the workshop.", 410);
387 }
388 return { serverTime: Date.now() };
389 }),
390 );
391});
392app.delete("/api/worlds/:world/viewers/:viewer", async (c) => {
393 const a = c.get("identity");
394 await pool.query(
395 "DELETE FROM viewer_sessions WHERE id=$1 AND world=$2 AND guest=$3 AND session=$4",
396 [
397 z.uuid().parse(c.req.param("viewer")),
398 z.uuid().parse(c.req.param("world")),
399 a.guest,
400 a.session,
401 ],
402 );
403 return c.json({ ok: true });
404});
405app.post("/api/worlds/:world/reset", async (c) => {
406 const a = c.get("identity"),
407 world = z.uuid().parse(c.req.param("world"));
408 const input = z
409 .object({
410 generation: z.number().int(),
411 starter: z.enum(["rover", "empty"]),
412 })
413 .parse(await c.req.json());
414 return c.json(
415 await transaction(async (client) => {
416 const s = await client.query(
417 "SELECT revoked,expires_at>clock_timestamp() AS valid FROM guest_sessions WHERE id=$1 FOR SHARE",
418 [a.session],
419 );
420 if (!s.rows[0]?.valid || s.rows[0].revoked)
421 throw new DomainError("Session expired", 401);
422 const { rows } = await client.query(
423 "SELECT * FROM worlds WHERE id=$1 FOR UPDATE",
424 [world],
425 );
426 const w = rows[0];
427 if (!w || w.owner !== a.guest)
428 throw new DomainError("Only the room creator can reset it", 403);
429 if (w.generation !== input.generation || w.status !== "open")
430 throw new DomainError("Workshop changed");
431 const parts = input.starter === "rover" ? starter(randomUUID) : [];
432 for (let i = 0; i < parts.length; i++) {
433 if (!validPart(parts[i])) throw new Error("Invalid starter");
434 for (let j = 0; j < i; j++)
435 if (collision(parts[i], parts[j]))
436 throw new Error("Starter collision");
437 }
438 await client.query("DELETE FROM connector_slot_claims WHERE world=$1", [
439 world,
440 ]);
441 await client.query(
442 "UPDATE part_connections SET deleted=1,revision=revision+1 WHERE world=$1 AND deleted=0",
443 [world],
444 );
445 await client.query(
446 "UPDATE part_instances SET deleted=1,revision=revision+1 WHERE world=$1 AND deleted=0",
447 [world],
448 );
449 for (const p of parts) await insertPart(client, world, p);
450 await reconnectParts(client, world, parts, parts, []);
451 await client.query(
452 "UPDATE worlds SET generation=generation+1 WHERE id=$1",
453 [world],
454 );
455 await client.query(
456 "UPDATE viewer_sessions SET preview=NULL,selection=$2,generation=$3 WHERE world=$1",
457 [world, JSON.stringify([]), w.generation + 1],
458 );
459 const tx = await client.query(
460 "SELECT pg_current_xact_id()::text AS txid",
461 );
462 return { generation: w.generation + 1, txid: tx.rows[0].txid };
463 }),
464 );
465});
466app.post("/api/worlds/:world/lifecycle", async (c) => {
467 const a = c.get("identity"),
468 world = z.uuid().parse(c.req.param("world")),
469 input = z
470 .object({
471 generation: z.number().int(),
472 status: z.enum(["open", "closed"]),
473 })
474 .parse(await c.req.json());
475 return c.json(
476 await transaction(async (client) => {
477 const session = await client.query(
478 "SELECT revoked,expires_at>clock_timestamp() AND absolute_expiry>clock_timestamp() AS valid FROM guest_sessions WHERE id=$1 AND guest=$2 FOR SHARE",
479 [a.session, a.guest],
480 );
481 if (!session.rows[0]?.valid || session.rows[0].revoked)
482 throw new DomainError("Session expired", 401);
483 const { rows } = await client.query(
484 "SELECT * FROM worlds WHERE id=$1 FOR UPDATE",
485 [world],
486 ),
487 w = rows[0];
488 if (!w || w.owner !== a.guest)
489 throw new DomainError(
490 "Only the creator can close or reopen this workshop",
491 403,
492 );
493 if (w.generation !== input.generation)
494 throw new DomainError("Workshop changed");
495 await client.query(
496 "UPDATE worlds SET status=$2,generation=generation+1,expires_at=CASE WHEN $2='open' THEN clock_timestamp()+interval '24 hours' ELSE expires_at END WHERE id=$1",
497 [world, input.status],
498 );
499 await client.query(
500 "UPDATE viewer_sessions SET preview=NULL,selection=$2,generation=$3 WHERE world=$1",
501 [world, JSON.stringify([]), w.generation + 1],
502 );
503 return { generation: w.generation + 1, status: input.status };
504 }),
505 );
506});
507app.onError((error, c) => {
508 if (error instanceof z.ZodError)
509 return c.json(
510 { error: "Invalid request", details: error.issues.map((i) => i.message) },
511 400,
512 );
513 if (error instanceof DomainError)
514 return c.json(
515 { error: error.message },
516 error.status as 400 | 401 | 403 | 404 | 409 | 410,
517 );
518 const code = (error as { code?: string }).code;
519 if (["55P03", "57014", "40P01", "40001"].includes(code || ""))
520 return c.json({ error: "Workshop busy. Retry this operation." }, 503);
521 console.error("[bricks]", error);
522 return c.json({ error: "The workshop is temporarily unavailable" }, 500);
523});
524export default app;