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,1329 @@
|
|
|
1
|
+
import { PendingBytes, createStoredNodeCodec, encodeReused, sharedStructures } from "../codec.js";
|
|
2
|
+
import { NodeCache } from "./cache.js";
|
|
3
|
+
import { rename, retrySync } from "../../utils/fs-retry.js";
|
|
4
|
+
import { dataStart, dataStartAt, digestStart, encodedSize, readHeader, recordSize, recordSizeAt, writeRecord } from "./record.js";
|
|
5
|
+
import { isMainThread } from "node:worker_threads";
|
|
6
|
+
import { randomBytes } from "node:crypto";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import fs from "node:fs";
|
|
9
|
+
import { Packr } from "msgpackr";
|
|
10
|
+
// src/node/datastore/logfile/index.ts
|
|
11
|
+
/** format version of the index snapshot and the index log files (another one is not restored) */
|
|
12
|
+
const FORMAT_VERSION = 1;
|
|
13
|
+
const MAGIC = "GOATLYSEG";
|
|
14
|
+
const LOG_MAGIC = "GOATLYSEGD";
|
|
15
|
+
/** persist() rewrites the index snapshot when the index log holds this many entries … */
|
|
16
|
+
const LOG_MIN_ENTRIES = 1e4;
|
|
17
|
+
/** … and this share of the nodes (otherwise it appends the changes to the log) */
|
|
18
|
+
const LOG_SHARE = .25;
|
|
19
|
+
const FLUSH_EVERY = 1e3;
|
|
20
|
+
/** an address packs the record's file offset and the node's type index */
|
|
21
|
+
const TYPE_SLOTS = 65536;
|
|
22
|
+
/** address of a node that has not been written yet */
|
|
23
|
+
const PENDING = -1;
|
|
24
|
+
/** compact a segment when superseded records (or an unpersisted tail) take this share … */
|
|
25
|
+
const SEGMENT_GARBAGE_SHARE = .5;
|
|
26
|
+
/**
|
|
27
|
+
* … and merge the smallest segments when more than this many are below the size cap (one per
|
|
28
|
+
* incremental run; full segments are not counted: merging them would not reduce their number)
|
|
29
|
+
*/
|
|
30
|
+
const MAX_SEGMENTS = 64;
|
|
31
|
+
/**
|
|
32
|
+
* a segment is closed for writes once it holds this many bytes, and a persist() copies
|
|
33
|
+
* at most twice this many live bytes when it compacts: the files a build creates are bounded by
|
|
34
|
+
* what it writes, not by the size of the store
|
|
35
|
+
*/
|
|
36
|
+
const SEGMENT_MAX = 67108864;
|
|
37
|
+
/**
|
|
38
|
+
* virtual offsets only grow (a new segment starts after the others); past this the
|
|
39
|
+
* bases are packed again, which changes no file (offset × TYPE_SLOTS has to stay below 2^53)
|
|
40
|
+
*/
|
|
41
|
+
const REBASE_AT = 2 ** 36;
|
|
42
|
+
const SEGMENT_LOG = /^index-log-(\d+)-(.+)$/;
|
|
43
|
+
/** first read of a record (most nodes fit: one read) */
|
|
44
|
+
const READ_AHEAD = 8192;
|
|
45
|
+
/** scans read the files in windows of this size (records of a scan are mostly in file order) */
|
|
46
|
+
const SCAN_WINDOW = 262144;
|
|
47
|
+
/**
|
|
48
|
+
* A read of a record (a cache miss) that starts at most READ_GAP bytes after the end of a recent
|
|
49
|
+
* one continues a run: it is read ahead in a window of this size, and the run's next records come
|
|
50
|
+
* from the window. Query workers run pages in createPage order, so their nodes are often runs of
|
|
51
|
+
* records written one after another, and so are linked nodes (one read per window instead of one
|
|
52
|
+
* per record: the syscall costs about as much as copying 8 KB).
|
|
53
|
+
*/
|
|
54
|
+
const READ_WINDOW = 32768;
|
|
55
|
+
/** … at most this many windows (runs that interleave, e.g. the pages' posts and their related posts) */
|
|
56
|
+
const READ_WINDOWS = 4;
|
|
57
|
+
const READ_GAP = 8192;
|
|
58
|
+
/** the ends of this many recent reads outside of windows are kept (where a run may start) */
|
|
59
|
+
const READ_RUNS = 8;
|
|
60
|
+
const parentOf = (node) => typeof node.parent === "string" && node.parent || null;
|
|
61
|
+
const ownerOf = (node) => typeof node.internal.owner === "string" ? node.internal.owner : "";
|
|
62
|
+
const digestOf = (node) => typeof node.internal.contentDigest === "string" && node.internal.contentDigest ? node.internal.contentDigest : null;
|
|
63
|
+
const indexCodec = () => new Packr({
|
|
64
|
+
useRecords: false,
|
|
65
|
+
moreTypes: true
|
|
66
|
+
});
|
|
67
|
+
const isObject = (v) => typeof v === "object" && v !== null;
|
|
68
|
+
const isSize = (v) => Number.isSafeInteger(v) && v >= 0;
|
|
69
|
+
const hasMeta = (v) => typeof v.maxCounter === "number" && Array.isArray(v.types) && Array.isArray(v.structures);
|
|
70
|
+
const hasSegments = (v) => Array.isArray(v.segments) && v.segments.every((s) => isObject(s) && typeof s.id === "string" && isSize(s.base) && isSize(s.length) && typeof s.live === "number");
|
|
71
|
+
const hasNodes = (v) => typeof v.snapshotId === "string" && Array.isArray(v.ids) && v.addresses instanceof Float64Array && v.addresses.length === v.ids.length && Array.isArray(v.parents);
|
|
72
|
+
const hasEntries = (v) => Array.isArray(v.entries) && v.entries.every((e) => Array.isArray(e) && typeof e[1] === "string" && typeof e[2] === "number");
|
|
73
|
+
const isIndexMain = (v) => isObject(v) && hasMeta(v) && hasSegments(v) && hasNodes(v);
|
|
74
|
+
const isLogFrame = (v) => isObject(v) && hasMeta(v) && hasSegments(v) && hasEntries(v);
|
|
75
|
+
const u32 = (n) => {
|
|
76
|
+
const b = Buffer.alloc(4);
|
|
77
|
+
b.writeUInt32LE(n);
|
|
78
|
+
return b;
|
|
79
|
+
};
|
|
80
|
+
/** a file header: the magic, the format version, then u32 fields */
|
|
81
|
+
function fileHead(magic, version, ...fields) {
|
|
82
|
+
const head = Buffer.alloc(magic.length + 4 * (1 + fields.length));
|
|
83
|
+
head.write(magic, 0, "latin1");
|
|
84
|
+
for (const [i, n] of [version, ...fields].entries()) head.writeUInt32LE(n, magic.length + 4 * i);
|
|
85
|
+
return head;
|
|
86
|
+
}
|
|
87
|
+
/** where the fields after the magic and the version start (-1: another magic or version) */
|
|
88
|
+
const headEnd = (raw, magic, version) => raw.length >= magic.length + 4 && raw.toString("latin1", 0, magic.length) === magic && raw.readUInt32LE(magic.length) === version ? magic.length + 4 : -1;
|
|
89
|
+
/**
|
|
90
|
+
* written to a temporary file and renamed: the file is complete or missing (the rename is retried
|
|
91
|
+
* on Windows while a reader holds the old file open)
|
|
92
|
+
*/
|
|
93
|
+
async function writeAtomic(file, data) {
|
|
94
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
95
|
+
await fs.promises.writeFile(tmp, data);
|
|
96
|
+
await rename(tmp, file);
|
|
97
|
+
}
|
|
98
|
+
function writeAt(fd, buffer, length, position) {
|
|
99
|
+
for (let done = 0; done < length;) done += fs.writeSync(fd, buffer, done, length - done, position + done);
|
|
100
|
+
}
|
|
101
|
+
const offsetOf = (address) => Math.floor(address / TYPE_SLOTS);
|
|
102
|
+
const newId = () => `${Date.now().toString(36)}-${randomBytes(4).toString("hex")}`;
|
|
103
|
+
const segmentRef = ({ id, base, length, live }) => ({
|
|
104
|
+
id,
|
|
105
|
+
base,
|
|
106
|
+
length,
|
|
107
|
+
live
|
|
108
|
+
});
|
|
109
|
+
var LogFileDataStore = class {
|
|
110
|
+
name = "logfile";
|
|
111
|
+
/** query workers read the segment files instead of loading a copy of all nodes */
|
|
112
|
+
sharedAcrossThreads = true;
|
|
113
|
+
/** nodes are decoded on demand: object identity is not stable, mutated nodes have to be set again */
|
|
114
|
+
lazy = true;
|
|
115
|
+
dir;
|
|
116
|
+
readonly;
|
|
117
|
+
/** the writer and main-thread readers keep the index digests; query workers read the record's */
|
|
118
|
+
withDigests;
|
|
119
|
+
cache;
|
|
120
|
+
/** the encoded size of the record decode() read last (the cache's size of its node) */
|
|
121
|
+
decodedBytes = 0;
|
|
122
|
+
/** id → address (record offset × TYPE_SLOTS + type index; PENDING: not written), insertion order */
|
|
123
|
+
addresses = /* @__PURE__ */ new Map();
|
|
124
|
+
/** type → ids in insertion order */
|
|
125
|
+
byType = /* @__PURE__ */ new Map();
|
|
126
|
+
types = [];
|
|
127
|
+
typeIndexes = /* @__PURE__ */ new Map();
|
|
128
|
+
/** parent ids (schema building asks for every node's parent, stale nodes are found by them) */
|
|
129
|
+
parents = /* @__PURE__ */ new Map();
|
|
130
|
+
/** writer only (warm builds compare digests) */
|
|
131
|
+
digests = /* @__PURE__ */ new Map();
|
|
132
|
+
/** writer only: `internal.owner` by id, "" for none (stale node checks) */
|
|
133
|
+
owners = /* @__PURE__ */ new Map();
|
|
134
|
+
/** one string per owner (a few plugins own all nodes; strings of decoded nodes may be slices) */
|
|
135
|
+
ownerNames = /* @__PURE__ */ new Map();
|
|
136
|
+
/**
|
|
137
|
+
* The index was written without owners (by an earlier version): owners are learned from decoded
|
|
138
|
+
* nodes, and the next persist() writes a snapshot with them
|
|
139
|
+
*/
|
|
140
|
+
ownersIncomplete = false;
|
|
141
|
+
/** node writes not encoded yet (the files have the previous version, if any) */
|
|
142
|
+
pending = /* @__PURE__ */ new Map();
|
|
143
|
+
/** the encoded nodes of the pending writes (cleared with them) */
|
|
144
|
+
pendingBytes = new PendingBytes();
|
|
145
|
+
structures = [];
|
|
146
|
+
codec;
|
|
147
|
+
maxCounter = 0;
|
|
148
|
+
/** the end of the bytes written to the current segment (a virtual offset) */
|
|
149
|
+
fileEnd = 0;
|
|
150
|
+
/** the segments by base, the one this run appends to, the last one a read used */
|
|
151
|
+
segments = [];
|
|
152
|
+
current;
|
|
153
|
+
lastSegment;
|
|
154
|
+
/** index log files written for the snapshot */
|
|
155
|
+
logSeq = 0;
|
|
156
|
+
/** (fields: tests lower them) */
|
|
157
|
+
rebaseAt = REBASE_AT;
|
|
158
|
+
segmentMax = SEGMENT_MAX;
|
|
159
|
+
/** changed since the last persist() / load() */
|
|
160
|
+
dirty = true;
|
|
161
|
+
/** the index snapshot the index log continues, and the entries the log holds */
|
|
162
|
+
snapshotId;
|
|
163
|
+
logEntries = 0;
|
|
164
|
+
/** writer: ids set or deleted since the last persist(); ids (re)appended, in insertion order */
|
|
165
|
+
changed = /* @__PURE__ */ new Set();
|
|
166
|
+
appended = /* @__PURE__ */ new Set();
|
|
167
|
+
/** counts changes of the store's state (see inspect()) */
|
|
168
|
+
version = 0;
|
|
169
|
+
readBuffer = Buffer.allocUnsafe(65536);
|
|
170
|
+
/** bytes of a segment around the last record a scan read: [windowStart, windowEnd) */
|
|
171
|
+
window = Buffer.allocUnsafe(SCAN_WINDOW);
|
|
172
|
+
windowStart = 0;
|
|
173
|
+
windowEnd = 0;
|
|
174
|
+
/** read-ahead windows of record reads (created for the first runs: random reads need none) */
|
|
175
|
+
readWindows = [];
|
|
176
|
+
/** the ends of recent record reads outside of the windows (a ring), and the reads so far */
|
|
177
|
+
readEnds = new Float64Array(READ_RUNS).fill(-1e400);
|
|
178
|
+
readEndAt = 0;
|
|
179
|
+
reads = 0;
|
|
180
|
+
writeBuffer = Buffer.allocUnsafe(1048576);
|
|
181
|
+
constructor(options = {}) {
|
|
182
|
+
this.dir = path.resolve(options.dir ?? path.join(options.cacheDir ?? ".cache", "data", "logfile"));
|
|
183
|
+
this.readonly = options.readonly === true || !isMainThread;
|
|
184
|
+
this.withDigests = isMainThread;
|
|
185
|
+
this.cache = new NodeCache(Math.max(1, options.cacheSize ?? (isMainThread ? 1e4 : 2e3)), options.cacheBytes ?? (isMainThread ? 256 : 64) * 1024 * 1024);
|
|
186
|
+
this.codec = this.createCodec([]);
|
|
187
|
+
}
|
|
188
|
+
createCodec(structures) {
|
|
189
|
+
this.structures = sharedStructures(structures);
|
|
190
|
+
return createStoredNodeCodec({
|
|
191
|
+
load: () => [...this.structures],
|
|
192
|
+
save: (s) => {
|
|
193
|
+
this.structures = sharedStructures(s);
|
|
194
|
+
this.version++;
|
|
195
|
+
return !this.readonly;
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
segmentFile(id) {
|
|
200
|
+
return path.join(this.dir, `segment-${id}`);
|
|
201
|
+
}
|
|
202
|
+
/** the segment that holds the virtual offset */
|
|
203
|
+
segmentAt(offset) {
|
|
204
|
+
const last = this.lastSegment;
|
|
205
|
+
if (last && offset >= last.base && offset < last.base + last.length) return last;
|
|
206
|
+
const segments = this.segments;
|
|
207
|
+
let lo = 0;
|
|
208
|
+
let hi = segments.length - 1;
|
|
209
|
+
while (lo < hi) {
|
|
210
|
+
const mid = lo + hi + 1 >> 1;
|
|
211
|
+
if (segments[mid].base <= offset) lo = mid;
|
|
212
|
+
else hi = mid - 1;
|
|
213
|
+
}
|
|
214
|
+
const segment = segments[lo];
|
|
215
|
+
if (!segment || offset < segment.base || offset >= segment.base + segment.length) throw new Error(`The logfile datastore has no segment for offset ${offset} in ${this.dir}`);
|
|
216
|
+
return this.lastSegment = segment;
|
|
217
|
+
}
|
|
218
|
+
/** end of the bytes readable at `offset` (records never cross a segment) */
|
|
219
|
+
endAt(offset) {
|
|
220
|
+
const segment = this.segmentAt(offset);
|
|
221
|
+
return segment.base + segment.length;
|
|
222
|
+
}
|
|
223
|
+
/** reads into `buffer` (from `into` on) from the segment that holds the virtual offset `position` */
|
|
224
|
+
readInto(buffer, position, length, into = 0) {
|
|
225
|
+
const segment = this.segmentAt(position);
|
|
226
|
+
const at = position - segment.base;
|
|
227
|
+
for (let done = 0; done < length;) {
|
|
228
|
+
const n = fs.readSync(segment.fd, buffer, into + done, length - done, at + done);
|
|
229
|
+
if (n <= 0) throw new Error(`The logfile datastore could not read ${this.segmentFile(segment.id)}`);
|
|
230
|
+
done += n;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
/** the file that holds `position` */
|
|
234
|
+
fileAt(position) {
|
|
235
|
+
return this.segmentFile(this.segmentAt(position).id);
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* throws unless `length` bytes at `position` are persisted bytes of one file (a corrupt index or
|
|
239
|
+
* record)
|
|
240
|
+
*/
|
|
241
|
+
inBounds(position, length) {
|
|
242
|
+
if (!(position >= 0 && length > 0 && position + length <= this.endAt(position))) throw new Error(`The logfile datastore could not read ${this.fileAt(position)}: a record at ${position} is past the persisted length`);
|
|
243
|
+
}
|
|
244
|
+
/** reads `length` bytes at `position` into the read buffer (from its start) */
|
|
245
|
+
readAt(position, length) {
|
|
246
|
+
this.inBounds(position, length);
|
|
247
|
+
if (length > this.readBuffer.length) this.readBuffer = Buffer.allocUnsafe(Math.max(length, this.readBuffer.length * 2));
|
|
248
|
+
this.readInto(this.readBuffer, position, length);
|
|
249
|
+
return this.readBuffer;
|
|
250
|
+
}
|
|
251
|
+
/** reads a whole record into the read buffer */
|
|
252
|
+
readRecord(address) {
|
|
253
|
+
const offset = offsetOf(address);
|
|
254
|
+
const first = Math.min(READ_AHEAD, this.endAt(offset) - offset);
|
|
255
|
+
const header = readHeader(this.readAt(offset, Math.max(first, 20)));
|
|
256
|
+
const size = recordSize(header);
|
|
257
|
+
if (size > first) this.readAt(offset, size);
|
|
258
|
+
return header;
|
|
259
|
+
}
|
|
260
|
+
/** reads a record's header and strings (not its data) */
|
|
261
|
+
readHead(address) {
|
|
262
|
+
const offset = offsetOf(address);
|
|
263
|
+
const header = readHeader(this.readAt(offset, 20));
|
|
264
|
+
this.readAt(offset, dataStart(header));
|
|
265
|
+
return header;
|
|
266
|
+
}
|
|
267
|
+
decode(address) {
|
|
268
|
+
const offset = offsetOf(address);
|
|
269
|
+
const window = this.readWindowFor(offset);
|
|
270
|
+
if (window) return this.decodeAt(window.buffer, offset - window.start, window.end - offset);
|
|
271
|
+
const first = Math.max(Math.min(READ_AHEAD, this.endAt(offset) - offset), 20);
|
|
272
|
+
const buffer = this.readAt(offset, first);
|
|
273
|
+
const size = recordSizeAt(buffer, 0);
|
|
274
|
+
if (size > first) this.readRest(offset, first, size);
|
|
275
|
+
if (size <= READ_WINDOW / 2) this.readEnds[this.readEndAt++ % READ_RUNS] = offset + size;
|
|
276
|
+
return this.decodeRead();
|
|
277
|
+
}
|
|
278
|
+
/** decodes the record at the start of the read buffer */
|
|
279
|
+
decodeRead() {
|
|
280
|
+
const buffer = this.readBuffer;
|
|
281
|
+
const start = dataStartAt(buffer, 0);
|
|
282
|
+
this.decodedBytes = buffer.readUInt32LE(0);
|
|
283
|
+
return this.codec.unpack(buffer, {
|
|
284
|
+
start,
|
|
285
|
+
end: start + this.decodedBytes
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
/** reads the rest of a record whose first `first` bytes are in the read buffer */
|
|
289
|
+
readRest(offset, first, size) {
|
|
290
|
+
this.inBounds(offset, size);
|
|
291
|
+
if (size > this.readBuffer.length) {
|
|
292
|
+
const grown = Buffer.allocUnsafe(Math.max(size, this.readBuffer.length * 2));
|
|
293
|
+
this.readBuffer.copy(grown, 0, 0, first);
|
|
294
|
+
this.readBuffer = grown;
|
|
295
|
+
}
|
|
296
|
+
this.readInto(this.readBuffer, offset + first, size - first, first);
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* The read-ahead window that holds the whole record at `offset`: one that has it, or one filled
|
|
300
|
+
* from `offset` when the read continues a run. Undefined: a read of its own (not in a run, or
|
|
301
|
+
* a record larger than a window, or one past the persisted length: the read throws).
|
|
302
|
+
*/
|
|
303
|
+
readWindowFor(offset) {
|
|
304
|
+
const used = ++this.reads;
|
|
305
|
+
let run;
|
|
306
|
+
for (const w of this.readWindows) if (offset >= w.start && offset + 20 <= w.end) {
|
|
307
|
+
const end = offset + recordSizeAt(w.buffer, offset - w.start);
|
|
308
|
+
if (end <= w.end) {
|
|
309
|
+
w.next = end;
|
|
310
|
+
w.used = used;
|
|
311
|
+
return w;
|
|
312
|
+
}
|
|
313
|
+
run = w;
|
|
314
|
+
} else if (!run && offset >= w.next && offset - w.next <= READ_GAP) run = w;
|
|
315
|
+
if (!run) {
|
|
316
|
+
let starts = false;
|
|
317
|
+
for (const end of this.readEnds) starts ||= offset >= end && offset - end <= READ_GAP;
|
|
318
|
+
if (!starts) return void 0;
|
|
319
|
+
if (this.readWindows.length < READ_WINDOWS) {
|
|
320
|
+
run = {
|
|
321
|
+
buffer: Buffer.allocUnsafe(READ_WINDOW),
|
|
322
|
+
start: 0,
|
|
323
|
+
end: 0,
|
|
324
|
+
next: 0,
|
|
325
|
+
used
|
|
326
|
+
};
|
|
327
|
+
this.readWindows.push(run);
|
|
328
|
+
} else run = this.readWindows.reduce((a, b) => b.used < a.used ? b : a);
|
|
329
|
+
}
|
|
330
|
+
const length = Math.min(READ_WINDOW, this.endAt(offset) - offset);
|
|
331
|
+
run.start = run.end = 0;
|
|
332
|
+
run.next = -1e400;
|
|
333
|
+
if (length < 20) return void 0;
|
|
334
|
+
this.readInto(run.buffer, offset, length);
|
|
335
|
+
const end = offset + recordSizeAt(run.buffer, 0);
|
|
336
|
+
if (end > offset + length) return void 0;
|
|
337
|
+
run.start = offset;
|
|
338
|
+
run.end = offset + length;
|
|
339
|
+
run.next = end;
|
|
340
|
+
run.used = used;
|
|
341
|
+
return run;
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Reads the record at `offset` into the scan window, which is read ahead in large chunks (records
|
|
345
|
+
* of a scan or a copy are mostly in file order); returns where the record starts in the window.
|
|
346
|
+
*/
|
|
347
|
+
inWindow(offset) {
|
|
348
|
+
if (offset < this.windowStart || offset + 20 > this.windowEnd) this.fillWindow(offset);
|
|
349
|
+
const at = offset - this.windowStart;
|
|
350
|
+
const size = recordSizeAt(this.window, at);
|
|
351
|
+
if (offset + size <= this.windowEnd) return at;
|
|
352
|
+
this.fillWindow(offset, size);
|
|
353
|
+
return 0;
|
|
354
|
+
}
|
|
355
|
+
/** decodes a record for a scan, from the scan window */
|
|
356
|
+
decodeInWindow(address) {
|
|
357
|
+
const at = this.inWindow(offsetOf(address));
|
|
358
|
+
return this.decodeAt(this.window, at, this.windowEnd - this.windowStart - at);
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Decodes the record at `at` of a window. A record that fits in the read buffer is copied to its
|
|
362
|
+
* start and decoded there, like a single read: on Bun, msgpackr decoded nodes in place, at their
|
|
363
|
+
* offset in a window, up to twice as slowly (scans and read-ahead reads of 2–4 KB nodes).
|
|
364
|
+
*/
|
|
365
|
+
decodeAt(window, at, available) {
|
|
366
|
+
const size = recordSizeAt(window, at);
|
|
367
|
+
if (size <= this.readBuffer.length) {
|
|
368
|
+
const length = Math.min(this.readBuffer.length, Math.max(size, Math.min(READ_AHEAD, available)));
|
|
369
|
+
window.copy(this.readBuffer, 0, at, at + length);
|
|
370
|
+
return this.decodeRead();
|
|
371
|
+
}
|
|
372
|
+
const start = at + dataStartAt(window, at);
|
|
373
|
+
this.decodedBytes = window.readUInt32LE(at);
|
|
374
|
+
return this.codec.unpack(window, {
|
|
375
|
+
start,
|
|
376
|
+
end: start + this.decodedBytes
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
fillWindow(offset, size = 0) {
|
|
380
|
+
this.inBounds(offset, Math.max(size, 20));
|
|
381
|
+
const length = Math.min(Math.max(SCAN_WINDOW, size), this.endAt(offset) - offset);
|
|
382
|
+
if (length > this.window.length) this.window = Buffer.allocUnsafe(length);
|
|
383
|
+
this.readInto(this.window, offset, length);
|
|
384
|
+
this.windowStart = offset;
|
|
385
|
+
this.windowEnd = offset + length;
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* the file changed under the windows (another file, records moved or offsets changed); appends
|
|
389
|
+
* do not: a window ends at or before the end of the bytes written when it was filled
|
|
390
|
+
*/
|
|
391
|
+
dropWindow() {
|
|
392
|
+
this.windowStart = 0;
|
|
393
|
+
this.windowEnd = 0;
|
|
394
|
+
this.readWindows = [];
|
|
395
|
+
this.readEnds.fill(-1e400);
|
|
396
|
+
}
|
|
397
|
+
sizeAt(address) {
|
|
398
|
+
return recordSize(readHeader(this.readAt(offsetOf(address), 20)));
|
|
399
|
+
}
|
|
400
|
+
/** a record is superseded or deleted: garbage of its segment */
|
|
401
|
+
supersede(address) {
|
|
402
|
+
this.segmentAt(offsetOf(address)).live -= this.sizeAt(address);
|
|
403
|
+
}
|
|
404
|
+
typeIndex(type) {
|
|
405
|
+
let index = this.typeIndexes.get(type);
|
|
406
|
+
if (index === void 0) {
|
|
407
|
+
index = this.types.length;
|
|
408
|
+
if (index >= TYPE_SLOTS) throw new Error(`The logfile datastore holds at most ${TYPE_SLOTS} node types`);
|
|
409
|
+
this.types.push(type);
|
|
410
|
+
this.typeIndexes.set(type, index);
|
|
411
|
+
}
|
|
412
|
+
return index;
|
|
413
|
+
}
|
|
414
|
+
idsOf(type) {
|
|
415
|
+
let ids = this.byType.get(type);
|
|
416
|
+
if (!ids) {
|
|
417
|
+
ids = /* @__PURE__ */ new Set();
|
|
418
|
+
this.byType.set(type, ids);
|
|
419
|
+
}
|
|
420
|
+
return ids;
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* creates this run's segment when there is none to append to: a new file after the others in the
|
|
424
|
+
* virtual address space (the files of earlier runs are not written again)
|
|
425
|
+
*/
|
|
426
|
+
openForAppend() {
|
|
427
|
+
if (this.current) return;
|
|
428
|
+
fs.mkdirSync(this.dir, { recursive: true });
|
|
429
|
+
const id = newId();
|
|
430
|
+
const base = this.segmentsEnd();
|
|
431
|
+
const fd = fs.openSync(this.segmentFile(id), "wx+");
|
|
432
|
+
this.current = {
|
|
433
|
+
id,
|
|
434
|
+
base,
|
|
435
|
+
length: 0,
|
|
436
|
+
live: 0,
|
|
437
|
+
fd,
|
|
438
|
+
size: 0
|
|
439
|
+
};
|
|
440
|
+
this.segments.push(this.current);
|
|
441
|
+
this.fileEnd = base;
|
|
442
|
+
}
|
|
443
|
+
/** the end of the virtual address space */
|
|
444
|
+
segmentsEnd() {
|
|
445
|
+
return this.segments.reduce((end, s) => Math.max(end, s.base + s.length), 0);
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* appends the first `used` bytes of the write buffer to the current segment; returns their
|
|
449
|
+
* (virtual) offset
|
|
450
|
+
*/
|
|
451
|
+
appendWriteBuffer(used) {
|
|
452
|
+
this.openForAppend();
|
|
453
|
+
const segment = this.current;
|
|
454
|
+
const start = this.fileEnd;
|
|
455
|
+
writeAt(segment.fd, this.writeBuffer, used, start - segment.base);
|
|
456
|
+
this.fileEnd += used;
|
|
457
|
+
segment.length += used;
|
|
458
|
+
segment.size = segment.length;
|
|
459
|
+
segment.live += used;
|
|
460
|
+
if (segment.length >= this.segmentMax) this.current = void 0;
|
|
461
|
+
return start;
|
|
462
|
+
}
|
|
463
|
+
/** (a write buffer grown for a large batch is not kept) */
|
|
464
|
+
trimWriteBuffer() {
|
|
465
|
+
if (this.writeBuffer.length > 16777216) this.writeBuffer = Buffer.allocUnsafe(1048576);
|
|
466
|
+
}
|
|
467
|
+
/** encodes buffered writes and appends them to the current segment (a write buffer at a time) */
|
|
468
|
+
flush() {
|
|
469
|
+
if (!this.pending.size || this.readonly) return;
|
|
470
|
+
this.version++;
|
|
471
|
+
const written = [];
|
|
472
|
+
let chunk = [];
|
|
473
|
+
let used = 0;
|
|
474
|
+
const append = () => {
|
|
475
|
+
if (!used) return;
|
|
476
|
+
const start = this.appendWriteBuffer(used);
|
|
477
|
+
for (const [id, at, typeIndex] of chunk) written.push([
|
|
478
|
+
id,
|
|
479
|
+
start + at,
|
|
480
|
+
typeIndex
|
|
481
|
+
]);
|
|
482
|
+
chunk = [];
|
|
483
|
+
used = 0;
|
|
484
|
+
};
|
|
485
|
+
try {
|
|
486
|
+
for (const [id, { data: encoded, work, type, parent, digest }] of this.pending) {
|
|
487
|
+
const data = encoded ?? this.encodeWork(id, work, false);
|
|
488
|
+
const size = encodedSize(id, parent, digest, data);
|
|
489
|
+
if (used + size > this.writeBuffer.length) {
|
|
490
|
+
append();
|
|
491
|
+
if (size > this.writeBuffer.length) this.writeBuffer = Buffer.allocUnsafe(size);
|
|
492
|
+
}
|
|
493
|
+
const typeIndex = this.typeIndex(type);
|
|
494
|
+
chunk.push([
|
|
495
|
+
id,
|
|
496
|
+
used,
|
|
497
|
+
typeIndex
|
|
498
|
+
]);
|
|
499
|
+
used += writeRecord(this.writeBuffer, used, id, typeIndex, parent, digest, data);
|
|
500
|
+
}
|
|
501
|
+
append();
|
|
502
|
+
} catch (e) {
|
|
503
|
+
for (const [, at, typeIndex] of written) this.supersede(at * TYPE_SLOTS + typeIndex);
|
|
504
|
+
throw e;
|
|
505
|
+
}
|
|
506
|
+
for (const [id, at, typeIndex] of written) {
|
|
507
|
+
const previous = this.addresses.get(id);
|
|
508
|
+
if (previous !== void 0 && previous !== PENDING) this.supersede(previous);
|
|
509
|
+
this.addresses.set(id, at * TYPE_SLOTS + typeIndex);
|
|
510
|
+
this.cache.delete(id);
|
|
511
|
+
}
|
|
512
|
+
this.pending.clear();
|
|
513
|
+
this.pendingBytes.clear();
|
|
514
|
+
this.trimWriteBuffer();
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* Copies the live records at the offsets `select` picks to `append` (which writes the first
|
|
518
|
+
* `used` bytes of the write buffer and returns their offset) and points their addresses at the
|
|
519
|
+
* copies. In insertion order: scans read the copies in file order. The moves are updates in
|
|
520
|
+
* place for the index log.
|
|
521
|
+
*/
|
|
522
|
+
copyRecords(select, append) {
|
|
523
|
+
let used = 0;
|
|
524
|
+
let batch = [];
|
|
525
|
+
const write = () => {
|
|
526
|
+
if (!used) return;
|
|
527
|
+
const start = append(used);
|
|
528
|
+
for (const [id, at, typeIndex] of batch) this.addresses.set(id, (start + at) * TYPE_SLOTS + typeIndex);
|
|
529
|
+
used = 0;
|
|
530
|
+
batch = [];
|
|
531
|
+
};
|
|
532
|
+
for (const [id, address] of this.addresses) {
|
|
533
|
+
if (address === PENDING) continue;
|
|
534
|
+
const offset = offsetOf(address);
|
|
535
|
+
if (!select(offset)) continue;
|
|
536
|
+
const at = this.inWindow(offset);
|
|
537
|
+
const size = recordSizeAt(this.window, at);
|
|
538
|
+
if (used + size > this.writeBuffer.length) {
|
|
539
|
+
write();
|
|
540
|
+
if (size > this.writeBuffer.length) this.writeBuffer = Buffer.allocUnsafe(size);
|
|
541
|
+
}
|
|
542
|
+
this.window.copy(this.writeBuffer, used, at, at + size);
|
|
543
|
+
batch.push([
|
|
544
|
+
id,
|
|
545
|
+
used,
|
|
546
|
+
address % TYPE_SLOTS
|
|
547
|
+
]);
|
|
548
|
+
this.changed.add(id);
|
|
549
|
+
used += size;
|
|
550
|
+
}
|
|
551
|
+
write();
|
|
552
|
+
this.dropWindow();
|
|
553
|
+
this.trimWriteBuffer();
|
|
554
|
+
}
|
|
555
|
+
/**
|
|
556
|
+
* Copies the live records of segments that are mostly garbage into the current
|
|
557
|
+
* segment, and of the smallest segments when there are many, and drops those segments (their
|
|
558
|
+
* files are deleted once the index no longer lists them). At most `2 × segmentMax` live bytes per
|
|
559
|
+
* call, the most garbage first: the rest waits for later persists.
|
|
560
|
+
*/
|
|
561
|
+
compactSegments() {
|
|
562
|
+
const dead = (s) => s.size - s.live;
|
|
563
|
+
let budget = 2 * this.segmentMax;
|
|
564
|
+
const chosen = /* @__PURE__ */ new Set();
|
|
565
|
+
const choose = (s) => {
|
|
566
|
+
if (s.live > 0 && s.live > budget && chosen.size) return;
|
|
567
|
+
chosen.add(s);
|
|
568
|
+
budget -= s.live;
|
|
569
|
+
};
|
|
570
|
+
const others = this.segments.filter((s) => s !== this.current);
|
|
571
|
+
for (const s of others.filter((s) => dead(s) > s.size * SEGMENT_GARBAGE_SHARE).sort((a, b) => dead(b) - dead(a))) choose(s);
|
|
572
|
+
const small = others.filter((s) => !chosen.has(s) && s.size < this.segmentMax);
|
|
573
|
+
if (small.length > MAX_SEGMENTS) for (const s of small.sort((a, b) => a.size - b.size).slice(0, small.length - MAX_SEGMENTS / 2)) choose(s);
|
|
574
|
+
if (!chosen.size) return;
|
|
575
|
+
this.version++;
|
|
576
|
+
this.copyRecords((offset) => chosen.has(this.segmentAt(offset)), (used) => this.appendWriteBuffer(used));
|
|
577
|
+
for (const s of chosen) fs.closeSync(s.fd);
|
|
578
|
+
this.segments = this.segments.filter((s) => !chosen.has(s));
|
|
579
|
+
this.lastSegment = void 0;
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* Packs the segments' bases again (virtual offsets only grow). Records stay where
|
|
583
|
+
* they are in their files: only addresses change, so the index gets a new snapshot.
|
|
584
|
+
*/
|
|
585
|
+
rebase() {
|
|
586
|
+
this.version++;
|
|
587
|
+
const bases = /* @__PURE__ */ new Map();
|
|
588
|
+
let end = 0;
|
|
589
|
+
for (const s of this.segments) {
|
|
590
|
+
bases.set(s, end);
|
|
591
|
+
end += s.length;
|
|
592
|
+
}
|
|
593
|
+
for (const [id, address] of this.addresses) {
|
|
594
|
+
if (address === PENDING) continue;
|
|
595
|
+
const offset = offsetOf(address);
|
|
596
|
+
const s = this.segmentAt(offset);
|
|
597
|
+
this.addresses.set(id, (offset - s.base + bases.get(s)) * TYPE_SLOTS + address % TYPE_SLOTS);
|
|
598
|
+
}
|
|
599
|
+
for (const s of this.segments) s.base = bases.get(s);
|
|
600
|
+
if (this.current) this.fileEnd = this.current.base + this.current.length;
|
|
601
|
+
this.lastSegment = void 0;
|
|
602
|
+
this.dropWindow();
|
|
603
|
+
}
|
|
604
|
+
pendingNode(pending) {
|
|
605
|
+
if (pending.node) return pending.node;
|
|
606
|
+
pending.data ??= this.encodeWork("", pending.work, true);
|
|
607
|
+
return pending.node = this.codec.unpack(pending.data);
|
|
608
|
+
}
|
|
609
|
+
/** encodes a working copy (`keep`: into the pending bytes, else into msgpackr's reused buffer) */
|
|
610
|
+
encodeWork(id, work, keep) {
|
|
611
|
+
try {
|
|
612
|
+
const bytes = encodeReused(this.codec, work);
|
|
613
|
+
return keep ? this.pendingBytes.add(bytes) : bytes;
|
|
614
|
+
} catch (e) {
|
|
615
|
+
throw new Error(`The logfile datastore could not serialize node "${id || work.id}" (${work.internal.type}): ${e.message}`, { cause: e });
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
getNodeForUpdate(id) {
|
|
619
|
+
if (this.readonly || id == null) return void 0;
|
|
620
|
+
let pending = this.pending.get(id);
|
|
621
|
+
if (!pending?.work) {
|
|
622
|
+
let work;
|
|
623
|
+
if (pending) work = this.codec.unpack(pending.data);
|
|
624
|
+
else {
|
|
625
|
+
const address = this.addresses.get(id);
|
|
626
|
+
if (address === void 0 || address === PENDING) return void 0;
|
|
627
|
+
work = this.decode(address);
|
|
628
|
+
pending = {
|
|
629
|
+
data: void 0,
|
|
630
|
+
type: this.types[address % TYPE_SLOTS],
|
|
631
|
+
parent: this.parents.get(id) ?? null,
|
|
632
|
+
digest: this.digests.get(id) ?? null
|
|
633
|
+
};
|
|
634
|
+
this.pending.set(id, pending);
|
|
635
|
+
}
|
|
636
|
+
pending.work = work;
|
|
637
|
+
}
|
|
638
|
+
pending.data = void 0;
|
|
639
|
+
pending.node = void 0;
|
|
640
|
+
this.changed.add(id);
|
|
641
|
+
this.dirty = true;
|
|
642
|
+
this.version++;
|
|
643
|
+
return pending.work;
|
|
644
|
+
}
|
|
645
|
+
peekNode(id) {
|
|
646
|
+
const pending = this.pending.get(id);
|
|
647
|
+
return pending ? pending.node : this.cache.peek(id);
|
|
648
|
+
}
|
|
649
|
+
getNode(id) {
|
|
650
|
+
if (id == null) return void 0;
|
|
651
|
+
const pending = this.pending.get(id);
|
|
652
|
+
if (pending) return this.pendingNode(pending);
|
|
653
|
+
const cached = this.cache.get(id);
|
|
654
|
+
if (cached) return cached;
|
|
655
|
+
const address = this.addresses.get(id);
|
|
656
|
+
if (address === void 0 || address === PENDING) return void 0;
|
|
657
|
+
const node = this.decode(address);
|
|
658
|
+
this.cache.set(id, node, this.decodedBytes);
|
|
659
|
+
if (this.ownersIncomplete && !this.owners.has(id)) this.setOwner(id, ownerOf(node));
|
|
660
|
+
return node;
|
|
661
|
+
}
|
|
662
|
+
/** batched lookup (keeps the order of `ids`, undefined for missing nodes) */
|
|
663
|
+
getNodesByIds(ids, options = {}) {
|
|
664
|
+
if (options.cache !== false) return ids.map((id) => this.getNode(id));
|
|
665
|
+
return ids.map((id) => {
|
|
666
|
+
const pending = this.pending.get(id);
|
|
667
|
+
if (pending) return this.pendingNode(pending);
|
|
668
|
+
const cached = this.cache.peek(id);
|
|
669
|
+
if (cached) return cached;
|
|
670
|
+
const address = this.addresses.get(id);
|
|
671
|
+
return address === void 0 || address === PENDING ? void 0 : this.decode(address);
|
|
672
|
+
});
|
|
673
|
+
}
|
|
674
|
+
getTypes() {
|
|
675
|
+
return [...this.byType].filter(([, ids]) => ids.size > 0).map(([type]) => type);
|
|
676
|
+
}
|
|
677
|
+
countNodes(typeName) {
|
|
678
|
+
if (!typeName) return this.addresses.size;
|
|
679
|
+
return this.byType.get(typeName)?.size ?? 0;
|
|
680
|
+
}
|
|
681
|
+
/** type of a node without reading it */
|
|
682
|
+
getNodeType(id) {
|
|
683
|
+
const pending = this.pending.get(id);
|
|
684
|
+
if (pending) return pending.type;
|
|
685
|
+
const address = this.addresses.get(id);
|
|
686
|
+
if (address === void 0 || address === PENDING) return void 0;
|
|
687
|
+
return this.types[address % TYPE_SLOTS];
|
|
688
|
+
}
|
|
689
|
+
/** parent id of a node without decoding it */
|
|
690
|
+
getNodeParent(id) {
|
|
691
|
+
const pending = this.pending.get(id);
|
|
692
|
+
if (pending) return pending.parent;
|
|
693
|
+
const address = this.addresses.get(id);
|
|
694
|
+
if (address === void 0 || address === PENDING) return void 0;
|
|
695
|
+
return this.parents.get(id) ?? null;
|
|
696
|
+
}
|
|
697
|
+
/** `internal.contentDigest` of a node without decoding it */
|
|
698
|
+
getNodeDigest(id) {
|
|
699
|
+
const pending = this.pending.get(id);
|
|
700
|
+
if (pending) return pending.digest ?? void 0;
|
|
701
|
+
const address = this.addresses.get(id);
|
|
702
|
+
if (address === void 0 || address === PENDING) return void 0;
|
|
703
|
+
if (this.withDigests) return this.digests.get(id);
|
|
704
|
+
const header = this.readHead(address);
|
|
705
|
+
if (!header.digestLength) return void 0;
|
|
706
|
+
const start = digestStart(header);
|
|
707
|
+
return this.readBuffer.toString("utf8", start, start + header.digestLength);
|
|
708
|
+
}
|
|
709
|
+
/** highest `internal.counter` of all nodes, without reading nodes */
|
|
710
|
+
getMaxNodeCounter() {
|
|
711
|
+
return this.maxCounter;
|
|
712
|
+
}
|
|
713
|
+
/** node ids of a type in insertion order, without reading nodes */
|
|
714
|
+
getNodeIdsByType(typeName) {
|
|
715
|
+
return [...this.byType.get(typeName) ?? []];
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* Nodes (all or of one type) in insertion order. Cached nodes are returned as they are; scanned
|
|
719
|
+
* nodes are not put into the cache, so one scan over 200k nodes does not evict the recently used
|
|
720
|
+
* ones.
|
|
721
|
+
*/
|
|
722
|
+
*scan(typeName) {
|
|
723
|
+
this.flush();
|
|
724
|
+
const ids = typeName === void 0 ? this.addresses.keys() : this.byType.get(typeName);
|
|
725
|
+
if (!ids) return;
|
|
726
|
+
for (const id of ids) {
|
|
727
|
+
const pending = this.pending.get(id);
|
|
728
|
+
if (pending) {
|
|
729
|
+
yield this.pendingNode(pending);
|
|
730
|
+
continue;
|
|
731
|
+
}
|
|
732
|
+
const address = this.addresses.get(id);
|
|
733
|
+
if (address === void 0 || address === PENDING) continue;
|
|
734
|
+
yield this.cache.peek(id) ?? this.decodeInWindow(address);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
getNodes() {
|
|
738
|
+
return [...this.scan()];
|
|
739
|
+
}
|
|
740
|
+
getNodesByType(typeName) {
|
|
741
|
+
return [...this.scan(typeName)];
|
|
742
|
+
}
|
|
743
|
+
iterateNodes() {
|
|
744
|
+
return this.scan();
|
|
745
|
+
}
|
|
746
|
+
iterateNodesByType(typeName) {
|
|
747
|
+
return this.scan(typeName);
|
|
748
|
+
}
|
|
749
|
+
setNode(node, oldNode) {
|
|
750
|
+
if (this.readonly) throw new Error("The logfile datastore is read-only (a query worker, or opened with readonly: true)");
|
|
751
|
+
const { id } = node;
|
|
752
|
+
const type = node.internal.type;
|
|
753
|
+
const current = this.pending.get(id);
|
|
754
|
+
if (current?.work === node && current.type === type && (!oldNode || oldNode.id === id)) {
|
|
755
|
+
current.data = void 0;
|
|
756
|
+
current.node = void 0;
|
|
757
|
+
current.parent = parentOf(node);
|
|
758
|
+
current.digest = digestOf(node);
|
|
759
|
+
if (!current.parent) this.parents.delete(id);
|
|
760
|
+
else if (this.parents.get(id) !== current.parent) this.parents.set(id, current.parent);
|
|
761
|
+
if (!current.digest) this.digests.delete(id);
|
|
762
|
+
else if (this.digests.get(id) !== current.digest) this.digests.set(id, current.digest);
|
|
763
|
+
this.setOwner(id, ownerOf(node));
|
|
764
|
+
const counter = node.internal.counter;
|
|
765
|
+
if (typeof counter === "number" && counter > this.maxCounter) this.maxCounter = counter;
|
|
766
|
+
this.changed.add(id);
|
|
767
|
+
this.dirty = true;
|
|
768
|
+
this.version++;
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
let data;
|
|
772
|
+
try {
|
|
773
|
+
data = this.pendingBytes.add(encodeReused(this.codec, node));
|
|
774
|
+
} catch (e) {
|
|
775
|
+
throw new Error(`The logfile datastore could not serialize node "${id}" (${type}): ${e.message}`, { cause: e });
|
|
776
|
+
}
|
|
777
|
+
if (oldNode && oldNode.id !== node.id) this.deleteNode(oldNode);
|
|
778
|
+
const previousType = this.getNodeType(id);
|
|
779
|
+
if (previousType !== void 0 && previousType !== type) this.deleteNode(node);
|
|
780
|
+
if (!this.addresses.has(id)) {
|
|
781
|
+
this.addresses.set(id, PENDING);
|
|
782
|
+
this.appended.add(id);
|
|
783
|
+
}
|
|
784
|
+
this.changed.add(id);
|
|
785
|
+
this.idsOf(type).add(id);
|
|
786
|
+
const parent = parentOf(node);
|
|
787
|
+
if (!parent) this.parents.delete(id);
|
|
788
|
+
else if (this.parents.get(id) !== parent) this.parents.set(id, parent);
|
|
789
|
+
const digest = digestOf(node);
|
|
790
|
+
if (!digest) this.digests.delete(id);
|
|
791
|
+
else if (this.digests.get(id) !== digest) this.digests.set(id, digest);
|
|
792
|
+
this.setOwner(id, ownerOf(node));
|
|
793
|
+
const counter = node.internal.counter;
|
|
794
|
+
if (typeof counter === "number" && counter > this.maxCounter) this.maxCounter = counter;
|
|
795
|
+
this.pending.set(id, {
|
|
796
|
+
data,
|
|
797
|
+
type,
|
|
798
|
+
parent,
|
|
799
|
+
digest
|
|
800
|
+
});
|
|
801
|
+
this.dirty = true;
|
|
802
|
+
this.version++;
|
|
803
|
+
if (this.pending.size >= FLUSH_EVERY || this.pendingBytes.full) this.flush();
|
|
804
|
+
}
|
|
805
|
+
deleteNode(node) {
|
|
806
|
+
if (this.readonly) throw new Error("The logfile datastore is read-only (a query worker, or opened with readonly: true)");
|
|
807
|
+
const { id } = node;
|
|
808
|
+
const address = this.addresses.get(id);
|
|
809
|
+
if (address === void 0) return;
|
|
810
|
+
const type = this.getNodeType(id);
|
|
811
|
+
if (type !== void 0) this.byType.get(type)?.delete(id);
|
|
812
|
+
if (address !== PENDING) this.supersede(address);
|
|
813
|
+
this.addresses.delete(id);
|
|
814
|
+
this.appended.delete(id);
|
|
815
|
+
this.changed.add(id);
|
|
816
|
+
this.pending.delete(id);
|
|
817
|
+
this.parents.delete(id);
|
|
818
|
+
this.digests.delete(id);
|
|
819
|
+
this.owners.delete(id);
|
|
820
|
+
this.cache.delete(id);
|
|
821
|
+
this.dirty = true;
|
|
822
|
+
this.version++;
|
|
823
|
+
}
|
|
824
|
+
setOwner(id, owner) {
|
|
825
|
+
if (owner == null) {
|
|
826
|
+
this.owners.delete(id);
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
let name = this.ownerNames.get(owner);
|
|
830
|
+
if (name === void 0) {
|
|
831
|
+
name = (" " + owner).slice(1);
|
|
832
|
+
this.ownerNames.set(name, name);
|
|
833
|
+
}
|
|
834
|
+
if (this.owners.get(id) !== name) this.owners.set(id, name);
|
|
835
|
+
}
|
|
836
|
+
/** `internal.owner` without decoding the node (writer only: undefined in query workers) */
|
|
837
|
+
getNodeOwner(id) {
|
|
838
|
+
if (this.readonly || !this.addresses.has(id)) return void 0;
|
|
839
|
+
return this.owners.get(id);
|
|
840
|
+
}
|
|
841
|
+
async ready() {
|
|
842
|
+
this.flush();
|
|
843
|
+
}
|
|
844
|
+
/** drops decoded nodes kept for reuse (memory pressure in query workers) */
|
|
845
|
+
trimCache() {
|
|
846
|
+
this.cache.clear();
|
|
847
|
+
this.readWindows = [];
|
|
848
|
+
}
|
|
849
|
+
clear() {
|
|
850
|
+
this.pending.clear();
|
|
851
|
+
this.pendingBytes.clear();
|
|
852
|
+
this.cache.clear();
|
|
853
|
+
this.addresses.clear();
|
|
854
|
+
this.byType.clear();
|
|
855
|
+
this.digests.clear();
|
|
856
|
+
this.owners.clear();
|
|
857
|
+
this.ownerNames.clear();
|
|
858
|
+
this.ownersIncomplete = false;
|
|
859
|
+
this.parents.clear();
|
|
860
|
+
this.types = [];
|
|
861
|
+
this.typeIndexes.clear();
|
|
862
|
+
this.codec = this.createCodec([]);
|
|
863
|
+
this.maxCounter = 0;
|
|
864
|
+
this.closeFile();
|
|
865
|
+
this.snapshotId = void 0;
|
|
866
|
+
this.logEntries = 0;
|
|
867
|
+
this.logSeq = 0;
|
|
868
|
+
this.changed.clear();
|
|
869
|
+
this.appended.clear();
|
|
870
|
+
this.dirty = true;
|
|
871
|
+
this.version++;
|
|
872
|
+
}
|
|
873
|
+
closeFile() {
|
|
874
|
+
for (const s of this.segments) fs.closeSync(s.fd);
|
|
875
|
+
this.fileEnd = 0;
|
|
876
|
+
this.segments = [];
|
|
877
|
+
this.current = void 0;
|
|
878
|
+
this.lastSegment = void 0;
|
|
879
|
+
this.dropWindow();
|
|
880
|
+
}
|
|
881
|
+
/**
|
|
882
|
+
* What the WASM data side (`wasm-data/host.ts`) ingests for query workers: every type with its
|
|
883
|
+
* index and its nodes' record addresses in insertion order, the shared record structures and the
|
|
884
|
+
* files that hold them – the nodes as they were persisted (what query workers load). Undefined
|
|
885
|
+
* when they changed since (`dirty`).
|
|
886
|
+
*
|
|
887
|
+
* The segments with their bases and lengths now. A later persist() may delete
|
|
888
|
+
* segment files (compaction, removeUnlisted()) or change the bases (rebase()): a reader opens the
|
|
889
|
+
* files right away and keeps them open (an open file stays readable after it is deleted on
|
|
890
|
+
* Linux and macOS) and maps offsets with the image's own bases.
|
|
891
|
+
*/
|
|
892
|
+
persistedImage() {
|
|
893
|
+
if (this.pending.size || this.dirty) return void 0;
|
|
894
|
+
return this.image();
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
897
|
+
* The same for the main thread: the nodes as they are now. Buffered writes are written to the
|
|
898
|
+
* current segment first; nothing needs to be persisted (the records are read from the segments
|
|
899
|
+
* by their addresses, which only persist() compacts – a build persists after its queries ran).
|
|
900
|
+
* The current segment's length as it is after the flush (later appends to it are
|
|
901
|
+
* not part of the image).
|
|
902
|
+
*/
|
|
903
|
+
liveImage() {
|
|
904
|
+
this.flush();
|
|
905
|
+
if (this.pending.size) return void 0;
|
|
906
|
+
return this.image();
|
|
907
|
+
}
|
|
908
|
+
image() {
|
|
909
|
+
const segments = this.segments.filter((s) => s.length > 0).map((s) => ({
|
|
910
|
+
base: s.base,
|
|
911
|
+
length: s.length,
|
|
912
|
+
path: this.segmentFile(s.id)
|
|
913
|
+
})).sort((a, b) => a.base - b.base);
|
|
914
|
+
const types = [];
|
|
915
|
+
for (const [name, ids] of this.byType) {
|
|
916
|
+
const index = this.typeIndexes.get(name);
|
|
917
|
+
if (index === void 0) return void 0;
|
|
918
|
+
const addresses = new Float64Array(ids.size);
|
|
919
|
+
let i = 0;
|
|
920
|
+
for (const id of ids) {
|
|
921
|
+
const address = this.addresses.get(id);
|
|
922
|
+
if (address === void 0 || address < 0) return void 0;
|
|
923
|
+
addresses[i++] = address;
|
|
924
|
+
}
|
|
925
|
+
types.push({
|
|
926
|
+
name,
|
|
927
|
+
index,
|
|
928
|
+
addresses
|
|
929
|
+
});
|
|
930
|
+
}
|
|
931
|
+
return {
|
|
932
|
+
types,
|
|
933
|
+
structures: [...this.structures],
|
|
934
|
+
segments
|
|
935
|
+
};
|
|
936
|
+
}
|
|
937
|
+
/**
|
|
938
|
+
* Restores the nodes of the last persist(). Returns true when nodes were restored. The segments
|
|
939
|
+
* are opened read-only and not truncated (bytes of a run that wrote and did not persist stay in
|
|
940
|
+
* its segment, after what the index covers, or in a segment the index does not list, which the
|
|
941
|
+
* next persist() deletes).
|
|
942
|
+
*/
|
|
943
|
+
async load() {
|
|
944
|
+
this.clear();
|
|
945
|
+
const index = this.readIndex();
|
|
946
|
+
if (!index) return false;
|
|
947
|
+
const { main, writer } = index;
|
|
948
|
+
const { frames, seq } = this.readLog(main.snapshotId);
|
|
949
|
+
const last = frames.at(-1);
|
|
950
|
+
const segments = [];
|
|
951
|
+
const fail = () => {
|
|
952
|
+
for (const s of segments) fs.closeSync(s.fd);
|
|
953
|
+
return false;
|
|
954
|
+
};
|
|
955
|
+
for (const ref of (last ?? main).segments) {
|
|
956
|
+
let fd;
|
|
957
|
+
try {
|
|
958
|
+
fd = fs.openSync(this.segmentFile(ref.id), "r");
|
|
959
|
+
} catch {
|
|
960
|
+
return fail();
|
|
961
|
+
}
|
|
962
|
+
const size = fs.fstatSync(fd).size;
|
|
963
|
+
segments.push({
|
|
964
|
+
...ref,
|
|
965
|
+
fd,
|
|
966
|
+
size
|
|
967
|
+
});
|
|
968
|
+
if (size < ref.length) return fail();
|
|
969
|
+
}
|
|
970
|
+
this.segments = segments.sort((a, b) => a.base - b.base);
|
|
971
|
+
this.snapshotId = main.snapshotId;
|
|
972
|
+
this.logSeq = seq;
|
|
973
|
+
this.restore(last ?? main, main, writer, frames);
|
|
974
|
+
return this.addresses.size > 0;
|
|
975
|
+
}
|
|
976
|
+
/** the node index of a snapshot and its log frames */
|
|
977
|
+
restore(meta, main, writer, frames) {
|
|
978
|
+
this.types = meta.types.slice();
|
|
979
|
+
this.types.forEach((type, i) => this.typeIndexes.set(type, i));
|
|
980
|
+
this.codec = this.createCodec(meta.structures.slice());
|
|
981
|
+
this.maxCounter = meta.maxCounter;
|
|
982
|
+
const { ids, addresses, parents } = main;
|
|
983
|
+
this.ownersIncomplete = !this.readonly && !!writer && !writer.owners;
|
|
984
|
+
for (let i = 0; i < ids.length; i++) {
|
|
985
|
+
const id = ids[i];
|
|
986
|
+
const address = addresses[i];
|
|
987
|
+
this.addresses.set(id, address);
|
|
988
|
+
this.idsOf(this.types[address % TYPE_SLOTS]).add(id);
|
|
989
|
+
const parent = parents[i];
|
|
990
|
+
if (parent) this.parents.set(id, parent);
|
|
991
|
+
const digest = writer?.digests[i];
|
|
992
|
+
if (digest) this.digests.set(id, digest);
|
|
993
|
+
const owner = writer?.owners?.[i];
|
|
994
|
+
if (owner !== void 0 && owner >= 0) this.setOwner(id, writer.ownerNames?.[owner]);
|
|
995
|
+
}
|
|
996
|
+
for (const frame of frames) for (const entry of frame.entries) this.replay(entry);
|
|
997
|
+
this.logEntries = frames.reduce((n, f) => n + f.entries.length, 0);
|
|
998
|
+
this.dirty = this.readonly || this.ownersIncomplete;
|
|
999
|
+
this.version++;
|
|
1000
|
+
}
|
|
1001
|
+
/** applies an index log entry (load) */
|
|
1002
|
+
replay([op, id, address, parent, digest, owner]) {
|
|
1003
|
+
const current = this.addresses.get(id);
|
|
1004
|
+
const typeIndex = address % TYPE_SLOTS;
|
|
1005
|
+
const moved = op === 2 || op === 1 && (current === void 0 || current % TYPE_SLOTS !== typeIndex);
|
|
1006
|
+
if (op === 0 || moved) {
|
|
1007
|
+
if (current !== void 0) {
|
|
1008
|
+
this.byType.get(this.types[current % TYPE_SLOTS])?.delete(id);
|
|
1009
|
+
this.addresses.delete(id);
|
|
1010
|
+
}
|
|
1011
|
+
this.parents.delete(id);
|
|
1012
|
+
this.digests.delete(id);
|
|
1013
|
+
this.owners.delete(id);
|
|
1014
|
+
if (op === 0) return;
|
|
1015
|
+
}
|
|
1016
|
+
this.addresses.set(id, address);
|
|
1017
|
+
this.idsOf(this.types[typeIndex]).add(id);
|
|
1018
|
+
if (parent) this.parents.set(id, parent);
|
|
1019
|
+
else this.parents.delete(id);
|
|
1020
|
+
if (!this.withDigests) return;
|
|
1021
|
+
if (digest) this.digests.set(id, digest);
|
|
1022
|
+
else this.digests.delete(id);
|
|
1023
|
+
this.setOwner(id, owner);
|
|
1024
|
+
}
|
|
1025
|
+
/** the index file: MAGIC, version, the main section, the writer section (each length-prefixed) */
|
|
1026
|
+
readIndex() {
|
|
1027
|
+
let raw;
|
|
1028
|
+
try {
|
|
1029
|
+
raw = retrySync(() => fs.readFileSync(path.join(this.dir, "index")));
|
|
1030
|
+
} catch {
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
1033
|
+
try {
|
|
1034
|
+
let at = headEnd(raw, MAGIC, FORMAT_VERSION);
|
|
1035
|
+
if (at < 0) return void 0;
|
|
1036
|
+
const codec = indexCodec();
|
|
1037
|
+
const mainLength = raw.readUInt32LE(at);
|
|
1038
|
+
const main = codec.unpack(raw.subarray(at + 4, at + 4 + mainLength));
|
|
1039
|
+
if (!isIndexMain(main)) return void 0;
|
|
1040
|
+
at += 4 + mainLength;
|
|
1041
|
+
if (!this.withDigests) return { main };
|
|
1042
|
+
const writerLength = raw.readUInt32LE(at);
|
|
1043
|
+
const writer = codec.unpack(raw.subarray(at + 4, at + 4 + writerLength));
|
|
1044
|
+
if (!isObject(writer) || !Array.isArray(writer.digests)) return void 0;
|
|
1045
|
+
const { owners, ownerNames } = writer;
|
|
1046
|
+
if (!(owners instanceof Int32Array) || !Array.isArray(ownerNames)) return {
|
|
1047
|
+
main,
|
|
1048
|
+
writer: { digests: writer.digests }
|
|
1049
|
+
};
|
|
1050
|
+
return {
|
|
1051
|
+
main,
|
|
1052
|
+
writer: {
|
|
1053
|
+
digests: writer.digests,
|
|
1054
|
+
owners,
|
|
1055
|
+
ownerNames
|
|
1056
|
+
}
|
|
1057
|
+
};
|
|
1058
|
+
} catch {
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
/**
|
|
1063
|
+
* The index log files of the snapshot (`index-log-<seq>-<snapshot id>`), replayed in
|
|
1064
|
+
* order up to the first one that is missing or incomplete. Each is written to a temporary file
|
|
1065
|
+
* and renamed, so an incomplete one only comes from a crash of the machine.
|
|
1066
|
+
*/
|
|
1067
|
+
readLog(snapshotId) {
|
|
1068
|
+
const files = /* @__PURE__ */ new Map();
|
|
1069
|
+
try {
|
|
1070
|
+
for (const name of fs.readdirSync(this.dir)) {
|
|
1071
|
+
const match = SEGMENT_LOG.exec(name);
|
|
1072
|
+
if (match?.[2] === snapshotId) files.set(Number(match[1]), name);
|
|
1073
|
+
}
|
|
1074
|
+
} catch {}
|
|
1075
|
+
const frames = [];
|
|
1076
|
+
const codec = indexCodec();
|
|
1077
|
+
for (let seq = 1; files.has(seq); seq++) try {
|
|
1078
|
+
const raw = fs.readFileSync(path.join(this.dir, files.get(seq)));
|
|
1079
|
+
const at = headEnd(raw, LOG_MAGIC, FORMAT_VERSION);
|
|
1080
|
+
if (at < 0 || raw.readUInt32LE(at) !== raw.length - at - 4) break;
|
|
1081
|
+
const frame = codec.unpack(raw.subarray(at + 4));
|
|
1082
|
+
if (!isLogFrame(frame)) break;
|
|
1083
|
+
frames.push(frame);
|
|
1084
|
+
} catch {
|
|
1085
|
+
break;
|
|
1086
|
+
}
|
|
1087
|
+
if (!this.readonly) {
|
|
1088
|
+
for (const [seq, name] of files) if (seq > frames.length) fs.rmSync(path.join(this.dir, name), { force: true });
|
|
1089
|
+
}
|
|
1090
|
+
return {
|
|
1091
|
+
frames,
|
|
1092
|
+
seq: frames.length
|
|
1093
|
+
};
|
|
1094
|
+
}
|
|
1095
|
+
/**
|
|
1096
|
+
* Makes the written nodes the persisted state, so query workers started from now on and the next
|
|
1097
|
+
* build see them: writes the changes since the last persist() to a new index log file (the
|
|
1098
|
+
* records are on disk already), or a new index snapshot when the log got long. Compaction first
|
|
1099
|
+
* copies the live records of single segments into the current one (logged as updates). Nothing
|
|
1100
|
+
* is written when nothing changed.
|
|
1101
|
+
*/
|
|
1102
|
+
async persist() {
|
|
1103
|
+
if (this.readonly) return;
|
|
1104
|
+
this.flush();
|
|
1105
|
+
if (!this.dirty && this.snapshotId !== void 0) return;
|
|
1106
|
+
let snapshot = this.snapshotId === void 0;
|
|
1107
|
+
fs.mkdirSync(this.dir, { recursive: true });
|
|
1108
|
+
this.compactSegments();
|
|
1109
|
+
if (this.segmentsEnd() > this.rebaseAt) {
|
|
1110
|
+
this.rebase();
|
|
1111
|
+
snapshot = true;
|
|
1112
|
+
}
|
|
1113
|
+
if (this.logEntries + this.changed.size > Math.max(LOG_MIN_ENTRIES, this.addresses.size * LOG_SHARE) || this.ownersIncomplete) snapshot = true;
|
|
1114
|
+
const writing = snapshot ? this.writeSnapshot() : this.writeLog();
|
|
1115
|
+
if (snapshot) this.ownersIncomplete = false;
|
|
1116
|
+
this.changed = /* @__PURE__ */ new Set();
|
|
1117
|
+
this.appended = /* @__PURE__ */ new Set();
|
|
1118
|
+
this.dirty = false;
|
|
1119
|
+
try {
|
|
1120
|
+
await writing;
|
|
1121
|
+
} catch (e) {
|
|
1122
|
+
this.snapshotId = void 0;
|
|
1123
|
+
this.dirty = true;
|
|
1124
|
+
this.version++;
|
|
1125
|
+
throw e;
|
|
1126
|
+
}
|
|
1127
|
+
this.version++;
|
|
1128
|
+
return this.removeUnlisted();
|
|
1129
|
+
}
|
|
1130
|
+
/**
|
|
1131
|
+
* Removes the segments the index does not list (compacted, or of a run that did not persist),
|
|
1132
|
+
* index log files of other snapshots and temporary files. Deleting a file is all a layer diff
|
|
1133
|
+
* records of it.
|
|
1134
|
+
*/
|
|
1135
|
+
async removeUnlisted() {
|
|
1136
|
+
const listed = new Set(this.segments.map((s) => `segment-${s.id}`));
|
|
1137
|
+
for (const name of await fs.promises.readdir(this.dir)) {
|
|
1138
|
+
const log = SEGMENT_LOG.exec(name);
|
|
1139
|
+
if (name.startsWith("segment-") ? !listed.has(name) : log && log[2] !== this.snapshotId || name.startsWith("index") && name.endsWith(".tmp")) await fs.promises.rm(path.join(this.dir, name), { force: true }).catch(() => {});
|
|
1140
|
+
}
|
|
1141
|
+
this.version++;
|
|
1142
|
+
}
|
|
1143
|
+
/** what every snapshot and log file holds besides the nodes */
|
|
1144
|
+
frameMeta() {
|
|
1145
|
+
return {
|
|
1146
|
+
maxCounter: this.maxCounter,
|
|
1147
|
+
types: this.types.slice(),
|
|
1148
|
+
structures: this.structures.map((s) => Array.isArray(s) ? [...s] : s)
|
|
1149
|
+
};
|
|
1150
|
+
}
|
|
1151
|
+
/** (the index log files of the earlier snapshot are removed after it is written) */
|
|
1152
|
+
async writeSnapshot() {
|
|
1153
|
+
const ids = [...this.addresses.keys()];
|
|
1154
|
+
const snapshotId = newId();
|
|
1155
|
+
const body = {
|
|
1156
|
+
...this.frameMeta(),
|
|
1157
|
+
ids,
|
|
1158
|
+
addresses: Float64Array.from(this.addresses.values()),
|
|
1159
|
+
parents: ids.map((id) => this.parents.get(id) ?? null)
|
|
1160
|
+
};
|
|
1161
|
+
const ownerNames = [...this.ownerNames.keys()];
|
|
1162
|
+
const positions = new Map(ownerNames.map((name, i) => [name, i]));
|
|
1163
|
+
const writer = {
|
|
1164
|
+
digests: ids.map((id) => this.digests.get(id) ?? null),
|
|
1165
|
+
owners: Int32Array.from(ids, (id) => {
|
|
1166
|
+
const owner = this.owners.get(id);
|
|
1167
|
+
return owner === void 0 ? -1 : positions.get(owner);
|
|
1168
|
+
}),
|
|
1169
|
+
ownerNames
|
|
1170
|
+
};
|
|
1171
|
+
const main = {
|
|
1172
|
+
version: FORMAT_VERSION,
|
|
1173
|
+
snapshotId,
|
|
1174
|
+
segments: this.segments.map(segmentRef),
|
|
1175
|
+
...body
|
|
1176
|
+
};
|
|
1177
|
+
this.logSeq = 0;
|
|
1178
|
+
await this.writeIndex(main, writer);
|
|
1179
|
+
this.snapshotId = snapshotId;
|
|
1180
|
+
this.logEntries = 0;
|
|
1181
|
+
}
|
|
1182
|
+
/** the index file */
|
|
1183
|
+
async writeIndex(main, writer) {
|
|
1184
|
+
const codec = indexCodec();
|
|
1185
|
+
const mainBytes = Buffer.from(codec.pack(main));
|
|
1186
|
+
const writerBytes = Buffer.from(codec.pack(writer));
|
|
1187
|
+
await writeAtomic(path.join(this.dir, "index"), Buffer.concat([
|
|
1188
|
+
fileHead(MAGIC, FORMAT_VERSION, mainBytes.length),
|
|
1189
|
+
mainBytes,
|
|
1190
|
+
u32(writerBytes.length),
|
|
1191
|
+
writerBytes
|
|
1192
|
+
]));
|
|
1193
|
+
}
|
|
1194
|
+
/** the changes since the last persist(), in the order replay() gives the same order of ids */
|
|
1195
|
+
logEntriesSince() {
|
|
1196
|
+
const entries = [];
|
|
1197
|
+
const entry = (op, id) => [
|
|
1198
|
+
op,
|
|
1199
|
+
id,
|
|
1200
|
+
this.addresses.get(id),
|
|
1201
|
+
this.parents.get(id) ?? null,
|
|
1202
|
+
this.digests.get(id) ?? null,
|
|
1203
|
+
this.owners.get(id) ?? null
|
|
1204
|
+
];
|
|
1205
|
+
for (const id of this.changed) if (!this.addresses.has(id)) entries.push([
|
|
1206
|
+
0,
|
|
1207
|
+
id,
|
|
1208
|
+
0,
|
|
1209
|
+
null,
|
|
1210
|
+
null
|
|
1211
|
+
]);
|
|
1212
|
+
else if (!this.appended.has(id)) entries.push(entry(1, id));
|
|
1213
|
+
for (const id of this.appended) entries.push(entry(2, id));
|
|
1214
|
+
return entries;
|
|
1215
|
+
}
|
|
1216
|
+
/**
|
|
1217
|
+
* The changes of this persist() as a new index log file (written to a temporary file
|
|
1218
|
+
* and renamed: a file is complete or missing). Earlier log files are not touched.
|
|
1219
|
+
*/
|
|
1220
|
+
async writeLog() {
|
|
1221
|
+
const entries = this.logEntriesSince();
|
|
1222
|
+
const frame = {
|
|
1223
|
+
segments: this.segments.map(segmentRef),
|
|
1224
|
+
...this.frameMeta(),
|
|
1225
|
+
entries
|
|
1226
|
+
};
|
|
1227
|
+
const bytes = Buffer.from(indexCodec().pack(frame));
|
|
1228
|
+
const seq = ++this.logSeq;
|
|
1229
|
+
await writeAtomic(path.join(this.dir, `index-log-${String(seq).padStart(6, "0")}-${this.snapshotId}`), Buffer.concat([fileHead(LOG_MAGIC, FORMAT_VERSION, bytes.length), bytes]));
|
|
1230
|
+
this.logEntries += entries.length;
|
|
1231
|
+
}
|
|
1232
|
+
/**
|
|
1233
|
+
* A read-only view of the store's internal state, for inspection tools (e.g. a devtools panel).
|
|
1234
|
+
* Experimental: not covered by semver. Reading it changes nothing: it does not flush, encode or
|
|
1235
|
+
* use the node cache (`value()` reads a node without keeping it).
|
|
1236
|
+
*/
|
|
1237
|
+
inspect() {
|
|
1238
|
+
const segments = this.segments.map(({ id, base, length, size, live }) => ({
|
|
1239
|
+
id,
|
|
1240
|
+
base,
|
|
1241
|
+
length,
|
|
1242
|
+
size,
|
|
1243
|
+
live,
|
|
1244
|
+
current: this.current?.id === id
|
|
1245
|
+
}));
|
|
1246
|
+
return {
|
|
1247
|
+
dir: this.dir,
|
|
1248
|
+
readonly: this.readonly,
|
|
1249
|
+
formatVersion: FORMAT_VERSION,
|
|
1250
|
+
version: this.version,
|
|
1251
|
+
snapshotId: this.snapshotId ?? null,
|
|
1252
|
+
fileEnd: segments.reduce((n, s) => n + s.size, 0),
|
|
1253
|
+
garbage: segments.reduce((n, s) => n + s.size - s.live, 0),
|
|
1254
|
+
segments,
|
|
1255
|
+
pendingWrites: this.pending.size,
|
|
1256
|
+
changed: this.changed.size,
|
|
1257
|
+
dirty: this.dirty,
|
|
1258
|
+
logEntries: this.logEntries,
|
|
1259
|
+
logFiles: this.logSeq,
|
|
1260
|
+
structures: this.structures.length,
|
|
1261
|
+
types: this.types.slice(),
|
|
1262
|
+
cache: {
|
|
1263
|
+
size: this.cache.size,
|
|
1264
|
+
max: this.cache.max
|
|
1265
|
+
},
|
|
1266
|
+
ids: () => this.addresses.keys(),
|
|
1267
|
+
record: (id) => this.recordInfo(id),
|
|
1268
|
+
value: (id) => this.inspectValue(id)
|
|
1269
|
+
};
|
|
1270
|
+
}
|
|
1271
|
+
inspectValue(id) {
|
|
1272
|
+
const pending = this.pending.get(id);
|
|
1273
|
+
if (pending) {
|
|
1274
|
+
if (pending.node) return pending.node;
|
|
1275
|
+
if (pending.work) return pending.work;
|
|
1276
|
+
return this.codec.unpack(pending.data);
|
|
1277
|
+
}
|
|
1278
|
+
const address = this.addresses.get(id);
|
|
1279
|
+
if (address === void 0 || address === PENDING) return void 0;
|
|
1280
|
+
return this.cache.peek(id) ?? this.decode(address);
|
|
1281
|
+
}
|
|
1282
|
+
recordInfo(id) {
|
|
1283
|
+
const address = this.addresses.get(id);
|
|
1284
|
+
if (address === void 0) return void 0;
|
|
1285
|
+
const pending = this.pending.get(id);
|
|
1286
|
+
if (address === PENDING) return {
|
|
1287
|
+
offset: null,
|
|
1288
|
+
typeIndex: this.typeIndexes.get(pending.type) ?? null,
|
|
1289
|
+
file: null,
|
|
1290
|
+
fileOffset: null,
|
|
1291
|
+
size: null,
|
|
1292
|
+
header: null,
|
|
1293
|
+
pending: true
|
|
1294
|
+
};
|
|
1295
|
+
const offset = offsetOf(address);
|
|
1296
|
+
const segment = this.segments.find((s) => offset >= s.base && offset < s.base + s.length);
|
|
1297
|
+
let header = null;
|
|
1298
|
+
if (segment && offset + 20 <= segment.base + segment.length) header = { ...readHeader(this.readAt(offset, 20)) };
|
|
1299
|
+
return {
|
|
1300
|
+
offset,
|
|
1301
|
+
typeIndex: address % TYPE_SLOTS,
|
|
1302
|
+
file: segment ? `segment-${segment.id}` : null,
|
|
1303
|
+
fileOffset: segment ? offset - segment.base : null,
|
|
1304
|
+
size: header ? recordSize(header) : null,
|
|
1305
|
+
header,
|
|
1306
|
+
pending: pending !== void 0
|
|
1307
|
+
};
|
|
1308
|
+
}
|
|
1309
|
+
/** flushes buffered writes and closes the segment files */
|
|
1310
|
+
close() {
|
|
1311
|
+
if (!this.readonly) this.flush();
|
|
1312
|
+
this.closeFile();
|
|
1313
|
+
}
|
|
1314
|
+
};
|
|
1315
|
+
/**
|
|
1316
|
+
* The datastore factory for gatsby-config (the default; use it to pass options):
|
|
1317
|
+
*
|
|
1318
|
+
* ```ts
|
|
1319
|
+
* import { logFileDataStore } from "gatsby/node"
|
|
1320
|
+
* export default { datastore: logFileDataStore({ cacheSize: 20_000 }) }
|
|
1321
|
+
* ```
|
|
1322
|
+
*/
|
|
1323
|
+
function logFileDataStore(options = {}) {
|
|
1324
|
+
return ({ cacheDir }) => new LogFileDataStore({
|
|
1325
|
+
...options,
|
|
1326
|
+
cacheDir
|
|
1327
|
+
});
|
|
1328
|
+
}
|
|
1329
|
+
export { LogFileDataStore, logFileDataStore };
|