goatly 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -1
- package/bin/goatly.js +8 -0
- package/dist/node/bootstrap.js +33 -3
- package/dist/node/build/index.js +16 -5
- package/dist/node/build/memory-governor.js +3 -1
- package/dist/node/build/page-files.js +133 -1
- package/dist/node/build/query-worker.js +187 -97
- package/dist/node/build/query-workers.js +42 -11
- package/dist/node/build/render-thread.js +103 -0
- package/dist/node/build/render-worker.js +49 -18
- package/dist/node/build/timing-breakdown.js +66 -5
- package/dist/node/build/work-clock.js +75 -0
- package/dist/node/build/worker-pool.js +8 -2
- package/dist/node/develop/index.js +1 -1
- package/dist/node/utils/cpus.js +104 -0
- package/dist/node/utils/env.js +1 -0
- package/dist/node/utils/memory-signals.js +42 -11
- package/dist/node/utils/memory.js +305 -48
- package/dist/node/vite/plugin.js +4 -2
- package/dist/node/vite/transforms.js +39 -8
- package/dist/runtime/client.js +1 -1
- package/package.json +2 -2
- package/types/node.d.ts +11 -2
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import reporter from "../reporter.js";
|
|
2
|
+
import { threadCpuMs, watchGarbageCollections } from "../utils/memory.js";
|
|
1
3
|
import { pageDataPrefix, readPageDataResult } from "./page-data.js";
|
|
2
|
-
import {
|
|
3
|
-
import { isMainThread, parentPort, workerData } from "node:worker_threads";
|
|
4
|
+
import { createPageWriter } from "./page-files.js";
|
|
5
|
+
import { isMainThread, parentPort, threadId, workerData } from "node:worker_threads";
|
|
4
6
|
import path from "node:path";
|
|
5
7
|
import fs from "node:fs";
|
|
6
8
|
import { pathToFileURL } from "node:url";
|
|
@@ -22,6 +24,7 @@ function oneAtATime(render) {
|
|
|
22
24
|
}
|
|
23
25
|
/** Creates the page renderer (used in worker threads and in-process for small sites). */
|
|
24
26
|
async function createRenderer(options) {
|
|
27
|
+
const writer = createPageWriter({ onSlow: (ms) => reporter.verbose(`writing page files several at a time: this disk takes ${ms.toFixed(1)} ms to write one${isMainThread ? "" : ` (thread ${threadId})`}`) });
|
|
25
28
|
const renderPage = (await import(pathToFileURL(options.ssrBundle).href)).renderPage;
|
|
26
29
|
const inlineStyles = async (hrefs) => {
|
|
27
30
|
const out = [];
|
|
@@ -44,7 +47,10 @@ async function createRenderer(options) {
|
|
|
44
47
|
}
|
|
45
48
|
return out;
|
|
46
49
|
};
|
|
47
|
-
/**
|
|
50
|
+
/**
|
|
51
|
+
* Renders the page (false: it had no result, see `missing`) and writes its files – `written`:
|
|
52
|
+
* they are being written (a slow disk, see createPageWriter), the page is done when it settles
|
|
53
|
+
*/
|
|
48
54
|
async function renderTask(task) {
|
|
49
55
|
let { resultJson, pageDataStaticQueryHashes } = task;
|
|
50
56
|
if (resultJson === void 0) {
|
|
@@ -75,9 +81,12 @@ async function createRenderer(options) {
|
|
|
75
81
|
generator: options.generator
|
|
76
82
|
}));
|
|
77
83
|
const sq = JSON.stringify(staticQueryHashes);
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
return
|
|
84
|
+
const pageData = sq !== pageDataStaticQueryHashes ? writer.write(task.pageDataFile, pageDataPrefix(task.componentChunkName, task.pagePath, task.matchPath) + `${json},"staticQueryHashes":${sq},"slicesMap":{}}`, !!task.filesExist) : void 0;
|
|
85
|
+
const page = writer.write(task.htmlFile, html, !!task.filesExist);
|
|
86
|
+
return {
|
|
87
|
+
staticQueryHashes,
|
|
88
|
+
written: pageData && page ? Promise.all([pageData, page]) : pageData ?? page
|
|
89
|
+
};
|
|
81
90
|
}
|
|
82
91
|
async function renderBatch(tasks) {
|
|
83
92
|
const result = {
|
|
@@ -86,24 +95,36 @@ async function createRenderer(options) {
|
|
|
86
95
|
staticQueryHashes: {},
|
|
87
96
|
missing: []
|
|
88
97
|
};
|
|
98
|
+
const done = (task, staticQueryHashes) => {
|
|
99
|
+
result.staticQueryHashes[task.pagePath] = staticQueryHashes;
|
|
100
|
+
result.rendered++;
|
|
101
|
+
};
|
|
102
|
+
const failed = (task, e) => {
|
|
103
|
+
const err = e;
|
|
104
|
+
result.errors.push({
|
|
105
|
+
pagePath: task.pagePath,
|
|
106
|
+
message: err?.message ?? String(e),
|
|
107
|
+
stack: err?.stack
|
|
108
|
+
});
|
|
109
|
+
};
|
|
110
|
+
/** pages whose files are being written (a slow disk: see createPageWriter) */
|
|
111
|
+
const writing = /* @__PURE__ */ new Set();
|
|
89
112
|
for (const task of tasks) {
|
|
90
113
|
try {
|
|
91
|
-
const
|
|
92
|
-
if (!
|
|
114
|
+
const page = await renderTask(task);
|
|
115
|
+
if (!page) result.missing.push(task.pagePath);
|
|
116
|
+
else if (!page.written) done(task, page.staticQueryHashes);
|
|
93
117
|
else {
|
|
94
|
-
|
|
95
|
-
|
|
118
|
+
const settled = page.written.then(() => done(task, page.staticQueryHashes), (e) => failed(task, e)).finally(() => writing.delete(settled));
|
|
119
|
+
writing.add(settled);
|
|
120
|
+
if (writing.size >= writer.window) await Promise.race(writing);
|
|
96
121
|
}
|
|
97
122
|
} catch (e) {
|
|
98
|
-
|
|
99
|
-
result.errors.push({
|
|
100
|
-
pagePath: task.pagePath,
|
|
101
|
-
message: err?.message ?? String(e),
|
|
102
|
-
stack: err?.stack
|
|
103
|
-
});
|
|
123
|
+
failed(task, e);
|
|
104
124
|
}
|
|
105
125
|
await new Promise((resolve) => setImmediate(resolve));
|
|
106
126
|
}
|
|
127
|
+
await Promise.all(writing);
|
|
107
128
|
return result;
|
|
108
129
|
}
|
|
109
130
|
return { renderBatch };
|
|
@@ -112,13 +133,23 @@ if (!isMainThread && parentPort && workerData?.__goatlyRenderWorker) {
|
|
|
112
133
|
const port = parentPort;
|
|
113
134
|
const options = workerData.options;
|
|
114
135
|
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({
|
|
136
|
+
rendererPromise.then(() => port.postMessage({ type: "ready" }), (e) => port.postMessage({
|
|
137
|
+
type: "ready",
|
|
138
|
+
error: e?.stack ?? String(e)
|
|
139
|
+
}));
|
|
140
|
+
let gcMs = 0;
|
|
141
|
+
watchGarbageCollections((collection) => gcMs += collection.ms);
|
|
142
|
+
const stats = () => ({
|
|
143
|
+
gcMs,
|
|
144
|
+
cpuMs: threadCpuMs()
|
|
145
|
+
});
|
|
116
146
|
port.on("message", async (msg) => {
|
|
117
147
|
try {
|
|
118
148
|
const result = await (await rendererPromise).renderBatch(msg.tasks);
|
|
119
149
|
port.postMessage({
|
|
120
150
|
id: msg.id,
|
|
121
|
-
result
|
|
151
|
+
result,
|
|
152
|
+
stats: stats()
|
|
122
153
|
});
|
|
123
154
|
} catch (e) {
|
|
124
155
|
port.postMessage({
|
|
@@ -11,8 +11,40 @@ const plural = (n, word, words = `${word}s`) => `${n} ${n === 1 ? word : words}`
|
|
|
11
11
|
*/
|
|
12
12
|
const BUILD_SEGMENTS = [
|
|
13
13
|
{
|
|
14
|
-
key: "
|
|
15
|
-
label: "
|
|
14
|
+
key: "config",
|
|
15
|
+
label: "load config and plugins"
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
key: "cache",
|
|
19
|
+
label: "initialize cache"
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
key: "preBootstrap",
|
|
23
|
+
label: "onPluginInit, onPreBootstrap"
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
key: "schemaCustomization",
|
|
27
|
+
label: "createSchemaCustomization"
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
key: "sourcing",
|
|
31
|
+
label: "source and transform nodes"
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
key: "schema",
|
|
35
|
+
label: "build schema"
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
key: "createPages",
|
|
39
|
+
label: "createPages"
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
key: "extractQueries",
|
|
43
|
+
label: "extract queries"
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
key: "postBootstrap",
|
|
47
|
+
label: "onPostBootstrap"
|
|
16
48
|
},
|
|
17
49
|
{
|
|
18
50
|
key: "staticQueries",
|
|
@@ -86,6 +118,35 @@ var SegmentClock = class {
|
|
|
86
118
|
}));
|
|
87
119
|
}
|
|
88
120
|
};
|
|
121
|
+
/** garbage collection shows in a part's status from this share of the workers' busy time (and 1 s) */
|
|
122
|
+
const NOTABLE_GC_SHARE = .1;
|
|
123
|
+
/** the CPU time shows when the workers were on a CPU for less than this share of their busy time */
|
|
124
|
+
const LOW_CPU_SHARE = .6;
|
|
125
|
+
const NOTABLE_MS = 1e3;
|
|
126
|
+
/**
|
|
127
|
+
* "workers busy 481.633s in total", and where that time went when it was not the work itself:
|
|
128
|
+
* V8's garbage collections (a large heap makes each one slow), or waiting – the threads' CPU time
|
|
129
|
+
* is much less than their busy time when they wait: for a CPU (more workers than CPUs, a CPU
|
|
130
|
+
* quota), for the disk, or for work done elsewhere (jobs in the main thread, a plugin's native
|
|
131
|
+
* code or requests).
|
|
132
|
+
*/
|
|
133
|
+
function busyText(span) {
|
|
134
|
+
const parts = [`workers busy ${seconds(span.ms)} in total`];
|
|
135
|
+
const { gcMs = 0, cpuMs } = span;
|
|
136
|
+
if (gcMs >= NOTABLE_MS && gcMs >= NOTABLE_GC_SHARE * span.ms) parts.push(`${seconds(gcMs)} of it collecting garbage`);
|
|
137
|
+
if (cpuMs !== void 0 && span.ms - cpuMs >= NOTABLE_MS && cpuMs < LOW_CPU_SHARE * span.ms) parts.push(`${seconds(cpuMs)} of it on a CPU`);
|
|
138
|
+
return parts.join(", ");
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* What the query workers' heap guards did, for the step's status: "caches dropped 38 times for
|
|
142
|
+
* memory, 29.702s of forced garbage collection" – the time of all the collections they forced
|
|
143
|
+
* (also those after which the caches stayed; between batches: not part of the workers' busy
|
|
144
|
+
* times), from a second. Empty when they did nothing worth a mention.
|
|
145
|
+
*/
|
|
146
|
+
function guardText(guard) {
|
|
147
|
+
if (!guard) return "";
|
|
148
|
+
return [guard.releases > 0 && `caches dropped ${plural(guard.releases, "time")} for memory`, guard.ms >= NOTABLE_MS && `${seconds(guard.ms)} of forced garbage collection`].filter(Boolean).join(", ");
|
|
149
|
+
}
|
|
89
150
|
/**
|
|
90
151
|
* When HTML rendering of the pipelined worker step began (ms since the epoch), or `undefined` when
|
|
91
152
|
* no page was rendered: never before the workers were ready or the bundles existed (the steps
|
|
@@ -126,7 +187,7 @@ function pipelineParts(o) {
|
|
|
126
187
|
status: [
|
|
127
188
|
plural(o.queries, "query", "queries"),
|
|
128
189
|
queried && o.queries > 0 && formatRate(o.queries, (query.end - query.start) / 1e3),
|
|
129
|
-
queried && query.ms > 0 &&
|
|
190
|
+
queried && query.ms > 0 && busyText(query)
|
|
130
191
|
].filter(Boolean).join(", ")
|
|
131
192
|
});
|
|
132
193
|
const queriesEnd = last;
|
|
@@ -147,9 +208,9 @@ function pipelineParts(o) {
|
|
|
147
208
|
rendering && o.rendered > 0 && formatRate(o.rendered, (render.end - render.start) / 1e3),
|
|
148
209
|
o.skipped && `${o.skipped} unchanged`,
|
|
149
210
|
alongside > 0 && `${seconds(alongside)} alongside the queries, ${seconds(after)} after them`,
|
|
150
|
-
rendering &&
|
|
211
|
+
rendering && busyText(render)
|
|
151
212
|
].filter(Boolean).join(", ")
|
|
152
213
|
});
|
|
153
214
|
return parts;
|
|
154
215
|
}
|
|
155
|
-
export { BUILD_SEGMENTS, SegmentClock, pipelineParts, pipelinedRenderStart };
|
|
216
|
+
export { BUILD_SEGMENTS, SegmentClock, busyText, guardText, pipelineParts, pipelinedRenderStart };
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// src/node/build/work-clock.ts
|
|
2
|
+
/** work that ended is kept for this many more, for the collections reported late */
|
|
3
|
+
const MAX_CLOSED = 256;
|
|
4
|
+
/**
|
|
5
|
+
* Measures the work of a thread by kind (a WorkSpan each): its time, the CPU time the thread used
|
|
6
|
+
* for it, and the time V8 paused the thread for garbage collections during it. Work may contain
|
|
7
|
+
* work of another kind (a page query that runs while a page is rendered): that counts for its own
|
|
8
|
+
* span only.
|
|
9
|
+
*
|
|
10
|
+
* Collections are reported after the fact – Node hands them over when the event loop turns, often
|
|
11
|
+
* after the work they interrupted has ended – so each is matched to the work that ran when it
|
|
12
|
+
* began.
|
|
13
|
+
*/
|
|
14
|
+
function createWorkClock(options) {
|
|
15
|
+
/** work in progress, the innermost last */
|
|
16
|
+
const open = [];
|
|
17
|
+
/** work that ended, until no collection can have begun during it any more */
|
|
18
|
+
const closed = [];
|
|
19
|
+
return {
|
|
20
|
+
begin(span) {
|
|
21
|
+
const work = {
|
|
22
|
+
span,
|
|
23
|
+
at: options.epoch(),
|
|
24
|
+
from: options.now(),
|
|
25
|
+
cpu: options.cpu(),
|
|
26
|
+
lessMs: 0,
|
|
27
|
+
lessCpu: 0
|
|
28
|
+
};
|
|
29
|
+
open.push(work);
|
|
30
|
+
return work;
|
|
31
|
+
},
|
|
32
|
+
/** the work ended; `counted: false` leaves it out (it turned out to be none) */
|
|
33
|
+
end(work, counted = true) {
|
|
34
|
+
const index = open.lastIndexOf(work);
|
|
35
|
+
if (index < 0) return;
|
|
36
|
+
open.splice(index, 1);
|
|
37
|
+
if (!counted) return;
|
|
38
|
+
const to = options.now();
|
|
39
|
+
const cpu = options.cpu();
|
|
40
|
+
const ms = to - work.from;
|
|
41
|
+
const cpuMs = work.cpu !== void 0 && cpu !== void 0 ? cpu - work.cpu : void 0;
|
|
42
|
+
const { span } = work;
|
|
43
|
+
span.ms += ms - work.lessMs;
|
|
44
|
+
span.start = Math.min(span.start, work.at);
|
|
45
|
+
span.end = Math.max(span.end, work.at + ms);
|
|
46
|
+
span.gcMs ??= 0;
|
|
47
|
+
if (cpuMs !== void 0) span.cpuMs = (span.cpuMs ?? 0) + cpuMs - work.lessCpu;
|
|
48
|
+
closed.push({
|
|
49
|
+
from: work.from,
|
|
50
|
+
to,
|
|
51
|
+
span
|
|
52
|
+
});
|
|
53
|
+
if (closed.length > MAX_CLOSED) closed.shift();
|
|
54
|
+
const outer = open[index - 1];
|
|
55
|
+
if (outer) {
|
|
56
|
+
outer.lessMs += ms;
|
|
57
|
+
if (cpuMs !== void 0) outer.lessCpu += cpuMs;
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
/**
|
|
61
|
+
* A collection that began at `start` (on the thread's clock) paused the thread for `ms`.
|
|
62
|
+
* Collections are reported in the order they ran.
|
|
63
|
+
*/
|
|
64
|
+
collected(start, ms) {
|
|
65
|
+
let at = closed.findIndex((work) => work.from <= start && start < work.to);
|
|
66
|
+
let span = at < 0 ? void 0 : closed[at].span;
|
|
67
|
+
if (!span) {
|
|
68
|
+
for (let i = open.length - 1; i >= 0 && !span; i--) if (open[i].from <= start) span = open[i].span;
|
|
69
|
+
}
|
|
70
|
+
if (span) span.gcMs = (span.gcMs ?? 0) + ms;
|
|
71
|
+
for (at = closed.length - 1; at >= 0; at--) if (closed[at].to <= start) closed.splice(at, 1);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
export { createWorkClock };
|
|
@@ -1,17 +1,23 @@
|
|
|
1
1
|
import reporter, { REPORTER_BRIDGE_ENV } from "../reporter.js";
|
|
2
|
+
import { cpuCount } from "../utils/cpus.js";
|
|
2
3
|
import { outOfMemoryHint, planWorkerHeap, workerLimitMb } from "../utils/memory.js";
|
|
3
4
|
import { createRenderer } from "./render-worker.js";
|
|
4
5
|
import { Worker } from "node:worker_threads";
|
|
5
6
|
import path from "node:path";
|
|
6
|
-
import os from "node:os";
|
|
7
7
|
import { fileURLToPath } from "node:url";
|
|
8
8
|
// src/node/build/worker-pool.ts
|
|
9
9
|
const workerFile = path.join(path.dirname(fileURLToPath(import.meta.url)), "render-worker.js");
|
|
10
|
+
/**
|
|
11
|
+
* The most worker threads of a build: `renderWorkers` in gatsby-config, GOATLY_RENDER_WORKERS, else
|
|
12
|
+
* one less than the CPUs it may use (see cpuCount: GOATLY_CPU_COUNT or Gatsby's GATSBY_CPU_COUNT,
|
|
13
|
+
* else the CPUs the process may run on, within its cgroups' CPU quota), at most 16 – like Gatsby,
|
|
14
|
+
* whose worker pool has one process less than its CPU count.
|
|
15
|
+
*/
|
|
10
16
|
function defaultWorkerCount(configured) {
|
|
11
17
|
if (configured && configured > 0) return configured;
|
|
12
18
|
const env = Number(process.env.GOATLY_RENDER_WORKERS);
|
|
13
19
|
if (env > 0) return env;
|
|
14
|
-
const cpus =
|
|
20
|
+
const cpus = cpuCount({ warn: (message) => reporter.warn(message) });
|
|
15
21
|
return Math.max(1, Math.min(cpus - 1, 16));
|
|
16
22
|
}
|
|
17
23
|
/** GOATLY_WORKERS=<n>: a fixed number of workers instead of the adaptive pool */
|
|
@@ -4,7 +4,6 @@ import { apiRunnerNode, cascadeIdle, waitForCascade } from "../api-runner.js";
|
|
|
4
4
|
import { extractAndCompileQueries } from "../query/compile.js";
|
|
5
5
|
import { graphqlEnvFile } from "../query/graphql-env.js";
|
|
6
6
|
import { clearDocumentCache, graphqlForApis, runGraphQL } from "../query/graphql-runner.js";
|
|
7
|
-
import { HYDRATION_EVENT } from "../../runtime/hydration-report.js";
|
|
8
7
|
import { emitter, store } from "../redux/index.js";
|
|
9
8
|
import reporter from "../reporter.js";
|
|
10
9
|
import { buildSchema } from "../schema/index.js";
|
|
@@ -22,6 +21,7 @@ import { createHydrationReportListener } from "./hydration-report.js";
|
|
|
22
21
|
import { graphiqlHtml } from "./graphiql.js";
|
|
23
22
|
import { localUrl } from "./local-url.js";
|
|
24
23
|
import { runtimeName } from "../utils/runtime.js";
|
|
24
|
+
import { HYDRATION_EVENT } from "../../runtime/hydration-report.js";
|
|
25
25
|
import { compatEnv } from "../utils/env.js";
|
|
26
26
|
import { isKeptNotFoundMirror, isNotFoundPage, notFoundPagePaths, resolveNotFoundEntries, resolveNotFoundPages, runtimeNotFoundPages } from "../not-found-pages.js";
|
|
27
27
|
import { notFoundCandidates, notFoundLookupPath } from "../../runtime/not-found.js";
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { compatEnv } from "./env.js";
|
|
2
|
+
import { findCgroupLevels } from "./memory-signals.js";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import { execFileSync } from "node:child_process";
|
|
7
|
+
// src/node/utils/cpus.ts
|
|
8
|
+
/**
|
|
9
|
+
* How many CPUs a build may use, which sizes its worker threads. Correct in containers: on Linux
|
|
10
|
+
* the CPU quota of every cgroup level counts (`docker run --cpus=2`, a Kubernetes CPU limit).
|
|
11
|
+
* os.availableParallelism() knows the CPUs the process may run on (its affinity, e.g.
|
|
12
|
+
* `--cpuset-cpus`) and, with cgroup v2, the quota of its own cgroup – not a quota of cgroup v1 (a
|
|
13
|
+
* 1.5-CPU quota there: all 4 CPUs of the machine, Node 22.23), so a container with 2 CPUs' worth
|
|
14
|
+
* of time on a 64-core host could start 16 workers that share them.
|
|
15
|
+
*/
|
|
16
|
+
const SYSCTL = "/usr/sbin/sysctl";
|
|
17
|
+
/** the logical CPUs this process may run on (its CPU affinity, where the runtime knows it) */
|
|
18
|
+
function logicalCpus() {
|
|
19
|
+
return Math.max(1, os.availableParallelism?.() ?? os.cpus().length);
|
|
20
|
+
}
|
|
21
|
+
/** the CPUs of a cgroup v2 `cpu.max` ("<quota> <period>" in µs, "max": none), undefined: no quota */
|
|
22
|
+
function parseCpuMax(text) {
|
|
23
|
+
const [quota, period] = text.trim().split(/\s+/).map(Number);
|
|
24
|
+
return quota > 0 && period > 0 ? quota / period : void 0;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The CPU quota (in CPUs, e.g. 1.5) of this process's cgroups, the lowest of every level's:
|
|
28
|
+
* cgroup v2's `cpu.max`, v1's `cpu.cfs_quota_us` / `cpu.cfs_period_us`. undefined: none (or not
|
|
29
|
+
* Linux).
|
|
30
|
+
*/
|
|
31
|
+
function cgroupCpuQuota(options = {}) {
|
|
32
|
+
if ((options.platform ?? process.platform) !== "linux") return void 0;
|
|
33
|
+
const read = (file) => {
|
|
34
|
+
try {
|
|
35
|
+
return fs.readFileSync(file, "utf8");
|
|
36
|
+
} catch {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
const levels = findCgroupLevels(read(path.join(options.procRoot ?? "/proc", "self/cgroup")) ?? "", "cpu", {
|
|
41
|
+
v1: ["cpu.cfs_quota_us", "cpu.cfs_period_us"],
|
|
42
|
+
v2: ["cpu.max"]
|
|
43
|
+
}, options.cgroupRoot);
|
|
44
|
+
let quota;
|
|
45
|
+
for (const { version, dir } of levels) {
|
|
46
|
+
const cpus = version === "v2" ? parseCpuMax(read(path.join(dir, "cpu.max")) ?? "") : parseCpuMax(`${read(path.join(dir, "cpu.cfs_quota_us")) ?? ""} ${read(path.join(dir, "cpu.cfs_period_us")) ?? ""}`);
|
|
47
|
+
if (cpus !== void 0) quota = Math.min(quota ?? 1e400, cpus);
|
|
48
|
+
}
|
|
49
|
+
return quota;
|
|
50
|
+
}
|
|
51
|
+
/** the cores of /proc/cpuinfo (each "physical id" and "core id" once), undefined: not told */
|
|
52
|
+
function parseCpuinfoCores(cpuinfo) {
|
|
53
|
+
const cores = /* @__PURE__ */ new Set();
|
|
54
|
+
for (const block of cpuinfo.split(/\n\s*\n/)) {
|
|
55
|
+
const field = (name) => new RegExp(`^${name}\\s*:\\s*(\\S+)`, "m").exec(block)?.[1];
|
|
56
|
+
const core = field("core id");
|
|
57
|
+
if (core !== void 0) cores.add(`${field("physical id") ?? ""}:${core}`);
|
|
58
|
+
}
|
|
59
|
+
return cores.size > 0 ? cores.size : void 0;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The physical cores (without SMT siblings, as Gatsby counts CPUs by default) – at most the
|
|
63
|
+
* logical CPUs the process may run on. Linux: /proc/cpuinfo, macOS: `sysctl hw.physicalcpu`; where
|
|
64
|
+
* the system doesn't tell (other platforms, some VMs and ARM boards): the logical CPUs.
|
|
65
|
+
*/
|
|
66
|
+
function physicalCpus(options = {}) {
|
|
67
|
+
const logical = options.logical ?? logicalCpus();
|
|
68
|
+
const platform = options.platform ?? process.platform;
|
|
69
|
+
let cores;
|
|
70
|
+
try {
|
|
71
|
+
if (platform === "linux") cores = parseCpuinfoCores(fs.readFileSync(path.join(options.procRoot ?? "/proc", "cpuinfo"), "utf8"));
|
|
72
|
+
else if (platform === "darwin") cores = Number(execFileSync(SYSCTL, ["-n", "hw.physicalcpu"], {
|
|
73
|
+
encoding: "utf8",
|
|
74
|
+
timeout: 2e3
|
|
75
|
+
}));
|
|
76
|
+
} catch {}
|
|
77
|
+
return cores !== void 0 && cores >= 1 ? Math.min(logical, Math.floor(cores)) : logical;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* The CPUs a build plans its worker threads with:
|
|
81
|
+
* 1. GOATLY_CPU_COUNT (or Gatsby's GATSBY_CPU_COUNT, so a site tuned for Gatsby builds with as
|
|
82
|
+
* many workers here): a number, `logical_cores` or `physical_cores`;
|
|
83
|
+
* 2. else the logical CPUs the process may run on, at most the CPU quota of its cgroups (Linux),
|
|
84
|
+
* rounded down like Node rounds the quota it knows of – at least 1.
|
|
85
|
+
*/
|
|
86
|
+
function cpuCount(options = {}) {
|
|
87
|
+
const logical = options.logical ?? logicalCpus();
|
|
88
|
+
const env = options.env ?? process.env;
|
|
89
|
+
const setting = compatEnv("GOATLY_CPU_COUNT", env)?.trim();
|
|
90
|
+
if (setting) {
|
|
91
|
+
if (setting === "logical_cores") return logical;
|
|
92
|
+
if (setting === "physical_cores") return physicalCpus({
|
|
93
|
+
...options,
|
|
94
|
+
logical
|
|
95
|
+
});
|
|
96
|
+
const count = Number(setting);
|
|
97
|
+
if (Number.isFinite(count) && count >= 1) return Math.floor(count);
|
|
98
|
+
const name = env.GOATLY_CPU_COUNT ? "GOATLY_CPU_COUNT" : "GATSBY_CPU_COUNT";
|
|
99
|
+
options.warn?.(`${name}=${setting} is not a number of CPUs, "logical_cores" or "physical_cores" – ignored`);
|
|
100
|
+
}
|
|
101
|
+
const quota = cgroupCpuQuota(options);
|
|
102
|
+
return quota === void 0 ? logical : Math.max(1, Math.min(logical, Math.floor(quota)));
|
|
103
|
+
}
|
|
104
|
+
export { cgroupCpuQuota, cpuCount, logicalCpus, parseCpuMax, parseCpuinfoCores, physicalCpus };
|
package/dist/node/utils/env.js
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
const GATSBY_ENV_ALIASES = {
|
|
10
10
|
GOATLY_ACTIVE_ENV: "GATSBY_ACTIVE_ENV",
|
|
11
|
+
GOATLY_CPU_COUNT: "GATSBY_CPU_COUNT",
|
|
11
12
|
GOATLY_VERBOSE: "GATSBY_VERBOSE",
|
|
12
13
|
GOATLY_EXPERIMENTAL_ENABLE_REFRESH: "GATSBY_EXPERIMENTAL_ENABLE_REFRESH",
|
|
13
14
|
ENABLE_GOATLY_REFRESH_ENDPOINT: "ENABLE_GATSBY_REFRESH_ENDPOINT"
|
|
@@ -131,36 +131,67 @@ function capacityAt(steps, queried) {
|
|
|
131
131
|
return step ? step[1] : 1e400;
|
|
132
132
|
}
|
|
133
133
|
/**
|
|
134
|
-
* The cgroup levels
|
|
135
|
-
* cgroup – or, when that isn't visible here (e.g. in a container that
|
|
136
|
-
* hierarchy), the nearest ancestor that is, else the mount – then each
|
|
137
|
-
*
|
|
138
|
-
* controller wins over a v2 hierarchy (hybrid
|
|
134
|
+
* The cgroup levels of a controller (e.g. "memory", "cpu") that apply to this process, from
|
|
135
|
+
* /proc/self/cgroup: its own cgroup – or, when that isn't visible here (e.g. in a container that
|
|
136
|
+
* sees only its part of the hierarchy), the nearest ancestor that is, else the mount – then each
|
|
137
|
+
* ancestor, up to the mount. Only levels that have all of `files` (by cgroup version) are returned:
|
|
138
|
+
* the root of cgroup v2 has no limits. cgroup v1's controller wins over a v2 hierarchy (hybrid
|
|
139
|
+
* setups mount both).
|
|
139
140
|
*/
|
|
140
|
-
function
|
|
141
|
+
function findCgroupLevels(procSelfCgroup, controller, files, root = "/sys/fs/cgroup") {
|
|
141
142
|
let v1;
|
|
143
|
+
/** the controllers mounted with it, as the mount is named (e.g. "cpu,cpuacct") */
|
|
144
|
+
let mounted = controller;
|
|
142
145
|
let v2;
|
|
143
146
|
for (const line of procSelfCgroup.split("\n")) {
|
|
144
147
|
const match = /^(\d+):([^:]*):(.*)$/.exec(line.trim());
|
|
145
148
|
if (!match) continue;
|
|
146
149
|
if (match[1] === "0" && match[2] === "") v2 = match[3];
|
|
147
|
-
else if (match[2].split(",").includes(
|
|
150
|
+
else if (match[2].split(",").includes(controller)) {
|
|
151
|
+
v1 = match[3];
|
|
152
|
+
mounted = match[2];
|
|
153
|
+
}
|
|
148
154
|
}
|
|
149
155
|
const version = v1 !== void 0 ? "v1" : "v2";
|
|
150
156
|
const own = v1 ?? v2;
|
|
151
157
|
if (own === void 0) return [];
|
|
152
|
-
const mount = version === "
|
|
153
|
-
const files = version === "v1" ? ["memory.limit_in_bytes", "memory.usage_in_bytes"] : ["memory.max", "memory.current"];
|
|
158
|
+
const mount = version === "v2" ? root : v1Mount(root, controller, mounted);
|
|
154
159
|
const levels = [];
|
|
155
160
|
for (let rel = path.posix.join("/", own);; rel = path.posix.dirname(rel)) {
|
|
156
161
|
const dir = rel === "/" ? mount : path.join(mount, rel);
|
|
157
|
-
if (files.every((file) => fs.existsSync(path.join(dir, file)))) levels.push({
|
|
162
|
+
if (files[version].every((file) => fs.existsSync(path.join(dir, file)))) levels.push({
|
|
158
163
|
version,
|
|
159
164
|
dir
|
|
160
165
|
});
|
|
161
166
|
if (rel === "/") return levels;
|
|
162
167
|
}
|
|
163
168
|
}
|
|
169
|
+
/**
|
|
170
|
+
* Where a cgroup v1 controller is mounted below `root`: under its own name (often a link to the
|
|
171
|
+
* mount it shares), under the names it is mounted with as /proc/self/cgroup lists them – or in the
|
|
172
|
+
* other order ("cpuacct,cpu" for the mount "cpu,cpuacct").
|
|
173
|
+
*/
|
|
174
|
+
function v1Mount(root, controller, mounted) {
|
|
175
|
+
for (const name of [controller, mounted]) {
|
|
176
|
+
const dir = path.join(root, name);
|
|
177
|
+
if (fs.existsSync(dir)) return dir;
|
|
178
|
+
}
|
|
179
|
+
try {
|
|
180
|
+
const shared = fs.readdirSync(root).find((name) => name.split(",").includes(controller));
|
|
181
|
+
if (shared) return path.join(root, shared);
|
|
182
|
+
} catch {}
|
|
183
|
+
return path.join(root, controller);
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* The cgroup levels whose memory limits apply to this process (see findCgroupLevels): those with
|
|
187
|
+
* a limit and usage file.
|
|
188
|
+
*/
|
|
189
|
+
function findMemoryCgroups(procSelfCgroup, root = "/sys/fs/cgroup") {
|
|
190
|
+
return findCgroupLevels(procSelfCgroup, "memory", {
|
|
191
|
+
v1: ["memory.limit_in_bytes", "memory.usage_in_bytes"],
|
|
192
|
+
v2: ["memory.max", "memory.current"]
|
|
193
|
+
}, root);
|
|
194
|
+
}
|
|
164
195
|
/** a reading of a file, undefined when it can't be read or parsed */
|
|
165
196
|
function readWith(file, parse) {
|
|
166
197
|
try {
|
|
@@ -407,4 +438,4 @@ function sampleMemoryOnce(options = {}) {
|
|
|
407
438
|
sampler.close();
|
|
408
439
|
}
|
|
409
440
|
}
|
|
410
|
-
export { capacityAt, createMemorySampler, findMemoryCgroups, parseCgroupLimit, parseCgroupStat, parseMeminfo, parsePressureLevel, parsePsiSomeTotal, parseStatusRssAnonMb, parseTestMemory, parseVmStatAvailableMb, sampleMemoryOnce };
|
|
441
|
+
export { capacityAt, createMemorySampler, findCgroupLevels, findMemoryCgroups, parseCgroupLimit, parseCgroupStat, parseMeminfo, parsePressureLevel, parsePsiSomeTotal, parseStatusRssAnonMb, parseTestMemory, parseVmStatAvailableMb, sampleMemoryOnce };
|