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.
- package/README.md +853 -1
- package/bin/goatly.js +91 -0
- package/dist/cli/index.js +234 -0
- package/dist/compat/gatsby-node-entry.js +16 -0
- package/dist/compat/gatsby-package.json +6 -0
- package/dist/compat/md5-file.js +47 -0
- package/dist/compat-apis.json +72 -0
- package/dist/compat-apis.json.js +62 -0
- package/dist/graphql.js +3 -0
- package/dist/node/actions/index.js +619 -0
- package/dist/node/actions/job-store.js +180 -0
- package/dist/node/actions/jobs.js +174 -0
- package/dist/node/api-runner.js +258 -0
- package/dist/node/bootstrap.js +539 -0
- package/dist/node/build/assets.js +110 -0
- package/dist/node/build/incremental.js +208 -0
- package/dist/node/build/index.js +752 -0
- package/dist/node/build/memory-governor.js +448 -0
- package/dist/node/build/output-dirs.js +70 -0
- package/dist/node/build/page-data.js +40 -0
- package/dist/node/build/page-files.js +54 -0
- package/dist/node/build/partitioned-state.js +258 -0
- package/dist/node/build/query-worker.js +536 -0
- package/dist/node/build/query-workers.js +832 -0
- package/dist/node/build/render-worker.js +131 -0
- package/dist/node/build/state.js +24 -0
- package/dist/node/build/timing-breakdown.js +155 -0
- package/dist/node/build/worker-pool.js +236 -0
- package/dist/node/cache-layout.js +99 -0
- package/dist/node/cache.js +1430 -0
- package/dist/node/compat/chokidar-shim.js +148 -0
- package/dist/node/compat/core-utils-lmdb.js +145 -0
- package/dist/node/compat/create-node-id-shim.js +1 -0
- package/dist/node/compat/module-hooks.js +245 -0
- package/dist/node/compat/redux-shim.js +1 -0
- package/dist/node/config/index.js +162 -0
- package/dist/node/config/not-found-pages.js +95 -0
- package/dist/node/datastore/codec.js +144 -0
- package/dist/node/datastore/index.js +127 -0
- package/dist/node/datastore/logfile/cache.js +89 -0
- package/dist/node/datastore/logfile/index.js +1329 -0
- package/dist/node/datastore/logfile/record.js +71 -0
- package/dist/node/datastore/types.js +1 -0
- package/dist/node/develop/express-compat.js +207 -0
- package/dist/node/develop/graphiql.js +22 -0
- package/dist/node/develop/hydration-report.js +41 -0
- package/dist/node/develop/index.js +618 -0
- package/dist/node/develop/local-url.js +10 -0
- package/dist/node/develop/ssr-runner.js +66 -0
- package/dist/node/gql.js +5 -0
- package/dist/node/index.js +15 -0
- package/dist/node/info.js +270 -0
- package/dist/node/internal-plugins/data-bridge.js +196 -0
- package/dist/node/internal-plugins/page-creator.js +318 -0
- package/dist/node/loader/import-module.js +160 -0
- package/dist/node/node-helpers.js +66 -0
- package/dist/node/not-found-pages.js +220 -0
- package/dist/node/plugins/api-list.js +12 -0
- package/dist/node/plugins/load-plugins.js +427 -0
- package/dist/node/plugins/resolve-plugin.js +79 -0
- package/dist/node/plugins/static-exports.js +64 -0
- package/dist/node/query/compile.js +326 -0
- package/dist/node/query/dependencies.js +45 -0
- package/dist/node/query/execute.js +417 -0
- package/dist/node/query/extract.js +372 -0
- package/dist/node/query/gql-tada-introspection.js +124 -0
- package/dist/node/query/graphql-env.js +231 -0
- package/dist/node/query/graphql-runner.js +79 -0
- package/dist/node/redux/actions.js +1 -0
- package/dist/node/redux/index.js +133 -0
- package/dist/node/redux/node-changes.js +128 -0
- package/dist/node/redux/reducers.js +193 -0
- package/dist/node/redux/state.js +71 -0
- package/dist/node/renderer.js +124 -0
- package/dist/node/reporter-transports.js +259 -0
- package/dist/node/reporter.js +497 -0
- package/dist/node/schema/date.js +539 -0
- package/dist/node/schema/extensions.js +315 -0
- package/dist/node/schema/index.js +542 -0
- package/dist/node/schema/infer.js +388 -0
- package/dist/node/schema/inline-objects.js +128 -0
- package/dist/node/schema/naming.js +20 -0
- package/dist/node/schema/node-model.js +207 -0
- package/dist/node/schema/query-engine.js +1808 -0
- package/dist/node/schema/resolver-kinds.js +7 -0
- package/dist/node/schema/resolvers.js +273 -0
- package/dist/node/schema/type-builders.js +45 -0
- package/dist/node/schema/types.js +241 -0
- package/dist/node/serve.js +90 -0
- package/dist/node/site-page-nodes.js +277 -0
- package/dist/node/types.js +1 -0
- package/dist/node/utils/content-digest.js +107 -0
- package/dist/node/utils/create-node-id.js +51 -0
- package/dist/node/utils/env.js +24 -0
- package/dist/node/utils/fs-retry.js +74 -0
- package/dist/node/utils/memory-signals.js +410 -0
- package/dist/node/utils/memory.js +400 -0
- package/dist/node/utils/murmurhash.js +32 -0
- package/dist/node/utils/parser.js +33 -0
- package/dist/node/utils/partition-hash.js +19 -0
- package/dist/node/utils/paths.js +122 -0
- package/dist/node/utils/resolver.js +48 -0
- package/dist/node/utils/runtime.js +5 -0
- package/dist/node/utils/serializable.js +41 -0
- package/dist/node/utils/strings.js +41 -0
- package/dist/node/vite/config.js +289 -0
- package/dist/node/vite/paths.js +12 -0
- package/dist/node/vite/plugin-deps.js +232 -0
- package/dist/node/vite/plugin.js +281 -0
- package/dist/node/vite/react-compiler.js +362 -0
- package/dist/node/vite/source-files.js +83 -0
- package/dist/node/vite/static-image.js +136 -0
- package/dist/node/vite/styled-components.js +73 -0
- package/dist/node/vite/transforms.js +299 -0
- package/dist/node/wasm-data/host.js +406 -0
- package/dist/node/wasm-data/lower.js +406 -0
- package/dist/node/wasm-data/runner.js +79 -0
- package/dist/node/wasm-data/worker.js +95 -0
- package/dist/reporter.js +5 -0
- package/dist/runtime/api-runner.js +81 -0
- package/dist/runtime/app.js +256 -0
- package/dist/runtime/client-entry.js +4 -0
- package/dist/runtime/client.js +383 -0
- package/dist/runtime/default-html.js +31 -0
- package/dist/runtime/head-markup.js +100 -0
- package/dist/runtime/head-sync.js +101 -0
- package/dist/runtime/head-tags.js +45 -0
- package/dist/runtime/hydration-report.js +111 -0
- package/dist/runtime/index.js +12 -0
- package/dist/runtime/link.js +293 -0
- package/dist/runtime/loader.js +449 -0
- package/dist/runtime/not-found.js +61 -0
- package/dist/runtime/page-renderer.js +35 -0
- package/dist/runtime/preamble.js +47 -0
- package/dist/runtime/react-compat.js +14 -0
- package/dist/runtime/renderer-shared.js +10 -0
- package/dist/runtime/renderers/react-client.js +14 -0
- package/dist/runtime/renderers/react-server.js +99 -0
- package/dist/runtime/renderers/react.js +17 -0
- package/dist/runtime/renderers/types.js +1 -0
- package/dist/runtime/root-error-handlers.js +29 -0
- package/dist/runtime/router/history.js +132 -0
- package/dist/runtime/router/index.js +240 -0
- package/dist/runtime/router/utils.js +118 -0
- package/dist/runtime/script.js +110 -0
- package/dist/runtime/scroll.js +40 -0
- package/dist/runtime/slice.js +11 -0
- package/dist/runtime/ssr.js +240 -0
- package/dist/runtime/static-query.js +47 -0
- package/dist/utils.js +4 -0
- package/package.json +105 -3
- package/types/graphql-tada.d.ts +223 -0
- package/types/graphql.d.ts +2 -0
- package/types/index.d.ts +2287 -0
- package/types/node.d.ts +380 -0
- package/types/reporter.d.ts +187 -0
- package/types/router.d.ts +102 -0
- package/types/vendor/gql-tada.d.ts +2529 -0
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { pageDataPrefix, readPageDataResult } from "./page-data.js";
|
|
2
|
+
import { writePageFile } from "./page-files.js";
|
|
3
|
+
import { isMainThread, parentPort, workerData } from "node:worker_threads";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import { pathToFileURL } from "node:url";
|
|
7
|
+
// src/node/build/render-worker.ts
|
|
8
|
+
const cssCache = /* @__PURE__ */ new Map();
|
|
9
|
+
/**
|
|
10
|
+
* Pages are rendered one at a time (also by concurrent batches of the in-process pool): plugins
|
|
11
|
+
* keep per-page state in module scope between rendering and `onRenderBody` – react-helmet's
|
|
12
|
+
* `Helmet.renderStatic()` in gatsby-plugin-react-helmet, a react-helmet-async context created in
|
|
13
|
+
* `wrapRootElement` – and would read another page's state if pages interleaved (Gatsby renders
|
|
14
|
+
* one at a time, too). Rendering is mostly synchronous work in this thread anyway: it costs about
|
|
15
|
+
* 10% of the render step (5,000 pages), and a page that waits (Suspense) holds up the next ones.
|
|
16
|
+
*/
|
|
17
|
+
let renderQueue = Promise.resolve();
|
|
18
|
+
function oneAtATime(render) {
|
|
19
|
+
const run = renderQueue.then(render, render);
|
|
20
|
+
renderQueue = run.catch(() => {});
|
|
21
|
+
return run;
|
|
22
|
+
}
|
|
23
|
+
/** Creates the page renderer (used in worker threads and in-process for small sites). */
|
|
24
|
+
async function createRenderer(options) {
|
|
25
|
+
const renderPage = (await import(pathToFileURL(options.ssrBundle).href)).renderPage;
|
|
26
|
+
const inlineStyles = async (hrefs) => {
|
|
27
|
+
const out = [];
|
|
28
|
+
for (const href of hrefs) {
|
|
29
|
+
let content = cssCache.get(href);
|
|
30
|
+
if (content === void 0) {
|
|
31
|
+
const rel = href.replace(/^https?:\/\/[^/]+/, "").replace(/^\/+/, "");
|
|
32
|
+
const candidates = [path.join(options.publicDir, rel), path.join(options.publicDir, rel.split("/").slice(1).join("/"))];
|
|
33
|
+
content = "";
|
|
34
|
+
for (const c of candidates) try {
|
|
35
|
+
content = await fs.promises.readFile(c, "utf8");
|
|
36
|
+
break;
|
|
37
|
+
} catch {}
|
|
38
|
+
cssCache.set(href, content);
|
|
39
|
+
}
|
|
40
|
+
out.push({
|
|
41
|
+
href,
|
|
42
|
+
content
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
};
|
|
47
|
+
/** renders the page (false: it had no result, see `missing`) */
|
|
48
|
+
async function renderTask(task) {
|
|
49
|
+
let { resultJson, pageDataStaticQueryHashes } = task;
|
|
50
|
+
if (resultJson === void 0) {
|
|
51
|
+
const cached = readPageDataResult(task.pageDataFile, task.componentChunkName, task.pagePath, task.matchPath);
|
|
52
|
+
if (!cached) return false;
|
|
53
|
+
resultJson = cached.resultJson;
|
|
54
|
+
pageDataStaticQueryHashes = cached.staticQueryHashes;
|
|
55
|
+
}
|
|
56
|
+
const json = resultJson;
|
|
57
|
+
const styles = options.inlineCss ? await inlineStyles(task.assets.stylesheets) : void 0;
|
|
58
|
+
const { html, staticQueryHashes } = await oneAtATime(() => renderPage({
|
|
59
|
+
pagePath: task.pagePath,
|
|
60
|
+
pageData: {
|
|
61
|
+
componentChunkName: task.componentChunkName,
|
|
62
|
+
path: task.pagePath,
|
|
63
|
+
...task.matchPath ? { matchPath: task.matchPath } : {},
|
|
64
|
+
result: JSON.parse(json),
|
|
65
|
+
staticQueryHashes: [],
|
|
66
|
+
slicesMap: {}
|
|
67
|
+
},
|
|
68
|
+
scripts: task.assets.scripts,
|
|
69
|
+
modulePreloads: task.assets.modulePreloads,
|
|
70
|
+
stylesheets: options.inlineCss ? [] : task.assets.stylesheets,
|
|
71
|
+
inlineStyles: styles,
|
|
72
|
+
pageDataUrl: task.pageDataUrl,
|
|
73
|
+
inlinePageData: options.inlinePageData,
|
|
74
|
+
buildHash: options.buildHash,
|
|
75
|
+
generator: options.generator
|
|
76
|
+
}));
|
|
77
|
+
const sq = JSON.stringify(staticQueryHashes);
|
|
78
|
+
if (sq !== pageDataStaticQueryHashes) writePageFile(task.pageDataFile, pageDataPrefix(task.componentChunkName, task.pagePath, task.matchPath) + `${json},"staticQueryHashes":${sq},"slicesMap":{}}`, !!task.filesExist);
|
|
79
|
+
writePageFile(task.htmlFile, html, !!task.filesExist);
|
|
80
|
+
return staticQueryHashes;
|
|
81
|
+
}
|
|
82
|
+
async function renderBatch(tasks) {
|
|
83
|
+
const result = {
|
|
84
|
+
rendered: 0,
|
|
85
|
+
errors: [],
|
|
86
|
+
staticQueryHashes: {},
|
|
87
|
+
missing: []
|
|
88
|
+
};
|
|
89
|
+
for (const task of tasks) {
|
|
90
|
+
try {
|
|
91
|
+
const staticQueryHashes = await renderTask(task);
|
|
92
|
+
if (!staticQueryHashes) result.missing.push(task.pagePath);
|
|
93
|
+
else {
|
|
94
|
+
result.staticQueryHashes[task.pagePath] = staticQueryHashes;
|
|
95
|
+
result.rendered++;
|
|
96
|
+
}
|
|
97
|
+
} catch (e) {
|
|
98
|
+
const err = e;
|
|
99
|
+
result.errors.push({
|
|
100
|
+
pagePath: task.pagePath,
|
|
101
|
+
message: err?.message ?? String(e),
|
|
102
|
+
stack: err?.stack
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
106
|
+
}
|
|
107
|
+
return result;
|
|
108
|
+
}
|
|
109
|
+
return { renderBatch };
|
|
110
|
+
}
|
|
111
|
+
if (!isMainThread && parentPort && workerData?.__goatlyRenderWorker) {
|
|
112
|
+
const port = parentPort;
|
|
113
|
+
const options = workerData.options;
|
|
114
|
+
const rendererPromise = options.renderer ? import("../renderer.js").then(({ useRenderer }) => useRenderer(options.renderer.descriptor, options.renderer.root)).then(() => createRenderer(options)) : createRenderer(options);
|
|
115
|
+
rendererPromise.then(() => port.postMessage({ type: "ready" }), () => port.postMessage({ type: "ready" }));
|
|
116
|
+
port.on("message", async (msg) => {
|
|
117
|
+
try {
|
|
118
|
+
const result = await (await rendererPromise).renderBatch(msg.tasks);
|
|
119
|
+
port.postMessage({
|
|
120
|
+
id: msg.id,
|
|
121
|
+
result
|
|
122
|
+
});
|
|
123
|
+
} catch (e) {
|
|
124
|
+
port.postMessage({
|
|
125
|
+
id: msg.id,
|
|
126
|
+
error: e?.stack ?? String(e)
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
export { createRenderer };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { BUILD_STATE_PATHS } from "../cache-layout.js";
|
|
2
|
+
import { markHtmlStatePending, readPartitionedHtmlState, readPartitionedQueryState, writePartitionedHtmlState, writePartitionedQueryState } from "./partitioned-state.js";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
// src/node/build/state.ts
|
|
6
|
+
/** the build state in `cacheDir` */
|
|
7
|
+
function openBuildState(cacheDir) {
|
|
8
|
+
const htmlDir = path.join(cacheDir, BUILD_STATE_PATHS.html);
|
|
9
|
+
const queriesDir = path.join(cacheDir, BUILD_STATE_PATHS.queries);
|
|
10
|
+
return {
|
|
11
|
+
readHtml: () => fs.existsSync(htmlDir) ? readPartitionedHtmlState(htmlDir) : null,
|
|
12
|
+
markHtmlPending: (previous, paths) => markHtmlStatePending(htmlDir, paths.filter((p) => !previous || !(p in previous.pages))),
|
|
13
|
+
writeHtml: (state) => writePartitionedHtmlState(htmlDir, state),
|
|
14
|
+
readQueries: () => readPartitionedQueryState(queriesDir),
|
|
15
|
+
async writeQueries(state, options) {
|
|
16
|
+
writePartitionedQueryState(queriesDir, state, { keepUnlisted: options?.pending });
|
|
17
|
+
},
|
|
18
|
+
writeNodeChanges(state) {
|
|
19
|
+
writePartitionedQueryState(queriesDir, state);
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
export { openBuildState };
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { formatRate } from "../reporter-transports.js";
|
|
2
|
+
import { performance } from "node:perf_hooks";
|
|
3
|
+
// src/node/build/timing-breakdown.ts
|
|
4
|
+
const seconds = (ms) => `${(ms / 1e3).toFixed(3)}s`;
|
|
5
|
+
const plural = (n, word, words = `${word}s`) => `${n} ${n === 1 ? word : words}`;
|
|
6
|
+
/**
|
|
7
|
+
* The fixed segments of the build's timing breakdown (in this order). They cover the build's
|
|
8
|
+
* wall-clock time. Only segments that really ran at the same time overlap (HTML rendering while
|
|
9
|
+
* the page queries still run in the query workers); other work that runs alongside a segment
|
|
10
|
+
* (bundling while the page queries run) only counts where the build waits for it.
|
|
11
|
+
*/
|
|
12
|
+
const BUILD_SEGMENTS = [
|
|
13
|
+
{
|
|
14
|
+
key: "bootstrap",
|
|
15
|
+
label: "bootstrap"
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
key: "staticQueries",
|
|
19
|
+
label: "run static queries"
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
key: "queryWorkers",
|
|
23
|
+
label: "start query workers"
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
key: "pageQueries",
|
|
27
|
+
label: "run page queries"
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
key: "bundle",
|
|
31
|
+
label: "wait for JavaScript bundles"
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
key: "render",
|
|
35
|
+
label: "build static HTML"
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
key: "postBuild",
|
|
39
|
+
label: "onPostBuild"
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
key: "finalize",
|
|
43
|
+
label: "save caches and state"
|
|
44
|
+
}
|
|
45
|
+
];
|
|
46
|
+
/**
|
|
47
|
+
* Splits the build's wall-clock time into the predefined segments: each `until()` attributes the
|
|
48
|
+
* time since the previous checkpoint to a segment, so the segments cover the whole build. A
|
|
49
|
+
* segment that began earlier, alongside the previous ones, passes `from`.
|
|
50
|
+
*/
|
|
51
|
+
var SegmentClock = class {
|
|
52
|
+
last;
|
|
53
|
+
start;
|
|
54
|
+
/** when each segment ran, in ms since the start */
|
|
55
|
+
spans = Object.fromEntries(BUILD_SEGMENTS.map((s) => [s.key, []]));
|
|
56
|
+
constructor(start = performance.now()) {
|
|
57
|
+
this.start = this.last = start;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* the time from the previous checkpoint (or from `from`, when the segment began earlier,
|
|
61
|
+
* alongside the previous segments) to `at` (default: now) belongs to `segment`
|
|
62
|
+
*/
|
|
63
|
+
until(segment, at = performance.now(), from) {
|
|
64
|
+
const end = Math.max(this.last, at);
|
|
65
|
+
const begin = from === void 0 ? this.last : Math.min(this.last, Math.max(this.start, from));
|
|
66
|
+
this.last = end;
|
|
67
|
+
if (end <= begin) return;
|
|
68
|
+
const spans = this.spans[segment];
|
|
69
|
+
const previous = spans.at(-1);
|
|
70
|
+
const span = [begin - this.start, end - this.start];
|
|
71
|
+
if (previous && previous[1] >= span[0]) previous[1] = Math.max(previous[1], span[1]);
|
|
72
|
+
else spans.push(span);
|
|
73
|
+
}
|
|
74
|
+
/** milliseconds per segment (segments that ran at the same time both count that time) */
|
|
75
|
+
totals() {
|
|
76
|
+
return Object.fromEntries(BUILD_SEGMENTS.map((s) => [s.key, this.spans[s.key].reduce((ms, [a, b]) => ms + b - a, 0)]));
|
|
77
|
+
}
|
|
78
|
+
/** all predefined segments (also the empty ones), in order, with when they ran */
|
|
79
|
+
segments() {
|
|
80
|
+
const totals = this.totals();
|
|
81
|
+
return BUILD_SEGMENTS.map((s) => ({
|
|
82
|
+
key: s.key,
|
|
83
|
+
label: s.label,
|
|
84
|
+
ms: totals[s.key],
|
|
85
|
+
spans: this.spans[s.key].map(([a, b]) => [a, b])
|
|
86
|
+
}));
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* When HTML rendering of the pipelined worker step began (ms since the epoch), or `undefined` when
|
|
91
|
+
* no page was rendered: never before the workers were ready or the bundles existed (the steps
|
|
92
|
+
* before it), so only the page queries overlap it.
|
|
93
|
+
*/
|
|
94
|
+
function pipelinedRenderStart(t) {
|
|
95
|
+
if (!(t.render.end >= t.render.start)) return void 0;
|
|
96
|
+
return Math.max(t.ready, t.renderJob, t.render.start);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* The parts of the pipelined worker step on its timeline: persisting the data for the workers,
|
|
100
|
+
* starting them (each loads the datastore, e.g. the logfile store's index), running the page
|
|
101
|
+
* queries, waiting for the bundles (when the queries were done first) and building the HTML.
|
|
102
|
+
* The first parts follow one another; HTML rendering starts as soon as the bundles exist, often
|
|
103
|
+
* while queries still run, so its part (with its `offset`) overlaps the queries: its time is the
|
|
104
|
+
* whole time it ran, and its status says how much of it was alongside the queries.
|
|
105
|
+
*/
|
|
106
|
+
function pipelineParts(o) {
|
|
107
|
+
const { query, render } = o.timings;
|
|
108
|
+
let last = o.start;
|
|
109
|
+
const until = (at) => {
|
|
110
|
+
const from = last;
|
|
111
|
+
last = Math.min(o.end, Math.max(last, at));
|
|
112
|
+
return (last - from) / 1e3;
|
|
113
|
+
};
|
|
114
|
+
const parts = [{
|
|
115
|
+
text: "persist data for the query workers",
|
|
116
|
+
elapsed: until(o.start + o.persistMs)
|
|
117
|
+
}, {
|
|
118
|
+
text: "start query workers",
|
|
119
|
+
elapsed: until(o.timings.ready),
|
|
120
|
+
status: plural(o.workers, "worker")
|
|
121
|
+
}];
|
|
122
|
+
const queried = query.end >= query.start;
|
|
123
|
+
parts.push({
|
|
124
|
+
text: "run page queries",
|
|
125
|
+
elapsed: until(queried ? query.end : o.timings.ready),
|
|
126
|
+
status: [
|
|
127
|
+
plural(o.queries, "query", "queries"),
|
|
128
|
+
queried && o.queries > 0 && formatRate(o.queries, (query.end - query.start) / 1e3),
|
|
129
|
+
queried && query.ms > 0 && `workers busy ${seconds(query.ms)} in total`
|
|
130
|
+
].filter(Boolean).join(", ")
|
|
131
|
+
});
|
|
132
|
+
const queriesEnd = last;
|
|
133
|
+
if (o.timings.renderJob > last) parts.push({
|
|
134
|
+
text: "wait for the JavaScript bundles",
|
|
135
|
+
elapsed: until(o.timings.renderJob)
|
|
136
|
+
});
|
|
137
|
+
const rendering = render.end >= render.start;
|
|
138
|
+
const renderStart = Math.min(o.end, Math.max(o.start, pipelinedRenderStart(o.timings) ?? last));
|
|
139
|
+
const alongside = Math.max(0, queriesEnd - renderStart);
|
|
140
|
+
const after = Math.max(0, o.end - Math.max(renderStart, queriesEnd));
|
|
141
|
+
parts.push({
|
|
142
|
+
text: "build static HTML for pages",
|
|
143
|
+
elapsed: (o.end - renderStart) / 1e3,
|
|
144
|
+
offset: (renderStart - o.start) / 1e3,
|
|
145
|
+
status: [
|
|
146
|
+
plural(o.rendered, "page"),
|
|
147
|
+
rendering && o.rendered > 0 && formatRate(o.rendered, (render.end - render.start) / 1e3),
|
|
148
|
+
o.skipped && `${o.skipped} unchanged`,
|
|
149
|
+
alongside > 0 && `${seconds(alongside)} alongside the queries, ${seconds(after)} after them`,
|
|
150
|
+
rendering && `workers busy ${seconds(render.ms)} in total`
|
|
151
|
+
].filter(Boolean).join(", ")
|
|
152
|
+
});
|
|
153
|
+
return parts;
|
|
154
|
+
}
|
|
155
|
+
export { BUILD_SEGMENTS, SegmentClock, pipelineParts, pipelinedRenderStart };
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import reporter, { REPORTER_BRIDGE_ENV } from "../reporter.js";
|
|
2
|
+
import { outOfMemoryHint, planWorkerHeap, workerLimitMb } from "../utils/memory.js";
|
|
3
|
+
import { createRenderer } from "./render-worker.js";
|
|
4
|
+
import { Worker } from "node:worker_threads";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
// src/node/build/worker-pool.ts
|
|
9
|
+
const workerFile = path.join(path.dirname(fileURLToPath(import.meta.url)), "render-worker.js");
|
|
10
|
+
function defaultWorkerCount(configured) {
|
|
11
|
+
if (configured && configured > 0) return configured;
|
|
12
|
+
const env = Number(process.env.GOATLY_RENDER_WORKERS);
|
|
13
|
+
if (env > 0) return env;
|
|
14
|
+
const cpus = os.availableParallelism?.() ?? os.cpus().length;
|
|
15
|
+
return Math.max(1, Math.min(cpus - 1, 16));
|
|
16
|
+
}
|
|
17
|
+
/** GOATLY_WORKERS=<n>: a fixed number of workers instead of the adaptive pool */
|
|
18
|
+
function fixedWorkerCount() {
|
|
19
|
+
const raw = process.env.GOATLY_WORKERS;
|
|
20
|
+
if (raw === void 0 || raw.trim() === "") return void 0;
|
|
21
|
+
const n = Number(raw);
|
|
22
|
+
if (Number.isInteger(n) && n > 0) return n;
|
|
23
|
+
reporter.warn(`GOATLY_WORKERS=${raw} is not a positive whole number – ignored`);
|
|
24
|
+
}
|
|
25
|
+
/** Renders in-process (small sites – avoids worker start-up cost). */
|
|
26
|
+
async function createInProcessPool(options) {
|
|
27
|
+
const renderer = await createRenderer(options);
|
|
28
|
+
return {
|
|
29
|
+
size: 1,
|
|
30
|
+
render: (tasks) => renderer.renderBatch(tasks),
|
|
31
|
+
close: async () => {}
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** tasks per message by attempt: a page whose worker ran out of memory is tried at most 3 times */
|
|
35
|
+
const RETRY_BATCH = [
|
|
36
|
+
1e400,
|
|
37
|
+
4,
|
|
38
|
+
1
|
|
39
|
+
];
|
|
40
|
+
const OOM = "ERR_WORKER_OUT_OF_MEMORY";
|
|
41
|
+
const pageList = (tasks) => tasks.slice(0, 5).map((t) => t.pagePath).join(", ") + (tasks.length > 5 ? ` and ${tasks.length - 5} more` : "");
|
|
42
|
+
/**
|
|
43
|
+
* A pool of worker threads, each holding the SSR bundle. Batches are dispatched to idle workers. A
|
|
44
|
+
* worker that runs out of memory is replaced (with a higher heap limit, unless the user chose one)
|
|
45
|
+
* and its batch is rendered again in smaller batches. Any other death of a worker fails the pool:
|
|
46
|
+
* its batches, later render() calls and – when nothing else reported it – close().
|
|
47
|
+
*/
|
|
48
|
+
function createWorkerPool(options, count, heap = planWorkerHeap({ workers: count })) {
|
|
49
|
+
const top = heap.ladder.length - 1;
|
|
50
|
+
const slots = [];
|
|
51
|
+
const queue = [];
|
|
52
|
+
const live = () => slots.filter((s) => !s.dead);
|
|
53
|
+
let respawnsLeft = 2 * count + 2;
|
|
54
|
+
let nextId = 0;
|
|
55
|
+
let closed = false;
|
|
56
|
+
/** the pool failed (a worker died, not out of memory, or none is left) */
|
|
57
|
+
let failure;
|
|
58
|
+
/** …and no batch was rejected with that error yet: close() throws it */
|
|
59
|
+
let unreported;
|
|
60
|
+
const fail = (group, error) => {
|
|
61
|
+
if (group.settled) return;
|
|
62
|
+
group.settled = true;
|
|
63
|
+
if (error === unreported) unreported = void 0;
|
|
64
|
+
group.reject(error);
|
|
65
|
+
};
|
|
66
|
+
const settle = (group, result) => {
|
|
67
|
+
if (group.settled) return;
|
|
68
|
+
group.result.rendered += result.rendered;
|
|
69
|
+
group.result.errors.push(...result.errors);
|
|
70
|
+
group.result.missing.push(...result.missing);
|
|
71
|
+
Object.assign(group.result.staticQueryHashes, result.staticQueryHashes);
|
|
72
|
+
if (--group.pending === 0) {
|
|
73
|
+
group.settled = true;
|
|
74
|
+
group.resolve(group.result);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* fails every batch, queued or in flight (`reported`: the death that caused it already failed a
|
|
79
|
+
* batch with its own error – close() doesn't throw this one over it)
|
|
80
|
+
*/
|
|
81
|
+
const stop = (error, reported = false) => {
|
|
82
|
+
if (failure) return;
|
|
83
|
+
failure = error;
|
|
84
|
+
unreported = reported ? void 0 : error;
|
|
85
|
+
for (const job of queue.splice(0)) fail(job.group, error);
|
|
86
|
+
for (const slot of slots) {
|
|
87
|
+
if (!slot.job) continue;
|
|
88
|
+
const { group } = slot.job;
|
|
89
|
+
slot.job = void 0;
|
|
90
|
+
fail(group, error);
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
const dispatch = () => {
|
|
94
|
+
if (failure || closed) return;
|
|
95
|
+
for (const slot of slots) {
|
|
96
|
+
if (slot.dead || !slot.ready || slot.job) continue;
|
|
97
|
+
const i = queue.findIndex((j) => !j.group.settled && (j.attempt <= slot.rung || !live().some((o) => o.rung >= j.attempt)));
|
|
98
|
+
if (i < 0) continue;
|
|
99
|
+
const [job] = queue.splice(i, 1);
|
|
100
|
+
slot.job = job;
|
|
101
|
+
slot.messageId = nextId++;
|
|
102
|
+
slot.worker.postMessage({
|
|
103
|
+
id: slot.messageId,
|
|
104
|
+
tasks: job.tasks
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
for (let i = queue.length - 1; i >= 0; i--) if (queue[i].group.settled) queue.splice(i, 1);
|
|
108
|
+
};
|
|
109
|
+
const spawn = (rung) => {
|
|
110
|
+
const limitMb = workerLimitMb(heap, rung);
|
|
111
|
+
const worker = new Worker(workerFile, {
|
|
112
|
+
workerData: {
|
|
113
|
+
__goatlyRenderWorker: true,
|
|
114
|
+
options
|
|
115
|
+
},
|
|
116
|
+
env: {
|
|
117
|
+
...process.env,
|
|
118
|
+
...REPORTER_BRIDGE_ENV,
|
|
119
|
+
NODE_ENV: "production"
|
|
120
|
+
},
|
|
121
|
+
...limitMb && !heap.soft ? { resourceLimits: { maxOldGenerationSizeMb: limitMb } } : {}
|
|
122
|
+
});
|
|
123
|
+
const slot = {
|
|
124
|
+
rung,
|
|
125
|
+
limitMb,
|
|
126
|
+
worker,
|
|
127
|
+
ready: false,
|
|
128
|
+
dead: false
|
|
129
|
+
};
|
|
130
|
+
worker.on("message", (msg) => {
|
|
131
|
+
if (slot.dead) return;
|
|
132
|
+
if (msg?.type === "ready") {
|
|
133
|
+
slot.ready = true;
|
|
134
|
+
return dispatch();
|
|
135
|
+
}
|
|
136
|
+
const job = slot.job;
|
|
137
|
+
if (!job || msg?.id !== slot.messageId) return;
|
|
138
|
+
slot.job = void 0;
|
|
139
|
+
if (msg.error) fail(job.group, new Error(msg.error));
|
|
140
|
+
else settle(job.group, msg.result);
|
|
141
|
+
dispatch();
|
|
142
|
+
});
|
|
143
|
+
const die = (error) => {
|
|
144
|
+
if (slot.dead) return;
|
|
145
|
+
slot.dead = true;
|
|
146
|
+
const job = slot.job;
|
|
147
|
+
slot.job = void 0;
|
|
148
|
+
if (closed) return;
|
|
149
|
+
worker.terminate();
|
|
150
|
+
const loading = !slot.ready ? " while loading the SSR bundle" : "";
|
|
151
|
+
if (error.code !== OOM) {
|
|
152
|
+
error.message += job ? ` (while rendering ${pageList(job.tasks)})` : loading && ` (${loading.trim()})`;
|
|
153
|
+
const reported = !!job && !job.group.settled;
|
|
154
|
+
if (job) fail(job.group, error);
|
|
155
|
+
return stop(error, reported);
|
|
156
|
+
}
|
|
157
|
+
let replacement;
|
|
158
|
+
if (respawnsLeft > 0) {
|
|
159
|
+
respawnsLeft--;
|
|
160
|
+
let next = Math.min(rung + 1, top);
|
|
161
|
+
if (next === top && top > 0 && live().some((s) => s.rung === top)) next = top - 1;
|
|
162
|
+
replacement = spawn(next);
|
|
163
|
+
}
|
|
164
|
+
let again = false;
|
|
165
|
+
/** the page failed the build (its own error, not "No render worker is left") */
|
|
166
|
+
let pageFailed = false;
|
|
167
|
+
if (job && !job.group.settled) {
|
|
168
|
+
const tried = limitMb ? [...job.tried, limitMb] : job.tried;
|
|
169
|
+
const attempt = Math.min(job.attempt + 1, RETRY_BATCH.length - 1);
|
|
170
|
+
if (job.attempt + 1 >= RETRY_BATCH.length && job.tasks.length === 1) {
|
|
171
|
+
const list = [...new Set(tried)].join(", ");
|
|
172
|
+
fail(job.group, /* @__PURE__ */ new Error(`The page "${job.tasks[0].pagePath}" ran out of memory while it was rendered in a worker thread${list ? ` (heap limits tried: ${list} MB)` : ""}. ${outOfMemoryHint(heap, Math.max(0, ...tried))}`));
|
|
173
|
+
pageFailed = true;
|
|
174
|
+
} else {
|
|
175
|
+
const size = RETRY_BATCH[attempt];
|
|
176
|
+
const parts = [];
|
|
177
|
+
for (let i = 0; i < job.tasks.length; i += size) parts.push({
|
|
178
|
+
tasks: job.tasks.slice(i, i + size),
|
|
179
|
+
attempt,
|
|
180
|
+
group: job.group,
|
|
181
|
+
tried
|
|
182
|
+
});
|
|
183
|
+
job.group.pending += parts.length - 1;
|
|
184
|
+
queue.unshift(...parts);
|
|
185
|
+
again = true;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
const left = live().length > 0;
|
|
189
|
+
reporter.warn(`A render worker ran out of memory (heap limit ${limitMb ? `${limitMb} MB` : "none"})` + (job ? ` while rendering ${pageList(job.tasks)}` : loading) + (again && left ? ` – rendering ${job.tasks.length === 1 ? "it" : "them"} again` : "") + "." + (replacement?.limitMb ? ` Starting a new worker with a heap limit of ${replacement.limitMb} MB.` : ""));
|
|
190
|
+
if (!left) stop(/* @__PURE__ */ new Error(`No render worker is left: the last one ran out of memory${loading} (heap limit ${limitMb ? `${limitMb} MB` : "none"}). ${outOfMemoryHint(heap, limitMb)}`), pageFailed);
|
|
191
|
+
dispatch();
|
|
192
|
+
};
|
|
193
|
+
worker.on("error", (e) => die(e instanceof Error ? e : new Error(String(e))));
|
|
194
|
+
worker.on("exit", (code) => die(/* @__PURE__ */ new Error(`render worker exited with code ${code}`)));
|
|
195
|
+
slots.push(slot);
|
|
196
|
+
return slot;
|
|
197
|
+
};
|
|
198
|
+
reporter.receiveWorkerOutput();
|
|
199
|
+
for (let i = 0; i < count; i++) spawn(0);
|
|
200
|
+
return {
|
|
201
|
+
size: count,
|
|
202
|
+
render(tasks) {
|
|
203
|
+
return new Promise((resolve, reject) => {
|
|
204
|
+
if (failure || closed) return reject(failure ?? /* @__PURE__ */ new Error("the render pool was closed"));
|
|
205
|
+
const group = {
|
|
206
|
+
pending: 1,
|
|
207
|
+
settled: false,
|
|
208
|
+
resolve,
|
|
209
|
+
reject,
|
|
210
|
+
result: {
|
|
211
|
+
rendered: 0,
|
|
212
|
+
errors: [],
|
|
213
|
+
staticQueryHashes: {},
|
|
214
|
+
missing: []
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
queue.push({
|
|
218
|
+
tasks,
|
|
219
|
+
attempt: 0,
|
|
220
|
+
group,
|
|
221
|
+
tried: []
|
|
222
|
+
});
|
|
223
|
+
dispatch();
|
|
224
|
+
});
|
|
225
|
+
},
|
|
226
|
+
async close() {
|
|
227
|
+
closed = true;
|
|
228
|
+
const error = /* @__PURE__ */ new Error("the render pool was closed");
|
|
229
|
+
for (const job of queue.splice(0)) fail(job.group, error);
|
|
230
|
+
for (const slot of slots) if (slot.job) fail(slot.job.group, error);
|
|
231
|
+
await Promise.all(slots.map((s) => s.worker.terminate()));
|
|
232
|
+
if (unreported) throw unreported;
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
export { createInProcessPool, createWorkerPool, defaultWorkerCount, fixedWorkerCount };
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { renameSync, retrySync } from "./utils/fs-retry.js";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
// src/node/cache-layout.ts
|
|
5
|
+
/**
|
|
6
|
+
* How `.cache` is laid out on disk: for caches that travel as container image layers (Docker /
|
|
7
|
+
* BuildKit, a `FROM <previous image>` build) or any other file-level diff or sync. An incremental
|
|
8
|
+
* build creates new files and rewrites only the small files whose content changed, instead of
|
|
9
|
+
* changing a few large files: overlayfs copies a whole file up into the new layer when any byte of
|
|
10
|
+
* it changes. The node datastore writes immutable segment files, the plugin cache writes a SQLite
|
|
11
|
+
* file per run (merged in size tiers), and the build state partition files that are only written
|
|
12
|
+
* when their content changed.
|
|
13
|
+
*/
|
|
14
|
+
/** the directory of the plugin cache (`<cacheDir>/caches-lsm`) */
|
|
15
|
+
const PLUGIN_CACHE_DIR = "caches-lsm";
|
|
16
|
+
/** the build state in `cacheDir` (see `openBuildState`) */
|
|
17
|
+
const BUILD_STATE_PATHS = {
|
|
18
|
+
html: "html-state",
|
|
19
|
+
queries: path.join("data", "query-state")
|
|
20
|
+
};
|
|
21
|
+
/** the prefix of `writeFileIfChanged`'s temporary files (`atomic`) */
|
|
22
|
+
const TMP_PREFIX = ".tmp-";
|
|
23
|
+
let tmpCounter = 0;
|
|
24
|
+
/** whether `file` has exactly these bytes (`sizeOnly`: as many) */
|
|
25
|
+
function sameBytes(file, data, sizeOnly = false) {
|
|
26
|
+
try {
|
|
27
|
+
const stat = fs.statSync(file);
|
|
28
|
+
const size = typeof data === "string" ? Buffer.byteLength(data) : data.length;
|
|
29
|
+
if (!stat.isFile() || stat.size !== size) return false;
|
|
30
|
+
return sizeOnly || fs.readFileSync(file).equals(typeof data === "string" ? Buffer.from(data) : data);
|
|
31
|
+
} catch {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Writes `data` to `file` unless the file already has exactly these bytes: a rewrite with the same
|
|
37
|
+
* content still changes the file for a layer diff (overlayfs copies it up).
|
|
38
|
+
* - `atomic`: via a temporary file and a rename, `file` has either its old or its new content
|
|
39
|
+
* - `contentAddressed`: the name has a hash of the content, so the same size is the same content
|
|
40
|
+
*/
|
|
41
|
+
function writeFileIfChanged(file, data, options = {}) {
|
|
42
|
+
if (sameBytes(file, data, options.contentAddressed)) return;
|
|
43
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
44
|
+
if (!options.atomic) return fs.writeFileSync(file, data);
|
|
45
|
+
const tmp = path.join(path.dirname(file), `${TMP_PREFIX}${process.pid}-${tmpCounter++}`);
|
|
46
|
+
fs.writeFileSync(tmp, data);
|
|
47
|
+
renameSync(tmp, file);
|
|
48
|
+
}
|
|
49
|
+
/** where the SSR bundle is built before `syncDirectory` moves it to page-ssr */
|
|
50
|
+
const SSR_BUILD_DIR = "page-ssr.next";
|
|
51
|
+
/** the files under `dir` (relative paths), none when it is missing */
|
|
52
|
+
function listFiles(dir) {
|
|
53
|
+
let entries;
|
|
54
|
+
try {
|
|
55
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
56
|
+
} catch {
|
|
57
|
+
return [];
|
|
58
|
+
}
|
|
59
|
+
return entries.flatMap((e) => e.isDirectory() ? listFiles(path.join(dir, e.name)).map((f) => path.join(e.name, f)) : [e.name]);
|
|
60
|
+
}
|
|
61
|
+
/** removes the empty directories under `dir` (not `dir` itself); returns whether it is empty */
|
|
62
|
+
function pruneEmpty(dir, root = dir) {
|
|
63
|
+
let entries;
|
|
64
|
+
try {
|
|
65
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
66
|
+
} catch {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
let empty = true;
|
|
70
|
+
for (const e of entries) if (!e.isDirectory() || !pruneEmpty(path.join(dir, e.name), root)) empty = false;
|
|
71
|
+
if (empty && dir !== root) fs.rmdirSync(dir);
|
|
72
|
+
return empty;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Makes `dest` hold the files of `src` and removes `src`. Files with the same bytes are left as
|
|
76
|
+
* they are (a rewrite would put them into the next layer), the others are moved, and files `src`
|
|
77
|
+
* doesn't have are deleted.
|
|
78
|
+
*/
|
|
79
|
+
function syncDirectory(src, dest) {
|
|
80
|
+
const wanted = new Set(listFiles(src));
|
|
81
|
+
for (const rel of listFiles(dest)) if (!wanted.has(rel)) fs.rmSync(path.join(dest, rel), { force: true });
|
|
82
|
+
for (const rel of wanted) {
|
|
83
|
+
const from = path.join(src, rel);
|
|
84
|
+
const to = path.join(dest, rel);
|
|
85
|
+
if (sameBytes(to, fs.readFileSync(from))) continue;
|
|
86
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
87
|
+
retrySync(() => fs.rmSync(to, {
|
|
88
|
+
recursive: true,
|
|
89
|
+
force: true
|
|
90
|
+
}));
|
|
91
|
+
renameSync(from, to);
|
|
92
|
+
}
|
|
93
|
+
pruneEmpty(dest);
|
|
94
|
+
fs.rmSync(src, {
|
|
95
|
+
recursive: true,
|
|
96
|
+
force: true
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
export { BUILD_STATE_PATHS, PLUGIN_CACHE_DIR, SSR_BUILD_DIR, TMP_PREFIX, syncDirectory, writeFileIfChanged };
|