Open History to see the last commit
1import assert from "node:assert/strict";
2import "./node-websocket";
3import { randomUUID } from "node:crypto";
4import {
5 createRealtimeClient,
6 type MaterializedLiveQuerySubscription,
7} from "@neon/realtime/client";
8import { pool } from "../src/server/db";
9import { connectorList } from "../src/shared/geometry";
10import {
11 sceneEntity,
12 type SceneRow,
13 type Part,
14 type Connection,
15 type Receipt,
16 type Edit,
17} from "../src/shared/types";
18const base = (
19 process.env.TEST_API_URL ||
20 process.env.VITE_API_URL ||
21 "http://127.0.0.1:3001"
22).replace(/\/$/, "");
23const trials = Number(process.env.RACE_TRIALS || 100),
24 workers = 4;
25async function api<T>(token: string, path: string, body?: unknown): Promise<T> {
26 const r = await fetch(`${base}/api${path}`, {
27 method: body === undefined ? "GET" : "POST",
28 headers: {
29 "Content-Type": "application/json",
30 ...(token ? { Authorization: `Bearer ${token}` } : {}),
31 },
32 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
33 signal: AbortSignal.timeout(30000),
34 });
35 const data = await r.json();
36 assert.ok(r.ok, `${path}: ${r.status} ${data.error}`);
37 return data;
38}
39const session = async () =>
40 (
41 await api<{ token: string }>("", "/session", {
42 name: "Database qualification",
43 color: "#289b74",
44 })
45 ).token;
46const piece = (key = "brick-1x1", x = 0, y = 0, z = 0, rotation = 0) => ({
47 id: randomUUID(),
48 key,
49 color: "#289b74",
50 position: { x, y, z },
51 rotation,
52});
53type Lab = {
54 a: string;
55 b: string;
56 world: string;
57 generation: number;
58 sub: MaterializedLiveQuerySubscription<SceneRow>;
59 client: ReturnType<typeof createRealtimeClient>;
60 renew: ReturnType<typeof setInterval>;
61};
62async function lab(): Promise<Lab> {
63 const [a, b] = await Promise.all([session(), session()]);
64 const w = await api<{ id: string; slug: string; generation: number }>(
65 a,
66 "/worlds",
67 { title: "Qualification — disposable", starter: "empty" },
68 );
69 await Promise.all([
70 api(a, `/worlds/${w.slug}/join`, {}),
71 api(b, `/worlds/${w.slug}/join`, {}),
72 ]);
73 const sealed = await api<any>(a, `/worlds/${w.id}/live/scene`),
74 client = createRealtimeClient({ url: process.env.VITE_NEON_REALTIME_URL! }),
75 sub = client.subscribe<SceneRow>(sealed);
76 const renew = setInterval(() => {
77 void api<any>(a, `/worlds/${w.id}/live/scene`).then((q) => sub.renew(q));
78 }, 30_000);
79 await sub.awaitRows((rows) => rows.some((r) => r.kind === "world"), 15000);
80 return { a, b, world: w.id, generation: w.generation, sub, client, renew };
81}
82function command(
83 l: Lab,
84 token: string,
85 changes: Edit["changes"],
86 connections: Edit["connections"] = [],
87 extra: Partial<Edit> = {},
88) {
89 return api<Receipt>(token, `/worlds/${l.world}/edit`, {
90 operationId: randomUUID(),
91 generation: l.generation,
92 action: "edit",
93 changes,
94 connections,
95 ...extra,
96 });
97}
98async function sync(l: Lab, r: Receipt) {
99 assert.ok(r.accepted, r.error);
100 if (r.txid) await l.sub.awaitTxId(r.txid, 15000);
101}
102const edges = (l: Lab) =>
103 l.sub
104 .getSnapshot()
105 .data!.filter((r) => r.kind === "connection")
106 .map((r) => sceneEntity(r) as Connection);
107async function clean(l: Lab, parts: Part[]) {
108 const ids = parts.map((p) => p.id);
109 await sync(
110 l,
111 await command(
112 l,
113 l.a,
114 parts
115 .filter((p) => !p.deleted)
116 .map((p) => ({ id: p.id, expected: p.revision, deleted: true })),
117 edges(l).filter((e) => ids.includes(e.a) || ids.includes(e.b)),
118 ),
119 );
120}
121const results: Record<string, number> = {};
122const labs: Lab[] = [];
123try {
124 for (let i = 0; i < workers; i++) labs.push(await lab());
125 for (const scenario of [
126 "empty collision",
127 "rotated bucket boundary",
128 "disjoint placements",
129 "move versus delete",
130 "new adjacent connectors",
131 "shared baseplate",
132 ]) {
133 let next = 0,
134 done = 0;
135 await Promise.all(
136 labs.map(async (l) => {
137 while (next < trials) {
138 const n = next++;
139 let parts: Part[] = [];
140 if (scenario === "move versus delete") {
141 const p = piece();
142 const initial = await command(l, l.a, [p]);
143 await sync(l, initial);
144 const requests = [
145 [{ id: p.id, expected: 1, position: { x: 30, y: 0, z: 0 } }],
146 [{ id: p.id, expected: 1, deleted: true }],
147 ];
148 const rs = await Promise.all([
149 command(l, l.a, requests[n % 2]),
150 command(l, l.b, requests[1 - (n % 2)]),
151 ]);
152 assert.equal(rs.filter((r) => r.accepted).length, 1);
153 const winner = rs.find((r) => r.accepted)!;
154 await sync(l, winner);
155 parts = winner.parts!;
156 } else if (
157 scenario === "new adjacent connectors" ||
158 scenario === "shared baseplate"
159 ) {
160 let lower: any;
161 if (scenario === "shared baseplate") {
162 lower = piece("plate-4x4");
163 await sync(l, await command(l, l.a, [lower]));
164 }
165 const a = piece(
166 "brick-1x1",
167 0,
168 scenario === "shared baseplate" ? 2 : 0,
169 ),
170 b = piece(
171 "brick-1x1",
172 scenario === "shared baseplate" ? 18 : 0,
173 scenario === "shared baseplate" ? 2 : 6,
174 );
175 const rs = await Promise.all([
176 command(l, l.a, [n % 2 ? a : b]),
177 command(l, l.b, [n % 2 ? b : a]),
178 ]);
179 for (const r of rs) await sync(l, r);
180 assert.equal(
181 edges(l).length,
182 scenario === "shared baseplate" ? 2 : 1,
183 );
184 parts = [
185 ...rs.flatMap((r) => r.parts!),
186 ...(lower ? [{ ...lower, revision: 1 }] : []),
187 ];
188 } else {
189 const boundary = scenario === "rotated bucket boundary",
190 disjoint = scenario === "disjoint placements";
191 const a = piece(
192 boundary ? "brick-1x2" : "brick-1x1",
193 boundary ? 23 : 0,
194 0,
195 0,
196 boundary ? 1 : 0,
197 ),
198 b = piece(
199 boundary ? "brick-1x2" : "brick-1x1",
200 disjoint ? 48 : boundary ? 23 : 0,
201 0,
202 0,
203 boundary ? 3 : 0,
204 );
205 const rs = await Promise.all([
206 command(l, l.a, [n % 2 ? a : b]),
207 command(l, l.b, [n % 2 ? b : a]),
208 ]);
209 assert.equal(rs.filter((r) => r.accepted).length, disjoint ? 2 : 1);
210 for (const r of rs.filter((r) => r.accepted)) await sync(l, r);
211 parts = rs.flatMap((r) => r.parts || []);
212 }
213 if (parts.some((p) => !p.deleted)) await clean(l, parts);
214 if (++done % 25 === 0) console.log(`${scenario}: ${done}/${trials}`);
215 }
216 }),
217 );
218 results[scenario] = done;
219 console.log("PASS", scenario, done);
220 }
221 const mechanical = labs[1];
222 for (let rotation = 0; rotation < 4; rotation++)
223 for (const key of [
224 "beam-3",
225 "bearing",
226 "gear-12",
227 "gear-20",
228 "wheel",
229 "hub",
230 "crank",
231 ]) {
232 const receiver = piece(key, 12, 12, 12, rotation),
233 axle = piece("axle-4", 0, 0, 0, rotation),
234 hole = connectorList({ ...receiver, revision: 1 }).find(
235 (c) => c.type === "hole",
236 )!,
237 shaft = connectorList({ ...axle, revision: 1 }).find(
238 (c) => c.type === "shaft",
239 )!;
240 axle.position = {
241 x: hole.at.x - shaft.at.x,
242 y: hole.at.y - shaft.at.y,
243 z: hole.at.z - shaft.at.z,
244 };
245 const assembled = await command(mechanical, mechanical.a, [
246 receiver,
247 axle,
248 ]);
249 await sync(mechanical, assembled);
250 assert.equal(
251 edges(mechanical).length,
252 1,
253 `${key}/${rotation}: missing shaft connection`,
254 );
255 const offset = await command(
256 mechanical,
257 mechanical.b,
258 [
259 {
260 id: axle.id,
261 expected: 1,
262 position: { ...axle.position, y: axle.position.y + 2 },
263 },
264 ],
265 edges(mechanical),
266 );
267 assert.equal(
268 offset.accepted,
269 false,
270 `${key}/${rotation}: shaft pierced body`,
271 );
272 assert.equal(
273 edges(mechanical).length,
274 1,
275 "Rejected move changed topology",
276 );
277 await clean(mechanical, assembled.parts!);
278 }
279 console.log(
280 "PASS 28 mechanical shaft fits, connection persistence and rejected offset moves",
281 );
282 const l = labs[0],
283 p = piece(),
284 placeId = randomUUID();
285 const original = {
286 operationId: placeId,
287 generation: 1,
288 action: "edit" as const,
289 changes: [p],
290 };
291 const placed = await api<Receipt>(l.a, `/worlds/${l.world}/edit`, original);
292 await sync(l, placed);
293 assert.deepEqual(await api(l.a, `/worlds/${l.world}/edit`, original), placed);
294 const recolorId = randomUUID();
295 await sync(
296 l,
297 await command(l, l.a, [{ id: p.id, expected: 1, color: "#d9594e" }], [], {
298 operationId: recolorId,
299 }),
300 );
301 for (const [action, target] of [
302 ["undo", recolorId],
303 ["redo", recolorId],
304 ["undo", recolorId],
305 ["undo", placeId],
306 ["redo", placeId],
307 ["redo", recolorId],
308 ] as const)
309 await sync(
310 l,
311 await command(l, l.a, undefined, undefined, { action, target }),
312 );
313 const current = l.sub.getSnapshot().data!.find((r) => r.id === p.id)!;
314 await sync(
315 l,
316 await command(l, l.b, [
317 { id: p.id, expected: current.revision, color: "#72a6c8" },
318 ]),
319 );
320 const conflict = await command(l, l.a, undefined, undefined, {
321 action: "undo",
322 target: recolorId,
323 });
324 assert.equal(conflict.accepted, false);
325 const invalid = {
326 operationId: randomUUID(),
327 generation: 1,
328 action: "edit" as const,
329 changes: [piece("brick-1x1", 96)],
330 };
331 const rejected = await api<Receipt>(l.a, `/worlds/${l.world}/edit`, invalid);
332 assert.equal(rejected.accepted, false);
333 assert.deepEqual(
334 await api(l.a, `/worlds/${l.world}/edit`, invalid),
335 rejected,
336 );
337 const reset = await api<{ generation: number }>(
338 l.a,
339 `/worlds/${l.world}/reset`,
340 { generation: 1, starter: "empty" },
341 );
342 assert.equal(reset.generation, 2);
343 await l.sub.awaitRows(
344 (rows) =>
345 rows.find((r) => r.kind === "world")?.generation === 2 &&
346 rows.filter((r) => r.kind !== "world").length === 0,
347 15000,
348 );
349 assert.deepEqual(await api(l.a, `/worlds/${l.world}/edit`, original), placed);
350 assert.equal((await command(l, l.a, [piece()])).accepted, false);
351 console.log(
352 "PASS receipts, chained compensation, third-party revision, coherent reset and old-generation replay",
353 );
354 // These predicates audit all test-created rooms, not the shared workshop.
355 const bad = await pool.query(
356 "SELECT count(*)::int AS n FROM connector_slot_claims c LEFT JOIN part_connections e ON e.id=c.connection WHERE c.world=ANY($1::uuid[]) AND (e.id IS NULL OR e.deleted<>0)",
357 [labs.map((l) => l.world)],
358 );
359 assert.equal(bad.rows[0].n, 0);
360 console.log(
361 JSON.stringify(
362 { api: base, trials: results, extraChecks: "PASS" },
363 null,
364 2,
365 ),
366 );
367} finally {
368 labs.forEach((l) => {
369 clearInterval(l.renew);
370 l.client.close();
371 });
372 await pool.end();
373}