goatly 0.1.0 → 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 +874 -1
- package/bin/goatly.js +99 -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 +569 -0
- package/dist/node/build/assets.js +110 -0
- package/dist/node/build/incremental.js +208 -0
- package/dist/node/build/index.js +763 -0
- package/dist/node/build/memory-governor.js +450 -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 +186 -0
- package/dist/node/build/partitioned-state.js +258 -0
- package/dist/node/build/query-worker.js +626 -0
- package/dist/node/build/query-workers.js +863 -0
- package/dist/node/build/render-thread.js +103 -0
- package/dist/node/build/render-worker.js +162 -0
- package/dist/node/build/state.js +24 -0
- package/dist/node/build/timing-breakdown.js +216 -0
- package/dist/node/build/work-clock.js +75 -0
- package/dist/node/build/worker-pool.js +242 -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/cpus.js +104 -0
- package/dist/node/utils/create-node-id.js +51 -0
- package/dist/node/utils/env.js +25 -0
- package/dist/node/utils/fs-retry.js +74 -0
- package/dist/node/utils/memory-signals.js +441 -0
- package/dist/node/utils/memory.js +657 -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 +283 -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 +330 -0
- package/dist/node/wasm-data/host.js +406 -0
- package/dist/node/wasm-data/lower.js +406 -0
- package/dist/node/wasm-data/runner.js +79 -0
- package/dist/node/wasm-data/worker.js +95 -0
- package/dist/reporter.js +5 -0
- package/dist/runtime/api-runner.js +81 -0
- package/dist/runtime/app.js +256 -0
- package/dist/runtime/client-entry.js +4 -0
- package/dist/runtime/client.js +383 -0
- package/dist/runtime/default-html.js +31 -0
- package/dist/runtime/head-markup.js +100 -0
- package/dist/runtime/head-sync.js +101 -0
- package/dist/runtime/head-tags.js +45 -0
- package/dist/runtime/hydration-report.js +111 -0
- package/dist/runtime/index.js +12 -0
- package/dist/runtime/link.js +293 -0
- package/dist/runtime/loader.js +449 -0
- package/dist/runtime/not-found.js +61 -0
- package/dist/runtime/page-renderer.js +35 -0
- package/dist/runtime/preamble.js +47 -0
- package/dist/runtime/react-compat.js +14 -0
- package/dist/runtime/renderer-shared.js +10 -0
- package/dist/runtime/renderers/react-client.js +14 -0
- package/dist/runtime/renderers/react-server.js +99 -0
- package/dist/runtime/renderers/react.js +17 -0
- package/dist/runtime/renderers/types.js +1 -0
- package/dist/runtime/root-error-handlers.js +29 -0
- package/dist/runtime/router/history.js +132 -0
- package/dist/runtime/router/index.js +240 -0
- package/dist/runtime/router/utils.js +118 -0
- package/dist/runtime/script.js +110 -0
- package/dist/runtime/scroll.js +40 -0
- package/dist/runtime/slice.js +11 -0
- package/dist/runtime/ssr.js +240 -0
- package/dist/runtime/static-query.js +47 -0
- package/dist/utils.js +4 -0
- package/package.json +105 -3
- package/types/graphql-tada.d.ts +223 -0
- package/types/graphql.d.ts +2 -0
- package/types/index.d.ts +2287 -0
- package/types/node.d.ts +389 -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,1430 @@
|
|
|
1
|
+
import { PendingBytes, createSelfContainedNodeCodec, createSelfContainedNodeDecoder, encodeReused } from "./datastore/codec.js";
|
|
2
|
+
import reporter from "./reporter.js";
|
|
3
|
+
import { isBun } from "./utils/runtime.js";
|
|
4
|
+
import { compatEnv } from "./utils/env.js";
|
|
5
|
+
import { isSerializable, sanitize } from "./utils/serializable.js";
|
|
6
|
+
import { PLUGIN_CACHE_DIR, TMP_PREFIX } from "./cache-layout.js";
|
|
7
|
+
import { partitionHash } from "./utils/partition-hash.js";
|
|
8
|
+
import { renameSync } from "./utils/fs-retry.js";
|
|
9
|
+
import { createRequire } from "node:module";
|
|
10
|
+
import { isMainThread } from "node:worker_threads";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import fs from "node:fs";
|
|
13
|
+
import zlib from "node:zlib";
|
|
14
|
+
// src/node/cache.ts
|
|
15
|
+
const require = createRequire(import.meta.url);
|
|
16
|
+
/** `readOnly`: fails when the file does not exist, and never opens it for writing */
|
|
17
|
+
function openSqlite(file, readOnly = false) {
|
|
18
|
+
if (isBun) {
|
|
19
|
+
const { Database } = require("bun:sqlite");
|
|
20
|
+
const db = new Database(file, readOnly ? { readonly: true } : { create: true });
|
|
21
|
+
const statements = [];
|
|
22
|
+
return {
|
|
23
|
+
exec: (sql) => db.exec(sql),
|
|
24
|
+
prepare: (sql) => {
|
|
25
|
+
const statement = db.prepare(sql);
|
|
26
|
+
statements.push(statement);
|
|
27
|
+
return statement;
|
|
28
|
+
},
|
|
29
|
+
close: () => {
|
|
30
|
+
for (const statement of statements) statement.finalize();
|
|
31
|
+
db.close();
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
const originalEmit = process.emitWarning;
|
|
36
|
+
process.emitWarning = ((warning, ...args) => {
|
|
37
|
+
if (String(warning?.message ?? warning).includes("SQLite")) return;
|
|
38
|
+
return originalEmit.call(process, warning, ...args);
|
|
39
|
+
});
|
|
40
|
+
let DatabaseSync;
|
|
41
|
+
try {
|
|
42
|
+
({DatabaseSync} = require("node:sqlite"));
|
|
43
|
+
} finally {
|
|
44
|
+
process.emitWarning = originalEmit;
|
|
45
|
+
}
|
|
46
|
+
return readOnly ? new DatabaseSync(file, { readOnly: true }) : new DatabaseSync(file);
|
|
47
|
+
}
|
|
48
|
+
/** a database of the runtime's built-in SQLite (`bun:sqlite` / `node:sqlite`), or null */
|
|
49
|
+
function openBuiltinSqlite(file) {
|
|
50
|
+
try {
|
|
51
|
+
return openSqlite(file);
|
|
52
|
+
} catch {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
const RESET_SQL = "DELETE FROM cache WHERE name = ?";
|
|
57
|
+
/** the value of a row of a run file's `cache` table */
|
|
58
|
+
function rowValue(row) {
|
|
59
|
+
if (!row || row.value == null) return void 0;
|
|
60
|
+
const value = row.value;
|
|
61
|
+
return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Values are stored zstd-compressed (level 1) when they have at least `COMPRESS_MIN_BYTES` encoded
|
|
65
|
+
* bytes and compressing saves at least an eighth; smaller values, and values that don't compress
|
|
66
|
+
* (e.g. images), are stored as they are. A compressed value is `COMPRESSED_TAG` followed by the
|
|
67
|
+
* zstd frame: 0xC1 is the one byte MessagePack never uses, so no encoded value starts with it.
|
|
68
|
+
* Values of earlier versions (all stored uncompressed) stay readable, and an earlier version reads
|
|
69
|
+
* a compressed value as a miss (msgpackr decodes the 0xC1 byte as a placeholder, then rejects the
|
|
70
|
+
* frame after it as trailing bytes).
|
|
71
|
+
*
|
|
72
|
+
* remark's ASTs (gatsby-transformer-remark) take half the space or less (a third for long posts),
|
|
73
|
+
* so a smaller `.cache` is written, kept and transferred (CI caches, image layers), at about 7% of
|
|
74
|
+
* a cold build's time on Node with 100k posts, within noise on Bun. Values below 1 KB would save
|
|
75
|
+
* little: the fixed cost of a call dominates there.
|
|
76
|
+
*/
|
|
77
|
+
const COMPRESSED_TAG = 193;
|
|
78
|
+
const COMPRESS_MIN_BYTES = 1024;
|
|
79
|
+
/** Bun's own zstd functions are faster than its node:zlib ones (no stream object per call) */
|
|
80
|
+
function createZstd() {
|
|
81
|
+
const bun = globalThis.Bun;
|
|
82
|
+
if (typeof bun?.zstdCompressSync === "function") return {
|
|
83
|
+
compress: (bytes) => bun.zstdCompressSync(bytes, { level: 1 }),
|
|
84
|
+
decompress: (bytes) => bun.zstdDecompressSync(bytes)
|
|
85
|
+
};
|
|
86
|
+
const options = { params: { [zlib.constants.ZSTD_c_compressionLevel]: 1 } };
|
|
87
|
+
return {
|
|
88
|
+
compress: (bytes) => zlib.zstdCompressSync(bytes, options),
|
|
89
|
+
decompress: (bytes) => zlib.zstdDecompressSync(bytes)
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
let zstd;
|
|
93
|
+
/** `bytes` as stored: compressed when that saves at least an eighth */
|
|
94
|
+
function compressValue(bytes) {
|
|
95
|
+
if (bytes.length < COMPRESS_MIN_BYTES) return bytes;
|
|
96
|
+
const frame = (zstd ??= createZstd()).compress(bytes);
|
|
97
|
+
if (frame.length + 1 > bytes.length - (bytes.length >> 3)) return bytes;
|
|
98
|
+
const stored = Buffer.allocUnsafe(frame.length + 1);
|
|
99
|
+
stored[0] = COMPRESSED_TAG;
|
|
100
|
+
stored.set(frame, 1);
|
|
101
|
+
return stored;
|
|
102
|
+
}
|
|
103
|
+
/** `compressValue`, or `bytes` as they are when compressing fails (flushes never throw) */
|
|
104
|
+
function compressValueOrNot(bytes) {
|
|
105
|
+
try {
|
|
106
|
+
return compressValue(bytes);
|
|
107
|
+
} catch {
|
|
108
|
+
return bytes;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/** the encoded value of stored bytes */
|
|
112
|
+
function decompressValue(bytes) {
|
|
113
|
+
if (bytes[0] !== COMPRESSED_TAG) return bytes;
|
|
114
|
+
const raw = (zstd ??= createZstd()).decompress(bytes.subarray(1));
|
|
115
|
+
return Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Writes `rows` in one transaction. Nothing throws (flushes also
|
|
119
|
+
* run in a timer), and an entry SQLite cannot store (e.g. a constraint or trigger rejects the row)
|
|
120
|
+
* does not discard the other writes of the batch.
|
|
121
|
+
*/
|
|
122
|
+
function writeRows(db, stmts, rows) {
|
|
123
|
+
try {
|
|
124
|
+
db.exec("BEGIN IMMEDIATE");
|
|
125
|
+
} catch (e) {
|
|
126
|
+
warnWriteFailure(e);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
let failures = 0;
|
|
130
|
+
let first;
|
|
131
|
+
for (const r of rows) try {
|
|
132
|
+
if (r.value) stmts.set.run(r.name, r.key, r.value);
|
|
133
|
+
else stmts.del.run(r.name, r.key);
|
|
134
|
+
} catch (error) {
|
|
135
|
+
failures++;
|
|
136
|
+
first ??= {
|
|
137
|
+
name: r.name,
|
|
138
|
+
key: r.key,
|
|
139
|
+
error
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
try {
|
|
143
|
+
db.exec("COMMIT");
|
|
144
|
+
} catch (e) {
|
|
145
|
+
try {
|
|
146
|
+
db.exec("ROLLBACK");
|
|
147
|
+
} catch {}
|
|
148
|
+
warnWriteFailure(first?.error ?? e);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
if (first && compatEnv("GOATLY_VERBOSE")) console.warn(`could not write ${failures} of ${rows.length} cache entries (first: key ${first.key} of cache "${first.name}")`, first.error);
|
|
152
|
+
}
|
|
153
|
+
/** What the SQLite backends share: the write buffer and the run ids (`cache_runs` of `runsDb`). */
|
|
154
|
+
var BufferedBackend = class {
|
|
155
|
+
runsDb;
|
|
156
|
+
threshold;
|
|
157
|
+
/**
|
|
158
|
+
* buffered writes (`value`: a view of `bytes`, null: deleted) – flushed in short transactions so
|
|
159
|
+
* concurrent workers rarely wait for the lock. Other threads and processes see them once they
|
|
160
|
+
* are committed.
|
|
161
|
+
*/
|
|
162
|
+
pending = /* @__PURE__ */ new Map();
|
|
163
|
+
/** the encoded values of the buffered writes (created on the first write) */
|
|
164
|
+
bytes;
|
|
165
|
+
timer;
|
|
166
|
+
newRunStmt;
|
|
167
|
+
oldRunsStmt;
|
|
168
|
+
constructor(runsDb, threshold) {
|
|
169
|
+
this.runsDb = runsDb;
|
|
170
|
+
this.threshold = threshold;
|
|
171
|
+
this.newRunStmt = runsDb.prepare("INSERT INTO cache_runs DEFAULT VALUES RETURNING id");
|
|
172
|
+
this.oldRunsStmt = runsDb.prepare("DELETE FROM cache_runs WHERE id < ?");
|
|
173
|
+
}
|
|
174
|
+
/** a new id, larger than all before (in a transaction of `runsDb`) */
|
|
175
|
+
newId() {
|
|
176
|
+
const id = Number(this.newRunStmt.get().id);
|
|
177
|
+
this.oldRunsStmt.run(id);
|
|
178
|
+
return id;
|
|
179
|
+
}
|
|
180
|
+
/** a new run (in a transaction of `runsDb`) */
|
|
181
|
+
newRun() {
|
|
182
|
+
return this.newId();
|
|
183
|
+
}
|
|
184
|
+
nextRun() {
|
|
185
|
+
const run = this.run;
|
|
186
|
+
if (run === void 0) return void 0;
|
|
187
|
+
this.flush();
|
|
188
|
+
let next = 0;
|
|
189
|
+
try {
|
|
190
|
+
transaction(this.runsDb, () => {
|
|
191
|
+
next = this.newRun();
|
|
192
|
+
});
|
|
193
|
+
} catch (e) {
|
|
194
|
+
warnRotationFailure(e);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
this.run = next;
|
|
198
|
+
return run;
|
|
199
|
+
}
|
|
200
|
+
get(name, key) {
|
|
201
|
+
const p = this.pending.get(`${name}\0${key}`);
|
|
202
|
+
if (p) return p.value ?? void 0;
|
|
203
|
+
return this.read(name, key);
|
|
204
|
+
}
|
|
205
|
+
schedule() {
|
|
206
|
+
if (this.pending.size >= this.threshold || this.bytes?.full) this.flush();
|
|
207
|
+
else if (!this.timer) {
|
|
208
|
+
this.timer = setTimeout(() => this.flush(), 2e3);
|
|
209
|
+
this.timer.unref?.();
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
set(name, key, value) {
|
|
213
|
+
const bytes = (this.bytes ??= new PendingBytes()).add(value);
|
|
214
|
+
this.pending.set(`${name}\0${key}`, {
|
|
215
|
+
name,
|
|
216
|
+
key,
|
|
217
|
+
value: bytes
|
|
218
|
+
});
|
|
219
|
+
this.schedule();
|
|
220
|
+
}
|
|
221
|
+
del(name, key) {
|
|
222
|
+
this.pending.set(`${name}\0${key}`, {
|
|
223
|
+
name,
|
|
224
|
+
key,
|
|
225
|
+
value: null
|
|
226
|
+
});
|
|
227
|
+
this.schedule();
|
|
228
|
+
}
|
|
229
|
+
/** drops the buffered writes (a process killed before they were written) */
|
|
230
|
+
discardPending() {
|
|
231
|
+
if (this.timer) {
|
|
232
|
+
clearTimeout(this.timer);
|
|
233
|
+
this.timer = void 0;
|
|
234
|
+
}
|
|
235
|
+
this.pending.clear();
|
|
236
|
+
this.bytes?.clear();
|
|
237
|
+
}
|
|
238
|
+
flush() {
|
|
239
|
+
if (this.timer) {
|
|
240
|
+
clearTimeout(this.timer);
|
|
241
|
+
this.timer = void 0;
|
|
242
|
+
}
|
|
243
|
+
if (this.pending.size === 0) return;
|
|
244
|
+
const rows = [...this.pending.values()];
|
|
245
|
+
this.pending.clear();
|
|
246
|
+
for (const row of rows) if (row.value) row.value = compressValueOrNot(row.value);
|
|
247
|
+
this.writeBatch(rows);
|
|
248
|
+
this.bytes?.clear();
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
function userVersion(db) {
|
|
252
|
+
return Number(db.prepare("PRAGMA user_version").get().user_version);
|
|
253
|
+
}
|
|
254
|
+
const readVersion = (stmt) => Number(stmt.get().data_version);
|
|
255
|
+
/** the tables of `meta.sqlite` */
|
|
256
|
+
const MANIFEST_TABLES = ["CREATE TABLE cache_runs (id INTEGER PRIMARY KEY AUTOINCREMENT)", "CREATE TABLE files (run INTEGER PRIMARY KEY, file TEXT NOT NULL, bytes INTEGER, committed INTEGER NOT NULL)"];
|
|
257
|
+
/**
|
|
258
|
+
* Opens `meta.sqlite` for writing, closed when it can't be set up (its statements fail e.g. for a
|
|
259
|
+
* file that is not a database: opening it succeeds). A manifest of another version is emptied (its
|
|
260
|
+
* run files are not listed any more), in one transaction: a thread that opens it at the same time
|
|
261
|
+
* waits, then finds the current version. Rollback journal: no `-wal`/`-shm` files next to it.
|
|
262
|
+
*/
|
|
263
|
+
function openManifest(file) {
|
|
264
|
+
const db = openSqlite(file);
|
|
265
|
+
try {
|
|
266
|
+
db.exec("PRAGMA busy_timeout = 60000");
|
|
267
|
+
db.exec("PRAGMA synchronous = OFF");
|
|
268
|
+
db.exec("PRAGMA journal_mode = DELETE");
|
|
269
|
+
if (userVersion(db) !== MANIFEST_VERSION) transaction(db, () => {
|
|
270
|
+
if (userVersion(db) === MANIFEST_VERSION) return;
|
|
271
|
+
for (const table of ["cache_runs", "files"]) db.exec(`DROP TABLE IF EXISTS ${table}`);
|
|
272
|
+
for (const sql of MANIFEST_TABLES) db.exec(sql);
|
|
273
|
+
db.exec(`PRAGMA user_version = ${MANIFEST_VERSION}`);
|
|
274
|
+
const dir = path.dirname(file);
|
|
275
|
+
for (const name of fs.readdirSync(dir)) if (RUN_FILE.test(name)) removeRunFile(path.join(dir, name));
|
|
276
|
+
});
|
|
277
|
+
return db;
|
|
278
|
+
} catch (e) {
|
|
279
|
+
try {
|
|
280
|
+
db.close();
|
|
281
|
+
} catch {}
|
|
282
|
+
throw e;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
/** runs `fn` in a write transaction (rolled back when it throws) */
|
|
286
|
+
function transaction(db, fn) {
|
|
287
|
+
db.exec("BEGIN IMMEDIATE");
|
|
288
|
+
try {
|
|
289
|
+
fn();
|
|
290
|
+
db.exec("COMMIT");
|
|
291
|
+
} catch (e) {
|
|
292
|
+
try {
|
|
293
|
+
db.exec("ROLLBACK");
|
|
294
|
+
} catch {}
|
|
295
|
+
throw e;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
let warnedWriteFailure = false;
|
|
299
|
+
/** a batch that could not be written (lock timeout, full disk …): warns once per thread */
|
|
300
|
+
function warnWriteFailure(e) {
|
|
301
|
+
if (warnedWriteFailure) return;
|
|
302
|
+
warnedWriteFailure = true;
|
|
303
|
+
reporter.warn(`The plugin cache could not be written, cache entries are dropped: ${e?.message ?? e}`);
|
|
304
|
+
}
|
|
305
|
+
let warnedRotationFailure = false;
|
|
306
|
+
/** a node persist could not start a new run (lock timeout …): warns once per thread */
|
|
307
|
+
function warnRotationFailure(e) {
|
|
308
|
+
if (warnedRotationFailure) return;
|
|
309
|
+
warnedRotationFailure = true;
|
|
310
|
+
reporter.warn(`The plugin cache could not start a new run: ${e?.message ?? e}. This run's cache writes become permanent with a later save of its nodes, or are reverted by the next start.`);
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* The backend when the database cannot be opened: keeps the encoded entries in memory until
|
|
314
|
+
* `closeCaches` (nothing is persisted, and the other threads don't see them)
|
|
315
|
+
*/
|
|
316
|
+
var MemoryBackend = class {
|
|
317
|
+
error;
|
|
318
|
+
entries = /* @__PURE__ */ new Map();
|
|
319
|
+
/** `error`: why the database could not be opened */
|
|
320
|
+
constructor(error) {
|
|
321
|
+
this.error = error;
|
|
322
|
+
}
|
|
323
|
+
get(name, key) {
|
|
324
|
+
return this.entries.get(`${name}\0${key}`);
|
|
325
|
+
}
|
|
326
|
+
othersCommitted() {
|
|
327
|
+
return false;
|
|
328
|
+
}
|
|
329
|
+
set(name, key, value) {
|
|
330
|
+
this.entries.set(`${name}\0${key}`, Buffer.from(value));
|
|
331
|
+
}
|
|
332
|
+
del(name, key) {
|
|
333
|
+
this.entries.delete(`${name}\0${key}`);
|
|
334
|
+
}
|
|
335
|
+
reset(name) {
|
|
336
|
+
for (const id of this.entries.keys()) if (id.startsWith(`${name}\0`)) this.entries.delete(id);
|
|
337
|
+
}
|
|
338
|
+
flush() {}
|
|
339
|
+
close() {}
|
|
340
|
+
run;
|
|
341
|
+
startRun() {
|
|
342
|
+
return 0;
|
|
343
|
+
}
|
|
344
|
+
nextRun() {}
|
|
345
|
+
commitRun() {}
|
|
346
|
+
};
|
|
347
|
+
/**
|
|
348
|
+
* The plugin cache's files: a build only creates files, and only the small manifest
|
|
349
|
+
* `caches-lsm/meta.sqlite` is rewritten. Made for caches that travel as image layers or are synced
|
|
350
|
+
* file by file, where a file that changes is copied whole:
|
|
351
|
+
*
|
|
352
|
+
* - each run writes its entries into a SQLite file of its own, `run-<run>.sqlite`, created when the
|
|
353
|
+
* run starts (the threads have it open) and removed again by the commit or close when nothing
|
|
354
|
+
* was written. Its row in `files` is inserted before the file exists, with `committed = 0`: a
|
|
355
|
+
* commit sets it to 1, so all of the run's
|
|
356
|
+
* writes, also those of query workers, become permanent at once. A start deletes the files of
|
|
357
|
+
* the runs that did not commit (also another live process's run: no locking between processes).
|
|
358
|
+
* - files of committed runs are never written again, only read, newest first: a run's entry wins
|
|
359
|
+
* over older ones, a tombstone is a deleted entry, and a `reset()` (`cache_resets`) hides the
|
|
360
|
+
* cache's entries in older files. A file other than the oldest is only probed when a hash of the
|
|
361
|
+
* key is in its filter (built at its first use); the oldest, largest one (the base) always is.
|
|
362
|
+
* - after a commit (`mergeCacheRuns`), files are merged in size tiers: while the newest is at least
|
|
363
|
+
* a quarter of the next older one, or there are more than `MERGE.maxFiles`, the two are merged
|
|
364
|
+
* into a new file and deleted. A merge into the base (a rewrite of the whole cache) only happens
|
|
365
|
+
* once newer files reach about a quarter of it.
|
|
366
|
+
* - a listed file that is missing or damaged (a torn copy of `.cache`) is left out with the older
|
|
367
|
+
* files, so no outdated value is read: their keys are misses, and the next merge unlists them.
|
|
368
|
+
* - the threads share the run's file (busy timeout), with a rollback journal: no `-wal`/`-shm`
|
|
369
|
+
* files, and the `-journal` of a write is deleted at its commit.
|
|
370
|
+
*/
|
|
371
|
+
const MERGE = {
|
|
372
|
+
maxFiles: 12,
|
|
373
|
+
ratio: 4
|
|
374
|
+
};
|
|
375
|
+
/** @internal (tests) the merge thresholds, `undefined`: the defaults */
|
|
376
|
+
function setMergePolicy(policy) {
|
|
377
|
+
Object.assign(MERGE, {
|
|
378
|
+
maxFiles: 12,
|
|
379
|
+
ratio: 4
|
|
380
|
+
}, policy);
|
|
381
|
+
}
|
|
382
|
+
/** (1: run files) the version of `meta.sqlite`: files of another version are not listed any more */
|
|
383
|
+
const MANIFEST_VERSION = 1;
|
|
384
|
+
const RUN_FILE = /^run-\d+(-\d+)?\.sqlite$/;
|
|
385
|
+
/** unlisted run files and merge outputs this old are removed by a start (younger: being written) */
|
|
386
|
+
const STALE_MS = 6e5;
|
|
387
|
+
/** the page cache of a merge (KiB): the index of the entries is built in random order */
|
|
388
|
+
const MERGE_CACHE_KIB = 65536;
|
|
389
|
+
const RUN_TABLES = ["CREATE TABLE IF NOT EXISTS cache (name TEXT NOT NULL, key TEXT NOT NULL, value BLOB, tombstone INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (name, key))", "CREATE TABLE IF NOT EXISTS cache_resets (name TEXT PRIMARY KEY)"];
|
|
390
|
+
const ROW_SQL = "SELECT value, tombstone FROM cache WHERE name = ? AND key = ?";
|
|
391
|
+
const OPEN_ROW_SQL = `SELECT value, tombstone FROM cache WHERE name = ?1 AND key = ?2
|
|
392
|
+
UNION ALL SELECT NULL, 2 FROM cache_resets WHERE name = ?1 ORDER BY 2 LIMIT 1`;
|
|
393
|
+
const runFileName = (run) => `run-${run}.sqlite`;
|
|
394
|
+
/** how often reads look for files other processes committed or merged (ms) */
|
|
395
|
+
let RELIST_MS = 1e3;
|
|
396
|
+
/** @internal (tests) how often reads list the files, `undefined`: the default */
|
|
397
|
+
function setRelistInterval(ms = 1e3) {
|
|
398
|
+
RELIST_MS = ms;
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* removes a run file and what SQLite may have left next to it. On Windows a file another
|
|
402
|
+
* connection (also of another process) has open can't be removed: it is marked as old instead
|
|
403
|
+
* (its modification time), so the next start removes it once it is closed (`removeUnlisted`). The
|
|
404
|
+
* callers unlisted the file before, or never listed it.
|
|
405
|
+
*/
|
|
406
|
+
function removeRunFile(file) {
|
|
407
|
+
for (const suffix of [
|
|
408
|
+
"",
|
|
409
|
+
"-journal",
|
|
410
|
+
"-wal",
|
|
411
|
+
"-shm"
|
|
412
|
+
]) try {
|
|
413
|
+
fs.rmSync(file + suffix, { force: true });
|
|
414
|
+
} catch {
|
|
415
|
+
try {
|
|
416
|
+
if (fs.existsSync(file + suffix)) fs.utimesSync(file + suffix, 0, 0);
|
|
417
|
+
} catch {}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
/** the entries a run file holds (0 when it can't be read) */
|
|
421
|
+
function countEntries(file) {
|
|
422
|
+
let db;
|
|
423
|
+
try {
|
|
424
|
+
if (!fs.existsSync(file)) return 0;
|
|
425
|
+
db = openSqlite(file);
|
|
426
|
+
return Number(db.prepare("SELECT (SELECT count(*) FROM cache) + (SELECT count(*) FROM cache_resets) AS n").get().n);
|
|
427
|
+
} catch {
|
|
428
|
+
return 0;
|
|
429
|
+
} finally {
|
|
430
|
+
try {
|
|
431
|
+
db?.close();
|
|
432
|
+
} catch {}
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* a listed file that is missing (e.g. merged by another process, or a torn restore) or damaged
|
|
437
|
+
* (an empty or partly copied file)
|
|
438
|
+
*/
|
|
439
|
+
var MissingFile = class extends Error {
|
|
440
|
+
file;
|
|
441
|
+
constructor(file) {
|
|
442
|
+
super(`missing plugin cache file ${file}`);
|
|
443
|
+
this.file = file;
|
|
444
|
+
}
|
|
445
|
+
};
|
|
446
|
+
/**
|
|
447
|
+
* whether a read failed because the file is not a complete run file (empty, truncated, not a
|
|
448
|
+
* database), not for a reason that may pass (out of file descriptors, a lock): SQLITE_CORRUPT,
|
|
449
|
+
* SQLITE_NOTADB, SQLITE_IOERR_SHORT_READ, or a missing table (`errcode`: node, `errno`: Bun)
|
|
450
|
+
*/
|
|
451
|
+
function isDamaged(e) {
|
|
452
|
+
const code = Number(e?.errcode ?? e?.errno);
|
|
453
|
+
if (code === 522) return true;
|
|
454
|
+
const primary = code & 255;
|
|
455
|
+
return primary === 11 || primary === 26 || primary === 1 && /no such table/.test(String(e?.message));
|
|
456
|
+
}
|
|
457
|
+
/** a run of this thread that is not committed: its file is written by this and other threads */
|
|
458
|
+
var OpenRun = class {
|
|
459
|
+
run;
|
|
460
|
+
file;
|
|
461
|
+
db;
|
|
462
|
+
rowStmt;
|
|
463
|
+
writes;
|
|
464
|
+
dataVersionStmt;
|
|
465
|
+
dataVersion = 0;
|
|
466
|
+
/** whether the file may have appeared since it was found missing (another thread created it) */
|
|
467
|
+
stale = true;
|
|
468
|
+
/** whether this thread wrote to the file, created it */
|
|
469
|
+
wrote = false;
|
|
470
|
+
created = false;
|
|
471
|
+
constructor(run, file) {
|
|
472
|
+
this.run = run;
|
|
473
|
+
this.file = file;
|
|
474
|
+
}
|
|
475
|
+
/** opens the file when it exists (checked again once `stale`), whether it is open */
|
|
476
|
+
open() {
|
|
477
|
+
if (this.db) return true;
|
|
478
|
+
if (!this.stale) return false;
|
|
479
|
+
this.stale = false;
|
|
480
|
+
if (!fs.existsSync(this.file)) return false;
|
|
481
|
+
this.connect();
|
|
482
|
+
return true;
|
|
483
|
+
}
|
|
484
|
+
connect() {
|
|
485
|
+
const db = openSqlite(this.file);
|
|
486
|
+
try {
|
|
487
|
+
db.exec("PRAGMA busy_timeout = 60000");
|
|
488
|
+
db.exec("PRAGMA synchronous = OFF");
|
|
489
|
+
this.dataVersionStmt = db.prepare("PRAGMA data_version");
|
|
490
|
+
this.dataVersion = readVersion(this.dataVersionStmt);
|
|
491
|
+
} catch (e) {
|
|
492
|
+
try {
|
|
493
|
+
db.close();
|
|
494
|
+
} catch {}
|
|
495
|
+
throw e;
|
|
496
|
+
}
|
|
497
|
+
this.db = db;
|
|
498
|
+
}
|
|
499
|
+
/** the entry in the run: a value, null (deleted or reset in the run), undefined (not written) */
|
|
500
|
+
get(name, key) {
|
|
501
|
+
if (!this.open()) return void 0;
|
|
502
|
+
try {
|
|
503
|
+
this.rowStmt ??= this.db.prepare(OPEN_ROW_SQL);
|
|
504
|
+
} catch {
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
const row = this.rowStmt.get(name, key);
|
|
508
|
+
if (!row) return void 0;
|
|
509
|
+
return row.tombstone ? null : rowValue(row);
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* the statements to write with, the file and its tables created if needed (in a transaction: the
|
|
513
|
+
* threads may create it at the same time). `created`: called when this thread created the file.
|
|
514
|
+
*/
|
|
515
|
+
writable(created) {
|
|
516
|
+
if (this.writes) return this.writes;
|
|
517
|
+
const existed = fs.existsSync(this.file);
|
|
518
|
+
if (!this.db) this.connect();
|
|
519
|
+
const db = this.db;
|
|
520
|
+
transaction(db, () => {
|
|
521
|
+
for (const sql of RUN_TABLES) db.exec(sql);
|
|
522
|
+
});
|
|
523
|
+
if (!existed) {
|
|
524
|
+
this.created = true;
|
|
525
|
+
created();
|
|
526
|
+
}
|
|
527
|
+
this.writes = {
|
|
528
|
+
set: db.prepare("INSERT OR REPLACE INTO cache (name, key, value, tombstone) VALUES (?, ?, ?, 0)"),
|
|
529
|
+
del: db.prepare("INSERT OR REPLACE INTO cache (name, key, value, tombstone) VALUES (?, ?, NULL, 1)"),
|
|
530
|
+
reset: db.prepare(RESET_SQL),
|
|
531
|
+
resetName: db.prepare("INSERT OR IGNORE INTO cache_resets (name) VALUES (?)")
|
|
532
|
+
};
|
|
533
|
+
return this.writes;
|
|
534
|
+
}
|
|
535
|
+
/** writes in one transaction (never throws) */
|
|
536
|
+
write(rows) {
|
|
537
|
+
this.wrote = true;
|
|
538
|
+
writeRows(this.db, this.writes, rows);
|
|
539
|
+
}
|
|
540
|
+
reset(name) {
|
|
541
|
+
this.wrote = true;
|
|
542
|
+
const { reset, resetName } = this.writes;
|
|
543
|
+
transaction(this.db, () => {
|
|
544
|
+
resetName.run(name);
|
|
545
|
+
reset.run(name);
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
/** whether another connection wrote to the file since the last call (a new file counts) */
|
|
549
|
+
othersCommitted() {
|
|
550
|
+
if (!this.db) return this.open();
|
|
551
|
+
let version;
|
|
552
|
+
try {
|
|
553
|
+
version = readVersion(this.dataVersionStmt);
|
|
554
|
+
} catch {
|
|
555
|
+
return true;
|
|
556
|
+
}
|
|
557
|
+
if (version === this.dataVersion) return false;
|
|
558
|
+
this.dataVersion = version;
|
|
559
|
+
return true;
|
|
560
|
+
}
|
|
561
|
+
/** whether the file is missing or has no entries (false when it can't be read) */
|
|
562
|
+
isEmpty() {
|
|
563
|
+
try {
|
|
564
|
+
if (!this.db) {
|
|
565
|
+
if (!fs.existsSync(this.file)) return true;
|
|
566
|
+
this.connect();
|
|
567
|
+
}
|
|
568
|
+
return !this.db.prepare("SELECT EXISTS (SELECT 1 FROM cache) OR EXISTS (SELECT 1 FROM cache_resets) AS found").get().found;
|
|
569
|
+
} catch {
|
|
570
|
+
return false;
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
close() {
|
|
574
|
+
this.rowStmt = this.writes = this.dataVersionStmt = void 0;
|
|
575
|
+
try {
|
|
576
|
+
this.db?.close();
|
|
577
|
+
} catch {}
|
|
578
|
+
this.db = void 0;
|
|
579
|
+
this.stale = true;
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
/** a committed run file (read-only, opened at its first read) */
|
|
583
|
+
var RunFile = class {
|
|
584
|
+
run;
|
|
585
|
+
file;
|
|
586
|
+
bytes;
|
|
587
|
+
db;
|
|
588
|
+
rowStmt;
|
|
589
|
+
/** the sorted `partitionHash` of its entries' names and keys (tombstones included) */
|
|
590
|
+
hashes;
|
|
591
|
+
resetNames;
|
|
592
|
+
constructor(run, file, bytes) {
|
|
593
|
+
this.run = run;
|
|
594
|
+
this.file = file;
|
|
595
|
+
this.bytes = bytes;
|
|
596
|
+
}
|
|
597
|
+
/** runs a read of the file: a missing or damaged one throws `MissingFile` */
|
|
598
|
+
read(fn) {
|
|
599
|
+
try {
|
|
600
|
+
return fn(this.connection());
|
|
601
|
+
} catch (e) {
|
|
602
|
+
if (isDamaged(e) || !fs.existsSync(this.file)) throw new MissingFile(path.basename(this.file));
|
|
603
|
+
throw e;
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
connection() {
|
|
607
|
+
if (this.db) return this.db;
|
|
608
|
+
const db = openSqlite(this.file, true);
|
|
609
|
+
try {
|
|
610
|
+
db.exec("PRAGMA locking_mode = EXCLUSIVE");
|
|
611
|
+
} catch {}
|
|
612
|
+
this.db = db;
|
|
613
|
+
return db;
|
|
614
|
+
}
|
|
615
|
+
/** the entry's row (`value`, `tombstone`), undefined: not in the file */
|
|
616
|
+
row(name, key) {
|
|
617
|
+
return this.read((db) => (this.rowStmt ??= db.prepare(ROW_SQL)).get(name, key) ?? void 0);
|
|
618
|
+
}
|
|
619
|
+
/** whether the file may have an entry with this `partitionHash` (also deleted) */
|
|
620
|
+
mayHave(hash) {
|
|
621
|
+
if (!this.hashes) {
|
|
622
|
+
const rows = this.read((db) => db.prepare("SELECT name, key FROM cache").all());
|
|
623
|
+
const hashes = new Uint32Array(rows.length);
|
|
624
|
+
for (let i = 0; i < rows.length; i++) hashes[i] = partitionHash(rows[i].name, rows[i].key);
|
|
625
|
+
this.hashes = hashes.sort();
|
|
626
|
+
}
|
|
627
|
+
const hashes = this.hashes;
|
|
628
|
+
let lo = 0;
|
|
629
|
+
let hi = hashes.length;
|
|
630
|
+
while (lo < hi) {
|
|
631
|
+
const mid = lo + hi >>> 1;
|
|
632
|
+
if (hashes[mid] < hash) lo = mid + 1;
|
|
633
|
+
else hi = mid;
|
|
634
|
+
}
|
|
635
|
+
return hashes[lo] === hash;
|
|
636
|
+
}
|
|
637
|
+
/** whether the file's runs reset cache `name` (its entries in older files are gone) */
|
|
638
|
+
wasReset(name) {
|
|
639
|
+
this.resetNames ??= new Set(this.read((db) => db.prepare("SELECT name FROM cache_resets").all()).map((row) => row.name));
|
|
640
|
+
return this.resetNames.has(name);
|
|
641
|
+
}
|
|
642
|
+
/** whether every page of the file can be read (reads all of it) */
|
|
643
|
+
intact() {
|
|
644
|
+
try {
|
|
645
|
+
return this.read((db) => db.prepare("PRAGMA quick_check").get().quick_check === "ok");
|
|
646
|
+
} catch (e) {
|
|
647
|
+
return !(e instanceof MissingFile);
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
close() {
|
|
651
|
+
this.rowStmt = void 0;
|
|
652
|
+
try {
|
|
653
|
+
this.db?.close();
|
|
654
|
+
} catch {}
|
|
655
|
+
this.db = void 0;
|
|
656
|
+
}
|
|
657
|
+
};
|
|
658
|
+
let warnedLostFile = false;
|
|
659
|
+
let warnedDiscardedRun = false;
|
|
660
|
+
/** the plugin cache's backend (see above), one per thread and cache root */
|
|
661
|
+
var RunFilesBackend = class extends BufferedBackend {
|
|
662
|
+
dir;
|
|
663
|
+
meta;
|
|
664
|
+
/** this thread's runs that are not committed, the one written to first */
|
|
665
|
+
open = [];
|
|
666
|
+
/** the committed files, newest first (the last one: the base) */
|
|
667
|
+
files = [];
|
|
668
|
+
byName = /* @__PURE__ */ new Map();
|
|
669
|
+
/**
|
|
670
|
+
* listed files found missing or damaged: left out, with the older files, until the manifest no
|
|
671
|
+
* longer lists them (a merge drops them)
|
|
672
|
+
*/
|
|
673
|
+
lost = /* @__PURE__ */ new Set();
|
|
674
|
+
/** `PRAGMA data_version` of `meta` when the files were listed */
|
|
675
|
+
metaVersion;
|
|
676
|
+
/** the list was reloaded after another connection changed it (for `othersCommitted`) */
|
|
677
|
+
listChanged = false;
|
|
678
|
+
/** when a read last checked whether the list changed (`performance.now()`) */
|
|
679
|
+
checked = -1e400;
|
|
680
|
+
/** a start that failed: the main thread starts the run at the first write (`ensureRun`) */
|
|
681
|
+
unstarted = false;
|
|
682
|
+
/** when `ensureRun` may try again (`performance.now()`): each try may wait the busy timeout */
|
|
683
|
+
retryAt = 0;
|
|
684
|
+
stmts;
|
|
685
|
+
constructor(dir, meta) {
|
|
686
|
+
super(meta, 500);
|
|
687
|
+
this.dir = dir;
|
|
688
|
+
this.meta = meta;
|
|
689
|
+
const prepare = (sql) => meta.prepare(sql);
|
|
690
|
+
this.stmts = {
|
|
691
|
+
metaVersion: prepare("PRAGMA data_version"),
|
|
692
|
+
list: prepare("SELECT run, file, bytes, committed FROM files ORDER BY run DESC"),
|
|
693
|
+
insert: prepare("INSERT INTO files (run, file, committed) VALUES (?, ?, 0)"),
|
|
694
|
+
uncommitted: prepare("SELECT file FROM files WHERE committed = 0"),
|
|
695
|
+
deleteUncommitted: prepare("DELETE FROM files WHERE committed = 0"),
|
|
696
|
+
row: prepare("SELECT committed FROM files WHERE run = ?"),
|
|
697
|
+
commit: prepare("UPDATE files SET committed = 1, bytes = ? WHERE run = ?"),
|
|
698
|
+
deleteRow: prepare("DELETE FROM files WHERE run = ?"),
|
|
699
|
+
touch: prepare("UPDATE files SET bytes = 0 WHERE run = ? AND committed = 0"),
|
|
700
|
+
inputs: prepare("SELECT count(*) AS n FROM files WHERE committed = 1 AND ((run = ? AND file = ?) OR (run = ? AND file = ?))"),
|
|
701
|
+
merged: prepare("INSERT INTO files (run, file, bytes, committed) VALUES (?, ?, ?, 1)")
|
|
702
|
+
};
|
|
703
|
+
for (const run of keptRuns.get(dir) ?? []) this.open.push(this.openRun(run));
|
|
704
|
+
}
|
|
705
|
+
get run() {
|
|
706
|
+
return this.open[0]?.run;
|
|
707
|
+
}
|
|
708
|
+
set run(run) {
|
|
709
|
+
if (run === this.run) return;
|
|
710
|
+
this.flush();
|
|
711
|
+
if (run === void 0) {
|
|
712
|
+
for (const r of this.open) r.close();
|
|
713
|
+
this.open = [];
|
|
714
|
+
} else this.open.unshift(this.openRun(run));
|
|
715
|
+
}
|
|
716
|
+
nextRun() {
|
|
717
|
+
const run = super.nextRun();
|
|
718
|
+
if (run !== void 0) this.writable(false);
|
|
719
|
+
return run;
|
|
720
|
+
}
|
|
721
|
+
openRun(run) {
|
|
722
|
+
return new OpenRun(run, path.join(this.dir, runFileName(run)));
|
|
723
|
+
}
|
|
724
|
+
newRun() {
|
|
725
|
+
const run = super.newRun();
|
|
726
|
+
this.stmts.insert.run(run, runFileName(run));
|
|
727
|
+
return run;
|
|
728
|
+
}
|
|
729
|
+
/** lists the committed files again (keeps the open ones) */
|
|
730
|
+
load() {
|
|
731
|
+
let rows;
|
|
732
|
+
try {
|
|
733
|
+
this.metaVersion = readVersion(this.stmts.metaVersion);
|
|
734
|
+
rows = this.stmts.list.all();
|
|
735
|
+
} catch {
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
const files = [];
|
|
739
|
+
const listed = /* @__PURE__ */ new Set();
|
|
740
|
+
let hidden = false;
|
|
741
|
+
for (const row of rows) {
|
|
742
|
+
const name = row.file;
|
|
743
|
+
listed.add(name);
|
|
744
|
+
if (row.committed && this.lost.has(name)) hidden = true;
|
|
745
|
+
if (!row.committed || hidden) continue;
|
|
746
|
+
let file = this.byName.get(name);
|
|
747
|
+
if (!file) {
|
|
748
|
+
file = new RunFile(Number(row.run), path.join(this.dir, name), Number(row.bytes ?? 0));
|
|
749
|
+
this.byName.set(name, file);
|
|
750
|
+
}
|
|
751
|
+
files.push(file);
|
|
752
|
+
}
|
|
753
|
+
for (const [name, file] of this.byName) if (!files.includes(file)) {
|
|
754
|
+
file.close();
|
|
755
|
+
this.byName.delete(name);
|
|
756
|
+
}
|
|
757
|
+
for (const name of this.lost) if (!listed.has(name)) this.lost.delete(name);
|
|
758
|
+
this.files = files;
|
|
759
|
+
for (const r of this.open) r.stale = true;
|
|
760
|
+
}
|
|
761
|
+
/** lists the files again when another connection changed the list; whether it did */
|
|
762
|
+
refresh() {
|
|
763
|
+
this.checked = performance.now();
|
|
764
|
+
let version;
|
|
765
|
+
try {
|
|
766
|
+
version = readVersion(this.stmts.metaVersion);
|
|
767
|
+
} catch {
|
|
768
|
+
return false;
|
|
769
|
+
}
|
|
770
|
+
if (version === this.metaVersion) return false;
|
|
771
|
+
this.load();
|
|
772
|
+
this.listChanged = true;
|
|
773
|
+
return true;
|
|
774
|
+
}
|
|
775
|
+
startRun() {
|
|
776
|
+
this.flush();
|
|
777
|
+
this.unstarted = true;
|
|
778
|
+
let run = 0;
|
|
779
|
+
let discarded = [];
|
|
780
|
+
transaction(this.meta, () => {
|
|
781
|
+
discarded = this.stmts.uncommitted.all().map((row) => row.file);
|
|
782
|
+
this.stmts.deleteUncommitted.run();
|
|
783
|
+
run = this.newRun();
|
|
784
|
+
});
|
|
785
|
+
this.unstarted = false;
|
|
786
|
+
for (const r of this.open) r.close();
|
|
787
|
+
this.open = [this.openRun(run)];
|
|
788
|
+
this.writable(false);
|
|
789
|
+
let reverted = 0;
|
|
790
|
+
for (const name of discarded) {
|
|
791
|
+
const file = path.join(this.dir, name);
|
|
792
|
+
reverted += countEntries(file);
|
|
793
|
+
removeRunFile(file);
|
|
794
|
+
}
|
|
795
|
+
this.removeUnlisted();
|
|
796
|
+
this.load();
|
|
797
|
+
return reverted;
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* removes old run files the manifest doesn't list, and merge outputs a process left (also the
|
|
801
|
+
* files a removal found open, see `removeRunFile`)
|
|
802
|
+
*/
|
|
803
|
+
removeUnlisted() {
|
|
804
|
+
let names;
|
|
805
|
+
let listed;
|
|
806
|
+
try {
|
|
807
|
+
names = fs.readdirSync(this.dir);
|
|
808
|
+
listed = new Set(this.stmts.list.all().map((row) => row.file));
|
|
809
|
+
} catch {
|
|
810
|
+
return;
|
|
811
|
+
}
|
|
812
|
+
const now = Date.now();
|
|
813
|
+
for (const name of names) {
|
|
814
|
+
const base = name.replace(/-(journal|wal|shm)$/, "");
|
|
815
|
+
if (!(RUN_FILE.test(base) && !listed.has(base)) && !name.startsWith(".tmp-")) continue;
|
|
816
|
+
try {
|
|
817
|
+
if (now - fs.statSync(path.join(this.dir, name)).mtimeMs > STALE_MS) fs.rmSync(path.join(this.dir, name), { force: true });
|
|
818
|
+
} catch {}
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
/**
|
|
822
|
+
* Also commits this thread's earlier runs that are not committed (a persist that failed): their
|
|
823
|
+
* writes were made before these nodes were persisted too. (No open run is then older than a
|
|
824
|
+
* committed file, so the open runs are read first.)
|
|
825
|
+
*/
|
|
826
|
+
commitRun(run) {
|
|
827
|
+
const runs = [run, ...this.open.filter((r) => r.run < run).map((r) => r.run)];
|
|
828
|
+
const files = runs.map((r) => {
|
|
829
|
+
const file = path.join(this.dir, runFileName(r));
|
|
830
|
+
const own = this.open.find((o) => o.run === r);
|
|
831
|
+
const wrote = !!own?.wrote;
|
|
832
|
+
if (own?.isEmpty()) {
|
|
833
|
+
own.close();
|
|
834
|
+
removeRunFile(file);
|
|
835
|
+
}
|
|
836
|
+
try {
|
|
837
|
+
return {
|
|
838
|
+
run: r,
|
|
839
|
+
file,
|
|
840
|
+
wrote,
|
|
841
|
+
bytes: fs.statSync(file).size
|
|
842
|
+
};
|
|
843
|
+
} catch {
|
|
844
|
+
return {
|
|
845
|
+
run: r,
|
|
846
|
+
file,
|
|
847
|
+
wrote,
|
|
848
|
+
bytes: void 0
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
});
|
|
852
|
+
const discarded = [];
|
|
853
|
+
try {
|
|
854
|
+
transaction(this.meta, () => {
|
|
855
|
+
for (const { run, file, wrote, bytes } of files) {
|
|
856
|
+
const row = this.stmts.row.get(run);
|
|
857
|
+
if (!row || wrote && bytes === void 0) {
|
|
858
|
+
if (bytes !== void 0 || wrote) discarded.push(file);
|
|
859
|
+
if (row) this.stmts.deleteRow.run(run);
|
|
860
|
+
} else if (row.committed) continue;
|
|
861
|
+
else if (bytes === void 0) this.stmts.deleteRow.run(run);
|
|
862
|
+
else this.stmts.commit.run(bytes, run);
|
|
863
|
+
}
|
|
864
|
+
});
|
|
865
|
+
} catch (e) {
|
|
866
|
+
warnWriteFailure(e);
|
|
867
|
+
return;
|
|
868
|
+
}
|
|
869
|
+
this.open = this.open.filter((r) => {
|
|
870
|
+
if (!runs.includes(r.run)) return true;
|
|
871
|
+
r.close();
|
|
872
|
+
return false;
|
|
873
|
+
});
|
|
874
|
+
for (const file of discarded) removeRunFile(file);
|
|
875
|
+
if (discarded.length && !warnedDiscardedRun) {
|
|
876
|
+
warnedDiscardedRun = true;
|
|
877
|
+
reporter.warn("The plugin cache entries of this run were discarded by another process that started meanwhile");
|
|
878
|
+
}
|
|
879
|
+
this.load();
|
|
880
|
+
}
|
|
881
|
+
othersCommitted() {
|
|
882
|
+
let changed = this.refresh() || this.listChanged;
|
|
883
|
+
this.listChanged = false;
|
|
884
|
+
for (const r of this.open) if (r.othersCommitted()) changed = true;
|
|
885
|
+
return changed;
|
|
886
|
+
}
|
|
887
|
+
read(name, key) {
|
|
888
|
+
for (;;) try {
|
|
889
|
+
return this.lookup(name, key);
|
|
890
|
+
} catch (e) {
|
|
891
|
+
if (!(e instanceof MissingFile)) throw e;
|
|
892
|
+
if (!this.refresh()) this.markLost(e.file);
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
markLost(name) {
|
|
896
|
+
this.lost.add(name);
|
|
897
|
+
this.load();
|
|
898
|
+
this.listChanged = true;
|
|
899
|
+
if (!warnedLostFile) {
|
|
900
|
+
warnedLostFile = true;
|
|
901
|
+
reporter.warn(`The plugin cache file ${name} is missing or damaged (an incomplete copy of .cache?): its entries and those of older files are misses`);
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
/**
|
|
905
|
+
* Reads check the list at most once per `RELIST_MS`: asking `meta.sqlite` costs about as much as
|
|
906
|
+
* a lookup. The threads of a run share its file, which is always read, and a merged file that is
|
|
907
|
+
* gone is listed anew; a value served from memory is checked every time (`othersCommitted`).
|
|
908
|
+
*/
|
|
909
|
+
lookup(name, key) {
|
|
910
|
+
if (performance.now() - this.checked >= RELIST_MS) this.refresh();
|
|
911
|
+
for (const r of this.open) {
|
|
912
|
+
const value = r.get(name, key);
|
|
913
|
+
if (value !== void 0) return value ?? void 0;
|
|
914
|
+
}
|
|
915
|
+
const files = this.files;
|
|
916
|
+
let hash;
|
|
917
|
+
for (let i = 0; i < files.length; i++) {
|
|
918
|
+
const file = files[i];
|
|
919
|
+
const base = i === files.length - 1;
|
|
920
|
+
if (base || file.mayHave(hash ??= partitionHash(name, key))) {
|
|
921
|
+
const row = file.row(name, key);
|
|
922
|
+
if (row) return row.tombstone ? void 0 : rowValue(row);
|
|
923
|
+
}
|
|
924
|
+
if (!base && file.wasReset(name)) return void 0;
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* Starts the run after a start that failed (main thread), without discarding the runs that did
|
|
929
|
+
* not commit: their files are not read, and the next start discards them. Returns the run.
|
|
930
|
+
*/
|
|
931
|
+
ensureRun() {
|
|
932
|
+
if (this.open.length || !this.unstarted || !isMainThread) return this.run;
|
|
933
|
+
if (performance.now() < this.retryAt) return void 0;
|
|
934
|
+
let run = 0;
|
|
935
|
+
try {
|
|
936
|
+
transaction(this.meta, () => {
|
|
937
|
+
run = this.newRun();
|
|
938
|
+
});
|
|
939
|
+
} catch (e) {
|
|
940
|
+
this.retryAt = performance.now() + 3e4;
|
|
941
|
+
warnWriteFailure(e);
|
|
942
|
+
return;
|
|
943
|
+
}
|
|
944
|
+
this.unstarted = false;
|
|
945
|
+
this.open = [this.openRun(run)];
|
|
946
|
+
this.writable(false);
|
|
947
|
+
return run;
|
|
948
|
+
}
|
|
949
|
+
/**
|
|
950
|
+
* The run's file, created if needed (tells the other threads: they look for it again). The main
|
|
951
|
+
* thread creates it when the run starts, so the threads have it open (an empty one is removed
|
|
952
|
+
* by the commit or close).
|
|
953
|
+
*/
|
|
954
|
+
writable(warn = true) {
|
|
955
|
+
if (!this.open.length) this.ensureRun();
|
|
956
|
+
const current = this.open[0];
|
|
957
|
+
if (!current) {
|
|
958
|
+
if (warn) warnWriteFailure(/* @__PURE__ */ new Error("no run was started"));
|
|
959
|
+
return;
|
|
960
|
+
}
|
|
961
|
+
try {
|
|
962
|
+
current.writable(() => {
|
|
963
|
+
try {
|
|
964
|
+
this.stmts.touch.run(current.run);
|
|
965
|
+
} catch {}
|
|
966
|
+
});
|
|
967
|
+
} catch (e) {
|
|
968
|
+
if (warn) warnWriteFailure(e);
|
|
969
|
+
return;
|
|
970
|
+
}
|
|
971
|
+
return current;
|
|
972
|
+
}
|
|
973
|
+
writeBatch(rows) {
|
|
974
|
+
this.writable()?.write(rows);
|
|
975
|
+
}
|
|
976
|
+
reset(name) {
|
|
977
|
+
this.flush();
|
|
978
|
+
try {
|
|
979
|
+
this.writable()?.reset(name);
|
|
980
|
+
} catch (e) {
|
|
981
|
+
warnWriteFailure(e);
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
/** merges files in size tiers (main thread, after a commit) */
|
|
985
|
+
merge() {
|
|
986
|
+
this.flush();
|
|
987
|
+
for (let i = 0; i < 64; i++) {
|
|
988
|
+
this.load();
|
|
989
|
+
if (this.lost.size && !this.dropLost()) return;
|
|
990
|
+
const [newer, older] = this.files;
|
|
991
|
+
if (!newer || !older) return;
|
|
992
|
+
if (this.files.length <= MERGE.maxFiles && newer.bytes * MERGE.ratio < older.bytes) return;
|
|
993
|
+
if (!this.mergePair(newer, older, this.files.length === 2)) return;
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
/**
|
|
997
|
+
* Unlists the lost files and the older ones (left out of reads already), so merges go on with
|
|
998
|
+
* the files after them: the oldest of those becomes the base.
|
|
999
|
+
*/
|
|
1000
|
+
dropLost() {
|
|
1001
|
+
const dropped = [];
|
|
1002
|
+
try {
|
|
1003
|
+
transaction(this.meta, () => {
|
|
1004
|
+
let drop = false;
|
|
1005
|
+
for (const row of this.stmts.list.all()) {
|
|
1006
|
+
if (!row.committed) continue;
|
|
1007
|
+
if (this.lost.has(row.file)) drop = true;
|
|
1008
|
+
if (!drop) continue;
|
|
1009
|
+
this.stmts.deleteRow.run(row.run);
|
|
1010
|
+
dropped.push(row.file);
|
|
1011
|
+
}
|
|
1012
|
+
});
|
|
1013
|
+
} catch {
|
|
1014
|
+
return false;
|
|
1015
|
+
}
|
|
1016
|
+
this.load();
|
|
1017
|
+
for (const name of dropped) removeRunFile(path.join(this.dir, name));
|
|
1018
|
+
return true;
|
|
1019
|
+
}
|
|
1020
|
+
/**
|
|
1021
|
+
* Merges two adjacent files into a new one, listed instead of them in one transaction. `intoBase`:
|
|
1022
|
+
* `older` is the base (tombstones and resets have nothing older to hide). Returns whether it did,
|
|
1023
|
+
* or found the list changed or an input lost (the next round goes on from the new list).
|
|
1024
|
+
*/
|
|
1025
|
+
mergePair(newer, older, intoBase) {
|
|
1026
|
+
let seq = 0;
|
|
1027
|
+
try {
|
|
1028
|
+
transaction(this.meta, () => {
|
|
1029
|
+
seq = this.newId();
|
|
1030
|
+
});
|
|
1031
|
+
} catch {
|
|
1032
|
+
return false;
|
|
1033
|
+
}
|
|
1034
|
+
const name = `run-${newer.run}-${seq}.sqlite`;
|
|
1035
|
+
const out = path.join(this.dir, name);
|
|
1036
|
+
const tmp = path.join(this.dir, `${TMP_PREFIX}merge-${newer.run}-${seq}.sqlite`);
|
|
1037
|
+
try {
|
|
1038
|
+
const missing = [newer, older].find((f) => !fs.existsSync(f.file));
|
|
1039
|
+
if (missing) {
|
|
1040
|
+
if (!this.refresh()) this.markLost(path.basename(missing.file));
|
|
1041
|
+
return true;
|
|
1042
|
+
}
|
|
1043
|
+
const db = openSqlite(tmp);
|
|
1044
|
+
try {
|
|
1045
|
+
db.exec("PRAGMA journal_mode = OFF");
|
|
1046
|
+
db.exec("PRAGMA synchronous = OFF");
|
|
1047
|
+
db.exec(`PRAGMA cache_size = -${MERGE_CACHE_KIB}`);
|
|
1048
|
+
for (const sql of RUN_TABLES) db.exec(sql);
|
|
1049
|
+
db.prepare("ATTACH DATABASE ? AS newer").run(newer.file);
|
|
1050
|
+
db.prepare("ATTACH DATABASE ? AS older").run(older.file);
|
|
1051
|
+
db.exec("BEGIN");
|
|
1052
|
+
db.exec(`INSERT INTO cache SELECT name, key, value, tombstone FROM older.cache
|
|
1053
|
+
WHERE name NOT IN (SELECT name FROM newer.cache_resets)${intoBase ? " AND tombstone = 0" : ""}`);
|
|
1054
|
+
db.exec("INSERT OR REPLACE INTO cache SELECT name, key, value, tombstone FROM newer.cache");
|
|
1055
|
+
if (intoBase) db.exec("DELETE FROM cache WHERE tombstone = 1");
|
|
1056
|
+
else db.exec("INSERT OR IGNORE INTO cache_resets SELECT name FROM older.cache_resets UNION SELECT name FROM newer.cache_resets");
|
|
1057
|
+
db.exec("COMMIT");
|
|
1058
|
+
db.exec("DETACH DATABASE newer");
|
|
1059
|
+
db.exec("DETACH DATABASE older");
|
|
1060
|
+
} finally {
|
|
1061
|
+
db.close();
|
|
1062
|
+
}
|
|
1063
|
+
renameSync(tmp, out);
|
|
1064
|
+
} catch (e) {
|
|
1065
|
+
removeRunFile(tmp);
|
|
1066
|
+
if (compatEnv("GOATLY_VERBOSE")) console.warn("could not merge plugin cache files", e);
|
|
1067
|
+
const damaged = isDamaged(e) && [newer, older].find((f) => !f.intact());
|
|
1068
|
+
if (!damaged) return false;
|
|
1069
|
+
this.markLost(path.basename(damaged.file));
|
|
1070
|
+
return true;
|
|
1071
|
+
}
|
|
1072
|
+
let swapped = false;
|
|
1073
|
+
try {
|
|
1074
|
+
const bytes = fs.statSync(out).size;
|
|
1075
|
+
transaction(this.meta, () => {
|
|
1076
|
+
const { n } = this.stmts.inputs.get(newer.run, path.basename(newer.file), older.run, path.basename(older.file));
|
|
1077
|
+
if (Number(n) !== 2) return;
|
|
1078
|
+
this.stmts.deleteRow.run(newer.run);
|
|
1079
|
+
this.stmts.deleteRow.run(older.run);
|
|
1080
|
+
this.stmts.merged.run(newer.run, name, bytes);
|
|
1081
|
+
swapped = true;
|
|
1082
|
+
});
|
|
1083
|
+
} catch {}
|
|
1084
|
+
if (!swapped) {
|
|
1085
|
+
removeRunFile(out);
|
|
1086
|
+
return false;
|
|
1087
|
+
}
|
|
1088
|
+
newer.close();
|
|
1089
|
+
older.close();
|
|
1090
|
+
removeRunFile(newer.file);
|
|
1091
|
+
removeRunFile(older.file);
|
|
1092
|
+
return true;
|
|
1093
|
+
}
|
|
1094
|
+
close() {
|
|
1095
|
+
this.flush();
|
|
1096
|
+
keptRuns.set(this.dir, this.open.map((r) => r.run));
|
|
1097
|
+
for (const r of this.open) {
|
|
1098
|
+
const empty = isMainThread && r.created && r.isEmpty();
|
|
1099
|
+
r.close();
|
|
1100
|
+
if (empty) removeRunFile(r.file);
|
|
1101
|
+
}
|
|
1102
|
+
for (const file of this.byName.values()) file.close();
|
|
1103
|
+
this.byName.clear();
|
|
1104
|
+
this.files = [];
|
|
1105
|
+
this.meta.close();
|
|
1106
|
+
}
|
|
1107
|
+
/** (tests) a process killed: closes the connections, writes and removes nothing */
|
|
1108
|
+
abandon() {
|
|
1109
|
+
this.discardPending();
|
|
1110
|
+
for (const r of this.open) r.close();
|
|
1111
|
+
this.open = [];
|
|
1112
|
+
for (const file of this.byName.values()) file.close();
|
|
1113
|
+
this.byName.clear();
|
|
1114
|
+
this.files = [];
|
|
1115
|
+
this.meta.close();
|
|
1116
|
+
}
|
|
1117
|
+
};
|
|
1118
|
+
/** the runs of a closed `RunFilesBackend` (by directory), for the next one in the thread */
|
|
1119
|
+
const keptRuns = /* @__PURE__ */ new Map();
|
|
1120
|
+
/** merges the plugin cache's run files in size tiers (main thread, after a commit) */
|
|
1121
|
+
function mergeCacheRuns() {
|
|
1122
|
+
const backend = backends.get(cacheRoot);
|
|
1123
|
+
if (isMainThread && backend instanceof RunFilesBackend) backend.merge();
|
|
1124
|
+
}
|
|
1125
|
+
let warnedOpenFailure = false;
|
|
1126
|
+
/** the database could not be opened: warns once (a query worker fails to start instead) */
|
|
1127
|
+
function warnOpenFailure(error) {
|
|
1128
|
+
if (warnedOpenFailure || !isMainThread) return;
|
|
1129
|
+
warnedOpenFailure = true;
|
|
1130
|
+
reporter.warn(`The plugin cache could not be opened, cache entries are kept in memory for this run only: ${error}`);
|
|
1131
|
+
}
|
|
1132
|
+
/** the backend of each cache root (also a memory backend: opening is not retried on every call) */
|
|
1133
|
+
const backends = /* @__PURE__ */ new Map();
|
|
1134
|
+
function getBackend(rootDir) {
|
|
1135
|
+
let backend = backends.get(rootDir);
|
|
1136
|
+
if (!backend) {
|
|
1137
|
+
backend = openBackend(rootDir);
|
|
1138
|
+
backends.set(rootDir, backend);
|
|
1139
|
+
}
|
|
1140
|
+
return backend;
|
|
1141
|
+
}
|
|
1142
|
+
function openBackend(rootDir) {
|
|
1143
|
+
let db;
|
|
1144
|
+
try {
|
|
1145
|
+
fs.mkdirSync(rootDir, { recursive: true });
|
|
1146
|
+
const dir = path.join(rootDir, PLUGIN_CACHE_DIR);
|
|
1147
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
1148
|
+
db = openManifest(path.join(dir, "meta.sqlite"));
|
|
1149
|
+
return new RunFilesBackend(dir, db);
|
|
1150
|
+
} catch (e) {
|
|
1151
|
+
try {
|
|
1152
|
+
db?.close();
|
|
1153
|
+
} catch {}
|
|
1154
|
+
const error = String(e?.message ?? e);
|
|
1155
|
+
warnOpenFailure(error);
|
|
1156
|
+
return new MemoryBackend(error);
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
/**
|
|
1160
|
+
* Recently read values kept decoded in memory per cache. Everything is in the backend, so evicted
|
|
1161
|
+
* values are read back when needed again – with SQLite this keeps memory flat even when plugins
|
|
1162
|
+
* cache large values (e.g. remark ASTs) for every node.
|
|
1163
|
+
*/
|
|
1164
|
+
const MEMORY_ENTRIES = Number(process.env.GOATLY_CACHE_MEMORY_ENTRIES ?? 500);
|
|
1165
|
+
/**
|
|
1166
|
+
* and at most about this many bytes per cache, counted as the values' encoded size (decoded values
|
|
1167
|
+
* of many small objects, e.g. ASTs, take up to 8 times as much): 500 large values would take
|
|
1168
|
+
* gigabytes per thread
|
|
1169
|
+
*/
|
|
1170
|
+
const MEMORY_BYTES = (isMainThread ? 128 : 32) * 1024 * 1024;
|
|
1171
|
+
/**
|
|
1172
|
+
* How values are encoded: the node stores' codec (structured clone, decoded Buffers are copies),
|
|
1173
|
+
* without shared record structures (every value carries its own: nothing else to store). On Bun
|
|
1174
|
+
* decoded without compiling record readers for each value (see createSelfContainedNodeDecoder).
|
|
1175
|
+
*/
|
|
1176
|
+
const codec = createSelfContainedNodeCodec();
|
|
1177
|
+
const decoder = createSelfContainedNodeDecoder(codec);
|
|
1178
|
+
/**
|
|
1179
|
+
* Incremented when the decoded values of all caches of the thread may be outdated (another
|
|
1180
|
+
* connection committed, the database was closed): a cache whose LRU was filled in an older
|
|
1181
|
+
* generation drops it at its next get.
|
|
1182
|
+
*/
|
|
1183
|
+
let lruGeneration = 0;
|
|
1184
|
+
var GatsbyCache = class {
|
|
1185
|
+
name;
|
|
1186
|
+
directory;
|
|
1187
|
+
/**
|
|
1188
|
+
* LRU of recently read values, decoded (avoids decoding them again; shared by the readers in
|
|
1189
|
+
* this thread, like the node stores' decoded nodes)
|
|
1190
|
+
*/
|
|
1191
|
+
memory = /* @__PURE__ */ new Map();
|
|
1192
|
+
/** encoded bytes of the values in `memory` */
|
|
1193
|
+
memoryBytes = 0;
|
|
1194
|
+
/** the `lruGeneration` the LRU's values belong to */
|
|
1195
|
+
generation = lruGeneration;
|
|
1196
|
+
rootDir;
|
|
1197
|
+
constructor(name, rootDir) {
|
|
1198
|
+
this.name = name;
|
|
1199
|
+
this.rootDir = rootDir;
|
|
1200
|
+
this.directory = path.join(rootDir, "caches", name.replace(/[/\\]/g, "-"));
|
|
1201
|
+
}
|
|
1202
|
+
init() {
|
|
1203
|
+
fs.mkdirSync(this.directory, { recursive: true });
|
|
1204
|
+
return this;
|
|
1205
|
+
}
|
|
1206
|
+
get backend() {
|
|
1207
|
+
return getBackend(this.rootDir);
|
|
1208
|
+
}
|
|
1209
|
+
/** `bytes`: the value's encoded size */
|
|
1210
|
+
remember(key, value, bytes) {
|
|
1211
|
+
this.forget(key);
|
|
1212
|
+
if (bytes > MEMORY_BYTES / 8) return;
|
|
1213
|
+
this.memory.set(key, {
|
|
1214
|
+
value,
|
|
1215
|
+
bytes
|
|
1216
|
+
});
|
|
1217
|
+
this.memoryBytes += bytes;
|
|
1218
|
+
while (this.memory.size > MEMORY_ENTRIES || this.memoryBytes > MEMORY_BYTES) this.forget(this.memory.keys().next().value);
|
|
1219
|
+
}
|
|
1220
|
+
forget(key) {
|
|
1221
|
+
const entry = this.memory.get(key);
|
|
1222
|
+
if (!entry) return;
|
|
1223
|
+
this.memory.delete(key);
|
|
1224
|
+
this.memoryBytes -= entry.bytes;
|
|
1225
|
+
}
|
|
1226
|
+
forgetAll() {
|
|
1227
|
+
this.memory.clear();
|
|
1228
|
+
this.memoryBytes = 0;
|
|
1229
|
+
}
|
|
1230
|
+
/**
|
|
1231
|
+
* The key as stored: a number becomes its string form, so `1` and `"1"` are the same entry in the
|
|
1232
|
+
* LRU, the write buffer and SQLite (bound as a number, SQLite would store it in a
|
|
1233
|
+
* runtime-dependent text form: "1.0" with node:sqlite). Other types are rejected: SQLite cannot
|
|
1234
|
+
* store most of them, and the plugin that passed one gets the error instead of a write that is
|
|
1235
|
+
* dropped later.
|
|
1236
|
+
*/
|
|
1237
|
+
toKey(key) {
|
|
1238
|
+
if (typeof key === "string") return key;
|
|
1239
|
+
if (typeof key === "number") return String(key);
|
|
1240
|
+
let type = typeof key;
|
|
1241
|
+
if (key === null) type = "null";
|
|
1242
|
+
else if (Array.isArray(key)) type = "array";
|
|
1243
|
+
else if (ArrayBuffer.isView(key) || key instanceof ArrayBuffer) {
|
|
1244
|
+
const name = key.constructor?.name;
|
|
1245
|
+
if (typeof name === "string" && name) type = name;
|
|
1246
|
+
}
|
|
1247
|
+
throw new TypeError(`cache "${this.name}": keys must be strings or numbers, got ${type}`);
|
|
1248
|
+
}
|
|
1249
|
+
/**
|
|
1250
|
+
* Drops the LRU when its values may be outdated. With `backend`: when another connection (a query
|
|
1251
|
+
* worker, another process) committed since a cache of the same database last asked. Asked before
|
|
1252
|
+
* every LRU hit (`PRAGMA data_version`, about 1 µs, a few µs when several threads contend): a
|
|
1253
|
+
* check once per macrotask, with a flag reset by setImmediate, would miss a worker's commit
|
|
1254
|
+
* announced by another callback of the same event loop iteration. Writes another thread still
|
|
1255
|
+
* buffers can't be seen until they are committed.
|
|
1256
|
+
*/
|
|
1257
|
+
dropOutdated(backend, key) {
|
|
1258
|
+
if (backend?.othersCommitted(this.name, key)) lruGeneration++;
|
|
1259
|
+
if (this.generation !== lruGeneration) {
|
|
1260
|
+
this.forgetAll();
|
|
1261
|
+
this.generation = lruGeneration;
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
async get(rawKey) {
|
|
1265
|
+
const key = this.toKey(rawKey);
|
|
1266
|
+
const backend = this.backend;
|
|
1267
|
+
if (this.memory.has(key)) this.dropOutdated(backend, key);
|
|
1268
|
+
const hit = this.memory.get(key);
|
|
1269
|
+
if (hit) {
|
|
1270
|
+
this.remember(key, hit.value, hit.bytes);
|
|
1271
|
+
return hit.value;
|
|
1272
|
+
}
|
|
1273
|
+
const stored = backend.get(this.name, key);
|
|
1274
|
+
if (!stored) return void 0;
|
|
1275
|
+
let value;
|
|
1276
|
+
let bytes;
|
|
1277
|
+
try {
|
|
1278
|
+
bytes = decompressValue(stored);
|
|
1279
|
+
value = decoder.unpack(bytes);
|
|
1280
|
+
} catch {
|
|
1281
|
+
return;
|
|
1282
|
+
}
|
|
1283
|
+
if (value !== void 0) {
|
|
1284
|
+
this.dropOutdated();
|
|
1285
|
+
this.remember(key, value, bytes.length);
|
|
1286
|
+
}
|
|
1287
|
+
return value;
|
|
1288
|
+
}
|
|
1289
|
+
async set(rawKey, value) {
|
|
1290
|
+
const key = this.toKey(rawKey);
|
|
1291
|
+
let bytes;
|
|
1292
|
+
try {
|
|
1293
|
+
bytes = encodeReused(codec, isSerializable(value) ? value : sanitize(value));
|
|
1294
|
+
} catch (e) {
|
|
1295
|
+
throw new Error(`cache "${this.name}": could not encode the value of key "${key}": ${e?.message ?? e}`, { cause: e });
|
|
1296
|
+
}
|
|
1297
|
+
this.backend.set(this.name, key, bytes);
|
|
1298
|
+
this.forget(key);
|
|
1299
|
+
return value;
|
|
1300
|
+
}
|
|
1301
|
+
async del(rawKey) {
|
|
1302
|
+
const key = this.toKey(rawKey);
|
|
1303
|
+
this.forget(key);
|
|
1304
|
+
this.backend.del(this.name, key);
|
|
1305
|
+
}
|
|
1306
|
+
async reset() {
|
|
1307
|
+
this.forgetAll();
|
|
1308
|
+
this.backend.reset(this.name);
|
|
1309
|
+
}
|
|
1310
|
+
/** drops the in-memory values (the backend keeps them) */
|
|
1311
|
+
release() {
|
|
1312
|
+
this.forgetAll();
|
|
1313
|
+
}
|
|
1314
|
+
};
|
|
1315
|
+
const caches = /* @__PURE__ */ new Map();
|
|
1316
|
+
let cacheRoot = path.join(process.cwd(), ".cache");
|
|
1317
|
+
function setCacheRoot(dir) {
|
|
1318
|
+
cacheRoot = dir;
|
|
1319
|
+
caches.clear();
|
|
1320
|
+
}
|
|
1321
|
+
function getCache(name) {
|
|
1322
|
+
let cache = caches.get(name);
|
|
1323
|
+
if (!cache) {
|
|
1324
|
+
cache = new GatsbyCache(name, cacheRoot).init();
|
|
1325
|
+
caches.set(name, cache);
|
|
1326
|
+
}
|
|
1327
|
+
return cache;
|
|
1328
|
+
}
|
|
1329
|
+
/**
|
|
1330
|
+
* Opens the backend of the current cache root. `shared`: its caches are in the database the other
|
|
1331
|
+
* threads use – not when it could not be opened (`error`), then they are kept in memory.
|
|
1332
|
+
*/
|
|
1333
|
+
function openPluginCache() {
|
|
1334
|
+
const backend = getBackend(cacheRoot);
|
|
1335
|
+
return backend instanceof MemoryBackend ? {
|
|
1336
|
+
shared: false,
|
|
1337
|
+
error: backend.error
|
|
1338
|
+
} : { shared: true };
|
|
1339
|
+
}
|
|
1340
|
+
/** called by `persistCaches` before it writes, e.g. to set a value kept in memory until then */
|
|
1341
|
+
const persistHooks = /* @__PURE__ */ new Set();
|
|
1342
|
+
/** `fn` runs at the start of every `persistCaches` (of this thread) */
|
|
1343
|
+
function onPersistCaches(fn) {
|
|
1344
|
+
persistHooks.add(fn);
|
|
1345
|
+
}
|
|
1346
|
+
function persistCaches() {
|
|
1347
|
+
for (const fn of persistHooks) fn();
|
|
1348
|
+
if (caches.size) getBackend(cacheRoot);
|
|
1349
|
+
for (const backend of backends.values()) backend.flush();
|
|
1350
|
+
}
|
|
1351
|
+
let warnedRunFailure = false;
|
|
1352
|
+
/** the run could not be started: warns once per thread */
|
|
1353
|
+
function warnRunFailure(e) {
|
|
1354
|
+
if (warnedRunFailure) return;
|
|
1355
|
+
warnedRunFailure = true;
|
|
1356
|
+
reporter.warn(`The plugin cache could not start its run: ${e?.message ?? e}. It is started at the first write.`);
|
|
1357
|
+
}
|
|
1358
|
+
/**
|
|
1359
|
+
* Starts the run of the plugin caches in the current cache root (main thread, before plugins use
|
|
1360
|
+
* them): discards what was written and never committed, then collects this run's writes until
|
|
1361
|
+
* `commitCacheRun`. Returns the number of entries discarded (the caller reports them).
|
|
1362
|
+
*/
|
|
1363
|
+
function startCacheRun() {
|
|
1364
|
+
const backend = getBackend(cacheRoot);
|
|
1365
|
+
let reverted;
|
|
1366
|
+
try {
|
|
1367
|
+
reverted = backend.startRun();
|
|
1368
|
+
} catch (e) {
|
|
1369
|
+
backend.run = void 0;
|
|
1370
|
+
warnRunFailure(e);
|
|
1371
|
+
return 0;
|
|
1372
|
+
}
|
|
1373
|
+
if (reverted) lruGeneration++;
|
|
1374
|
+
return reverted;
|
|
1375
|
+
}
|
|
1376
|
+
/** query workers: logs their writes under the main thread's run (`getCacheRun()` there) */
|
|
1377
|
+
function setCacheRun(run) {
|
|
1378
|
+
if (run !== void 0) getBackend(cacheRoot).run = run;
|
|
1379
|
+
}
|
|
1380
|
+
/** the run the writes to the current cache root are logged under */
|
|
1381
|
+
function getCacheRun() {
|
|
1382
|
+
const backend = backends.get(cacheRoot);
|
|
1383
|
+
return backend instanceof RunFilesBackend ? backend.ensureRun() : backend?.run;
|
|
1384
|
+
}
|
|
1385
|
+
/**
|
|
1386
|
+
* Persists the run's nodes with `persist` and then makes the plugin cache writes made before the
|
|
1387
|
+
* call permanent (main thread). A datastore takes its snapshot when persist() is called, so what is
|
|
1388
|
+
* written while it runs (e.g. by a source plugin's refetch) is not in these nodes: it is logged
|
|
1389
|
+
* under a new run id, like all later writes, until the next commit (or reverted by the next start).
|
|
1390
|
+
* Nothing is committed when `persist` throws.
|
|
1391
|
+
*/
|
|
1392
|
+
async function commitCacheRun(persist) {
|
|
1393
|
+
persistCaches();
|
|
1394
|
+
const run = backends.get(cacheRoot)?.nextRun();
|
|
1395
|
+
await persist?.();
|
|
1396
|
+
persistCaches();
|
|
1397
|
+
if (run !== void 0) backends.get(cacheRoot)?.commitRun(run);
|
|
1398
|
+
}
|
|
1399
|
+
/**
|
|
1400
|
+
* Flushes the caches and drops their in-memory values – the query workers' heap guard calls it
|
|
1401
|
+
* under memory pressure (a memory backend keeps its entries)
|
|
1402
|
+
*/
|
|
1403
|
+
function releaseCaches() {
|
|
1404
|
+
persistCaches();
|
|
1405
|
+
for (const cache of caches.values()) cache.release();
|
|
1406
|
+
}
|
|
1407
|
+
/**
|
|
1408
|
+
* The end of a build, of develop or of a query worker: writes the buffered entries and closes the
|
|
1409
|
+
* files, so they are complete and no connection holds them when `.cache` is copied into an image
|
|
1410
|
+
* layer (reopened if something reads later).
|
|
1411
|
+
*/
|
|
1412
|
+
function finishCaches() {
|
|
1413
|
+
closeCaches();
|
|
1414
|
+
}
|
|
1415
|
+
function closeCaches() {
|
|
1416
|
+
for (const backend of backends.values()) backend.close();
|
|
1417
|
+
backends.clear();
|
|
1418
|
+
lruGeneration++;
|
|
1419
|
+
}
|
|
1420
|
+
/**
|
|
1421
|
+
* @internal (tests) the process is killed: its connections are closed (as the OS closes a killed
|
|
1422
|
+
* process's files), without writing or removing anything
|
|
1423
|
+
*/
|
|
1424
|
+
function abandonCaches() {
|
|
1425
|
+
for (const backend of backends.values()) if (backend instanceof RunFilesBackend) backend.abandon();
|
|
1426
|
+
else backend.close();
|
|
1427
|
+
backends.clear();
|
|
1428
|
+
lruGeneration++;
|
|
1429
|
+
}
|
|
1430
|
+
export { GatsbyCache, abandonCaches, closeCaches, commitCacheRun, finishCaches, getCache, getCacheRun, mergeCacheRuns, onPersistCaches, openBuiltinSqlite, openPluginCache, persistCaches, releaseCaches, setCacheRoot, setCacheRun, setMergePolicy, setRelistInterval, startCacheRun };
|