Open History to see the last commit
1import { randomUUID } from "node:crypto";
2import type { PoolClient } from "pg";
3import {
4 type Part,
5 type Connection,
6 type Edit,
7 type Receipt,
8 CATALOGUE_VERSION,
9 MAX_AI_PARTS,
10} from "../shared/types";
11import {
12 bounds,
13 bucketKeys,
14 enclosing,
15 collision,
16 validPart,
17 connectorList,
18 mating,
19} from "../shared/geometry";
20import { transaction } from "./db";
21import { DomainError, hash, lockAccess, type Identity } from "./auth";
22import { partFromRow, insertPart } from "./worlds";
23type Entry = {
24 id: string;
25 expected: Part[];
26 connections: Connection[];
27 geometry: boolean;
28 bridgeBefore: (Part | null)[];
29 bridgeConnections: Connection[];
30};
31type History = { undo: Entry[]; redo: Entry[]; generation: number };
32const connFromRow = (r: Record<string, any>): Connection => ({
33 id: r.id,
34 a: r.a,
35 b: r.b,
36 ca: r.ca,
37 cb: r.cb,
38 revision: r.revision,
39});
40const sortedConnections = (cs: { id: string; revision: number }[]) =>
41 JSON.stringify(
42 cs
43 .map((c) => ({ id: c.id, revision: c.revision }))
44 .sort((a, b) => a.id.localeCompare(b.id)),
45 );
46function canonical(v: any): string {
47 if (Array.isArray(v)) return `[${v.map(canonical).join(",")}]`;
48 if (v && typeof v === "object")
49 return `{${Object.keys(v)
50 .sort()
51 .map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`)
52 .join(",")}}`;
53 return JSON.stringify(v);
54}
55async function incident(c: PoolClient, world: string, ids: string[]) {
56 const { rows } = await c.query(
57 "SELECT * FROM part_connections WHERE world=$1 AND deleted=0 AND (a=ANY($2::uuid[]) OR b=ANY($2::uuid[])) ORDER BY id",
58 [world, ids],
59 );
60 return rows.map(connFromRow);
61}
62export async function reconnectParts(
63 c: PoolClient,
64 world: string,
65 changed: Part[],
66 candidates: Part[],
67 old: Connection[],
68) {
69 if (old.length) {
70 await c.query(
71 "DELETE FROM connector_slot_claims WHERE connection=ANY($1::uuid[])",
72 [old.map((c) => c.id)],
73 );
74 await c.query(
75 "UPDATE part_connections SET deleted=1,revision=revision+1 WHERE id=ANY($1::uuid[])",
76 [old.map((c) => c.id)],
77 );
78 }
79 const seen = new Set<string>();
80 const after: Connection[] = [];
81 for (const p of changed.filter((p) => !p.deleted))
82 for (const n of candidates.filter((n) => !n.deleted && n.id !== p.id)) {
83 const aa = connectorList(p),
84 bb = connectorList(n);
85 for (const a of aa)
86 for (const b of bb)
87 if (mating(a, b)) {
88 const [pa, pb, ca, cb] = p.id < n.id ? [p, n, a, b] : [n, p, b, a];
89 const k = `${pa.id}/${pb.id}/${ca.id}/${cb.id}`;
90 if (seen.has(k)) continue;
91 seen.add(k);
92 const { rows } = await c.query(
93 "INSERT INTO part_connections(id,world,a,b,ca,cb,revision) VALUES($1,$2,$3,$4,$5,$6,1) ON CONFLICT(world,a,b,ca,cb) DO UPDATE SET deleted=0,revision=part_connections.revision+1 RETURNING *",
94 [randomUUID(), world, pa.id, pb.id, ca.id, cb.id],
95 );
96 const edge = connFromRow(rows[0]);
97 after.push(edge);
98 for (const [part, connector] of [
99 [pa, ca],
100 [pb, cb],
101 ] as const)
102 if (connector.exclusive)
103 await c.query(
104 "INSERT INTO connector_slot_claims(world,part,slot,connection) VALUES($1,$2,$3,$4)",
105 [world, part.id, connector.id, edge.id],
106 );
107 }
108 }
109 return after;
110}
111async function applyChanges(
112 c: PoolClient,
113 world: string,
114 changes: NonNullable<Edit["changes"]>,
115 expectedConnections: { id: string; revision: number }[] | undefined,
116 compensation = false,
117) {
118 if (
119 !changes.length ||
120 changes.length > MAX_AI_PARTS * 2 ||
121 new Set(changes.map((x) => x.id)).size !== changes.length
122 )
123 throw new DomainError(
124 `Select between one and ${MAX_AI_PARTS * 2} distinct parts`,
125 );
126 const ids = changes.map((x) => x.id),
127 prelim = await c.query(
128 "SELECT * FROM part_instances WHERE world=$1 AND id=ANY($2::uuid[])",
129 [world, ids],
130 );
131 const oldMap = new Map<string, Part>(
132 prelim.rows.map((r) => [r.id, partFromRow(r)]),
133 );
134 const before: (Part | null)[] = changes.map(
135 (change) => oldMap.get(change.id) || null,
136 );
137 const after = changes.map((change) => {
138 const old = oldMap.get(change.id);
139 if (old) {
140 if (change.expected !== old.revision || (!compensation && old.deleted))
141 throw new DomainError("That part has changed. Try again.");
142 } else if (change.expected !== undefined)
143 throw new DomainError("That part no longer exists");
144 const p: Part = {
145 id: change.id,
146 key: change.key || old?.key || "",
147 color: change.color || old?.color || "",
148 position: change.position || old?.position || { x: NaN, y: NaN, z: NaN },
149 rotation: change.rotation ?? old?.rotation ?? 0,
150 revision: (old?.revision || 0) + 1,
151 deleted: change.deleted ?? false,
152 };
153 if (!validPart(p))
154 throw new DomainError("Invalid part or outside the workbench");
155 return p;
156 });
157 const geometric = after.some(
158 (p, i) =>
159 !before[i] ||
160 before[i]!.key !== p.key ||
161 before[i]!.rotation !== p.rotation ||
162 JSON.stringify(before[i]!.position) !== JSON.stringify(p.position) ||
163 !!before[i]!.deleted !== !!p.deleted,
164 );
165 const footprint = [...before.filter((p): p is Part => !!p), ...after];
166 if (geometric) {
167 const keys = bucketKeys(footprint).map((k) => k.split(",").map(Number));
168 const locked = await c.query(
169 "SELECT b.x,b.y,b.z FROM spatial_buckets b JOIN unnest($2::int[],$3::int[],$4::int[]) AS k(x,y,z) USING(x,y,z) WHERE b.world=$1 ORDER BY b.x,b.y,b.z FOR UPDATE OF b",
170 [
171 world,
172 keys.map((k) => k[0]),
173 keys.map((k) => k[1]),
174 keys.map((k) => k[2]),
175 ],
176 );
177 if (locked.rowCount !== keys.length)
178 throw new DomainError("Outside the workbench");
179 }
180 const locked = await c.query(
181 "SELECT * FROM part_instances WHERE world=$1 AND id=ANY($2::uuid[]) ORDER BY id FOR UPDATE",
182 [world, ids],
183 );
184 for (const row of locked.rows) {
185 const original = oldMap.get(row.id);
186 if (!original || original.revision !== row.revision)
187 throw new DomainError("That part has changed. Try again.");
188 }
189 if (locked.rows.length !== prelim.rows.length)
190 throw new DomainError("That part has changed. Try again.");
191 const beforeConnections = await incident(c, world, ids);
192 if (geometric && before.some((p) => !!p && !p.deleted)) {
193 if (
194 expectedConnections === undefined ||
195 sortedConnections(expectedConnections) !==
196 sortedConnections(beforeConnections)
197 )
198 throw new DomainError("Connections changed. Refresh the selection.");
199 }
200 let candidates: Part[] = [];
201 if (geometric) {
202 // A new READ COMMITTED statement after bucket waits sees the winner's commit.
203 const b = enclosing(footprint);
204 const result = await c.query(
205 "SELECT * FROM part_instances WHERE world=$1 AND deleted=0 AND minx<=$2 AND maxx>=$3 AND miny<=$4 AND maxy>=$5 AND minz<=$6 AND maxz>=$7 AND NOT(id=ANY($8::uuid[]))",
206 [world, b.maxx, b.minx, b.maxy, b.miny, b.maxz, b.minz, ids],
207 );
208 candidates = result.rows.map(partFromRow);
209 const active = after.filter((p) => !p.deleted);
210 for (let i = 0; i < active.length; i++) {
211 for (const other of candidates)
212 if (collision(active[i], other))
213 throw new DomainError("That space is occupied");
214 for (let j = 0; j < i; j++)
215 if (collision(active[i], active[j]))
216 throw new DomainError("Selected parts overlap");
217 }
218 }
219 for (const [i, p] of after.entries()) {
220 if (!before[i]) await insertPart(c, world, p);
221 else {
222 const b = bounds(p);
223 await c.query(
224 "UPDATE part_instances SET key=$3,color=$4,x=$5,y=$6,z=$7,rotation=$8,revision=$9,deleted=$10,minx=$11,miny=$12,minz=$13,maxx=$14,maxy=$15,maxz=$16 WHERE world=$1 AND id=$2",
225 [
226 world,
227 p.id,
228 p.key,
229 p.color,
230 p.position.x,
231 p.position.y,
232 p.position.z,
233 p.rotation,
234 p.revision,
235 p.deleted ? 1 : 0,
236 b.minx,
237 b.miny,
238 b.minz,
239 b.maxx,
240 b.maxy,
241 b.maxz,
242 ],
243 );
244 }
245 }
246 const afterConnections = geometric
247 ? await reconnectParts(
248 c,
249 world,
250 after,
251 [...candidates, ...after],
252 beforeConnections,
253 )
254 : beforeConnections;
255 return { before, after, beforeConnections, afterConnections, geometric };
256}
257function rebase(
258 entry: Entry | undefined,
259 originalBefore: (Part | null)[],
260 now: Part[],
261 beforeConnections: Connection[],
262 afterConnections: Connection[],
263) {
264 if (!entry) return;
265 for (const expected of entry.expected) {
266 const before = originalBefore.find((p) => p?.id === expected.id);
267 const current = now.find((p) => p.id === expected.id);
268 if (
269 before &&
270 current &&
271 before.revision === expected.revision &&
272 !!before.deleted === !!expected.deleted
273 )
274 Object.assign(expected, current);
275 }
276 if (entry.geometry)
277 for (const expected of entry.connections) {
278 const before = beforeConnections.find((c) => c.id === expected.id),
279 current = afterConnections.find((c) => c.id === expected.id);
280 if (before && current && before.revision === expected.revision)
281 Object.assign(expected, current);
282 }
283}
284export async function execute(
285 a: Identity,
286 world: string,
287 request: Edit,
288): Promise<Receipt> {
289 return transaction((c) => executeInTransaction(c, a, world, request));
290}
291
292// Reuse the normal spatial locks, receipts and undo history for atomic AI apply.
293export async function executeInTransaction(
294 c: PoolClient,
295 a: Identity,
296 world: string,
297 request: Edit,
298): Promise<Receipt> {
299 const w = await lockAccess(c, a, world),
300 digest = hash(canonical(request));
301 const inserted = await c.query(
302 "INSERT INTO build_operations(world,guest,id,generation,digest) VALUES($1,$2,$3,$4,$5) ON CONFLICT DO NOTHING RETURNING *,pg_current_xact_id()::text AS txid",
303 [world, a.guest, request.operationId, request.generation, digest],
304 );
305 const { rows: ops } = inserted.rowCount
306 ? inserted
307 : await c.query(
308 "SELECT * FROM build_operations WHERE world=$1 AND guest=$2 AND id=$3 FOR UPDATE",
309 [world, a.guest, request.operationId],
310 );
311 if (ops[0].digest !== digest)
312 throw new DomainError("Operation ID reused with different changes");
313 if (!inserted.rowCount) {
314 if (!ops[0].receipt) throw new Error("Incomplete operation record");
315 return ops[0].receipt;
316 }
317 const historyRow = await c.query(
318 "SELECT * FROM guest_world_history WHERE world=$1 AND guest=$2 FOR UPDATE",
319 [world, a.guest],
320 );
321 const h: History = historyRow.rows[0] || {
322 undo: [],
323 redo: [],
324 generation: w.generation,
325 };
326 if (h.generation !== w.generation) {
327 h.undo = [];
328 h.redo = [];
329 h.generation = w.generation;
330 }
331 await c.query("SAVEPOINT edit");
332 try {
333 if (request.generation !== w.generation || w.status !== "open")
334 throw new DomainError(
335 "The workshop was reset or closed. Refresh your preview.",
336 );
337 if (w.catalogue !== CATALOGUE_VERSION)
338 throw new DomainError("Catalogue version unavailable");
339 let changes = request.changes,
340 expectedConnections = request.connections,
341 entry: Entry | undefined,
342 original: any;
343 if (request.action !== "edit") {
344 const stack = request.action === "undo" ? h.undo : h.redo;
345 entry = stack.at(-1);
346 if (!entry || entry.id !== request.target)
347 throw new DomainError("Undo history changed. Try again.");
348 const { rows } = await c.query(
349 "SELECT * FROM build_operations WHERE world=$1 AND guest=$2 AND id=$3",
350 [world, a.guest, entry.id],
351 );
352 original = rows[0];
353 const desired: (Part | null)[] =
354 request.action === "undo" ? original.before : original.after;
355 changes = entry.expected.map((current) => {
356 const p = desired.find((p) => p?.id === current.id);
357 return p
358 ? { ...p, expected: current.revision }
359 : { id: current.id, expected: current.revision, deleted: true };
360 });
361 expectedConnections = entry.connections;
362 }
363 if (!changes) throw new DomainError("No parts selected");
364 const result = await applyChanges(
365 c,
366 world,
367 changes,
368 expectedConnections,
369 request.action !== "edit",
370 );
371 if (request.action === "edit") {
372 h.undo.push({
373 id: request.operationId,
374 expected: result.after,
375 connections: result.afterConnections,
376 geometry: result.geometric,
377 bridgeBefore: result.before,
378 bridgeConnections: result.beforeConnections,
379 });
380 h.undo = h.undo.slice(-100);
381 h.redo = [];
382 } else {
383 const stack = request.action === "undo" ? h.undo : h.redo,
384 other = request.action === "undo" ? h.redo : h.undo;
385 stack.pop();
386 other.push({
387 id: entry!.id,
388 expected: result.after,
389 connections: result.afterConnections,
390 geometry: entry!.geometry,
391 bridgeBefore: result.before,
392 bridgeConnections: result.beforeConnections,
393 });
394 // Carry the effective revision bridge through repeated compensation,
395 // including intervening actions on unrelated parts. Immutable receipts
396 // remain unchanged; a third party's revision never matches this bridge.
397 for (const remaining of stack)
398 rebase(
399 remaining,
400 entry!.bridgeBefore || original.before,
401 result.after,
402 entry!.bridgeConnections || original.before_connections,
403 result.afterConnections,
404 );
405 }
406 await c.query(
407 "UPDATE guest_world_history SET generation=$3,undo=$4,redo=$5 WHERE world=$1 AND guest=$2",
408 [
409 world,
410 a.guest,
411 w.generation,
412 JSON.stringify(h.undo),
413 JSON.stringify(h.redo),
414 ],
415 );
416 const receipt: Receipt = {
417 accepted: true,
418 operationId: request.operationId,
419 generation: w.generation,
420 txid: ops[0].txid,
421 parts: result.after,
422 history: {
423 undo: h.undo.at(-1)?.id || null,
424 redo: h.redo.at(-1)?.id || null,
425 },
426 };
427 await c.query(
428 "UPDATE build_operations SET receipt=$4,before=$5,after=$6,before_connections=$7,after_connections=$8 WHERE world=$1 AND guest=$2 AND id=$3",
429 [
430 world,
431 a.guest,
432 request.operationId,
433 JSON.stringify(receipt),
434 JSON.stringify(result.before),
435 JSON.stringify(result.after),
436 JSON.stringify(result.beforeConnections),
437 JSON.stringify(result.afterConnections),
438 ],
439 );
440 return receipt;
441 } catch (error) {
442 if (
443 !(error instanceof DomainError) &&
444 !["23505", "23503"].includes((error as { code?: string }).code || "")
445 )
446 throw error;
447 await c.query("ROLLBACK TO SAVEPOINT edit");
448 const receipt: Receipt = {
449 accepted: false,
450 operationId: request.operationId,
451 generation: request.generation,
452 error:
453 error instanceof DomainError
454 ? error.message
455 : "This part or connector is already in use",
456 };
457 await c.query(
458 "UPDATE build_operations SET receipt=$4 WHERE world=$1 AND guest=$2 AND id=$3",
459 [world, a.guest, request.operationId, JSON.stringify(receipt)],
460 );
461 return receipt;
462 }
463}