Open History to see the last commit
1import assert from "node:assert/strict";
2import "./node-websocket";
3import { randomUUID } from "node:crypto";
4import { mkdir, writeFile } from "node:fs/promises";
5import {
6 createRealtimeClient,
7 type SealedLiveQuery,
8 type MaterializedLiveQuerySubscription,
9} from "@neon/realtime/client";
10import { pool } from "../src/server/db";
11import { bounds, validPart } from "../src/shared/geometry";
12import type { Part, SceneRow, Receipt } from "../src/shared/types";
13const base = (process.env.TEST_API_URL || process.env.VITE_API_URL!).replace(
14 /\/$/,
15 "",
16);
17const burst = Number(process.env.BURST_SECONDS || 60),
18 steady = Number(process.env.STEADY_SECONDS || 600),
19 size = Number(process.env.SCENE_PARTS || 2000),
20 builders = Number(process.env.BENCH_BUILDERS || 12);
21async function api<T>(token: string, path: string, body?: unknown): Promise<T> {
22 const r = await fetch(`${base}/api${path}`, {
23 method: body === undefined ? "GET" : "POST",
24 headers: {
25 "Content-Type": "application/json",
26 ...(token ? { Authorization: `Bearer ${token}` } : {}),
27 },
28 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
29 signal: AbortSignal.timeout(30000),
30 });
31 const result = await r.json();
32 const timing = r.headers.get("server-timing")?.match(/app;dur=([\d.]+)/);
33 if (path.endsWith("/edit") && timing) serverTimes.push(Number(timing[1]));
34 assert.ok(r.ok, `${r.status}: ${result.error}`);
35 return result;
36}
37const sleep = (ms: number) =>
38 new Promise((r) => setTimeout(r, Math.max(0, ms)));
39const clients: ReturnType<typeof createRealtimeClient>[] = [],
40 timers: ReturnType<typeof setInterval>[] = [];
41type Builder = {
42 token: string;
43 viewer: string;
44 sub: MaterializedLiveQuerySubscription<SceneRow>;
45 p: Part;
46 sequence: number;
47};
48const participants: Builder[] = [],
49 latencies: number[] = [],
50 requestTimes: number[] = [],
51 serverTimes: number[] = [],
52 errors: string[] = [];
53const diagnostics: Record<string, number> = {},
54 states: Record<string, number> = {};
55const watches = new Set<{
56 id: string;
57 revision: number;
58 deleted: boolean;
59 sent: number;
60 measure: boolean;
61 resolve: () => void;
62}>();
63let commands = 0,
64 world: any,
65 peerRows = new Map<string, SceneRow>();
66try {
67 const owner = await api<{ token: string }>("", "/session", {
68 name: "Capacity owner",
69 color: "#289b74",
70 });
71 world = await api<any>(owner.token, "/worlds", {
72 title: `Capacity ${size} — disposable`,
73 starter: "empty",
74 });
75 const keys = [
76 "brick-1x1",
77 "brick-1x2",
78 "plate-1x1",
79 "plate-1x2",
80 "tile-1x1",
81 "round",
82 "bearing",
83 ];
84 const parts: Part[] = Array.from({ length: size }, (_, i) => ({
85 id: randomUUID(),
86 key: keys[i % keys.length],
87 color: ["#289b74", "#edbc46", "#d9594e", "#72a6c8"][i % 4],
88 position: {
89 x: -96 + (i % 16) * 12,
90 y: Math.floor(i / 256) * 8,
91 z: -96 + (Math.floor(i / 16) % 16) * 12,
92 },
93 rotation: 0,
94 revision: 1,
95 }));
96 assert.ok(parts.every(validPart), "Fixture exceeds the board");
97 const bs = parts.map(bounds);
98 await pool.query(
99 "INSERT INTO part_instances(id,world,key,color,x,y,z,rotation,revision,deleted,minx,miny,minz,maxx,maxy,maxz) SELECT id,$1,key,color,x,y,z,0,1,0,minx,miny,minz,maxx,maxy,maxz FROM unnest($2::uuid[],$3::text[],$4::text[],$5::int[],$6::int[],$7::int[],$8::int[],$9::int[],$10::int[],$11::int[],$12::int[],$13::int[]) AS p(id,key,color,x,y,z,minx,miny,minz,maxx,maxy,maxz)",
100 [
101 world.id,
102 parts.map((p) => p.id),
103 parts.map((p) => p.key),
104 parts.map((p) => p.color),
105 parts.map((p) => p.position.x),
106 parts.map((p) => p.position.y),
107 parts.map((p) => p.position.z),
108 bs.map((b) => b.minx),
109 bs.map((b) => b.miny),
110 bs.map((b) => b.minz),
111 bs.map((b) => b.maxx),
112 bs.map((b) => b.maxy),
113 bs.map((b) => b.maxz),
114 ],
115 );
116 const editable = parts.filter((p) => p.key === "brick-1x1");
117 for (let i = 0; i < builders; i++) {
118 const session = await api<{ token: string }>("", "/session", {
119 name: `Capacity builder ${i + 1}`,
120 color: "#289b74",
121 }),
122 joined = await api<any>(session.token, `/worlds/${world.slug}/join`, {}),
123 token = session.token;
124 const seal = () =>
125 api<SealedLiveQuery<SceneRow>>(token, `/worlds/${world.id}/live/scene`),
126 q = await seal(),
127 client = createRealtimeClient({
128 url: process.env.VITE_NEON_REALTIME_URL!,
129 logLevel: "warn",
130 logger: (e) => {
131 const key = `${e.event}:${(e as any).error?.code || ""}`;
132 diagnostics[key] = (diagnostics[key] || 0) + 1;
133 },
134 }),
135 sub = client.subscribe(q);
136 clients.push(client);
137 await sub.awaitRows(
138 (rows) => rows.filter((r) => r.kind === "part").length === size,
139 20000,
140 );
141 timers.push(
142 setInterval(() => {
143 void seal()
144 .then((q) => sub.renew(q))
145 .catch((e) => errors.push(`renewal: ${e.message}`));
146 }, 35_000),
147 );
148 for (const kind of ["presence", "history"]) {
149 const seal = () =>
150 api<SealedLiveQuery<unknown>>(
151 token,
152 `/worlds/${world.id}/live/${kind}`,
153 ),
154 aux = client.subscribe(await seal());
155 timers.push(
156 setInterval(() => {
157 void seal()
158 .then((q) => aux.renew(q))
159 .catch((e) => errors.push(`renewal: ${e.message}`));
160 }, 35_000),
161 );
162 }
163 const participant = {
164 token,
165 viewer: joined.viewer,
166 sub,
167 p: editable[i],
168 sequence: 0,
169 };
170 participants.push(participant);
171 timers.push(
172 setInterval(() => {
173 void api(token, `/worlds/${world.id}/presence`, {
174 viewer: participant.viewer,
175 sequence: ++participant.sequence,
176 generation: 1,
177 selection: [participant.p.id],
178 preview: null,
179 sample: false,
180 }).catch((e) => errors.push(`presence: ${e.message}`));
181 }, 10_000),
182 );
183 if (i === 0)
184 sub.onChange((s) => {
185 states[s.status] = (states[s.status] || 0) + 1;
186 if (s.status === "live") {
187 peerRows = new Map(
188 s.data?.filter((r) => r.kind === "part").map((r) => [r.id, r]),
189 );
190 for (const w of watches) {
191 const p = peerRows.get(w.id);
192 if (w.deleted ? !p : p && p.revision >= w.revision) {
193 if (w.measure) latencies.push(performance.now() - w.sent);
194 w.resolve();
195 watches.delete(w);
196 }
197 }
198 }
199 });
200 }
201 await mkdir("artifacts", { recursive: true });
202 await writeFile(
203 "artifacts/capacity-room.json",
204 JSON.stringify(
205 { url: `http://127.0.0.1:5173/w/${world.slug}`, parts: size, builders },
206 null,
207 2,
208 ),
209 );
210 console.log(
211 `Ready: ${size} parts, ${builders} live clients; room /w/${world.slug}`,
212 );
213 async function runPhase(seconds: number, interval: number, label: string) {
214 const begin = performance.now();
215 await Promise.all(
216 participants.map(async (b, index) => {
217 let n = 0;
218 while (
219 n < Math.ceil((seconds * 1000) / interval) &&
220 performance.now() - begin < seconds * 1000
221 ) {
222 await sleep(begin + n * interval + index * 7 - performance.now());
223 if (performance.now() - begin >= seconds * 1000) break;
224 const old = b.p,
225 deleted = n % 8 === 6,
226 replace = !!old.deleted;
227 const change = replace
228 ? {
229 ...old,
230 id: randomUUID(),
231 deleted: false,
232 expected: undefined,
233 revision: undefined,
234 }
235 : {
236 id: old.id,
237 expected: old.revision,
238 ...(deleted
239 ? { deleted: true }
240 : n % 3 === 0
241 ? {
242 position: {
243 ...old.position,
244 x: editable[index].position.x + (n % 2 ? 1 : 0),
245 },
246 }
247 : { color: n % 2 ? "#d9594e" : "#289b74" }),
248 };
249 const id = change.id,
250 revision = replace ? 1 : old.revision + 1,
251 sent = performance.now();
252 let complete!: () => void;
253 const delivered = new Promise<void>((r) => (complete = r)),
254 w = {
255 id,
256 revision,
257 deleted,
258 sent,
259 measure: index !== 0,
260 resolve: complete,
261 };
262 watches.add(w);
263 try {
264 const receipt = await api<Receipt>(
265 b.token,
266 `/worlds/${world.id}/edit`,
267 {
268 operationId: randomUUID(),
269 generation: 1,
270 action: "edit",
271 changes: [change],
272 connections: [],
273 },
274 );
275 requestTimes.push(performance.now() - sent);
276 assert.ok(receipt.accepted, receipt.error);
277 b.p = receipt.parts![0];
278 commands++;
279 await Promise.race([
280 delivered,
281 sleep(15000).then(() => {
282 if (watches.has(w)) throw new Error("Peer visibility timeout");
283 }),
284 ]);
285 } catch (e) {
286 watches.delete(w);
287 errors.push((e as Error).message);
288 }
289 n++;
290 }
291 }),
292 );
293 console.log(
294 `${label}: ${commands} cumulative commands; ${errors.length} errors`,
295 );
296 }
297 await runPhase(burst, 500, "60-second burst");
298 await runPhase(steady, 5000, "steady session");
299 const percentile = (xs: number[], n: number) =>
300 [...xs].sort((a, b) => a - b)[
301 Math.min(xs.length - 1, Math.floor(xs.length * n))
302 ];
303 const expectedCommands = builders * (burst * 2 + Math.ceil(steady / 5));
304 if (commands < expectedCommands)
305 errors.push(`Workload shortfall: ${commands}/${expectedCommands}`);
306 const report = {
307 date: new Date().toISOString(),
308 api: base,
309 region: "aws-us-east-2",
310 client: `Node 22/ws, London; ${builders} independent guest sessions and live clients`,
311 parts: size,
312 builders,
313 burstSeconds: burst,
314 steadySeconds: steady,
315 commands,
316 expectedCommands,
317 diagnostics,
318 states,
319 errors,
320 peerVisibilityMs: {
321 p50: percentile(latencies, 0.5),
322 p95: percentile(latencies, 0.95),
323 max: Math.max(...latencies),
324 },
325 httpReceiptMs: { p95: percentile(requestTimes, 0.95) },
326 functionProcessingMs: {
327 p50: percentile(serverTimes, 0.5),
328 p95: percentile(serverTimes, 0.95),
329 },
330 measurement:
331 "Command dispatch to authoritative SDK snapshot in one peer; browser frame/render timing is measured separately",
332 room: world.slug,
333 };
334 await writeFile("artifacts/capacity.json", JSON.stringify(report, null, 2));
335 console.log(JSON.stringify(report, null, 2));
336 assert.equal(errors.length, 0);
337} finally {
338 timers.forEach(clearInterval);
339 clients.forEach((c) => c.close());
340 await pool.end();
341}