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
package/README.md
CHANGED
|
@@ -703,7 +703,10 @@ are ignored with a warning.
|
|
|
703
703
|
|
|
704
704
|
- **`onCreateWebpackConfig`** runs with webpack-like helpers. `resolve.alias` and `DefinePlugin`
|
|
705
705
|
definitions are translated to Vite; loaders and rules are ignored (Vite handles CSS, assets, Sass and PostCSS
|
|
706
|
-
natively). Use `onCreateViteConfig` or `vite` in gatsby-config for anything else.
|
|
706
|
+
natively). Use `onCreateViteConfig` or `vite` in gatsby-config for anything else. A
|
|
707
|
+
`require(NAME)` of a defined name that is a string becomes an import of that string in develop
|
|
708
|
+
too, as webpack resolves it after the substitution (gatsby-plugin-layout's
|
|
709
|
+
`require(GATSBY_LAYOUT_COMPONENT_PATH)`).
|
|
707
710
|
- **Babel APIs** are accepted and have no effect, except for two plugins that Oxc has a port of:
|
|
708
711
|
- `babel-plugin-styled-components` (e.g. from `gatsby-plugin-styled-components`): its options drive
|
|
709
712
|
Oxc's styled-components transform, with stable component ids always on so dev SSR and the browser
|
|
@@ -766,6 +769,24 @@ are ignored with a warning.
|
|
|
766
769
|
and its mutexes) is kept in the built-in SQLite (`.cache/data/gatsby-core-utils.sqlite`) instead
|
|
767
770
|
of the `lmdb` 2.5.3 it pins, which doesn't load on Bun.
|
|
768
771
|
|
|
772
|
+
### Tested plugins
|
|
773
|
+
|
|
774
|
+
Besides the plugins in the examples, these npm plugins are built unchanged in a test site
|
|
775
|
+
([`test/utility-plugins.e2e.test.ts`](test/utility-plugins.e2e.test.ts), with the browser behaviour of
|
|
776
|
+
their gatsby-browser files checked in Playwright) and work as in Gatsby:
|
|
777
|
+
|
|
778
|
+
- `gatsby-plugin-layout`: the layout wraps every page and stays mounted on client-side
|
|
779
|
+
navigation. Pass the `component` as an absolute path (`require.resolve("./src/layouts/index.js")`
|
|
780
|
+
or `fileURLToPath(new URL(…, import.meta.url))`), as in Gatsby, where a relative path is resolved
|
|
781
|
+
from the plugin's directory.
|
|
782
|
+
- `gatsby-plugin-nprogress`, `gatsby-plugin-google-gtag` (page views on route changes),
|
|
783
|
+
`gatsby-plugin-google-tagmanager` (its `<head>` script, the `<noscript>` iframe and
|
|
784
|
+
`gatsby-route-change` events), `gatsby-plugin-canonical-urls`, `gatsby-plugin-robots-txt`,
|
|
785
|
+
`gatsby-plugin-remove-serviceworker`, `gatsby-transformer-yaml` and `gatsby-transformer-json`.
|
|
786
|
+
- `gatsby-plugin-react-helmet-async` with `react-helmet-async` 1.x: both declare React ≤ 18 as their
|
|
787
|
+
peer, but render the `<Helmet>` tags of each page into `<head>` with React 19 too (pnpm prints a
|
|
788
|
+
peer dependency warning).
|
|
789
|
+
|
|
769
790
|
### Not supported
|
|
770
791
|
|
|
771
792
|
- Rendering modes other than SSG. A page that exports `getServerData` (SSR) fails the build, with steps to
|
package/bin/goatly.js
CHANGED
|
@@ -3,6 +3,14 @@ import os from "node:os"
|
|
|
3
3
|
import v8 from "node:v8"
|
|
4
4
|
import { spawn } from "node:child_process"
|
|
5
5
|
|
|
6
|
+
// More threads for file operations than libuv's 4 (read when its pool is first used, and
|
|
7
|
+
// inherited by the restarted process below): they let a build's file writes overlap on a
|
|
8
|
+
// filesystem that is slow to write to (src/node/build/page-files.ts). 16 per CPU, 32 to 128.
|
|
9
|
+
if (!process.env.UV_THREADPOOL_SIZE) {
|
|
10
|
+
const cpus = os.availableParallelism?.() ?? os.cpus().length
|
|
11
|
+
process.env.UV_THREADPOOL_SIZE = String(Math.min(128, Math.max(32, 16 * cpus)))
|
|
12
|
+
}
|
|
13
|
+
|
|
6
14
|
/** the heap limit Node gives every thread when nobody chose one (worker threads too) */
|
|
7
15
|
const nodeHeapMb = v8.getHeapStatistics().heap_size_limit / 1048576
|
|
8
16
|
|
package/dist/node/bootstrap.js
CHANGED
|
@@ -25,12 +25,25 @@ import { useRenderer } from "./renderer.js";
|
|
|
25
25
|
import { createContentDigest } from "./utils/content-digest.js";
|
|
26
26
|
import { TEMP_MODULE, resolveApiFile } from "./loader/import-module.js";
|
|
27
27
|
import { runtimeName } from "./utils/runtime.js";
|
|
28
|
+
import { performance } from "node:perf_hooks";
|
|
28
29
|
import { isMainThread } from "node:worker_threads";
|
|
29
30
|
import path from "node:path";
|
|
30
31
|
import fs from "node:fs";
|
|
31
32
|
import v8 from "node:v8";
|
|
32
33
|
// src/node/bootstrap.ts
|
|
33
|
-
|
|
34
|
+
/** the phases of the bootstrap, in order (see `BootstrapResult.phases`) */
|
|
35
|
+
const BOOTSTRAP_PHASES = [
|
|
36
|
+
"config",
|
|
37
|
+
"cache",
|
|
38
|
+
"preBootstrap",
|
|
39
|
+
"schemaCustomization",
|
|
40
|
+
"sourcing",
|
|
41
|
+
"schema",
|
|
42
|
+
"createPages",
|
|
43
|
+
"extractQueries",
|
|
44
|
+
"postBootstrap"
|
|
45
|
+
];
|
|
46
|
+
const GOATLY_VERSION = "0.1.2";
|
|
34
47
|
const DEFAULT_EXTENSIONS = [
|
|
35
48
|
".mjs",
|
|
36
49
|
".js",
|
|
@@ -297,6 +310,13 @@ async function loadSiteAndPlugins(directory, options, dirs, renderer) {
|
|
|
297
310
|
* createPages → createPagesStatefully → query extraction → onPostBootstrap.
|
|
298
311
|
*/
|
|
299
312
|
async function bootstrap(options) {
|
|
313
|
+
const phases = {};
|
|
314
|
+
let phaseStart = performance.now();
|
|
315
|
+
const phaseDone = (phase) => {
|
|
316
|
+
const end = performance.now();
|
|
317
|
+
phases[phase] = [phaseStart, end];
|
|
318
|
+
phaseStart = end;
|
|
319
|
+
};
|
|
300
320
|
const directory = path.resolve(options.directory);
|
|
301
321
|
const cacheDir = path.join(directory, ".cache");
|
|
302
322
|
const publicDir = path.join(directory, "public");
|
|
@@ -325,6 +345,7 @@ async function bootstrap(options) {
|
|
|
325
345
|
}
|
|
326
346
|
const pluginKeys = store.getState().flattenedPlugins.map((p) => `${p.name}@${p.version}:${safeJson(p.pluginOptions)}`);
|
|
327
347
|
await apiRunnerNode("onPreInit", {});
|
|
348
|
+
phaseDone("config");
|
|
328
349
|
activity = reporter.activityTimer("initialize cache");
|
|
329
350
|
activity.start();
|
|
330
351
|
const cacheKey = computeCacheKey(directory, pluginKeys);
|
|
@@ -376,13 +397,16 @@ async function bootstrap(options) {
|
|
|
376
397
|
const prunedJobs = await pruneCompletedJobs();
|
|
377
398
|
if (prunedJobs) reporter.verbose(`Deleted ${prunedJobs} completed job(s) whose files are gone`);
|
|
378
399
|
activity.end();
|
|
400
|
+
phaseDone("cache");
|
|
379
401
|
await apiRunnerNode("onPluginInit", {});
|
|
380
402
|
await apiRunnerNode("onPreBootstrap", {});
|
|
403
|
+
phaseDone("preBootstrap");
|
|
381
404
|
store.getState().nodesTouched.clear();
|
|
382
405
|
activity = reporter.activityTimer("createSchemaCustomization");
|
|
383
406
|
activity.start();
|
|
384
407
|
await apiRunnerNode("createSchemaCustomization", { traceId: "initial-createSchemaCustomization" });
|
|
385
408
|
activity.end();
|
|
409
|
+
phaseDone("schemaCustomization");
|
|
386
410
|
activity = reporter.activityTimer("source and transform nodes");
|
|
387
411
|
activity.start();
|
|
388
412
|
await apiRunnerNode("sourceNodes", {
|
|
@@ -394,10 +418,12 @@ async function bootstrap(options) {
|
|
|
394
418
|
deleteStaleNodes();
|
|
395
419
|
activity.setStatus(`${ds.countNodes()} nodes`);
|
|
396
420
|
activity.end();
|
|
421
|
+
phaseDone("sourcing");
|
|
397
422
|
activity = reporter.activityTimer("building schema");
|
|
398
423
|
activity.start();
|
|
399
424
|
await buildSchema();
|
|
400
425
|
activity.end();
|
|
426
|
+
phaseDone("schema");
|
|
401
427
|
let queries = {
|
|
402
428
|
pageQueries: /* @__PURE__ */ new Map(),
|
|
403
429
|
staticQueries: /* @__PURE__ */ new Map(),
|
|
@@ -429,11 +455,13 @@ async function bootstrap(options) {
|
|
|
429
455
|
deleteOrphanSitePages();
|
|
430
456
|
activity.setStatus(`${store.getState().pages.size} pages`);
|
|
431
457
|
activity.end();
|
|
458
|
+
phaseDone("createPages");
|
|
432
459
|
reportNotFoundPages();
|
|
433
460
|
activity = reporter.activityTimer("extract queries from components");
|
|
434
461
|
activity.start();
|
|
435
462
|
queries = await extractAndCompileQueries();
|
|
436
463
|
activity.end();
|
|
464
|
+
phaseDone("extractQueries");
|
|
437
465
|
}
|
|
438
466
|
await apiRunnerNode("onPostBootstrap", {});
|
|
439
467
|
store.dispatch({
|
|
@@ -441,9 +469,11 @@ async function bootstrap(options) {
|
|
|
441
469
|
payload: {}
|
|
442
470
|
});
|
|
443
471
|
reporter.info(`bootstrap finished - ${runtimeName}`);
|
|
472
|
+
phaseDone("postBootstrap");
|
|
444
473
|
return {
|
|
445
474
|
queries,
|
|
446
|
-
cacheRestored
|
|
475
|
+
cacheRestored,
|
|
476
|
+
phases
|
|
447
477
|
};
|
|
448
478
|
}
|
|
449
479
|
/**
|
|
@@ -536,4 +566,4 @@ function writeInferenceState(cacheDir) {
|
|
|
536
566
|
metadata: valid
|
|
537
567
|
}));
|
|
538
568
|
}
|
|
539
|
-
export { bootstrap, bootstrapWorker, datastoreRestored, deleteStaleNodes, emitter, getCache, persistState, publicDirWasMissing, restoredGeneration };
|
|
569
|
+
export { BOOTSTRAP_PHASES, bootstrap, bootstrapWorker, datastoreRestored, deleteStaleNodes, emitter, getCache, persistState, publicDirWasMissing, restoredGeneration };
|
package/dist/node/build/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { bootstrap, datastoreRestored, persistState, publicDirWasMissing, restoredGeneration } from "../bootstrap.js";
|
|
1
|
+
import { BOOTSTRAP_PHASES, bootstrap, datastoreRestored, persistState, publicDirWasMissing, restoredGeneration } from "../bootstrap.js";
|
|
2
2
|
import { apiRunnerNode } from "../api-runner.js";
|
|
3
3
|
import { graphqlForApis, runGraphQL } from "../query/graphql-runner.js";
|
|
4
4
|
import { store } from "../redux/index.js";
|
|
@@ -10,6 +10,8 @@ import { notFoundPagesManifest } from "../not-found-pages.js";
|
|
|
10
10
|
import { generateHtmlPath, generatePageDataPath } from "../utils/paths.js";
|
|
11
11
|
import { AssetResolver, manifestFingerprint, readManifest } from "./assets.js";
|
|
12
12
|
import { createDirectoryMaker, outputDirs } from "./output-dirs.js";
|
|
13
|
+
import { ioThreads } from "./page-files.js";
|
|
14
|
+
import { logicalCpus } from "../utils/cpus.js";
|
|
13
15
|
import { createInProcessPool, createWorkerPool, defaultWorkerCount, fixedWorkerCount } from "./worker-pool.js";
|
|
14
16
|
import { hasPendingJobs, waitUntilAllJobsComplete } from "../actions/jobs.js";
|
|
15
17
|
import { getDataStore, nodeTypeOf } from "../datastore/index.js";
|
|
@@ -26,7 +28,7 @@ import { clearQueryEngineCaches, clearSlimNodes } from "../schema/query-engine.j
|
|
|
26
28
|
import { runtimeName } from "../utils/runtime.js";
|
|
27
29
|
import { collectGarbage, configureBuildHeap, heapText, planQueryWorkers, planRenderWorkers } from "../utils/memory.js";
|
|
28
30
|
import { indexQueries, prepareMainThreadWasm, prepareWorkerWasm, resetWasmMismatches } from "../wasm-data/host.js";
|
|
29
|
-
import { SegmentClock, pipelineParts, pipelinedRenderStart } from "./timing-breakdown.js";
|
|
31
|
+
import { SegmentClock, guardText, pipelineParts, pipelinedRenderStart } from "./timing-breakdown.js";
|
|
30
32
|
import { materializedChanges, readSitePageNodes, sitePageNodesCreated, sitePageNodesDependedOn, sitePageNodesWereRead } from "../site-page-nodes.js";
|
|
31
33
|
import { performance } from "node:perf_hooks";
|
|
32
34
|
import { randomUUID } from "node:crypto";
|
|
@@ -35,7 +37,7 @@ import fs from "node:fs";
|
|
|
35
37
|
import v8 from "node:v8";
|
|
36
38
|
import { build as build$1 } from "vite";
|
|
37
39
|
// src/node/build/index.ts
|
|
38
|
-
const GENERATOR = "goatly 0.1.
|
|
40
|
+
const GENERATOR = "goatly 0.1.2";
|
|
39
41
|
const IN_PROCESS_THRESHOLD = 150;
|
|
40
42
|
const BATCH_SIZE = 32;
|
|
41
43
|
/**
|
|
@@ -81,17 +83,25 @@ async function build(options) {
|
|
|
81
83
|
const timings = {};
|
|
82
84
|
const segments = new SegmentClock(t0);
|
|
83
85
|
process.env.NODE_ENV = "production";
|
|
86
|
+
const threads = ioThreads(logicalCpus());
|
|
87
|
+
if (threads) process.env.UV_THREADPOOL_SIZE = String(threads);
|
|
84
88
|
if (options.reporter) reporter.setTransports(options.reporter);
|
|
85
89
|
reporter.isBuild = true;
|
|
86
90
|
configureBuildHeap();
|
|
87
|
-
await bootstrap({
|
|
91
|
+
const { phases } = await bootstrap({
|
|
88
92
|
directory: options.directory,
|
|
89
93
|
command: "build",
|
|
90
94
|
prefixPaths: options.prefixPaths,
|
|
91
95
|
verbose: options.verbose
|
|
92
96
|
});
|
|
93
97
|
timings.bootstrap = performance.now() - t0;
|
|
94
|
-
|
|
98
|
+
for (const phase of BOOTSTRAP_PHASES) {
|
|
99
|
+
const span = phases[phase];
|
|
100
|
+
if (!span) continue;
|
|
101
|
+
segments.until(phase, span[1]);
|
|
102
|
+
timings[phase] = span[1] - span[0];
|
|
103
|
+
}
|
|
104
|
+
segments.until("postBootstrap");
|
|
95
105
|
clearQueryEngineCaches({ keepSlimNodes: true });
|
|
96
106
|
store.getState().nodesTouched.clear();
|
|
97
107
|
const state = store.getState();
|
|
@@ -451,6 +461,7 @@ async function build(options) {
|
|
|
451
461
|
`${queriesRun} queries`,
|
|
452
462
|
skipped && `${skipped} unchanged`,
|
|
453
463
|
res.recovered && `${res.recovered} out of memory`,
|
|
464
|
+
guardText(workerTimings.guard),
|
|
454
465
|
again && `${rebuilt} again with SitePage nodes`,
|
|
455
466
|
leftovers.length + deferredItems.length && `${leftovers.length + deferredItems.length} left to the main thread`
|
|
456
467
|
].filter(Boolean).join(", "));
|
|
@@ -6,7 +6,9 @@
|
|
|
6
6
|
*
|
|
7
7
|
* 1. each worker's heap budget – the continuous backpressure: a worker measures its heap against
|
|
8
8
|
* it, so it drops its caches, sizes its batches and buffers results by it;
|
|
9
|
-
* 2. squeezing workers (a budget at their current heap: they drop their caches at once
|
|
9
|
+
* 2. squeezing workers (a budget at their current heap: they drop their caches at once – unless
|
|
10
|
+
* they dropped them before and had to build them again, see createHeapGuard: such a worker
|
|
11
|
+
* needs them, and what helps is the next step);
|
|
10
12
|
* 3. retiring workers (they finish what they hold, then stop) and shedding one (it is stopped at
|
|
11
13
|
* once, its pages are built again) when memory runs out faster than caches can be dropped, or
|
|
12
14
|
* when the system slows down for memory (PSI, macOS's memory pressure);
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { performance } from "node:perf_hooks";
|
|
1
2
|
import path from "node:path";
|
|
2
3
|
import fs from "node:fs";
|
|
3
4
|
// src/node/build/page-files.ts
|
|
@@ -51,4 +52,135 @@ function overwrite(file, data) {
|
|
|
51
52
|
}
|
|
52
53
|
return true;
|
|
53
54
|
}
|
|
54
|
-
|
|
55
|
+
/** like writePageFile, through libuv's thread pool: other work goes on while the file is written */
|
|
56
|
+
async function writePageFileAsync(file, data, exists) {
|
|
57
|
+
if (exists && await overwriteAsync(file, data)) return;
|
|
58
|
+
try {
|
|
59
|
+
await fs.promises.writeFile(file, data);
|
|
60
|
+
} catch (e) {
|
|
61
|
+
if (e.code !== "ENOENT") throw e;
|
|
62
|
+
await fs.promises.mkdir(path.dirname(file), { recursive: true });
|
|
63
|
+
await fs.promises.writeFile(file, data);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
async function overwriteAsync(file, data) {
|
|
67
|
+
let handle;
|
|
68
|
+
try {
|
|
69
|
+
handle = await fs.promises.open(file, fs.constants.O_WRONLY);
|
|
70
|
+
} catch (e) {
|
|
71
|
+
if (e.code === "ENOENT") return false;
|
|
72
|
+
throw e;
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
const bytes = Buffer.from(data);
|
|
76
|
+
let written = 0;
|
|
77
|
+
while (written < bytes.length) written += (await handle.write(bytes, written, bytes.length - written, written)).bytesWritten;
|
|
78
|
+
if ((await handle.stat()).size > bytes.length) await handle.truncate(bytes.length);
|
|
79
|
+
} finally {
|
|
80
|
+
await handle.close();
|
|
81
|
+
}
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* A filesystem is slow to write a page's file to when a synchronous write takes this long (ms) on
|
|
86
|
+
* average – it takes 0.02–0.1 ms into the page cache of a local disk. What takes milliseconds is
|
|
87
|
+
* creating a file on a bind mount of Docker Desktop, on a network drive, or under an antivirus
|
|
88
|
+
* scanner, and a thread that waits for it does nothing else: 5 workers that write two files per
|
|
89
|
+
* page at 27 ms each build 90 pages a second, however fast they render.
|
|
90
|
+
*/
|
|
91
|
+
const SLOW_WRITE_MS = 1;
|
|
92
|
+
/** …measured over this many writes (fewer when the first ones already took that long in sum) */
|
|
93
|
+
const WRITES_MEASURED = 8;
|
|
94
|
+
/**
|
|
95
|
+
* While writes overlap, the disk is tried again after this many files, with synchronous writes:
|
|
96
|
+
* when 8 of them are fast (a quarter of what counts as slow, on average), the writes are
|
|
97
|
+
* synchronous again. A try ends with the first write that is too slow for that, and the next one
|
|
98
|
+
* comes after twice as many files (at most PROBE_EVERY_MAX): on a disk that stays slow, trying
|
|
99
|
+
* costs a write now and then.
|
|
100
|
+
*/
|
|
101
|
+
const PROBE_EVERY = 512;
|
|
102
|
+
const PROBE_EVERY_MAX = 65536;
|
|
103
|
+
/**
|
|
104
|
+
* The threads of libuv's pool (UV_THREADPOOL_SIZE: the CLI sets it, see ioThreads): how many file
|
|
105
|
+
* operations of the whole process run at a time
|
|
106
|
+
*/
|
|
107
|
+
function ioPoolSize(env = process.env) {
|
|
108
|
+
const size = Number(env.UV_THREADPOOL_SIZE);
|
|
109
|
+
return size >= 1 ? Math.floor(size) : 4;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* The size of libuv's thread pool for a build (UV_THREADPOOL_SIZE, read when the pool is first
|
|
113
|
+
* used: set it before): 16 threads per CPU, 32 to 128. They are what lets file writes overlap on a
|
|
114
|
+
* slow filesystem (see createPageWriter) – a thread that waits for the disk needs no CPU – and idle
|
|
115
|
+
* threads cost nothing. undefined: it is set already.
|
|
116
|
+
*/
|
|
117
|
+
function ioThreads(cpus, env = process.env) {
|
|
118
|
+
if (env.UV_THREADPOOL_SIZE) return void 0;
|
|
119
|
+
return Math.min(128, Math.max(32, 16 * cpus));
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Writes the output files of the pages a thread renders, the way that is fastest on the disk it
|
|
123
|
+
* finds:
|
|
124
|
+
*
|
|
125
|
+
* - synchronously (writePageFile) while that is fast – on a local disk a write is a copy into the
|
|
126
|
+
* page cache, and a trip through the thread pool per open, write and close costs more than it
|
|
127
|
+
* saves (see docs/decisions-writing-pages.md);
|
|
128
|
+
* - several at a time (writePageFileAsync) once the writes are slow: `write` then returns a
|
|
129
|
+
* promise, and the thread goes on rendering while the files are written. Whoever calls it limits
|
|
130
|
+
* the writes in flight (`window`: pages, by the size of the thread pool) and waits for them
|
|
131
|
+
* before it reports its pages as written.
|
|
132
|
+
*
|
|
133
|
+
* It measures the synchronous writes, and tries them again now and then while writes overlap.
|
|
134
|
+
*/
|
|
135
|
+
function createPageWriter(options = {}) {
|
|
136
|
+
const mode = options.mode ?? process.env.GOATLY_PAGE_WRITES;
|
|
137
|
+
const now = options.now ?? (() => performance.now());
|
|
138
|
+
const writeSync = options.writeSync ?? writePageFile;
|
|
139
|
+
const writeAsync = options.writeAsync ?? writePageFileAsync;
|
|
140
|
+
let overlapping = mode === "overlap";
|
|
141
|
+
/** the synchronous writes being measured: how many, and what they took (ms) */
|
|
142
|
+
let count = 0;
|
|
143
|
+
let sum = 0;
|
|
144
|
+
/** while writes overlap: files written since the disk was last tried, and when it is tried again */
|
|
145
|
+
let sinceProbe = 0;
|
|
146
|
+
let probeEvery = PROBE_EVERY;
|
|
147
|
+
let probing = false;
|
|
148
|
+
const measure = (ms) => {
|
|
149
|
+
count++;
|
|
150
|
+
sum += ms;
|
|
151
|
+
if (mode) return;
|
|
152
|
+
if (sum >= (overlapping ? SLOW_WRITE_MS / 4 : SLOW_WRITE_MS) * WRITES_MEASURED) {
|
|
153
|
+
if (!overlapping) {
|
|
154
|
+
overlapping = true;
|
|
155
|
+
options.onSlow?.(sum / count);
|
|
156
|
+
probeEvery = PROBE_EVERY;
|
|
157
|
+
} else probeEvery = Math.min(PROBE_EVERY_MAX, probeEvery * 2);
|
|
158
|
+
} else if (count < WRITES_MEASURED) return;
|
|
159
|
+
else if (overlapping) {
|
|
160
|
+
overlapping = false;
|
|
161
|
+
probeEvery = PROBE_EVERY;
|
|
162
|
+
}
|
|
163
|
+
count = sum = sinceProbe = 0;
|
|
164
|
+
probing = false;
|
|
165
|
+
};
|
|
166
|
+
return {
|
|
167
|
+
/** writes overlap (the disk is slow) */
|
|
168
|
+
get overlapping() {
|
|
169
|
+
return overlapping;
|
|
170
|
+
},
|
|
171
|
+
/** pages whose files may be in flight at a time: half the thread pool's size, 2 to 32 */
|
|
172
|
+
window: Math.min(32, Math.max(2, Math.floor((options.poolSize ?? ioPoolSize()) / 2))),
|
|
173
|
+
/** undefined: the file is written; else a promise that settles when it is (or failed) */
|
|
174
|
+
write(file, data, exists) {
|
|
175
|
+
if (overlapping && !probing) {
|
|
176
|
+
if (mode || ++sinceProbe < probeEvery) return writeAsync(file, data, exists);
|
|
177
|
+
probing = true;
|
|
178
|
+
count = sum = 0;
|
|
179
|
+
}
|
|
180
|
+
const start = now();
|
|
181
|
+
writeSync(file, data, exists);
|
|
182
|
+
measure(now() - start);
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
export { createPageWriter, ioPoolSize, ioThreads, writePageFile, writePageFileAsync };
|