goatly 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import { WorkerControl } from "./memory-governor.js";
2
2
  import { performance } from "node:perf_hooks";
3
- import { isMainThread, parentPort, workerData } from "node:worker_threads";
3
+ import { isMainThread, parentPort, resourceLimits, workerData } from "node:worker_threads";
4
4
  // src/node/build/query-worker.ts
5
5
  /**
6
6
  * Query worker (parallel query running): loads the datastore (e.g. the logfile store's index), runs
@@ -11,13 +11,28 @@ import { isMainThread, parentPort, workerData } from "node:worker_threads";
11
11
  * (incremental builds) are rendered from their existing page-data.json when their HTML is outdated
12
12
  * (the main thread sends them once the bundles exist). Pages are rendered in chunks of at most
13
13
  * RENDER_CHUNK pages or RENDER_CHUNK_CHARS characters of page data, and the worker drops its caches
14
- * when its heap fills up (createHeapGuard).
14
+ * when its heap fills up (createHeapGuard). A worker whose heap holds node data renders in a thread
15
+ * of its own (RENDER_THREAD_HEAP_MB).
15
16
  */
16
17
  /** pages and characters of page data rendered at a time (cached results are read per chunk, too) */
17
18
  const RENDER_CHUNK = 64;
18
19
  const RENDER_CHUNK_CHARS = 8388608;
19
20
  /** page queries of a batch running at a time (Gatsby: 4) */
20
21
  const QUERY_CONCURRENCY = 8;
22
+ /**
23
+ * A query worker with this much heap in use (MB) renders its pages in a thread of its own
24
+ * (render-thread.ts), which holds the SSR bundle and one batch of pages. Rendering is mostly
25
+ * garbage – parsed results, elements, HTML – and what collecting it costs depends on the heap it
26
+ * is collected in: next to the node data of page queries that ran in JS (slim nodes, views,
27
+ * indexes), in a heap of 750 MB, rendering took 2.5 ms a page instead of 2.0 ms in a thread of its
28
+ * own. That thread costs about 55 MB, and handing it the results a little time: with a heap of
29
+ * 220 MB it was the slower way (2.4 instead of 2.1 ms a page). A worker whose queries run in WASM
30
+ * keeps a small heap (35–140 MB).
31
+ * (GOATLY_RENDER_THREAD=on|off|later: internal, for tests – "later": after the first batch)
32
+ */
33
+ const RENDER_THREAD_HEAP_MB = 512;
34
+ /** the least heap limit (MB) of that thread, when the worker's heap leaves less of its own limit */
35
+ const RENDER_THREAD_MIN_MB = 256;
21
36
  async function main(data) {
22
37
  const port = parentPort;
23
38
  try {
@@ -26,6 +41,8 @@ async function main(data) {
26
41
  const { generateHtmlPath, generatePageDataPath } = await import("../utils/paths.js");
27
42
  const { AssetResolver } = await import("./assets.js");
28
43
  const { createRenderer } = await import("./render-worker.js");
44
+ const { createWorkClock } = await import("./work-clock.js");
45
+ const { startRenderThread } = await import("./render-thread.js");
29
46
  const { createDirectoryMaker, outputDirs } = await import("./output-dirs.js");
30
47
  const { finishCaches, persistCaches, releaseCaches } = await import("../cache.js");
31
48
  const { getDataStore, nodeTypeOf } = await import("../datastore/index.js");
@@ -64,7 +81,7 @@ async function main(data) {
64
81
  waiting.reject(Object.assign(new Error(msg.message), { stack: msg.stack }));
65
82
  });
66
83
  const { clearQueryEngineCaches, setSlimNodesHeap } = await import("../schema/query-engine.js");
67
- const { createHeapGuard, heapRatio, heapUsedMb } = await import("../utils/memory.js");
84
+ const { createHeapGuard, heapRatio, heapUsedMb, RUNTIME, threadCpuMs, watchGarbageCollections } = await import("../utils/memory.js");
68
85
  const { reporter } = await import("../reporter.js");
69
86
  const { QueryDependencies } = await import("../query/dependencies.js");
70
87
  const { hashString, htmlDigest, htmlRemovedEachBuild, readCachedResult, serializeDependencies } = await import("./incremental.js");
@@ -97,6 +114,38 @@ async function main(data) {
97
114
  const deferrals = createSitePageDeferrals();
98
115
  let job;
99
116
  let renderer;
117
+ /** the thread this worker renders in when its heap is large (see RENDER_THREAD_HEAP_MB) */
118
+ let renderThread;
119
+ /** the thread could not load the SSR bundle this worker loaded: not tried again */
120
+ let renderThreadFailed = false;
121
+ const renderThreadMode = process.env.GOATLY_RENDER_THREAD;
122
+ /**
123
+ * Whether to render in a thread of its own: by the heap that stays – without the results the
124
+ * worker holds for rendering (`setup`: when the render job arrives; "later": only afterwards).
125
+ * (Bun: not tried there – its worker threads have no heap limits of their own)
126
+ */
127
+ const wantsRenderThread = (setup) => RUNTIME !== "bun" && !renderThreadFailed && renderThreadMode !== "off" && (renderThreadMode === "on" || renderThreadMode === "later" && !setup || renderThreadMode !== "later" && heapUsedMb() - bufferedBytes / 1048576 >= RENDER_THREAD_HEAP_MB);
128
+ /** undefined: the thread could not be started – this worker renders, as without one */
129
+ const startRenderThreadFor = async (options) => {
130
+ const heapMb = Math.round(heapUsedMb());
131
+ const limitMb = resourceLimits?.maxOldGenerationSizeMb;
132
+ try {
133
+ renderThread = await startRenderThread(options, {
134
+ limitMb: limitMb ? Math.max(RENDER_THREAD_MIN_MB, Math.round(limitMb - heapMb)) : void 0,
135
+ onDeath: (error, oom) => port.postMessage({
136
+ type: "failed",
137
+ error: oom ? "its render thread ran out of memory" : error.stack ?? error.message,
138
+ oom
139
+ })
140
+ });
141
+ } catch (e) {
142
+ renderThreadFailed = true;
143
+ reporter.verbose(`query worker ${data.workerId} renders in its own thread: a render thread could not be started (${e?.message ?? e})`);
144
+ return;
145
+ }
146
+ reporter.verbose(`query worker ${data.workerId} renders in a thread of its own (its heap holds ${heapMb} MB)`);
147
+ return renderThread;
148
+ };
100
149
  /** creates the output directories of the pages this worker renders */
101
150
  let dirs;
102
151
  let assets;
@@ -111,37 +160,64 @@ async function main(data) {
111
160
  /** characters of cached results render() read (they count towards a batch's bytes) */
112
161
  let readChars = 0;
113
162
  const ratio = () => heapRatio(budget());
163
+ const clock = () => performance.timeOrigin + performance.now();
164
+ /** where this worker's time goes (see WorkerTimings) */
165
+ const work = createWorkClock({
166
+ epoch: clock,
167
+ now: () => performance.now(),
168
+ cpu: threadCpuMs
169
+ });
170
+ let collectedMb;
171
+ const gcWatch = watchGarbageCollections(({ start, ms, major }) => {
172
+ work.collected(start, ms);
173
+ if (major) collectedMb = heapUsedMb();
174
+ });
175
+ /**
176
+ * the heap (MB) the guard measures against (see heapRatio): the budget, at most the heap limit
177
+ * (Bun, which has no limit: the budget)
178
+ */
179
+ const measuredAgainst = () => {
180
+ const mb = budget();
181
+ return RUNTIME === "bun" ? mb : Math.min(mb ?? 1e400, heapLimitMb());
182
+ };
114
183
  const guard = createHeapGuard({
115
184
  ratio,
185
+ collected() {
186
+ const seen = collectedMb;
187
+ collectedMb = void 0;
188
+ const against = measuredAgainst();
189
+ return seen === void 0 || !against ? void 0 : seen / against;
190
+ },
191
+ ceiling: () => RUNTIME === "bun" ? 1 : heapLimitMb() / (measuredAgainst() ?? 1),
192
+ hold: control ? void 0 : () => 1.25,
116
193
  release() {
117
194
  clearQueryEngineCaches();
118
195
  releaseCaches();
119
196
  getDataStore().trimCache?.();
120
197
  }
121
198
  });
122
- /** the budget the guard measured against at its last check (or rebase) */
123
- let guardBudget = budget();
199
+ /** what the guard measured against at its last check */
200
+ let guardBudget = measuredAgainst();
124
201
  /**
125
- * Checks the heap after a batch (see createHeapGuard) against the current budget: a budget cut
126
- * by the adaptive pool – also step by step – is checked at once; the slim nodes follow it, too
202
+ * Checks the heap after a batch (see createHeapGuard) against the current budget: what the
203
+ * guard knows about the heap follows a budget the adaptive pool changed (a lower one applies
204
+ * with this check); the slim nodes follow it, too
127
205
  */
128
206
  const checkHeap = () => {
129
- const now = budget();
130
- let rebased = false;
131
- if (now !== void 0 && guardBudget !== void 0 && now < .9 * guardBudget) {
132
- guard.rebase();
133
- rebased = true;
134
- }
135
- const forSlim = now ?? heapLimitMb();
207
+ const now = measuredAgainst();
208
+ if (now && guardBudget && now !== guardBudget) guard.rescale(guardBudget / now);
209
+ guardBudget = now;
210
+ const forSlim = budget() ?? heapLimitMb();
136
211
  if (Math.abs(forSlim - slimFor) >= .25 * slimFor) setSlimNodesHeap(slimFor = forSlim);
137
212
  const checks = guard.checks;
138
213
  guard.afterBatch();
139
- const checked = guard.checks !== checks;
140
- if (rebased || checked || (now ?? 0) > (guardBudget ?? 0)) guardBudget = now;
141
- if (control && checked) Atomics.store(control, WorkerControl.LIVE, Math.round(heapUsedMb()));
214
+ timings.guard = {
215
+ ms: guard.forcedMs,
216
+ releases: guard.releases
217
+ };
218
+ if (control && guard.checks !== checks) Atomics.store(control, WorkerControl.LIVE, Math.round(heapUsedMb()));
142
219
  publish();
143
220
  };
144
- const clock = () => performance.timeOrigin + performance.now();
145
221
  const emptySpan = () => ({
146
222
  ms: 0,
147
223
  start: 1e400,
@@ -151,11 +227,6 @@ async function main(data) {
151
227
  query: emptySpan(),
152
228
  render: emptySpan()
153
229
  };
154
- const track = (span, start, end = clock(), ms = end - start) => {
155
- span.ms += ms;
156
- span.start = Math.min(span.start, start);
157
- span.end = Math.max(span.end, end);
158
- };
159
230
  const emptyResult = () => ({
160
231
  rendered: 0,
161
232
  skipped: 0,
@@ -310,9 +381,8 @@ async function main(data) {
310
381
  }
311
382
  return out;
312
383
  }
313
- const start = clock();
314
- /** queries that ran after all (missing cached results) count as query time */
315
- let queryMs = 0;
384
+ const rendering = work.begin(timings.render);
385
+ if (!renderThread && wantsRenderThread(false)) renderer = await startRenderThreadFor(job.renderer) ?? renderer;
316
386
  let tasks = [];
317
387
  let taskChars = 0;
318
388
  const renderTasks = async () => {
@@ -322,57 +392,66 @@ async function main(data) {
322
392
  taskChars = 0;
323
393
  await dirs?.ensure(outputDirs(chunk));
324
394
  const res = await renderer.renderBatch(chunk);
395
+ if (renderThread) {
396
+ const { gcMs, cpuMs } = renderThread.takeStats();
397
+ timings.render.gcMs = (timings.render.gcMs ?? 0) + gcMs;
398
+ if (cpuMs !== void 0) timings.render.cpuMs = (timings.render.cpuMs ?? 0) + cpuMs;
399
+ }
325
400
  publish();
326
401
  out.rendered += res.rendered;
327
402
  out.errors.push(...res.errors);
328
403
  };
329
- for (let item of items) {
330
- const { page } = item;
331
- let digest = htmlDigest(page, item.resultHash);
332
- if (job.previousSsrHash === job.ssrHash && item.previous === digest && !htmlRemovedEachBuild(page.path)) {
404
+ try {
405
+ for (let item of items) {
406
+ const { page } = item;
407
+ let digest = htmlDigest(page, item.resultHash);
408
+ if (job.previousSsrHash === job.ssrHash && item.previous === digest && !htmlRemovedEachBuild(page.path)) {
409
+ out.digests[page.path] = digest;
410
+ out.skipped++;
411
+ continue;
412
+ }
413
+ const htmlFile = generateHtmlPath(job.publicDir, page.path);
414
+ const pageDataFile = generatePageDataPath(job.publicDir, page.path);
415
+ const cached = item.resultJson === void 0 ? readCachedResult(job.publicDir, page) : void 0;
416
+ let resultJson = item.resultJson ?? cached?.resultJson;
417
+ if (cached) readChars += cached.resultJson.length;
418
+ if (resultJson === void 0) {
419
+ const querying = work.begin(timings.query);
420
+ let ran;
421
+ try {
422
+ ran = await runQuery(page, queryOut);
423
+ } finally {
424
+ work.end(querying);
425
+ }
426
+ if (!ran) continue;
427
+ item = {
428
+ ...ran,
429
+ previous: item.previous
430
+ };
431
+ resultJson = item.resultJson;
432
+ digest = htmlDigest(page, item.resultHash);
433
+ }
333
434
  out.digests[page.path] = digest;
334
- out.skipped++;
335
- continue;
336
- }
337
- const htmlFile = generateHtmlPath(job.publicDir, page.path);
338
- const pageDataFile = generatePageDataPath(job.publicDir, page.path);
339
- const cached = item.resultJson === void 0 ? readCachedResult(job.publicDir, page) : void 0;
340
- let resultJson = item.resultJson ?? cached?.resultJson;
341
- if (cached) readChars += cached.resultJson.length;
342
- if (resultJson === void 0) {
343
- const t = clock();
344
- const ran = await runQuery(page, queryOut);
345
- const tEnd = clock();
346
- track(timings.query, t, tEnd);
347
- queryMs += tEnd - t;
348
- if (!ran) continue;
349
- item = {
350
- ...ran,
351
- previous: item.previous
352
- };
353
- resultJson = item.resultJson;
354
- digest = htmlDigest(page, item.resultHash);
435
+ const fixed = page.path === "/" ? "index" : page.path.replace(/^\/|\/$/g, "");
436
+ tasks.push({
437
+ pagePath: page.path,
438
+ componentChunkName: page.componentChunkName,
439
+ matchPath: page.matchPath,
440
+ resultJson,
441
+ assets: assets.forComponents([page.componentPath]),
442
+ pageDataUrl: `${job.pagePrefix}/page-data/${fixed}/page-data.json`,
443
+ htmlFile,
444
+ pageDataFile,
445
+ pageDataStaticQueryHashes: cached?.staticQueryHashes,
446
+ filesExist: job.outputFiles === "any" || job.outputFiles === "listed" && item.previous !== void 0
447
+ });
448
+ taskChars += resultJson.length;
449
+ if (tasks.length >= RENDER_CHUNK || taskChars >= RENDER_CHUNK_CHARS) await renderTasks();
355
450
  }
356
- out.digests[page.path] = digest;
357
- const fixed = page.path === "/" ? "index" : page.path.replace(/^\/|\/$/g, "");
358
- tasks.push({
359
- pagePath: page.path,
360
- componentChunkName: page.componentChunkName,
361
- matchPath: page.matchPath,
362
- resultJson,
363
- assets: assets.forComponents([page.componentPath]),
364
- pageDataUrl: `${job.pagePrefix}/page-data/${fixed}/page-data.json`,
365
- htmlFile,
366
- pageDataFile,
367
- pageDataStaticQueryHashes: cached?.staticQueryHashes,
368
- filesExist: job.outputFiles === "any" || job.outputFiles === "listed" && item.previous !== void 0
369
- });
370
- taskChars += resultJson.length;
371
- if (tasks.length >= RENDER_CHUNK || taskChars >= RENDER_CHUNK_CHARS) await renderTasks();
451
+ await renderTasks();
452
+ } finally {
453
+ work.end(rendering);
372
454
  }
373
- await renderTasks();
374
- const end = clock();
375
- track(timings.render, start, end, end - start - queryMs);
376
455
  return out;
377
456
  }
378
457
  const reply = (id, result = {}) => port.postMessage({
@@ -398,34 +477,37 @@ async function main(data) {
398
477
  async function handle(msg) {
399
478
  if (msg.type === "query") {
400
479
  const out = queryOutput();
401
- const tQuery = clock();
480
+ const querying = work.begin(timings.query);
402
481
  const ran = Array.from({ length: msg.items.length });
403
- const done = wasm && wasmModule ? await runWasm(wasm, wasmModule, msg.items, ran, out) : void 0;
404
- let next = 0;
405
- const runNext = async () => {
406
- while (next < msg.items.length) {
407
- const i = next++;
408
- if (done?.has(i)) continue;
409
- const item = msg.items[i];
410
- if (item.resultHash !== void 0) {
411
- ran[i] = {
412
- page: item.page,
413
- resultHash: item.resultHash,
482
+ try {
483
+ const done = wasm && wasmModule ? await runWasm(wasm, wasmModule, msg.items, ran, out) : void 0;
484
+ let next = 0;
485
+ const runNext = async () => {
486
+ while (next < msg.items.length) {
487
+ const i = next++;
488
+ if (done?.has(i)) continue;
489
+ const item = msg.items[i];
490
+ if (item.resultHash !== void 0) {
491
+ ran[i] = {
492
+ page: item.page,
493
+ resultHash: item.resultHash,
494
+ previous: item.previous
495
+ };
496
+ continue;
497
+ }
498
+ const result = await runQuery(item.page, out);
499
+ publish();
500
+ ran[i] = result && {
501
+ ...result,
414
502
  previous: item.previous
415
503
  };
416
- continue;
417
504
  }
418
- const result = await runQuery(item.page, out);
419
- publish();
420
- ran[i] = result && {
421
- ...result,
422
- previous: item.previous
423
- };
424
- }
425
- };
426
- await Promise.all(Array.from({ length: Math.min(QUERY_CONCURRENCY, msg.items.length) }, runNext));
505
+ };
506
+ await Promise.all(Array.from({ length: Math.min(QUERY_CONCURRENCY, msg.items.length) }, runNext));
507
+ } finally {
508
+ work.end(querying, out.queries.length > 0 || out.deferred.length > 0);
509
+ }
427
510
  const items = ran.filter((item) => item !== void 0);
428
- if (out.queries.length || out.deferred.length) track(timings.query, tQuery);
429
511
  let bytes = 0;
430
512
  for (const item of items) bytes += itemBytes(item);
431
513
  if (job) {
@@ -459,17 +541,19 @@ async function main(data) {
459
541
  return;
460
542
  }
461
543
  if (msg.type === "render") {
462
- const tSetup = clock();
544
+ const setup = work.begin(timings.render);
463
545
  job = msg.job;
464
546
  dirs = void 0;
547
+ await renderThread?.close();
548
+ renderThread = void 0;
465
549
  try {
466
550
  assets = new AssetResolver(job.manifest, job.root, job.base);
467
- renderer = await createRenderer(job.renderer);
551
+ renderer = (wantsRenderThread(true) ? await startRenderThreadFor(job.renderer) : void 0) ?? await createRenderer(job.renderer);
468
552
  dirs = createDirectoryMaker(job.publicDir);
469
553
  } catch (e) {
470
554
  setupError = e instanceof Error ? e : new Error(String(e));
471
555
  }
472
- track(timings.render, tSetup);
556
+ work.end(setup);
473
557
  reply(msg.id);
474
558
  return;
475
559
  }
@@ -493,9 +577,15 @@ async function main(data) {
493
577
  }
494
578
  if (msg.type === "finish") {
495
579
  wasm?.detach();
580
+ await renderThread?.close();
496
581
  persistCaches();
497
582
  finishCaches();
498
- if (guard.releases) reporter.verbose(`query worker ${data.workerId} dropped its caches ${guard.releases} time(s): its heap was full${budget() ? ` (budget ${data.heapBudgetMb && data.heapBudgetMb !== budget() ? `${data.heapBudgetMb} → ` : ""}${budget()} MB)` : ""}`);
583
+ gcWatch.close();
584
+ if (guard.checks) {
585
+ const budgetText = budget() ? ` (budget ${data.heapBudgetMb && data.heapBudgetMb !== budget() ? `${data.heapBudgetMb} → ` : ""}${budget()} MB)` : "";
586
+ const skipped = guard.skipped ? `, ${guard.skipped} left out (they had taken their share of its time)` : "";
587
+ reporter.verbose(`query worker ${data.workerId} ${guard.releases ? `dropped its caches ${guard.releases} time(s): its heap was full` : "checked its heap"}${budgetText} – ${guard.checks} forced collection(s), ${(guard.forcedMs / 1e3).toFixed(3)}s${skipped}`);
588
+ }
499
589
  port.postMessage({
500
590
  type: "finished",
501
591
  id: msg.id,
@@ -46,11 +46,22 @@ const limitText = (mb) => mb ? `${mb} MB` : "no limit";
46
46
  * nodes include SitePage nodes)
47
47
  */
48
48
  function mergeRunResults(first, second) {
49
- const span = (a, b) => ({
50
- ms: a.ms + b.ms,
51
- start: Math.min(a.start, b.start),
52
- end: Math.max(a.end, b.end)
53
- });
49
+ const span = (a, b) => {
50
+ const sum = {
51
+ ms: 0,
52
+ start: 1e400,
53
+ end: -1e400
54
+ };
55
+ addSpan(sum, a);
56
+ addSpan(sum, b);
57
+ return sum;
58
+ };
59
+ const guard = {
60
+ ms: 0,
61
+ releases: 0
62
+ };
63
+ addGuard(guard, first.timings.guard);
64
+ addGuard(guard, second.timings.guard);
54
65
  return {
55
66
  queryErrors: [...first.queryErrors, ...second.queryErrors],
56
67
  queries: [...first.queries, ...second.queries],
@@ -66,6 +77,7 @@ function mergeRunResults(first, second) {
66
77
  timings: {
67
78
  query: span(first.timings.query, second.timings.query),
68
79
  render: span(first.timings.render, second.timings.render),
80
+ ...first.timings.guard || second.timings.guard ? { guard } : {},
69
81
  ready: first.timings.ready,
70
82
  handled: Math.max(first.timings.handled, second.timings.handled),
71
83
  renderJob: first.timings.renderJob || second.timings.renderJob
@@ -84,6 +96,19 @@ function mergeRunResults(first, second) {
84
96
  }
85
97
  };
86
98
  }
99
+ /** adds a span to `sum`: busy times add up, the spans are merged */
100
+ function addSpan(sum, span) {
101
+ sum.ms += span.ms;
102
+ sum.start = Math.min(sum.start, span.start);
103
+ sum.end = Math.max(sum.end, span.end);
104
+ if (span.gcMs !== void 0) sum.gcMs = (sum.gcMs ?? 0) + span.gcMs;
105
+ if (span.cpuMs !== void 0) sum.cpuMs = (sum.cpuMs ?? 0) + span.cpuMs;
106
+ }
107
+ function addGuard(sum, guard) {
108
+ if (!guard) return;
109
+ sum.ms += guard.ms;
110
+ sum.releases += guard.releases;
111
+ }
87
112
  const formatMb = (n) => n >= 1024 ? `${(n / 1024).toFixed(1)} GB` : `${Math.max(0, Math.round(n))} MB`;
88
113
  /**
89
114
  * The adaptive pool of a build (see AdaptivePool): `maxWorkers` is the most query workers, the
@@ -255,6 +280,10 @@ function createQueryWorkers(count, data, options) {
255
280
  settleStarting(slot);
256
281
  hooks?.dispatch(slot);
257
282
  } else if (msg.type === "error") die(slot, /* @__PURE__ */ new Error(`query worker failed to start:\n${msg.error}`));
283
+ else if (msg.type === "failed") die(slot, Object.assign(/* @__PURE__ */ new Error(msg.oom ? `query worker: ${msg.error}` : `query worker failed:\n${msg.error}`), msg.oom ? {
284
+ code: OOM,
285
+ renderThread: true
286
+ } : {}));
258
287
  else hooks?.onMessage(slot, msg);
259
288
  });
260
289
  worker.on("error", (e) => die(slot, e instanceof Error ? e : new Error(String(e))));
@@ -312,6 +341,10 @@ function createQueryWorkers(count, data, options) {
312
341
  const timings = {
313
342
  query: span(),
314
343
  render: span(),
344
+ guard: {
345
+ ms: 0,
346
+ releases: 0
347
+ },
315
348
  ready: 0,
316
349
  handled: 0,
317
350
  renderJob: 0
@@ -365,11 +398,8 @@ function createQueryWorkers(count, data, options) {
365
398
  timings.ready = readyAt || lastReadyAt || clock();
366
399
  for (const slot of slots) {
367
400
  if (!slot.timings) continue;
368
- for (const key of ["query", "render"]) {
369
- timings[key].ms += slot.timings[key].ms;
370
- timings[key].start = Math.min(timings[key].start, slot.timings[key].start);
371
- timings[key].end = Math.max(timings[key].end, slot.timings[key].end);
372
- }
401
+ for (const key of ["query", "render"]) addSpan(timings[key], slot.timings[key]);
402
+ addGuard(timings.guard, slot.timings.guard);
373
403
  }
374
404
  resolve({
375
405
  queryErrors: [...queryErrors.values()].flat(),
@@ -800,7 +830,8 @@ function createQueryWorkers(count, data, options) {
800
830
  const lost = others + suspects.length;
801
831
  const where = !s.ready ? " while starting" : suspects.length ? ` while building ${pageList(suspects.map((i) => items[i].page.path))}` : unit?.kind === "render" ? " while loading the renderer" : "";
802
832
  const inMainThread = !replacement && !live().length ? " in the main thread" : "";
803
- reporter.warn(`A query worker ran out of memory (heap limit ${limitText(s.limitMb)})${where}.` + (lost ? ` ${lost} page(s) will be built again${inMainThread}.` : "") + (replacement ? ` Starting a new worker with a heap limit of ${limitText(replacement.limitMb)}.` : ""));
833
+ const who = error.renderThread ? "The render thread of a query worker" : "A query worker";
834
+ reporter.warn(`${who} ran out of memory (heap limit ${limitText(s.limitMb)})${where}.` + (lost ? ` ${lost} page(s) will be built again${inMainThread}.` : "") + (replacement ? ` Starting a new worker with a heap limit of ${limitText(replacement.limitMb)}.` : ""));
804
835
  keepOneWorking();
805
836
  if (!live().length) return done(leftovers());
806
837
  dispatchAll();
@@ -0,0 +1,103 @@
1
+ import { REPORTER_BRIDGE_ENV } from "../reporter.js";
2
+ import { Worker } from "node:worker_threads";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ // src/node/build/render-thread.ts
6
+ const workerFile = path.join(path.dirname(fileURLToPath(import.meta.url)), "render-worker.js");
7
+ const OOM = "ERR_WORKER_OUT_OF_MEMORY";
8
+ /**
9
+ * Starts a render worker (render-worker.ts) for a query worker: a thread that only holds the SSR
10
+ * bundle and the pages of one batch, so that pages are not rendered in a heap that holds node data
11
+ * – there every garbage collection the rendering causes scans that data, too. Batches are rendered
12
+ * one at a time, as by the query worker itself.
13
+ *
14
+ * Resolves once the SSR bundle is loaded, rejects when that fails. When the thread is gone
15
+ * otherwise – out of memory (`oom`), or it exited – `onDeath` is called: the query worker can't
16
+ * go on, batches in flight never settle.
17
+ */
18
+ function startRenderThread(options, o) {
19
+ return new Promise((resolve, reject) => {
20
+ const worker = new Worker(workerFile, {
21
+ workerData: {
22
+ __goatlyRenderWorker: true,
23
+ options
24
+ },
25
+ env: {
26
+ ...process.env,
27
+ ...REPORTER_BRIDGE_ENV,
28
+ NODE_ENV: "production"
29
+ },
30
+ ...o.limitMb ? { resourceLimits: { maxOldGenerationSizeMb: o.limitMb } } : {}
31
+ });
32
+ let ready = false;
33
+ let closed = false;
34
+ let dead = false;
35
+ let nextId = 0;
36
+ const pending = /* @__PURE__ */ new Map();
37
+ let stats = {
38
+ gcMs: 0,
39
+ cpuMs: void 0
40
+ };
41
+ let taken = {
42
+ gcMs: 0,
43
+ cpuMs: 0
44
+ };
45
+ const die = (error) => {
46
+ if (dead || closed) return;
47
+ dead = true;
48
+ worker.terminate();
49
+ o.onDeath(error, error.code === OOM);
50
+ };
51
+ worker.on("message", (msg) => {
52
+ if (msg?.type === "ready") {
53
+ if (msg.error) {
54
+ closed = true;
55
+ worker.terminate();
56
+ return reject(new Error(msg.error));
57
+ }
58
+ ready = true;
59
+ return resolve(thread);
60
+ }
61
+ const batch = pending.get(msg?.id);
62
+ if (!batch) return;
63
+ pending.delete(msg.id);
64
+ if (msg.stats) stats = msg.stats;
65
+ if (msg.error) batch.reject(new Error(msg.error));
66
+ else batch.resolve(msg.result);
67
+ });
68
+ worker.on("error", (e) => die(e instanceof Error ? e : new Error(String(e))));
69
+ worker.on("exit", (code) => die(/* @__PURE__ */ new Error(`render thread exited with code ${code}${ready ? "" : " while starting"}`)));
70
+ const thread = {
71
+ renderBatch(tasks) {
72
+ return new Promise((done, failed) => {
73
+ const id = nextId++;
74
+ pending.set(id, {
75
+ resolve: done,
76
+ reject: failed
77
+ });
78
+ worker.postMessage({
79
+ id,
80
+ tasks
81
+ });
82
+ });
83
+ },
84
+ takeStats() {
85
+ const cpuMs = stats.cpuMs === void 0 ? void 0 : stats.cpuMs - taken.cpuMs;
86
+ const delta = {
87
+ gcMs: stats.gcMs - taken.gcMs,
88
+ cpuMs
89
+ };
90
+ taken = {
91
+ gcMs: stats.gcMs,
92
+ cpuMs: stats.cpuMs ?? 0
93
+ };
94
+ return delta;
95
+ },
96
+ async close() {
97
+ closed = true;
98
+ await worker.terminate();
99
+ }
100
+ };
101
+ });
102
+ }
103
+ export { startRenderThread };