goatly 0.0.0-stage → 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/LICENSE +24 -0
- package/README.md +854 -2
- 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 +110 -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,752 @@
|
|
|
1
|
+
import { bootstrap, datastoreRestored, persistState, publicDirWasMissing, restoredGeneration } from "../bootstrap.js";
|
|
2
|
+
import { apiRunnerNode } from "../api-runner.js";
|
|
3
|
+
import { graphqlForApis, runGraphQL } from "../query/graphql-runner.js";
|
|
4
|
+
import { store } from "../redux/index.js";
|
|
5
|
+
import reporter from "../reporter.js";
|
|
6
|
+
import { createViteConfig } from "../vite/config.js";
|
|
7
|
+
import { computeMatchPaths, getPageComponents } from "../vite/plugin.js";
|
|
8
|
+
import { getNodeChangeCount, takeNodeChanges } from "../redux/node-changes.js";
|
|
9
|
+
import { notFoundPagesManifest } from "../not-found-pages.js";
|
|
10
|
+
import { generateHtmlPath, generatePageDataPath } from "../utils/paths.js";
|
|
11
|
+
import { AssetResolver, manifestFingerprint, readManifest } from "./assets.js";
|
|
12
|
+
import { createDirectoryMaker, outputDirs } from "./output-dirs.js";
|
|
13
|
+
import { createInProcessPool, createWorkerPool, defaultWorkerCount, fixedWorkerCount } from "./worker-pool.js";
|
|
14
|
+
import { hasPendingJobs, waitUntilAllJobsComplete } from "../actions/jobs.js";
|
|
15
|
+
import { getDataStore, nodeTypeOf } from "../datastore/index.js";
|
|
16
|
+
import { commitCacheRun, finishCaches, getCacheRun, openPluginCache, releaseCaches } from "../cache.js";
|
|
17
|
+
import { createAdaptivePool, createQueryWorkers, mergeRunResults } from "./query-workers.js";
|
|
18
|
+
import { getRendererDescriptor, getRendererFingerprint } from "../renderer.js";
|
|
19
|
+
import { applyNodeChanges, classifyPages, createQueryState, currentNodeStates, hashString, htmlDigest, htmlRemovedEachBuild, serializeDependencies } from "./incremental.js";
|
|
20
|
+
import { openBuildState } from "./state.js";
|
|
21
|
+
import { syncDirectory, writeFileIfChanged } from "../cache-layout.js";
|
|
22
|
+
import { QueryDependencies } from "../query/dependencies.js";
|
|
23
|
+
import { printSchema } from "../gql.js";
|
|
24
|
+
import { getInferenceMetadata, getSchema } from "../schema/index.js";
|
|
25
|
+
import { clearQueryEngineCaches, clearSlimNodes } from "../schema/query-engine.js";
|
|
26
|
+
import { runtimeName } from "../utils/runtime.js";
|
|
27
|
+
import { collectGarbage, configureBuildHeap, heapText, planQueryWorkers, planRenderWorkers } from "../utils/memory.js";
|
|
28
|
+
import { indexQueries, prepareMainThreadWasm, prepareWorkerWasm, resetWasmMismatches } from "../wasm-data/host.js";
|
|
29
|
+
import { SegmentClock, pipelineParts, pipelinedRenderStart } from "./timing-breakdown.js";
|
|
30
|
+
import { materializedChanges, readSitePageNodes, sitePageNodesCreated, sitePageNodesDependedOn, sitePageNodesWereRead } from "../site-page-nodes.js";
|
|
31
|
+
import { performance } from "node:perf_hooks";
|
|
32
|
+
import { randomUUID } from "node:crypto";
|
|
33
|
+
import path from "node:path";
|
|
34
|
+
import fs from "node:fs";
|
|
35
|
+
import v8 from "node:v8";
|
|
36
|
+
import { build as build$1 } from "vite";
|
|
37
|
+
// src/node/build/index.ts
|
|
38
|
+
const GENERATOR = "goatly 0.1.1";
|
|
39
|
+
const IN_PROCESS_THRESHOLD = 150;
|
|
40
|
+
const BATCH_SIZE = 32;
|
|
41
|
+
/**
|
|
42
|
+
* Minimum number of page queries to run them in query workers. Every worker rebuilds the whole
|
|
43
|
+
* data layer (seconds and memory for large sites), so a few dirty queries of an incremental build
|
|
44
|
+
* of a large site run faster in the main thread (overridable for tests).
|
|
45
|
+
*/
|
|
46
|
+
function parallelQueryThreshold(pageCount) {
|
|
47
|
+
const configured = Number(process.env.GOATLY_PARALLEL_QUERY_THRESHOLD);
|
|
48
|
+
if (configured > 0) return configured;
|
|
49
|
+
return Math.max(500, Math.min(2e3, Math.round(pageCount / 4)));
|
|
50
|
+
}
|
|
51
|
+
/** e.g. "3 workers", "2–5 workers, 1 stopped for memory" (the adaptive pool) */
|
|
52
|
+
function workersText(started, w) {
|
|
53
|
+
return `${w.min === w.peak ? `${started}` : `${w.min}–${w.peak}`} workers${w.shed ? `, ${w.shed} stopped for memory` : ""}`;
|
|
54
|
+
}
|
|
55
|
+
async function mapLimit(items, limit, fn) {
|
|
56
|
+
const results = Array.from({ length: items.length });
|
|
57
|
+
let next = 0;
|
|
58
|
+
const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
59
|
+
while (next < items.length) {
|
|
60
|
+
const i = next++;
|
|
61
|
+
results[i] = await fn(items[i], i);
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
await Promise.all(runners);
|
|
65
|
+
return results;
|
|
66
|
+
}
|
|
67
|
+
async function writeJson(file, value) {
|
|
68
|
+
await fs.promises.mkdir(path.dirname(file), { recursive: true });
|
|
69
|
+
await fs.promises.writeFile(file, JSON.stringify(value));
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* `gatsby build`: bootstrap → static queries → (Vite client + SSR builds ‖ page queries) →
|
|
73
|
+
* HTML + page-data rendering in worker threads → onPostBuild.
|
|
74
|
+
*
|
|
75
|
+
* Large sites use parallel query running: worker threads load the datastore (e.g. the logfile store's
|
|
76
|
+
* file), run the page queries while the main thread bundles
|
|
77
|
+
* and then render their pages.
|
|
78
|
+
*/
|
|
79
|
+
async function build(options) {
|
|
80
|
+
const t0 = performance.now();
|
|
81
|
+
const timings = {};
|
|
82
|
+
const segments = new SegmentClock(t0);
|
|
83
|
+
process.env.NODE_ENV = "production";
|
|
84
|
+
if (options.reporter) reporter.setTransports(options.reporter);
|
|
85
|
+
reporter.isBuild = true;
|
|
86
|
+
configureBuildHeap();
|
|
87
|
+
await bootstrap({
|
|
88
|
+
directory: options.directory,
|
|
89
|
+
command: "build",
|
|
90
|
+
prefixPaths: options.prefixPaths,
|
|
91
|
+
verbose: options.verbose
|
|
92
|
+
});
|
|
93
|
+
timings.bootstrap = performance.now() - t0;
|
|
94
|
+
segments.until("bootstrap");
|
|
95
|
+
clearQueryEngineCaches({ keepSlimNodes: true });
|
|
96
|
+
store.getState().nodesTouched.clear();
|
|
97
|
+
const state = store.getState();
|
|
98
|
+
const { program, config } = state;
|
|
99
|
+
const publicDir = program.publicDir;
|
|
100
|
+
const hadOutput = fs.existsSync(path.join(publicDir, "page-data", "app-data.json"));
|
|
101
|
+
fs.mkdirSync(publicDir, { recursive: true });
|
|
102
|
+
await apiRunnerNode("onPreBuild", { graphql: graphqlForApis });
|
|
103
|
+
let queryErrors = 0;
|
|
104
|
+
const activity = reporter.activityTimer("run static queries");
|
|
105
|
+
activity.start();
|
|
106
|
+
const tStatic = performance.now();
|
|
107
|
+
const staticResults = /* @__PURE__ */ new Map();
|
|
108
|
+
const staticQueries = [...state.staticQueryComponents.values()];
|
|
109
|
+
await mapLimit(staticQueries, 16, async (sq) => {
|
|
110
|
+
const result = await runGraphQL(sq.query, {}, `sq--${sq.hash}`);
|
|
111
|
+
if (result.errors?.length) {
|
|
112
|
+
queryErrors++;
|
|
113
|
+
reporter.error({
|
|
114
|
+
id: "95313",
|
|
115
|
+
context: { sourceMessage: `Error in static query in ${sq.componentPath}:\n${result.errors.map((e) => e.message).join("\n")}` }
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
staticResults.set(sq.hash, result.data);
|
|
119
|
+
await writeJson(path.join(publicDir, "page-data", "sq", "d", `${sq.hash}.json`), { data: result.data });
|
|
120
|
+
});
|
|
121
|
+
activity.setStatus(`${staticQueries.length} queries`);
|
|
122
|
+
activity.end();
|
|
123
|
+
timings.staticQueries = performance.now() - tStatic;
|
|
124
|
+
segments.until("staticQueries");
|
|
125
|
+
const pluginCtx = {
|
|
126
|
+
command: "build",
|
|
127
|
+
buildHash: "",
|
|
128
|
+
devSSR: false,
|
|
129
|
+
getStaticQueryResult: (hash) => staticResults.get(hash)
|
|
130
|
+
};
|
|
131
|
+
fs.rmSync(path.join(publicDir, "assets"), {
|
|
132
|
+
recursive: true,
|
|
133
|
+
force: true
|
|
134
|
+
});
|
|
135
|
+
const tBundle = performance.now();
|
|
136
|
+
const bundleActivity = reporter.activityTimer("build JavaScript and HTML renderer (Vite + Rolldown)");
|
|
137
|
+
bundleActivity.start();
|
|
138
|
+
const bundlePromise = (async () => {
|
|
139
|
+
const [clientConfig, ssrConfig] = await Promise.all([createViteConfig({
|
|
140
|
+
stage: "build-javascript",
|
|
141
|
+
ctx: pluginCtx
|
|
142
|
+
}), createViteConfig({
|
|
143
|
+
stage: "build-html",
|
|
144
|
+
ctx: pluginCtx
|
|
145
|
+
})]);
|
|
146
|
+
await Promise.all([build$1(clientConfig), build$1(ssrConfig)]);
|
|
147
|
+
const ssrOutDir = ssrConfig.build?.outDir;
|
|
148
|
+
const pageSsrDir = path.join(program.cacheDir, "page-ssr");
|
|
149
|
+
if (ssrOutDir && path.resolve(ssrOutDir) !== pageSsrDir) syncDirectory(ssrOutDir, pageSsrDir);
|
|
150
|
+
timings.bundle = performance.now() - tBundle;
|
|
151
|
+
bundleActivity.end();
|
|
152
|
+
})();
|
|
153
|
+
bundlePromise.catch(() => {});
|
|
154
|
+
const pages = [...state.pages.values()];
|
|
155
|
+
const pagePrefix = program.prefixPaths ? `${config.assetPrefix || ""}${config.pathPrefix || ""}` : "";
|
|
156
|
+
const base = `${pagePrefix}/`;
|
|
157
|
+
const buildState = openBuildState(program.cacheDir);
|
|
158
|
+
resetWasmMismatches(program.cacheDir);
|
|
159
|
+
const previous = buildState.readHtml();
|
|
160
|
+
const renderedSsrHash = publicDirWasMissing ? void 0 : previous?.ssrHash;
|
|
161
|
+
/**
|
|
162
|
+
* Which pages' files probably exist (an earlier build wrote them): they are overwritten in place
|
|
163
|
+
* (see writePageFile). None when public/ was missing or empty; without an HTML state, any page's
|
|
164
|
+
* when public/ holds the output of a completed build; else those of the pages the state lists.
|
|
165
|
+
*/
|
|
166
|
+
const outputFiles = publicDirWasMissing ? "none" : previous ? "listed" : hadOutput ? "any" : "none";
|
|
167
|
+
const filesExist = (pagePath) => outputFiles === "any" || outputFiles === "listed" && previous?.pages[pagePath] !== void 0;
|
|
168
|
+
const prepareRender = () => {
|
|
169
|
+
const manifest = readManifest(publicDir);
|
|
170
|
+
fs.rmSync(path.join(publicDir, ".vite"), {
|
|
171
|
+
recursive: true,
|
|
172
|
+
force: true
|
|
173
|
+
});
|
|
174
|
+
fs.writeFileSync(path.join(publicDir, "chunk-map.json"), JSON.stringify(new AssetResolver(manifest, program.directory, base).chunkMap(getPageComponents())));
|
|
175
|
+
const buildHash = hashString(manifestFingerprint(manifest));
|
|
176
|
+
const ssrBundle = path.join(program.cacheDir, "page-ssr", "render-page.mjs");
|
|
177
|
+
const ssrHash = hashString(fs.readFileSync(ssrBundle, "utf8") + JSON.stringify(manifest) + JSON.stringify({
|
|
178
|
+
inlinePageData: !!config.inlinePageData,
|
|
179
|
+
inlineCss: !!config.inlineCss,
|
|
180
|
+
base,
|
|
181
|
+
pagePrefix
|
|
182
|
+
}) + getRendererFingerprint() + GENERATOR);
|
|
183
|
+
const rendererDescriptor = getRendererDescriptor();
|
|
184
|
+
return {
|
|
185
|
+
manifest,
|
|
186
|
+
buildHash,
|
|
187
|
+
ssrHash,
|
|
188
|
+
rendererOptions: {
|
|
189
|
+
ssrBundle,
|
|
190
|
+
buildHash,
|
|
191
|
+
inlinePageData: !!config.inlinePageData,
|
|
192
|
+
inlineCss: !!config.inlineCss,
|
|
193
|
+
publicDir,
|
|
194
|
+
generator: GENERATOR,
|
|
195
|
+
renderer: rendererDescriptor && {
|
|
196
|
+
descriptor: rendererDescriptor,
|
|
197
|
+
root: program.directory
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
};
|
|
202
|
+
const componentQueries = {};
|
|
203
|
+
for (const [componentPath, c] of state.components) if (c.query) componentQueries[componentPath] = c.query;
|
|
204
|
+
const ds = getDataStore();
|
|
205
|
+
const previousQueries = process.env.GOATLY_INCREMENTAL_QUERIES === "false" ? null : buildState.readQueries();
|
|
206
|
+
const schemaHash = hashString(`${printSchema(getSchema())}\0${program.prefixPaths ? `${config.assetPrefix ?? ""}|${config.pathPrefix ?? ""}` : ""}`);
|
|
207
|
+
const current = currentNodeStates({
|
|
208
|
+
base: previousQueries?.generation !== void 0 && datastoreRestored && previousQueries.generation === restoredGeneration ? previousQueries : null,
|
|
209
|
+
restored: datastoreRestored,
|
|
210
|
+
changes: takeNodeChanges(),
|
|
211
|
+
store: ds
|
|
212
|
+
});
|
|
213
|
+
const nextQueries = createQueryState(schemaHash, current.states, current.count);
|
|
214
|
+
let changesAtSnapshot = getNodeChangeCount();
|
|
215
|
+
let materializedAtSnapshot = materializedChanges();
|
|
216
|
+
/**
|
|
217
|
+
* Adds the node changes since the digests were taken to them when they are all SitePage nodes
|
|
218
|
+
* created for the pages by their first read (e.g. a query in a worker, gatsby-plugin-sitemap in
|
|
219
|
+
* onPostBuild): no query that ran before read these nodes. False when other nodes changed.
|
|
220
|
+
*/
|
|
221
|
+
const takeMaterializedChanges = () => {
|
|
222
|
+
const changes = getNodeChangeCount() - changesAtSnapshot;
|
|
223
|
+
if (changes === 0) return true;
|
|
224
|
+
if (changes !== materializedChanges() - materializedAtSnapshot) return false;
|
|
225
|
+
nextQueries.nodeCount = applyNodeChanges(nextQueries.nodes, nextQueries.nodeCount ?? Object.keys(nextQueries.nodes).length, takeNodeChanges());
|
|
226
|
+
changesAtSnapshot = getNodeChangeCount();
|
|
227
|
+
materializedAtSnapshot = materializedChanges();
|
|
228
|
+
return true;
|
|
229
|
+
};
|
|
230
|
+
const { dirty, clean, queryHashes, reason } = classifyPages({
|
|
231
|
+
pages,
|
|
232
|
+
componentQueries,
|
|
233
|
+
previous: previousQueries,
|
|
234
|
+
nodes: nextQueries.nodes,
|
|
235
|
+
changed: current.changed,
|
|
236
|
+
schemaHash
|
|
237
|
+
});
|
|
238
|
+
for (const page of clean) nextQueries.pages[page.path] = previousQueries.pages[page.path];
|
|
239
|
+
/** page query results recorded in this build (also queries run for a page-data.json that was gone) */
|
|
240
|
+
let queriesRecorded = 0;
|
|
241
|
+
const recordQuery = ([pagePath, r, n, c]) => {
|
|
242
|
+
queriesRecorded++;
|
|
243
|
+
nextQueries.pages[pagePath] = {
|
|
244
|
+
q: queryHashes.get(pagePath),
|
|
245
|
+
r,
|
|
246
|
+
n,
|
|
247
|
+
c
|
|
248
|
+
};
|
|
249
|
+
};
|
|
250
|
+
if (previousQueries && reason) reporter.info(`Running all page queries: ${reason}`);
|
|
251
|
+
const unchangedQueries = clean.length ? `${clean.length} unchanged` : "";
|
|
252
|
+
const fixedWorkers = fixedWorkerCount();
|
|
253
|
+
const workerCount = fixedWorkers ?? defaultWorkerCount(config.renderWorkers);
|
|
254
|
+
let wantParallel = dirty.length >= parallelQueryThreshold(pages.length) && workerCount > 1 && config.parallelQueryRunning !== false && process.env.GOATLY_PARALLEL_QUERIES !== "false" && typeof ds.persist === "function" && typeof ds.load === "function";
|
|
255
|
+
if (wantParallel && !openPluginCache().shared) {
|
|
256
|
+
reporter.verbose("plugin cache not shared between threads – running the page queries in the main thread");
|
|
257
|
+
wantParallel = false;
|
|
258
|
+
}
|
|
259
|
+
if (wantParallel) {
|
|
260
|
+
clearSlimNodes();
|
|
261
|
+
ds.trimCache?.();
|
|
262
|
+
releaseCaches();
|
|
263
|
+
}
|
|
264
|
+
const workerPlan = planQueryWorkers({
|
|
265
|
+
wanted: workerCount,
|
|
266
|
+
heapUsedMb: process.memoryUsage().heapUsed / 1048576,
|
|
267
|
+
sharedDatastore: !!ds.sharedAcrossThreads
|
|
268
|
+
});
|
|
269
|
+
const adaptive = wantParallel && workerCount > 1 && fixedWorkers === void 0 ? createAdaptivePool(workerCount, workerPlan) : void 0;
|
|
270
|
+
if (adaptive) workerPlan.count = adaptive.initialCount;
|
|
271
|
+
if (wantParallel) reporter.verbose(`query workers: ${workerPlan.count}, ${heapText(workerPlan.heap)}`);
|
|
272
|
+
if (adaptive) reporter.verbose(adaptive.startText);
|
|
273
|
+
if (wantParallel && !adaptive && workerPlan.count < workerCount) reporter.warn(`Not enough memory for ${workerCount} query workers (about ${workerPlan.perWorkerMb} MB each) – using ${workerPlan.count >= 2 ? workerPlan.count : "the main thread"}.${ds.sharedAcrossThreads ? "" : " A datastore shared between threads (the default logfile store or SQLite) needs less memory."}`);
|
|
274
|
+
const parallel = wantParallel && workerPlan.count >= (adaptive ? 1 : 2);
|
|
275
|
+
if (wantParallel && !parallel) adaptive?.close();
|
|
276
|
+
const nextState = {
|
|
277
|
+
ssrHash: "",
|
|
278
|
+
pages: {}
|
|
279
|
+
};
|
|
280
|
+
let setup;
|
|
281
|
+
let skipped = 0;
|
|
282
|
+
/**
|
|
283
|
+
* pages query workers did not build (no worker could be started any more, or their queries read
|
|
284
|
+
* SitePage nodes the workers didn't have)
|
|
285
|
+
*/
|
|
286
|
+
let leftovers = [];
|
|
287
|
+
/**
|
|
288
|
+
* of those, pages whose query has to run and that no query worker could build: queried when
|
|
289
|
+
* their render batch comes (their results would otherwise be held here all at once until
|
|
290
|
+
* rendering – the memory the workers may just have run out of)
|
|
291
|
+
*/
|
|
292
|
+
const queriedLater = /* @__PURE__ */ new Set();
|
|
293
|
+
let rendered = 0;
|
|
294
|
+
let renderErrors = [];
|
|
295
|
+
const reportQueryErrors = (errors) => {
|
|
296
|
+
for (const e of errors.slice(0, 20)) reporter.error({
|
|
297
|
+
id: "85925",
|
|
298
|
+
context: { sourceMessage: `Error running page query for "${e.pagePath}":\n${e.message}` }
|
|
299
|
+
});
|
|
300
|
+
queryErrors += errors.length;
|
|
301
|
+
};
|
|
302
|
+
const panicOnQueryErrors = () => {
|
|
303
|
+
if (queryErrors) reporter.panic(`Failed to run ${queryErrors} queries – see the errors above.`);
|
|
304
|
+
};
|
|
305
|
+
let htmlPending = false;
|
|
306
|
+
const markHtmlPending = () => {
|
|
307
|
+
if (htmlPending) return;
|
|
308
|
+
htmlPending = true;
|
|
309
|
+
buildState.markHtmlPending(previous, pages.map((p) => p.path));
|
|
310
|
+
};
|
|
311
|
+
if (parallel || publicDirWasMissing && previous) markHtmlPending();
|
|
312
|
+
let pendingWritten;
|
|
313
|
+
const writePendingState = () => {
|
|
314
|
+
if (pendingWritten) return pendingWritten;
|
|
315
|
+
pendingWritten = (async () => {
|
|
316
|
+
if (previousQueries && dirty.length) await buildState.writeQueries(nextQueries, { pending: true });
|
|
317
|
+
})();
|
|
318
|
+
pendingWritten.catch(() => {});
|
|
319
|
+
return pendingWritten;
|
|
320
|
+
};
|
|
321
|
+
if (parallel) try {
|
|
322
|
+
const tWork = performance.now();
|
|
323
|
+
const progress = reporter.createProgress("run page queries and build static HTML", pages.length);
|
|
324
|
+
let queried = 0;
|
|
325
|
+
/** the query workers running now (the adaptive pool changes their number) */
|
|
326
|
+
let workersNow = workerPlan.count;
|
|
327
|
+
const liveStatus = () => queried ? `${workersNow} workers, ${Math.min(queried, dirty.length)}/${dirty.length} queries` : `starting ${workersNow} query workers`;
|
|
328
|
+
progress.setStatus(liveStatus());
|
|
329
|
+
progress.start();
|
|
330
|
+
const sitePageNodes = sitePageNodesCreated();
|
|
331
|
+
await commitCacheRun(() => ds.persist());
|
|
332
|
+
const inferenceFile = path.join(program.cacheDir, "data", "inference.v8");
|
|
333
|
+
const inference = getInferenceMetadata();
|
|
334
|
+
if (inference) writeFileIfChanged(inferenceFile, v8.serialize(inference));
|
|
335
|
+
collectGarbage();
|
|
336
|
+
const persistMs = performance.now() - tWork;
|
|
337
|
+
const { queryTexts, components: workerQueries } = indexQueries(componentQueries);
|
|
338
|
+
const setupPromise = bundlePromise.then(prepareRender);
|
|
339
|
+
const renderJob = setupPromise.then(async (s) => {
|
|
340
|
+
await writePendingState();
|
|
341
|
+
return {
|
|
342
|
+
renderer: s.rendererOptions,
|
|
343
|
+
manifest: s.manifest,
|
|
344
|
+
root: program.directory,
|
|
345
|
+
base,
|
|
346
|
+
pagePrefix,
|
|
347
|
+
publicDir,
|
|
348
|
+
ssrHash: s.ssrHash,
|
|
349
|
+
previousSsrHash: renderedSsrHash ?? null,
|
|
350
|
+
outputFiles
|
|
351
|
+
};
|
|
352
|
+
});
|
|
353
|
+
const items = dirty.map((page) => ({
|
|
354
|
+
page,
|
|
355
|
+
previous: previous?.pages[page.path]
|
|
356
|
+
}));
|
|
357
|
+
for (const page of clean) items.push({
|
|
358
|
+
page,
|
|
359
|
+
resultHash: nextQueries.pages[page.path].r,
|
|
360
|
+
previous: previous?.pages[page.path]
|
|
361
|
+
});
|
|
362
|
+
let startedWorkers = 0;
|
|
363
|
+
/** builds the items in query workers (`withSitePages`: their nodes include SitePage nodes) */
|
|
364
|
+
const runWorkers = async (work, withSitePages) => {
|
|
365
|
+
const wasm = await prepareWorkerWasm({
|
|
366
|
+
ds,
|
|
367
|
+
schema: getSchema(),
|
|
368
|
+
queryTexts,
|
|
369
|
+
componentQueries: workerQueries,
|
|
370
|
+
components: work.flatMap((item) => item.resultHash === void 0 ? [item.page.componentPath] : []),
|
|
371
|
+
cacheDir: program.cacheDir
|
|
372
|
+
});
|
|
373
|
+
const queriesInWasm = () => !!wasm && !!ds.sharedAcrossThreads && work.every((item) => item.resultHash !== void 0 || wasm.covers(item.page.componentPath));
|
|
374
|
+
const inWasm = queriesInWasm();
|
|
375
|
+
adaptive?.queriesInWasm(false);
|
|
376
|
+
const jsCount = adaptive && startedWorkers ? adaptive.countNow() : workerPlan.count;
|
|
377
|
+
adaptive?.queriesInWasm(inWasm);
|
|
378
|
+
const count = adaptive && inWasm ? Math.max(jsCount, adaptive.countNow(!!startedWorkers)) : jsCount;
|
|
379
|
+
if (count > jsCount) reporter.verbose(`query workers: the page queries run in WASM – ${count} to start (of at most ${workerCount})`);
|
|
380
|
+
let started;
|
|
381
|
+
let result;
|
|
382
|
+
try {
|
|
383
|
+
const queryWorkers = started = createQueryWorkers(count, {
|
|
384
|
+
directory: program.directory,
|
|
385
|
+
prefixPaths: program.prefixPaths,
|
|
386
|
+
queryTexts,
|
|
387
|
+
componentQueries: workerQueries,
|
|
388
|
+
inferenceFile: inference ? inferenceFile : void 0,
|
|
389
|
+
renderer: getRendererDescriptor() ?? null,
|
|
390
|
+
sitePageNodes: withSitePages,
|
|
391
|
+
cacheRun: getCacheRun()
|
|
392
|
+
}, {
|
|
393
|
+
heap: workerPlan.heap,
|
|
394
|
+
minFreeMb: workerPlan.perWorkerMb,
|
|
395
|
+
adaptive: adaptive?.pool,
|
|
396
|
+
wasm: wasm && {
|
|
397
|
+
options: () => wasm.workerOptions(),
|
|
398
|
+
stop: (o) => wasm.stopWorker(o),
|
|
399
|
+
exited: (o) => wasm.workerExited(o)
|
|
400
|
+
}
|
|
401
|
+
});
|
|
402
|
+
writePendingState();
|
|
403
|
+
wasm?.build();
|
|
404
|
+
const stillInWasm = queriesInWasm();
|
|
405
|
+
adaptive?.queriesInWasm(stillInWasm);
|
|
406
|
+
if (!stillInWasm && count > jsCount) {
|
|
407
|
+
queryWorkers.trim(jsCount);
|
|
408
|
+
reporter.verbose(`query workers: the store took fewer page queries than were lowered – ${queryWorkers.size} to start`);
|
|
409
|
+
}
|
|
410
|
+
wasm?.onGiveUp(() => adaptive?.queriesInWasm(false));
|
|
411
|
+
startedWorkers ||= queryWorkers.size;
|
|
412
|
+
result = await queryWorkers.run(work, renderJob, {
|
|
413
|
+
onQueried: (n) => {
|
|
414
|
+
queried += n;
|
|
415
|
+
workersNow = queryWorkers.size;
|
|
416
|
+
progress.setStatus(liveStatus());
|
|
417
|
+
},
|
|
418
|
+
onRendered: (n) => progress.tick(n)
|
|
419
|
+
});
|
|
420
|
+
} finally {
|
|
421
|
+
await started?.close();
|
|
422
|
+
wasm?.close();
|
|
423
|
+
}
|
|
424
|
+
wasm?.finish();
|
|
425
|
+
return result;
|
|
426
|
+
};
|
|
427
|
+
let res = await runWorkers(items, sitePageNodes);
|
|
428
|
+
if (res.sitePagesRead || res.deferred.length) readSitePageNodes("a page query in a query worker");
|
|
429
|
+
const rebuilt = res.deferred.length;
|
|
430
|
+
const again = rebuilt >= parallelQueryThreshold(pages.length);
|
|
431
|
+
if (rebuilt) reporter.info(`Building ${rebuilt} page(s) ${again ? "again in query workers" : "in the main thread"}: their queries read SitePage nodes, which the query workers did not have. The next build creates them up front.`);
|
|
432
|
+
if (again) {
|
|
433
|
+
await commitCacheRun(() => ds.persist());
|
|
434
|
+
res = mergeRunResults(res, await runWorkers(res.deferred, true));
|
|
435
|
+
}
|
|
436
|
+
adaptive?.close();
|
|
437
|
+
setup = await setupPromise;
|
|
438
|
+
reportQueryErrors(res.queryErrors);
|
|
439
|
+
for (const q of res.queries) recordQuery(q);
|
|
440
|
+
const queriesRun = res.queries.length;
|
|
441
|
+
const workerTimings = res.timings;
|
|
442
|
+
Object.assign(nextState.pages, res.render.digests);
|
|
443
|
+
skipped = res.render.skipped;
|
|
444
|
+
rendered = res.render.rendered;
|
|
445
|
+
renderErrors = res.render.errors;
|
|
446
|
+
leftovers = res.unfinished;
|
|
447
|
+
const deferredItems = res.deferred;
|
|
448
|
+
progress.total = pages.length - leftovers.length - deferredItems.length;
|
|
449
|
+
progress.setStatus([
|
|
450
|
+
workersText(startedWorkers, res.workers),
|
|
451
|
+
`${queriesRun} queries`,
|
|
452
|
+
skipped && `${skipped} unchanged`,
|
|
453
|
+
res.recovered && `${res.recovered} out of memory`,
|
|
454
|
+
again && `${rebuilt} again with SitePage nodes`,
|
|
455
|
+
leftovers.length + deferredItems.length && `${leftovers.length + deferredItems.length} left to the main thread`
|
|
456
|
+
].filter(Boolean).join(", "));
|
|
457
|
+
const stepEnd = performance.timeOrigin + performance.now();
|
|
458
|
+
progress.end();
|
|
459
|
+
const start = performance.timeOrigin + tWork;
|
|
460
|
+
reporter.activityParts(progress, pipelineParts({
|
|
461
|
+
start,
|
|
462
|
+
end: stepEnd,
|
|
463
|
+
persistMs,
|
|
464
|
+
workers: startedWorkers,
|
|
465
|
+
timings: workerTimings,
|
|
466
|
+
queries: queriesRun,
|
|
467
|
+
rendered,
|
|
468
|
+
skipped
|
|
469
|
+
}));
|
|
470
|
+
timings.queriesAndRender = performance.now() - tWork;
|
|
471
|
+
const toLocal = (epochMs) => epochMs - performance.timeOrigin;
|
|
472
|
+
const queriesDone = Math.max(workerTimings.ready, workerTimings.query.end);
|
|
473
|
+
segments.until("queryWorkers", toLocal(workerTimings.ready));
|
|
474
|
+
segments.until("pageQueries", toLocal(queriesDone));
|
|
475
|
+
if (workerTimings.renderJob) segments.until("bundle", toLocal(workerTimings.renderJob));
|
|
476
|
+
const renderStart = pipelinedRenderStart(workerTimings);
|
|
477
|
+
segments.until("render", void 0, renderStart && toLocal(renderStart));
|
|
478
|
+
timings.queryWorkers = workerTimings.ready - start;
|
|
479
|
+
timings.pageQueries = Math.max(0, workerTimings.query.end - workerTimings.query.start);
|
|
480
|
+
timings.render = Math.max(0, workerTimings.render.end - workerTimings.render.start);
|
|
481
|
+
panicOnQueryErrors();
|
|
482
|
+
if (leftovers.length) reporter.warn(`Building ${leftovers.length} page(s) in the main thread: no query worker could be started any more.`);
|
|
483
|
+
for (const item of leftovers) if (item.resultHash === void 0) queriedLater.add(item.page.path);
|
|
484
|
+
leftovers = [...leftovers, ...deferredItems];
|
|
485
|
+
} finally {
|
|
486
|
+
adaptive?.close();
|
|
487
|
+
}
|
|
488
|
+
if (!parallel || leftovers.length) {
|
|
489
|
+
await writePendingState();
|
|
490
|
+
const queryPages = parallel ? leftovers.filter((item) => item.resultHash === void 0 && !queriedLater.has(item.page.path)).map((item) => item.page) : dirty;
|
|
491
|
+
const renderPages = parallel ? leftovers.map((item) => item.page) : pages;
|
|
492
|
+
const tQueries = performance.now();
|
|
493
|
+
const progress = reporter.createProgress("run page queries", queryPages.length);
|
|
494
|
+
progress.start();
|
|
495
|
+
const results = /* @__PURE__ */ new Map();
|
|
496
|
+
const wasm = await prepareMainThreadWasm({
|
|
497
|
+
ds,
|
|
498
|
+
schema: getSchema(),
|
|
499
|
+
componentQueries,
|
|
500
|
+
components: [...queryPages.map((page) => page.componentPath), ...renderPages.flatMap((page) => queriedLater.has(page.path) ? [page.componentPath] : [])],
|
|
501
|
+
cacheDir: program.cacheDir
|
|
502
|
+
});
|
|
503
|
+
const wasmResults = wasm?.run(queryPages) ?? /* @__PURE__ */ new Map();
|
|
504
|
+
/** the pages WASM ran (or fell back on) above */
|
|
505
|
+
const triedInWasm = wasm && new Set(queryPages.map((page) => page.path));
|
|
506
|
+
const runPageQuery = async (page) => {
|
|
507
|
+
const query = componentQueries[page.componentPath];
|
|
508
|
+
let wasmResult = wasmResults.get(page.path);
|
|
509
|
+
if (wasmResult) wasmResults.delete(page.path);
|
|
510
|
+
else if (wasm && query && !triedInWasm.has(page.path)) wasmResult = wasm.run([page]).get(page.path);
|
|
511
|
+
if (wasmResult && wasm.mode !== "verify") {
|
|
512
|
+
recordQuery([
|
|
513
|
+
page.path,
|
|
514
|
+
hashString(wasmResult.resultJson),
|
|
515
|
+
wasmResult.n,
|
|
516
|
+
wasmResult.c
|
|
517
|
+
]);
|
|
518
|
+
return wasmResult.resultJson;
|
|
519
|
+
}
|
|
520
|
+
const deps = new QueryDependencies();
|
|
521
|
+
let data;
|
|
522
|
+
let errors = 0;
|
|
523
|
+
if (query) {
|
|
524
|
+
const res = await runGraphQL(query, {
|
|
525
|
+
...page,
|
|
526
|
+
...page.context
|
|
527
|
+
}, page.path, deps, { plainObjects: true });
|
|
528
|
+
if (res.errors?.length) {
|
|
529
|
+
errors = res.errors.length;
|
|
530
|
+
reportQueryErrors([{
|
|
531
|
+
pagePath: page.path,
|
|
532
|
+
message: res.errors.map((e) => e.message).join("\n")
|
|
533
|
+
}]);
|
|
534
|
+
}
|
|
535
|
+
data = res.data;
|
|
536
|
+
}
|
|
537
|
+
const resultJson = JSON.stringify({
|
|
538
|
+
data,
|
|
539
|
+
pageContext: page.context
|
|
540
|
+
});
|
|
541
|
+
const { n, c } = serializeDependencies(deps, nodeTypeOf);
|
|
542
|
+
if (wasmResult) wasm.compare(page, wasmResult, {
|
|
543
|
+
resultJson,
|
|
544
|
+
n,
|
|
545
|
+
c,
|
|
546
|
+
errors
|
|
547
|
+
});
|
|
548
|
+
recordQuery([
|
|
549
|
+
page.path,
|
|
550
|
+
hashString(resultJson),
|
|
551
|
+
n,
|
|
552
|
+
c
|
|
553
|
+
]);
|
|
554
|
+
return resultJson;
|
|
555
|
+
};
|
|
556
|
+
await mapLimit(queryPages, 64, async (page) => {
|
|
557
|
+
results.set(page.path, await runPageQuery(page));
|
|
558
|
+
progress.tick();
|
|
559
|
+
});
|
|
560
|
+
progress.setStatus(parallel ? "" : unchangedQueries);
|
|
561
|
+
progress.end();
|
|
562
|
+
timings.pageQueries = (parallel ? timings.pageQueries : 0) + performance.now() - tQueries;
|
|
563
|
+
segments.until("pageQueries");
|
|
564
|
+
panicOnQueryErrors();
|
|
565
|
+
if (!parallel) {
|
|
566
|
+
await bundlePromise;
|
|
567
|
+
setup = prepareRender();
|
|
568
|
+
segments.until("bundle");
|
|
569
|
+
}
|
|
570
|
+
const tRender = performance.now();
|
|
571
|
+
const renderProgress = reporter.createProgress("build static HTML for pages", renderPages.length);
|
|
572
|
+
renderProgress.start();
|
|
573
|
+
const assets = new AssetResolver(setup.manifest, program.directory, base);
|
|
574
|
+
const outdated = [];
|
|
575
|
+
let skippedHere = 0;
|
|
576
|
+
for (const page of renderPages) {
|
|
577
|
+
if (queriedLater.has(page.path)) {
|
|
578
|
+
outdated.push(page);
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
const digest = htmlDigest(page, nextQueries.pages[page.path].r);
|
|
582
|
+
nextState.pages[page.path] = digest;
|
|
583
|
+
if (renderedSsrHash === setup.ssrHash && previous?.pages[page.path] === digest && !htmlRemovedEachBuild(page.path)) {
|
|
584
|
+
skipped++;
|
|
585
|
+
skippedHere++;
|
|
586
|
+
continue;
|
|
587
|
+
}
|
|
588
|
+
outdated.push(page);
|
|
589
|
+
}
|
|
590
|
+
renderProgress.total = outdated.length;
|
|
591
|
+
const toTask = async (page, rerun = false) => {
|
|
592
|
+
let resultJson = results.get(page.path);
|
|
593
|
+
results.delete(page.path);
|
|
594
|
+
if (resultJson === void 0 && (rerun || queriedLater.has(page.path))) {
|
|
595
|
+
resultJson = await runPageQuery(page);
|
|
596
|
+
nextState.pages[page.path] = htmlDigest(page, nextQueries.pages[page.path].r);
|
|
597
|
+
}
|
|
598
|
+
const fixed = page.path === "/" ? "index" : page.path.replace(/^\/|\/$/g, "");
|
|
599
|
+
return {
|
|
600
|
+
pagePath: page.path,
|
|
601
|
+
componentChunkName: page.componentChunkName,
|
|
602
|
+
matchPath: page.matchPath,
|
|
603
|
+
resultJson,
|
|
604
|
+
assets: assets.forComponents([page.componentPath]),
|
|
605
|
+
pageDataUrl: `${pagePrefix}/page-data/${fixed}/page-data.json`,
|
|
606
|
+
htmlFile: generateHtmlPath(publicDir, page.path),
|
|
607
|
+
pageDataFile: generatePageDataPath(publicDir, page.path),
|
|
608
|
+
filesExist: filesExist(page.path)
|
|
609
|
+
};
|
|
610
|
+
};
|
|
611
|
+
let status = "";
|
|
612
|
+
if (outdated.length) {
|
|
613
|
+
markHtmlPending();
|
|
614
|
+
const renderPlan = outdated.length < IN_PROCESS_THRESHOLD || workerCount === 1 || parallel ? void 0 : planRenderWorkers({
|
|
615
|
+
wanted: workerCount,
|
|
616
|
+
batches: Math.ceil(outdated.length / BATCH_SIZE)
|
|
617
|
+
});
|
|
618
|
+
if (renderPlan) reporter.verbose(`render workers: ${renderPlan.count}, ${heapText(renderPlan.heap)}`);
|
|
619
|
+
const pool = !renderPlan || renderPlan.count < 2 ? await createInProcessPool(setup.rendererOptions) : createWorkerPool(setup.rendererOptions, renderPlan.count, renderPlan.heap);
|
|
620
|
+
const batches = [];
|
|
621
|
+
for (let i = 0; i < outdated.length; i += BATCH_SIZE) batches.push(outdated.slice(i, i + BATCH_SIZE));
|
|
622
|
+
const dirs = createDirectoryMaker(publicDir);
|
|
623
|
+
try {
|
|
624
|
+
await mapLimit(batches, Math.max(4, pool.size * 3), async (batch) => {
|
|
625
|
+
let tasks = await Promise.all(batch.map((page) => toTask(page)));
|
|
626
|
+
while (tasks.length) {
|
|
627
|
+
await dirs.ensure(outputDirs(tasks));
|
|
628
|
+
const res = await pool.render(tasks);
|
|
629
|
+
rendered += res.rendered;
|
|
630
|
+
renderProgress.tick(res.rendered);
|
|
631
|
+
renderErrors = renderErrors.concat(res.errors);
|
|
632
|
+
const missing = new Set(res.missing);
|
|
633
|
+
tasks = missing.size ? await Promise.all(batch.filter((p) => missing.has(p.path)).map((p) => toTask(p, true))) : [];
|
|
634
|
+
}
|
|
635
|
+
});
|
|
636
|
+
} finally {
|
|
637
|
+
await pool.close();
|
|
638
|
+
}
|
|
639
|
+
status = `${pool.size} ${pool.size === 1 ? "thread" : "workers"}`;
|
|
640
|
+
}
|
|
641
|
+
renderProgress.setStatus(`${status}${skippedHere ? `${status ? ", " : ""}${skippedHere} unchanged` : ""}`);
|
|
642
|
+
renderProgress.end();
|
|
643
|
+
timings.render = (parallel ? timings.render : 0) + performance.now() - tRender;
|
|
644
|
+
wasm?.finish();
|
|
645
|
+
segments.until("render");
|
|
646
|
+
panicOnQueryErrors();
|
|
647
|
+
}
|
|
648
|
+
nextState.ssrHash = setup.ssrHash;
|
|
649
|
+
if (renderErrors.length) {
|
|
650
|
+
for (const e of renderErrors.slice(0, 10)) reporter.error(`Building static HTML failed for path "${e.pagePath}"\n\n${e.stack ?? e.message}`);
|
|
651
|
+
reporter.panic(`Building static HTML failed for ${renderErrors.length} page(s)`);
|
|
652
|
+
}
|
|
653
|
+
await writePendingState();
|
|
654
|
+
if (previous) {
|
|
655
|
+
let current;
|
|
656
|
+
for (const oldPath of Object.keys(previous.pages)) {
|
|
657
|
+
if (nextState.pages[oldPath]) continue;
|
|
658
|
+
if (!current) {
|
|
659
|
+
current = /* @__PURE__ */ new Set();
|
|
660
|
+
for (const page of pages) {
|
|
661
|
+
current.add(generateHtmlPath(publicDir, page.path));
|
|
662
|
+
current.add(generatePageDataPath(publicDir, page.path));
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
const htmlFile = generateHtmlPath(publicDir, oldPath);
|
|
666
|
+
const pageDataFile = generatePageDataPath(publicDir, oldPath);
|
|
667
|
+
markHtmlPending();
|
|
668
|
+
if (!current.has(htmlFile)) fs.rmSync(htmlFile, { force: true });
|
|
669
|
+
if (!current.has(pageDataFile)) {
|
|
670
|
+
fs.rmSync(pageDataFile, { force: true });
|
|
671
|
+
try {
|
|
672
|
+
fs.rmdirSync(path.dirname(pageDataFile));
|
|
673
|
+
} catch {}
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
/**
|
|
678
|
+
* Whether the saved state still describes this build but for node digests no page depends on, so
|
|
679
|
+
* it is kept instead of written again: no query ran, no page was rendered or removed, the pages, schema and renderer are the
|
|
680
|
+
* same, and the nodes are the restored ones the saved digests vouch for. Nodes still change in
|
|
681
|
+
* such a build – SiteBuildMetadata's buildTime with every run, a source plugin's sync state –
|
|
682
|
+
* their digests are recorded with `writeNodeChanges` (the partitions they are in): the
|
|
683
|
+
* next build reads exactly the state it would have read, a node changing back to a digest saved
|
|
684
|
+
* before is not mistaken for unchanged.
|
|
685
|
+
*/
|
|
686
|
+
const keepState = () => {
|
|
687
|
+
if (htmlPending) return false;
|
|
688
|
+
if (!previous || !previousQueries?.generation || !current.changed) return false;
|
|
689
|
+
if (dirty.length || queriesRecorded || previousQueries.schemaHash !== schemaHash) return false;
|
|
690
|
+
if (rendered || skipped !== pages.length || previous.ssrHash !== setup.ssrHash) return false;
|
|
691
|
+
if (current.states !== previousQueries.nodes) return false;
|
|
692
|
+
if (getNodeChangeCount() !== changesAtSnapshot) return false;
|
|
693
|
+
if (Object.keys(previousQueries.pages).length !== pages.length || Object.keys(previous.pages).length !== pages.length) return false;
|
|
694
|
+
return !current.changed.nodes.size || buildState.writeNodeChanges({
|
|
695
|
+
...nextQueries,
|
|
696
|
+
generation: previousQueries.generation
|
|
697
|
+
}, current.changed.nodes);
|
|
698
|
+
};
|
|
699
|
+
if (hasPendingJobs()) {
|
|
700
|
+
const jobs = reporter.activityTimer("Waiting for jobs to finish");
|
|
701
|
+
jobs.start();
|
|
702
|
+
await waitUntilAllJobsComplete();
|
|
703
|
+
jobs.end();
|
|
704
|
+
}
|
|
705
|
+
const stateKept = keepState();
|
|
706
|
+
if (stateKept) reporter.verbose("build state unchanged but for node digests – not written again");
|
|
707
|
+
else buildState.writeHtml(nextState);
|
|
708
|
+
let generation = stateKept ? previousQueries.generation : takeMaterializedChanges() ? randomUUID() : void 0;
|
|
709
|
+
if (!stateKept) await buildState.writeQueries({
|
|
710
|
+
...nextQueries,
|
|
711
|
+
generation
|
|
712
|
+
});
|
|
713
|
+
writeFileIfChanged(path.join(program.cacheDir, "match-paths.json"), JSON.stringify(computeMatchPaths()));
|
|
714
|
+
writeFileIfChanged(path.join(program.cacheDir, "redirects.json"), JSON.stringify(store.getState().redirects));
|
|
715
|
+
writeFileIfChanged(path.join(program.cacheDir, "not-found-pages.json"), JSON.stringify(notFoundPagesManifest()));
|
|
716
|
+
await writeJson(path.join(publicDir, "page-data", "app-data.json"), { webpackCompilationHash: setup.buildHash });
|
|
717
|
+
segments.until("finalize");
|
|
718
|
+
const post = reporter.activityTimer("onPostBuild");
|
|
719
|
+
post.start();
|
|
720
|
+
await apiRunnerNode("onPostBuild", { graphql: graphqlForApis });
|
|
721
|
+
await waitUntilAllJobsComplete();
|
|
722
|
+
post.end();
|
|
723
|
+
segments.until("postBuild");
|
|
724
|
+
if (generation && getNodeChangeCount() !== changesAtSnapshot) {
|
|
725
|
+
if (stateKept) generation = randomUUID();
|
|
726
|
+
if (takeMaterializedChanges()) await buildState.writeQueries({
|
|
727
|
+
...nextQueries,
|
|
728
|
+
generation
|
|
729
|
+
});
|
|
730
|
+
else {
|
|
731
|
+
generation = void 0;
|
|
732
|
+
await buildState.writeQueries(nextQueries);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
if (!sitePageNodesWereRead()) sitePageNodesDependedOn(nextQueries.pages);
|
|
736
|
+
await persistState(generation);
|
|
737
|
+
finishCaches();
|
|
738
|
+
const tEnd = performance.now();
|
|
739
|
+
timings.total = tEnd - t0;
|
|
740
|
+
segments.until("finalize", tEnd);
|
|
741
|
+
reporter.timingBreakdown(`Done building ${pages.length} pages in ${(timings.total / 1e3).toFixed(2)}s (${runtimeName})`, segments.segments(), "success");
|
|
742
|
+
return {
|
|
743
|
+
pages: pages.length,
|
|
744
|
+
queries: dirty.length,
|
|
745
|
+
rendered,
|
|
746
|
+
skipped,
|
|
747
|
+
parallelQueries: parallel,
|
|
748
|
+
timings,
|
|
749
|
+
breakdown: segments.totals()
|
|
750
|
+
};
|
|
751
|
+
}
|
|
752
|
+
export { build };
|