goatly 0.1.0 → 0.1.1

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.
Files changed (158) hide show
  1. package/README.md +853 -1
  2. package/bin/goatly.js +91 -0
  3. package/dist/cli/index.js +234 -0
  4. package/dist/compat/gatsby-node-entry.js +16 -0
  5. package/dist/compat/gatsby-package.json +6 -0
  6. package/dist/compat/md5-file.js +47 -0
  7. package/dist/compat-apis.json +72 -0
  8. package/dist/compat-apis.json.js +62 -0
  9. package/dist/graphql.js +3 -0
  10. package/dist/node/actions/index.js +619 -0
  11. package/dist/node/actions/job-store.js +180 -0
  12. package/dist/node/actions/jobs.js +174 -0
  13. package/dist/node/api-runner.js +258 -0
  14. package/dist/node/bootstrap.js +539 -0
  15. package/dist/node/build/assets.js +110 -0
  16. package/dist/node/build/incremental.js +208 -0
  17. package/dist/node/build/index.js +752 -0
  18. package/dist/node/build/memory-governor.js +448 -0
  19. package/dist/node/build/output-dirs.js +70 -0
  20. package/dist/node/build/page-data.js +40 -0
  21. package/dist/node/build/page-files.js +54 -0
  22. package/dist/node/build/partitioned-state.js +258 -0
  23. package/dist/node/build/query-worker.js +536 -0
  24. package/dist/node/build/query-workers.js +832 -0
  25. package/dist/node/build/render-worker.js +131 -0
  26. package/dist/node/build/state.js +24 -0
  27. package/dist/node/build/timing-breakdown.js +155 -0
  28. package/dist/node/build/worker-pool.js +236 -0
  29. package/dist/node/cache-layout.js +99 -0
  30. package/dist/node/cache.js +1430 -0
  31. package/dist/node/compat/chokidar-shim.js +148 -0
  32. package/dist/node/compat/core-utils-lmdb.js +145 -0
  33. package/dist/node/compat/create-node-id-shim.js +1 -0
  34. package/dist/node/compat/module-hooks.js +245 -0
  35. package/dist/node/compat/redux-shim.js +1 -0
  36. package/dist/node/config/index.js +162 -0
  37. package/dist/node/config/not-found-pages.js +95 -0
  38. package/dist/node/datastore/codec.js +144 -0
  39. package/dist/node/datastore/index.js +127 -0
  40. package/dist/node/datastore/logfile/cache.js +89 -0
  41. package/dist/node/datastore/logfile/index.js +1329 -0
  42. package/dist/node/datastore/logfile/record.js +71 -0
  43. package/dist/node/datastore/types.js +1 -0
  44. package/dist/node/develop/express-compat.js +207 -0
  45. package/dist/node/develop/graphiql.js +22 -0
  46. package/dist/node/develop/hydration-report.js +41 -0
  47. package/dist/node/develop/index.js +618 -0
  48. package/dist/node/develop/local-url.js +10 -0
  49. package/dist/node/develop/ssr-runner.js +66 -0
  50. package/dist/node/gql.js +5 -0
  51. package/dist/node/index.js +15 -0
  52. package/dist/node/info.js +270 -0
  53. package/dist/node/internal-plugins/data-bridge.js +196 -0
  54. package/dist/node/internal-plugins/page-creator.js +318 -0
  55. package/dist/node/loader/import-module.js +160 -0
  56. package/dist/node/node-helpers.js +66 -0
  57. package/dist/node/not-found-pages.js +220 -0
  58. package/dist/node/plugins/api-list.js +12 -0
  59. package/dist/node/plugins/load-plugins.js +427 -0
  60. package/dist/node/plugins/resolve-plugin.js +79 -0
  61. package/dist/node/plugins/static-exports.js +64 -0
  62. package/dist/node/query/compile.js +326 -0
  63. package/dist/node/query/dependencies.js +45 -0
  64. package/dist/node/query/execute.js +417 -0
  65. package/dist/node/query/extract.js +372 -0
  66. package/dist/node/query/gql-tada-introspection.js +124 -0
  67. package/dist/node/query/graphql-env.js +231 -0
  68. package/dist/node/query/graphql-runner.js +79 -0
  69. package/dist/node/redux/actions.js +1 -0
  70. package/dist/node/redux/index.js +133 -0
  71. package/dist/node/redux/node-changes.js +128 -0
  72. package/dist/node/redux/reducers.js +193 -0
  73. package/dist/node/redux/state.js +71 -0
  74. package/dist/node/renderer.js +124 -0
  75. package/dist/node/reporter-transports.js +259 -0
  76. package/dist/node/reporter.js +497 -0
  77. package/dist/node/schema/date.js +539 -0
  78. package/dist/node/schema/extensions.js +315 -0
  79. package/dist/node/schema/index.js +542 -0
  80. package/dist/node/schema/infer.js +388 -0
  81. package/dist/node/schema/inline-objects.js +128 -0
  82. package/dist/node/schema/naming.js +20 -0
  83. package/dist/node/schema/node-model.js +207 -0
  84. package/dist/node/schema/query-engine.js +1808 -0
  85. package/dist/node/schema/resolver-kinds.js +7 -0
  86. package/dist/node/schema/resolvers.js +273 -0
  87. package/dist/node/schema/type-builders.js +45 -0
  88. package/dist/node/schema/types.js +241 -0
  89. package/dist/node/serve.js +90 -0
  90. package/dist/node/site-page-nodes.js +277 -0
  91. package/dist/node/types.js +1 -0
  92. package/dist/node/utils/content-digest.js +107 -0
  93. package/dist/node/utils/create-node-id.js +51 -0
  94. package/dist/node/utils/env.js +24 -0
  95. package/dist/node/utils/fs-retry.js +74 -0
  96. package/dist/node/utils/memory-signals.js +410 -0
  97. package/dist/node/utils/memory.js +400 -0
  98. package/dist/node/utils/murmurhash.js +32 -0
  99. package/dist/node/utils/parser.js +33 -0
  100. package/dist/node/utils/partition-hash.js +19 -0
  101. package/dist/node/utils/paths.js +122 -0
  102. package/dist/node/utils/resolver.js +48 -0
  103. package/dist/node/utils/runtime.js +5 -0
  104. package/dist/node/utils/serializable.js +41 -0
  105. package/dist/node/utils/strings.js +41 -0
  106. package/dist/node/vite/config.js +289 -0
  107. package/dist/node/vite/paths.js +12 -0
  108. package/dist/node/vite/plugin-deps.js +232 -0
  109. package/dist/node/vite/plugin.js +281 -0
  110. package/dist/node/vite/react-compiler.js +362 -0
  111. package/dist/node/vite/source-files.js +83 -0
  112. package/dist/node/vite/static-image.js +136 -0
  113. package/dist/node/vite/styled-components.js +73 -0
  114. package/dist/node/vite/transforms.js +299 -0
  115. package/dist/node/wasm-data/host.js +406 -0
  116. package/dist/node/wasm-data/lower.js +406 -0
  117. package/dist/node/wasm-data/runner.js +79 -0
  118. package/dist/node/wasm-data/worker.js +95 -0
  119. package/dist/reporter.js +5 -0
  120. package/dist/runtime/api-runner.js +81 -0
  121. package/dist/runtime/app.js +256 -0
  122. package/dist/runtime/client-entry.js +4 -0
  123. package/dist/runtime/client.js +383 -0
  124. package/dist/runtime/default-html.js +31 -0
  125. package/dist/runtime/head-markup.js +100 -0
  126. package/dist/runtime/head-sync.js +101 -0
  127. package/dist/runtime/head-tags.js +45 -0
  128. package/dist/runtime/hydration-report.js +111 -0
  129. package/dist/runtime/index.js +12 -0
  130. package/dist/runtime/link.js +293 -0
  131. package/dist/runtime/loader.js +449 -0
  132. package/dist/runtime/not-found.js +61 -0
  133. package/dist/runtime/page-renderer.js +35 -0
  134. package/dist/runtime/preamble.js +47 -0
  135. package/dist/runtime/react-compat.js +14 -0
  136. package/dist/runtime/renderer-shared.js +10 -0
  137. package/dist/runtime/renderers/react-client.js +14 -0
  138. package/dist/runtime/renderers/react-server.js +99 -0
  139. package/dist/runtime/renderers/react.js +17 -0
  140. package/dist/runtime/renderers/types.js +1 -0
  141. package/dist/runtime/root-error-handlers.js +29 -0
  142. package/dist/runtime/router/history.js +132 -0
  143. package/dist/runtime/router/index.js +240 -0
  144. package/dist/runtime/router/utils.js +118 -0
  145. package/dist/runtime/script.js +110 -0
  146. package/dist/runtime/scroll.js +40 -0
  147. package/dist/runtime/slice.js +11 -0
  148. package/dist/runtime/ssr.js +240 -0
  149. package/dist/runtime/static-query.js +47 -0
  150. package/dist/utils.js +4 -0
  151. package/package.json +105 -3
  152. package/types/graphql-tada.d.ts +223 -0
  153. package/types/graphql.d.ts +2 -0
  154. package/types/index.d.ts +2287 -0
  155. package/types/node.d.ts +380 -0
  156. package/types/reporter.d.ts +187 -0
  157. package/types/router.d.ts +102 -0
  158. package/types/vendor/gql-tada.d.ts +2529 -0
@@ -0,0 +1,448 @@
1
+ // src/node/build/memory-governor.ts
2
+ /**
3
+ * The memory governor of the query workers: adjusts a build to the memory that is free now, on a
4
+ * machine other processes share. Every tick (250 ms) the main thread passes it a memory sample
5
+ * and a view of the workers; it decides, cheapest first:
6
+ *
7
+ * 1. each worker's heap budget – the continuous backpressure: a worker measures its heap against
8
+ * it, so it drops its caches, sizes its batches and buffers results by it;
9
+ * 2. squeezing workers (a budget at their current heap: they drop their caches at once);
10
+ * 3. retiring workers (they finish what they hold, then stop) and shedding one (it is stopped at
11
+ * once, its pages are built again) when memory runs out faster than caches can be dropped, or
12
+ * when the system slows down for memory (PSI, macOS's memory pressure);
13
+ * 4. starting one more worker when memory stayed free for a moment and work is left.
14
+ *
15
+ * It controls on capacity, C = A + U: the memory available (A) plus the build's own (U). The
16
+ * build's own growth lowers A as much as it raises U, so only other processes move C – the build
17
+ * can't oscillate against itself. Its pool for the workers' heaps is P = A + ΣH − F − G (H: the
18
+ * workers' heaps, F: the memory it leaves free, G: room for the main thread).
19
+ *
20
+ * F starts at 2S (S: a reserve that grows with how fast other processes took memory) and is
21
+ * lowered step by step towards 1.25 S while the build uses what it has and nothing pushes back: an
22
+ * OS often frees memory only once a process asks for it (it compresses or swaps out idle pages,
23
+ * other programs drop caches on memory pressure), so the free memory alone understates what the
24
+ * build can get. Trouble – memory pressure, other processes taking memory – hands back half of
25
+ * what was taken every second (A below S, the system slowing down a lot: all of it at once), and
26
+ * while the system keeps slowing down F rises beyond 2 S, up to 3 S. S itself is never given up:
27
+ * below it the build stops workers.
28
+ *
29
+ * What a worker needs, N, sets how many fit (one more starts when P / (n + 1) ≥ N, workers retire
30
+ * when P / n < N). Until the workers report, it is a prior: 512 MB when the page queries run in
31
+ * JS (a worker's heap holds the nodes and caches its queries read), 256 MB when they run in WASM
32
+ * (the nodes are in the main thread's shared store: a worker holds its renderer and its pages'
33
+ * results). In WASM it then follows the reports, once a ready worker reported for 5 s with the
34
+ * bundles built (its renderer loaded): 1.25 × the decaying peak of a ready worker's live heap and
35
+ * WASM memory, plus what a worker takes beside them (its thread, V8's young generation and code:
36
+ * ~32 MB), at least 64 MB – about 75–135 MB for 20k–100k pages (Bun: 1.7 × plus 64 MB, never below
37
+ * the prior). In JS the reports only raise it (1.25 × a worker's live heap).
38
+ *
39
+ * Pure: no I/O, no timers – the inputs carry the time (deterministic, tested against a model).
40
+ */
41
+ /**
42
+ * The Int32 slots of a query worker's control word (a SharedArrayBuffer of CONTROL_SLOTS × 4
43
+ * bytes): BUDGET (MB) is written by the main thread (0: the worker's `heapBudgetMb`), HEAP (MB,
44
+ * after every query and render chunk), LIVE (MB after its last heap check) and BEAT (a counter) by
45
+ * the worker. A lower budget takes effect at the worker's next heap check, without a message.
46
+ * WASM (MB) is the worker's private WASM memory (the WASM data side of the page queries: its input
47
+ * and output buffers; the shared store is the main thread's), counted with its heap.
48
+ */
49
+ const WorkerControl = {
50
+ BUDGET: 0,
51
+ HEAP: 1,
52
+ LIVE: 2,
53
+ BEAT: 3,
54
+ WASM: 4
55
+ };
56
+ const CONTROL_SLOTS = 5;
57
+ /** the tick (s) the governor is made for */
58
+ const TICK = .25;
59
+ /** below this the fall rate of the capacity (MB/s) is noise */
60
+ const RATE_DEADBAND = 128;
61
+ /** half-life (s) of the peak fall rate */
62
+ const PEAK_HALF_LIFE = 120;
63
+ /** least / most worker budget step (MB): budgets are multiples */
64
+ const BUDGET_STEP = 64;
65
+ const MIN_BUDGET = 256;
66
+ /** budgets rise by at most this factor per tick (cuts are at once) */
67
+ const RAISE = 1.05;
68
+ /** main thread's room (MB) while Vite bundles / after */
69
+ const MAIN_ROOM_BUNDLING = 512;
70
+ const MAIN_ROOM = 256;
71
+ /** a worker is squeezed / pinged at most every (s) */
72
+ const SQUEEZE_EVERY = 2;
73
+ /** spawn: green for (s), since the last worker became ready (s) */
74
+ const SPAWN_GREEN = 2;
75
+ /** spawn: at least this much work (s at the current rate) is left – a start takes a few seconds */
76
+ const SPAWN_WORK = 10;
77
+ /** what a worker takes while it starts (MB), before the others dropped their caches for it */
78
+ const STARTING_MB = 256;
79
+ /** spawn cooldown after a retire or shed (s): from, after a shed, at most */
80
+ const COOLDOWN = 20;
81
+ const COOLDOWN_SHED = 60;
82
+ const COOLDOWN_MAX = 320;
83
+ /** a retire or shed within this (s) after a spawn doubles the cooldown; calm this long halves it */
84
+ const FLAP_WINDOW = 60;
85
+ const CALM = 120;
86
+ /** PSI "some" share (last 10 s) above which memory is under pressure (no raise, no spawn) */
87
+ const PSI_PRESSURE = .05;
88
+ /** PSI "some" share (last 2 s) at which the system slows down for memory: a worker retires */
89
+ const PSI_HEAVY = .2;
90
+ /**
91
+ * probe: the memory left free F goes from 2 × the reserve down to PROBE_FLOOR × the reserve, by
92
+ * PROBE_STEP MB every PROBE_EVERY s; trouble halves what was taken (at most every PROBE_EVERY s)
93
+ * and holds the next step back for PROBE_HOLD s, while the system slows down F rises a step every
94
+ * PROBE_EVERY s, up to PROBE_CEIL × the reserve. When the system slowed down, the probe goes half
95
+ * as far from then on – a step further for every PROBE_RECOVER s without trouble.
96
+ */
97
+ const PROBE_FLOOR = 1.25;
98
+ const PROBE_CEIL = 3;
99
+ const PROBE_STEP = BUDGET_STEP;
100
+ /**
101
+ * the need a worker learned (learnNeed): NEED_MARGIN × the peak of a ready worker's live heap and
102
+ * WASM memory (half-life NEED_HALF_LIFE s) plus WORKER_OVERHEAD MB for what the reports don't
103
+ * count – its thread's stack, V8's young generation and code space (measured on Node: a worker adds
104
+ * ~90 MB of RSS next to ~60 MB of heap) – at least NEED_FLOOR MB. It replaces the prior once a ready
105
+ * worker reported for NEED_LEARN s after the bundles were built (before, the higher of both: until
106
+ * then a worker hasn't loaded its renderer). Bun (not measured: a worker's RSS is ~1.7 × its heap,
107
+ * and a JSC VM beside it) has a larger margin and overhead, and the prior stays the least.
108
+ */
109
+ const NEED_MARGIN = {
110
+ node: 1.25,
111
+ bun: 1.7
112
+ };
113
+ const NEED_HALF_LIFE = 60;
114
+ const WORKER_OVERHEAD = {
115
+ node: 32,
116
+ bun: 64
117
+ };
118
+ const NEED_FLOOR = BUDGET_STEP;
119
+ const ceil64 = (mb) => Math.ceil(mb / BUDGET_STEP) * BUDGET_STEP;
120
+ /** a budget of at least MIN_BUDGET – unless the worker's cap is lower (e.g. a limit the user set) */
121
+ const withinCap = (mb, capMb) => Math.min(capMb, Math.max(256, mb));
122
+ const floor64 = (mb) => Math.floor(mb / BUDGET_STEP) * BUDGET_STEP;
123
+ const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
124
+ function createMemoryGovernor(options) {
125
+ const scale = options.timeScale && options.timeScale > 0 ? options.timeScale : 1;
126
+ const killLatency = options.runtime === "bun" ? .25 : .05;
127
+ /** capacity, pool and PSI by time (s) – the last 10 s */
128
+ const history = [];
129
+ let lastT;
130
+ let peak = 0;
131
+ let lagPeak = 0;
132
+ let greenSince;
133
+ let lowSince;
134
+ let lastShed = -1e400;
135
+ let lastRetire = -1e400;
136
+ let lastDown = -1e400;
137
+ let lastSpawn = -1e400;
138
+ let lastReady = -1e400;
139
+ let lastCalm = -1e400;
140
+ let cooldown = COOLDOWN;
141
+ let spawns = 0;
142
+ /**
143
+ * probe: the memory (MB) taken beyond what 2 × the reserve leaves free (< 0: given back while the
144
+ * system slows down); its last step and the last trouble
145
+ */
146
+ let probeMb = 0;
147
+ let lastProbe = -1e400;
148
+ let lastTrouble = -1e400;
149
+ /** how far the probe may go (MB): half of where the system slowed down, recovering slowly */
150
+ let probeCap = 1e400;
151
+ let slowed = false;
152
+ let lastRecover = -1e400;
153
+ let heavySince;
154
+ let lastPressureRetire = -1e400;
155
+ /**
156
+ * the need's prior (MB), whether it follows the reports, their peak (MB) and since when (s) they
157
+ * came with the bundles built
158
+ */
159
+ let prior = options.needMb;
160
+ let learn = !!options.learnNeed;
161
+ let peakLive = 0;
162
+ let reportedSince;
163
+ const live = /* @__PURE__ */ new Map();
164
+ const lastSqueeze = /* @__PURE__ */ new Map();
165
+ const lastPing = /* @__PURE__ */ new Map();
166
+ const starting = /* @__PURE__ */ new Set();
167
+ let state;
168
+ /** seconds of the governor's clock */
169
+ const secs = (ms) => ms / 1e3 / scale;
170
+ function reserveFor(limitMb) {
171
+ return options.reserveMb ?? clamp(Math.round(.03 * limitMb), 512, 1536);
172
+ }
173
+ /** the reserve now: more after fast drops (at most a quarter of the memory – not the user's) */
174
+ function reserveNow(limitMb, peakRate, reactS) {
175
+ const grown = Math.min(.25 * limitMb, Math.max(reserveFor(limitMb), peakRate * reactS));
176
+ return Math.max(options.reserveMb ?? 0, grown);
177
+ }
178
+ /** what a worker needs (MB) at `t` (s), before the live sizes of the workers in JS */
179
+ function baseNeed(t) {
180
+ if (!learn) return prior;
181
+ const rt = options.runtime === "bun" ? "bun" : "node";
182
+ const learned = Math.max(NEED_FLOOR, NEED_MARGIN[rt] * peakLive + WORKER_OVERHEAD[rt]);
183
+ return rt === "node" && reportedSince !== void 0 && t !== void 0 && t - reportedSince >= 4.999999999 ? learned : Math.max(prior, learned);
184
+ }
185
+ /** the fall rate of C over the last second (MB/s, 0 within the deadband) */
186
+ function fallRate(t, c) {
187
+ let then;
188
+ for (const h of history) if (h.t >= t - 1) {
189
+ then = h;
190
+ break;
191
+ }
192
+ if (!then || t - then.t <= 0) return 0;
193
+ const rate = (then.c - c) / Math.max(t - then.t, TICK);
194
+ return rate > RATE_DEADBAND ? rate : 0;
195
+ }
196
+ /** the share of the last `window` s some task stalled for memory (PSI "some") */
197
+ function psiShare(t, psi, window) {
198
+ if (psi === void 0) return 0;
199
+ const then = history.find((h) => h.t >= t - window && h.psi !== void 0);
200
+ if (!then || t - then.t <= 0) return 0;
201
+ return (psi - then.psi) / 1e6 / ((t - then.t) * scale);
202
+ }
203
+ function assess(input, t, rate, peakRate) {
204
+ const { availMb: a, ownMb: u, limitMb: l } = input.sample;
205
+ const reactS = clamp(TICK + lagPeak + secs(input.sample.ageMs) + killLatency, .5, 3);
206
+ const reserve = reserveNow(l, peakRate, reactS);
207
+ const mainRoom = input.bundlesReady ? MAIN_ROOM : MAIN_ROOM_BUNDLING;
208
+ let heaps = 0;
209
+ let retiring = 0;
210
+ let need = baseNeed(t);
211
+ for (const w of input.workers) {
212
+ if (w.finished) continue;
213
+ if (w.retiring) {
214
+ retiring += w.heapMb;
215
+ continue;
216
+ }
217
+ heaps += w.heapMb;
218
+ const x = live.get(w.id);
219
+ if (x !== void 0 && !learn) need = Math.max(need, 1.25 * x);
220
+ }
221
+ const free = freeTarget(reserve);
222
+ const pool = a + heaps - free - mainRoom;
223
+ const zone = a - rate * reactS < reserve ? "red" : a - rate * 1 < free ? "yellow" : "green";
224
+ const level = input.sample.pressureLevel;
225
+ return {
226
+ zone,
227
+ capacityMb: a + u,
228
+ fallRate: rate,
229
+ peakFallRate: peakRate,
230
+ reserveMb: reserve,
231
+ mainRoomMb: mainRoom,
232
+ freeTargetMb: free,
233
+ poolMb: pool,
234
+ effectivePoolMb: pool - rate * 1,
235
+ retiringMb: retiring,
236
+ needMb: need,
237
+ pressure: level !== void 0 && level !== "normal" || psiShare(t, input.sample.psiSomeUs, 10) > PSI_PRESSURE,
238
+ heavyPressure: level === "critical" || psiShare(t, input.sample.psiSomeUs, 2) > PSI_HEAVY
239
+ };
240
+ }
241
+ /** the memory (MB) the build leaves free: 2 × the reserve, less what the probe took */
242
+ function freeTarget(reserve) {
243
+ return clamp(2 * reserve - probeMb, PROBE_FLOOR * reserve, PROBE_CEIL * reserve);
244
+ }
245
+ return {
246
+ get state() {
247
+ return state;
248
+ },
249
+ get cooldown() {
250
+ return cooldown;
251
+ },
252
+ /**
253
+ * the prior of what a worker needs (MB), and whether the need follows the workers' reports also
254
+ * below it (the page queries of the next run run in WASM) – the reports so far are kept
255
+ */
256
+ setNeed(needMb, learnNeed) {
257
+ prior = needMb;
258
+ learn = learnNeed;
259
+ },
260
+ /**
261
+ * how many workers to start with (0: none fits – the main thread builds): those that fit into
262
+ * the free memory now (with room for what a worker takes beside its heap); more start during
263
+ * the run as memory turns out to be there
264
+ */
265
+ initialCount(sample, bundlesReady = false) {
266
+ const room = sample.availMb - 2 * reserveFor(sample.limitMb) - (bundlesReady ? MAIN_ROOM : MAIN_ROOM_BUNDLING);
267
+ return clamp(Math.floor(room / (1.25 * baseNeed(lastT))), 0, options.maxWorkers);
268
+ },
269
+ /** the budget (MB) of a worker that starts now, next to `others` */
270
+ initialBudget(sample, workers, capMb, bundlesReady = false) {
271
+ const room = sample.availMb - (state?.freeTargetMb ?? 2 * reserveFor(sample.limitMb)) - (bundlesReady ? MAIN_ROOM : MAIN_ROOM_BUNDLING);
272
+ return withinCap(floor64(room / Math.max(1, workers)), capMb);
273
+ },
274
+ /** whether a worker that ran out of memory may be replaced now */
275
+ admitRespawn(input) {
276
+ const t = secs(input.t);
277
+ const s = assess(input, t, fallRate(t, input.sample.availMb + input.sample.ownMb), peak);
278
+ if (s.zone === "red") return false;
279
+ const n = input.workers.filter((w) => !w.retiring && !w.finished).length;
280
+ return s.effectivePoolMb / (n + 1) >= s.needMb || n === 0 && input.sample.availMb >= s.reserveMb + s.needMb;
281
+ },
282
+ step(input) {
283
+ const t = secs(input.t);
284
+ const dt = lastT === void 0 ? TICK : t - lastT;
285
+ lastT = t;
286
+ lagPeak = Math.max(dt - TICK, lagPeak * Math.pow(.5, dt / 30));
287
+ const c = input.sample.availMb + input.sample.ownMb;
288
+ const rate = fallRate(t, c);
289
+ peak = Math.max(rate, peak * Math.pow(.5, dt / PEAK_HALF_LIFE));
290
+ let reported = 0;
291
+ let any = false;
292
+ for (const w of input.workers) {
293
+ if (w.starting) {
294
+ starting.add(w.id);
295
+ continue;
296
+ }
297
+ if (starting.delete(w.id)) lastReady = t;
298
+ const x = Math.max(0, w.liveMb - w.bufferedMb);
299
+ const prev = live.get(w.id);
300
+ live.set(w.id, prev === void 0 ? x : .75 * prev + .25 * x);
301
+ if (w.finished) continue;
302
+ reported = Math.max(reported, x);
303
+ any = true;
304
+ }
305
+ peakLive = Math.max(reported, peakLive * Math.pow(.5, dt / NEED_HALF_LIFE));
306
+ if (any && input.bundlesReady) reportedSince ??= t;
307
+ const ids = new Set(input.workers.map((w) => w.id));
308
+ for (const map of [
309
+ live,
310
+ lastSqueeze,
311
+ lastPing
312
+ ]) for (const id of map.keys()) if (!ids.has(id)) map.delete(id);
313
+ for (const id of starting) if (!ids.has(id)) starting.delete(id);
314
+ const s = assess(input, t, rate, peak);
315
+ state = s;
316
+ history.push({
317
+ t,
318
+ c,
319
+ p: s.poolMb,
320
+ psi: input.sample.psiSomeUs
321
+ });
322
+ while (history.length && history[0].t < t - 10) history.shift();
323
+ if (s.zone === "green") greenSince ??= t;
324
+ else greenSince = void 0;
325
+ if (s.zone === "green") lowSince = void 0;
326
+ else lowSince ??= t;
327
+ const a = input.sample.availMb;
328
+ const decision = {
329
+ zone: s.zone,
330
+ budgets: /* @__PURE__ */ new Map(),
331
+ ping: [],
332
+ retire: [],
333
+ spawn: false,
334
+ note: ""
335
+ };
336
+ const notes = [];
337
+ const down = () => {
338
+ if (t - lastSpawn < FLAP_WINDOW) cooldown = Math.min(COOLDOWN_MAX, cooldown * 2);
339
+ lastDown = t;
340
+ };
341
+ let workers = input.workers;
342
+ const shedEvery = options.runtime === "bun" ? 2 * TICK : TICK;
343
+ if (s.zone === "red" && t - lastShed >= shedEvery - 1e-9) {
344
+ const candidates = workers.filter((w) => w.unit !== "finish" && !w.finished && !w.finalAttempt);
345
+ const building = workers.filter((w) => w.unit !== "finish" && !w.finished).length;
346
+ if (candidates.length && (building > 1 || a < s.reserveMb / 2)) {
347
+ const victim = candidates.reduce((best, w) => w.heapMb > best.heapMb || w.heapMb === best.heapMb && (Number(w.retiring) > Number(best.retiring) || w.retiring === best.retiring && w.bufferedMb < best.bufferedMb) ? w : best);
348
+ const atPost = victim.unitHeapMb ?? victim.heapMb;
349
+ const budgetAtPost = victim.unitBudgetMb ?? victim.budgetMb;
350
+ const own = victim.heapMb - atPost > Math.max(512, .5 * budgetAtPost) && victim.heapMb > 1.25 * Math.max(budgetAtPost, options.needMb);
351
+ decision.shed = {
352
+ id: victim.id,
353
+ own
354
+ };
355
+ notes.push(`stopped a worker (${Math.round(victim.heapMb)} MB)`);
356
+ workers = workers.filter((w) => w !== victim);
357
+ lastShed = t;
358
+ down();
359
+ cooldown = Math.max(cooldown, COOLDOWN_SHED);
360
+ }
361
+ }
362
+ const active = workers.filter((w) => !w.retiring && !w.finished);
363
+ const n = Math.max(1, active.length);
364
+ const share = floor64(s.effectivePoolMb / n);
365
+ const raise = s.zone === "green" && !s.pressure;
366
+ let squeezed = 0;
367
+ for (const w of workers) {
368
+ if (w.finished) continue;
369
+ const cur = w.budgetMb;
370
+ const target = withinCap(share, w.capMb);
371
+ let next = Math.min(cur, w.capMb);
372
+ if (w.retiring) next = Math.min(next, withinCap(ceil64(w.heapMb), w.capMb));
373
+ else if (target < cur) next = target;
374
+ else if (raise) next = Math.min(target, Math.max(cur, ceil64(cur * RAISE)));
375
+ let squeeze = false;
376
+ if (s.zone !== "green" && !w.starting && !w.retiring && w.unit !== "finish" && t - (lastSqueeze.get(w.id) ?? -1e400) >= SQUEEZE_EVERY) {
377
+ next = Math.min(next, withinCap(ceil64(w.heapMb), w.capMb));
378
+ lastSqueeze.set(w.id, t);
379
+ squeeze = true;
380
+ squeezed++;
381
+ }
382
+ decision.budgets.set(w.id, next);
383
+ if ((squeeze || next <= .75 * cur) && !w.unit && !w.starting && t - (lastPing.get(w.id) ?? -1e400) >= SQUEEZE_EVERY) {
384
+ decision.ping.push(w.id);
385
+ lastPing.set(w.id, t);
386
+ }
387
+ }
388
+ if (squeezed) notes.push(`squeezed ${squeezed} worker(s)`);
389
+ const order = active.filter((w) => !w.finalAttempt && w.unit !== "finish").sort((x, y) => Number(y.starting) - Number(x.starting) || Number(x.bufferedMb > 0) - Number(y.bufferedMb > 0) || y.heapMb - x.heapMb);
390
+ if (s.heavyPressure) heavySince ??= t;
391
+ else heavySince = void 0;
392
+ let byPressure = false;
393
+ if (lowSince !== void 0 && t - lowSince >= .999999999 && t - lastRetire >= 1.999999999 && active.length >= 2 && (s.effectivePoolMb + s.retiringMb) / active.length < s.needMb) {
394
+ const keep = Math.max(1, Math.floor((s.effectivePoolMb + s.retiringMb) / s.needMb));
395
+ const k = Math.min(Math.ceil(active.length / 2), active.length - keep);
396
+ decision.retire = order.slice(0, Math.max(0, k)).map((w) => w.id);
397
+ } else if (heavySince !== void 0 && t - heavySince >= .999999999 && t - Math.max(lastRetire, lastPressureRetire) >= 4.999999999 && active.length >= 2 && !workers.some((w) => w.retiring && !w.finished)) {
398
+ decision.retire = order.slice(0, 1).map((w) => w.id);
399
+ byPressure = decision.retire.length > 0;
400
+ if (byPressure) lastPressureRetire = t;
401
+ }
402
+ if (decision.retire.length) {
403
+ notes.push(`retiring ${decision.retire.length} worker(s)${byPressure ? " (memory pressure)" : ""}`);
404
+ lastRetire = t;
405
+ down();
406
+ }
407
+ const recentPool = Math.min(...history.filter((h) => h.t >= t - SPAWN_GREEN).map((h) => h.p));
408
+ const count = active.length;
409
+ const wantsWorker = count < options.maxWorkers && input.pending >= Math.max(50 * (count + 1), SPAWN_WORK * scale * input.queriedPerSec);
410
+ const fits = recentPool / (count + 1) >= s.needMb;
411
+ if (!decision.shed && !decision.retire.length && !workers.some((w) => w.starting) && spawns < 4 * options.maxWorkers + 4 && t - lastReady >= 2.999999999 && t - lastDown >= cooldown - 1e-9 && greenSince !== void 0 && t - greenSince >= 1.999999999 && wantsWorker && fits && a - s.fallRate * 1 - STARTING_MB >= s.reserveMb && !s.pressure) {
412
+ decision.spawn = true;
413
+ spawns++;
414
+ lastSpawn = t;
415
+ notes.push("starting a worker");
416
+ }
417
+ const wantsMemory = wantsWorker && !fits || active.some((w) => !w.starting && w.budgetMb < w.capMb && w.heapMb >= .75 * w.budgetMb);
418
+ const slowing = s.pressure || s.heavyPressure;
419
+ const trouble = s.zone === "red" || slowing || s.fallRate > 0;
420
+ if (slowing && !slowed) probeCap = floor64(Math.max(0, probeMb) / 2);
421
+ slowed = slowing;
422
+ if (!trouble && probeCap < 1e400 && t - Math.max(lastTrouble, lastRecover) >= 29.999999999) {
423
+ probeCap += PROBE_STEP;
424
+ lastRecover = t;
425
+ }
426
+ const maxProbe = Math.min(probeCap, .75 * s.reserveMb);
427
+ const minProbe = -1 * s.reserveMb;
428
+ probeMb = clamp(probeMb, minProbe, maxProbe);
429
+ const stepDue = t - lastProbe >= .999999999;
430
+ if (trouble) lastTrouble = t;
431
+ if (s.zone === "red" || s.heavyPressure) probeMb = Math.min(probeMb, 0);
432
+ if (trouble && stepDue && (probeMb > 0 || slowing)) {
433
+ probeMb = probeMb > 0 ? floor64(probeMb / 2) : Math.max(minProbe, probeMb - PROBE_STEP);
434
+ lastProbe = t;
435
+ } else if (!trouble && stepDue && s.zone === "green" && t - lastTrouble >= 19.999999999 && (probeMb < 0 || wantsMemory && probeMb < maxProbe)) {
436
+ probeMb = Math.min(maxProbe, probeMb + PROBE_STEP);
437
+ lastProbe = t;
438
+ }
439
+ if (t - Math.max(lastDown, lastCalm) >= CALM && cooldown > COOLDOWN) {
440
+ cooldown = Math.max(COOLDOWN, cooldown / 2);
441
+ lastCalm = t;
442
+ }
443
+ decision.note = notes.join(", ");
444
+ return decision;
445
+ }
446
+ };
447
+ }
448
+ export { CONTROL_SLOTS, MIN_BUDGET, TICK, WORKER_OVERHEAD, WorkerControl, createMemoryGovernor };
@@ -0,0 +1,70 @@
1
+ import path from "node:path";
2
+ import fs from "node:fs";
3
+ // src/node/build/output-dirs.ts
4
+ /** mkdirs in flight at a time (each one is a round trip through the libuv threadpool) */
5
+ const MKDIR_CONCURRENCY = 16;
6
+ /** directories remembered as created (bounded: the pages of a large site have more) */
7
+ const MAX_KNOWN = 16384;
8
+ /**
9
+ * The directories `tasks` write into that may not exist yet: a page's HTML and page-data
10
+ * directories – unless the page was built before: its page-data.json was read (its result is
11
+ * cached), or an earlier build wrote its files (so do pages whose result the renderer reads). Then
12
+ * both are there (if not, the renderer creates them when the write fails), and its page-data.json is
13
+ * written again only if its static queries changed.
14
+ */
15
+ function outputDirs(tasks) {
16
+ const dirs = /* @__PURE__ */ new Set();
17
+ for (const task of tasks) {
18
+ if (task.pageDataStaticQueryHashes !== void 0 || task.filesExist) continue;
19
+ dirs.add(path.dirname(task.htmlFile));
20
+ dirs.add(path.dirname(task.pageDataFile));
21
+ }
22
+ return [...dirs];
23
+ }
24
+ /**
25
+ * Creates the output directories of pages before they are rendered (instead of a recursive mkdir
26
+ * per file in the renderer): each directory once, its parent first, with a plain mkdir – a
27
+ * recursive one walks up the path when the directory is new. Directories under `root` only (the
28
+ * public directory, created first); others are created recursively.
29
+ */
30
+ function createDirectoryMaker(root) {
31
+ root = path.resolve(root);
32
+ /** created (or being created): a directory's children wait for it */
33
+ const known = /* @__PURE__ */ new Map();
34
+ let active = 0;
35
+ const waiting = [];
36
+ const limited = async (mkdir) => {
37
+ if (active >= MKDIR_CONCURRENCY) await new Promise((resolve) => waiting.push(resolve));
38
+ else active++;
39
+ try {
40
+ await mkdir();
41
+ } catch (e) {
42
+ if (e.code !== "EEXIST") throw e;
43
+ } finally {
44
+ const next = waiting.shift();
45
+ if (next) next();
46
+ else active--;
47
+ }
48
+ };
49
+ const make = (dir) => {
50
+ let made = known.get(dir);
51
+ if (made) return made;
52
+ if (known.size >= MAX_KNOWN) known.clear();
53
+ const parent = path.dirname(dir);
54
+ const inRoot = parent === root || parent.startsWith(root + path.sep);
55
+ made = dir === root || !inRoot ? limited(() => fs.promises.mkdir(dir, { recursive: true })) : make(parent).then(() => limited(() => fs.promises.mkdir(dir)));
56
+ made = made.catch(() => {
57
+ known.delete(dir);
58
+ });
59
+ known.set(dir, made);
60
+ return made;
61
+ };
62
+ return {
63
+ /** creates `dirs` (and their parents under the root); never rejects */
64
+ async ensure(dirs) {
65
+ const all = [];
66
+ for (const dir of dirs) all.push(make(path.resolve(dir)));
67
+ await Promise.all(all);
68
+ } };
69
+ }
70
+ export { createDirectoryMaker, outputDirs };
@@ -0,0 +1,40 @@
1
+ import fs from "node:fs";
2
+ // src/node/build/page-data.ts
3
+ /**
4
+ * The start of page-data.json as render workers write it, up to the page's query result: the
5
+ * result follows as the JSON text the query produced, so it can be taken out of the file again
6
+ * without parsing (`readPageDataResult`).
7
+ */
8
+ function pageDataPrefix(componentChunkName, pagePath, matchPath) {
9
+ return `{"componentChunkName":${JSON.stringify(componentChunkName)},"path":${JSON.stringify(pagePath)},` + (matchPath ? `"matchPath":${JSON.stringify(matchPath)},` : "") + `"result":`;
10
+ }
11
+ /** what render workers write after the result */
12
+ const PAGE_DATA_END = /^,"staticQueryHashes":(\[(?:"[^"\\]*"(?:,"[^"\\]*")*)?\]),"slicesMap":\{\}\}$/;
13
+ /**
14
+ * The query result (`{ data, pageContext }` JSON) of a page from its existing page-data.json
15
+ * (`file`), with the file's static query hashes (JSON) when it is exactly what a render worker
16
+ * writes for the page with this result: then it needs to be written again only if they changed.
17
+ * Undefined when the file is missing or has no result.
18
+ */
19
+ function readPageDataResult(file, componentChunkName, pagePath, matchPath) {
20
+ let text;
21
+ try {
22
+ text = fs.readFileSync(file, "utf8");
23
+ } catch {
24
+ return;
25
+ }
26
+ const prefix = pageDataPrefix(componentChunkName, pagePath, matchPath);
27
+ const end = text.lastIndexOf(",\"staticQueryHashes\":");
28
+ const tail = end > prefix.length && text.startsWith(prefix) ? PAGE_DATA_END.exec(text.slice(end)) : null;
29
+ if (tail) return {
30
+ resultJson: text.slice(prefix.length, end),
31
+ staticQueryHashes: tail[1]
32
+ };
33
+ try {
34
+ const pageData = JSON.parse(text);
35
+ return pageData?.result === void 0 ? void 0 : { resultJson: JSON.stringify(pageData.result) };
36
+ } catch {
37
+ return;
38
+ }
39
+ }
40
+ export { pageDataPrefix, readPageDataResult };
@@ -0,0 +1,54 @@
1
+ import path from "node:path";
2
+ import fs from "node:fs";
3
+ // src/node/build/page-files.ts
4
+ /**
5
+ * Writes an output file of a page (its HTML or page-data.json) synchronously, in the thread that
6
+ * rendered the page. A build writes two files per page, 200,000 or more for a large site, and the
7
+ * cost per file adds up:
8
+ *
9
+ * - Synchronous calls, not `fs.promises`: `writeFile` takes three trips through libuv's thread
10
+ * pool (open, write, close) and `mkdir` one more, and all worker threads of the process share that
11
+ * pool (4 threads by default). Writing 100,000 pages from 3 threads took 22–32 s instead of
12
+ * 30–39 s, with less kernel time.
13
+ * - `exists` (an earlier build wrote the page): the file is overwritten in place – written from the
14
+ * start and truncated only when the new content is shorter – instead of being truncated to zero
15
+ * first. Truncating frees the file's blocks and the write allocates new ones, and on ext4
16
+ * (`auto_da_alloc`) closing a file that was truncated to zero starts its writeback at once.
17
+ * Rewriting the files of 100,000 pages took 18 s instead of 36 s. A file that is missing after
18
+ * all is created.
19
+ * - New pages: written first – the build creates the directories of new pages before rendering
20
+ * them (output-dirs.ts) – and their directory is created when the write finds none.
21
+ *
22
+ * Neither way is atomic: a build that stops while writing leaves the files it was writing, as
23
+ * before. Its HTML state is still marked pending then, so the next build writes them again.
24
+ */
25
+ function writePageFile(file, data, exists) {
26
+ if (exists && overwrite(file, data)) return;
27
+ try {
28
+ fs.writeFileSync(file, data);
29
+ } catch (e) {
30
+ if (e.code !== "ENOENT") throw e;
31
+ fs.mkdirSync(path.dirname(file), { recursive: true });
32
+ fs.writeFileSync(file, data);
33
+ }
34
+ }
35
+ /** overwrites `file` in place; false when it doesn't exist */
36
+ function overwrite(file, data) {
37
+ let fd;
38
+ try {
39
+ fd = fs.openSync(file, fs.constants.O_WRONLY);
40
+ } catch (e) {
41
+ if (e.code === "ENOENT") return false;
42
+ throw e;
43
+ }
44
+ try {
45
+ const bytes = Buffer.from(data);
46
+ let written = 0;
47
+ while (written < bytes.length) written += fs.writeSync(fd, bytes, written, bytes.length - written, written);
48
+ if (fs.fstatSync(fd).size > bytes.length) fs.ftruncateSync(fd, bytes.length);
49
+ } finally {
50
+ fs.closeSync(fd);
51
+ }
52
+ return true;
53
+ }
54
+ export { writePageFile };