@agency-lang/memento 0.0.0-stage → 0.1.0

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.
Files changed (64) hide show
  1. package/README.md +64 -2
  2. package/dist/agency/embed.d.ts +22 -0
  3. package/dist/agency/embed.js +458 -0
  4. package/dist/agencyApi.d.ts +98 -0
  5. package/dist/agencyApi.js +237 -0
  6. package/dist/embed.d.ts +45 -0
  7. package/dist/embed.js +77 -0
  8. package/dist/engine/files/engine.d.ts +85 -0
  9. package/dist/engine/files/engine.js +284 -0
  10. package/dist/engine/files/lock.d.ts +18 -0
  11. package/dist/engine/files/lock.js +247 -0
  12. package/dist/engine/files/manifest.d.ts +43 -0
  13. package/dist/engine/files/manifest.js +111 -0
  14. package/dist/engine/files/safe-delete.d.ts +19 -0
  15. package/dist/engine/files/safe-delete.js +79 -0
  16. package/dist/engine/files/segments.d.ts +17 -0
  17. package/dist/engine/files/segments.js +128 -0
  18. package/dist/engine/memory/engine.d.ts +27 -0
  19. package/dist/engine/memory/engine.js +87 -0
  20. package/dist/engine/open.d.ts +7 -0
  21. package/dist/engine/open.js +28 -0
  22. package/dist/engine/shared/filter.d.ts +7 -0
  23. package/dist/engine/shared/filter.js +72 -0
  24. package/dist/engine/shared/keyword.d.ts +27 -0
  25. package/dist/engine/shared/keyword.js +92 -0
  26. package/dist/engine/shared/settings.d.ts +5 -0
  27. package/dist/engine/shared/settings.js +9 -0
  28. package/dist/engine/shared/state.d.ts +58 -0
  29. package/dist/engine/shared/state.js +275 -0
  30. package/dist/engine/shared/tokens.d.ts +15 -0
  31. package/dist/engine/shared/tokens.js +23 -0
  32. package/dist/engine/shared/vectors.d.ts +36 -0
  33. package/dist/engine/shared/vectors.js +70 -0
  34. package/dist/engine/types.d.ts +121 -0
  35. package/dist/engine/types.js +1 -0
  36. package/dist/files.d.ts +75 -0
  37. package/dist/files.js +190 -0
  38. package/dist/filter.d.ts +3 -0
  39. package/dist/filter.js +80 -0
  40. package/dist/fusion.d.ts +24 -0
  41. package/dist/fusion.js +26 -0
  42. package/dist/ids.d.ts +2 -0
  43. package/dist/ids.js +19 -0
  44. package/dist/index.d.ts +4 -0
  45. package/dist/index.js +3 -0
  46. package/dist/local.d.ts +36 -0
  47. package/dist/local.js +75 -0
  48. package/dist/memento.d.ts +151 -0
  49. package/dist/memento.js +470 -0
  50. package/dist/query.d.ts +50 -0
  51. package/dist/query.js +138 -0
  52. package/dist/rows.d.ts +17 -0
  53. package/dist/rows.js +90 -0
  54. package/dist/stem.d.ts +2 -0
  55. package/dist/stem.js +121 -0
  56. package/dist/types.d.ts +246 -0
  57. package/dist/types.js +3 -0
  58. package/dist/vectors.d.ts +2 -0
  59. package/dist/vectors.js +10 -0
  60. package/dist/windows.d.ts +44 -0
  61. package/dist/windows.js +77 -0
  62. package/index.agency +268 -0
  63. package/index.js +1803 -0
  64. package/package.json +55 -4
@@ -0,0 +1,284 @@
1
+ // FilesEngine: a store kept as files in a directory. In memory it is the same
2
+ // StoreState the memory engine uses; on disk it is a manifest and segments,
3
+ // one segment per write, replayed in order at open. The manifest's rename is
4
+ // the commit. docs/dev/engine.md explains the layout and the rules.
5
+ import { mkdir, readdir, stat } from "node:fs/promises";
6
+ import path from "node:path";
7
+ import { resolveUserPath } from "../../files.js";
8
+ import { copySettings, mergeSettings } from "../shared/settings.js";
9
+ import { StoreState } from "../shared/state.js";
10
+ import { withLock } from "./lock.js";
11
+ import { commitManifest, hasForeignFiles, MANIFEST_FILE, manifestStamp, readManifest, SCHEMA_VERSION, SEGMENTS_DIR } from "./manifest.js";
12
+ import { deleteSegment, readSegment, segmentBytes, segmentName, segmentNamesOnDisk, writeSegment } from "./segments.js";
13
+ /** Compaction runs when the dead records, replaced and removed, exceed this many times the live ones. */
14
+ const COMPACT_WHEN_DEAD_RATIO = 1;
15
+ /**
16
+ * Compaction also runs when the store has more segments than this, so a
17
+ * store that grows one write at a time stays quick to open. Each compaction
18
+ * rewrites the whole store, so a store that only grows pays a rewrite every
19
+ * MAX_SEGMENTS writes; that cost grows with the store, and is accepted at
20
+ * the sizes the files engine is for.
21
+ */
22
+ const MAX_SEGMENTS = 64;
23
+ /** How many times a read retries when a compaction removes a segment under it. */
24
+ const RELOAD_ATTEMPTS = 5;
25
+ let afterManifestRead;
26
+ /**
27
+ * Runs `hook` in every load, between reading the manifest and reading its
28
+ * segments, for the test of a compaction that lands in that gap.
29
+ * `undefined` removes it.
30
+ */
31
+ export function useAfterManifestRead(hook) {
32
+ afterManifestRead = hook;
33
+ }
34
+ /** Opens the directory, creating a missing one. Writes nothing inside it; `initialize` does, once the directory is known to be a store or empty. */
35
+ export async function openFilesEngine(storage) {
36
+ const dir = resolveUserPath(storage.path);
37
+ const existing = await stat(dir).catch(() => undefined);
38
+ if (existing !== undefined && !existing.isDirectory()) {
39
+ throw new Error(`store path ${storage.path} is not a directory`);
40
+ }
41
+ await mkdir(dir, { recursive: true });
42
+ return new FilesEngine(dir);
43
+ }
44
+ /** True when the directory holds a manifest, or other files, such as an earlier Memento's store, which open then rejects with a message. Creates nothing. */
45
+ export async function filesStoreExists(storage) {
46
+ const dir = resolveUserPath(storage.path);
47
+ const names = await readdir(dir).catch(() => []);
48
+ return names.includes(MANIFEST_FILE) || (await hasForeignFiles(dir));
49
+ }
50
+ /** The settings in the manifest, or undefined when the directory holds no store. Reads the manifest alone, and creates nothing. */
51
+ export async function filesStoreSettings(storage) {
52
+ return (await readManifest(resolveUserPath(storage.path)))?.settings;
53
+ }
54
+ export class FilesEngine {
55
+ kind = "files";
56
+ dir;
57
+ state = new StoreState();
58
+ loaded;
59
+ constructor(dir) {
60
+ this.dir = dir;
61
+ }
62
+ store() {
63
+ if (this.state === undefined) {
64
+ throw new Error("store is closed");
65
+ }
66
+ return this.state;
67
+ }
68
+ // Settings
69
+ /**
70
+ * A new directory gets a manifest with the defaults, written under the
71
+ * lock through the rename, so two processes creating the same store get
72
+ * one manifest and the loser reads what the winner wrote. An existing
73
+ * store is read without the lock.
74
+ */
75
+ async initialize(defaults) {
76
+ this.store();
77
+ if ((await readManifest(this.dir)) === undefined) {
78
+ await withLock(this.dir, async () => {
79
+ if ((await readManifest(this.dir)) === undefined) {
80
+ await mkdir(path.join(this.dir, SEGMENTS_DIR), { recursive: true });
81
+ await commitManifest(this.dir, { schemaVersion: SCHEMA_VERSION, settings: copySettings(defaults), generation: 1, writes: 0, segments: [] });
82
+ }
83
+ });
84
+ }
85
+ await this.sync();
86
+ return this.getSettings();
87
+ }
88
+ async getSettings() {
89
+ await this.sync();
90
+ return copySettings(this.current().manifest.settings);
91
+ }
92
+ async setSettings(patch) {
93
+ await withLock(this.dir, async () => {
94
+ await this.sync();
95
+ const { manifest } = this.current();
96
+ const settings = mergeSettings(manifest.settings, patch);
97
+ await this.commit({ ...manifest, settings, generation: manifest.generation + 1 }, []);
98
+ });
99
+ }
100
+ // Reading
101
+ async getDocsById(ids) {
102
+ await this.sync();
103
+ return this.store().getDocsById(ids);
104
+ }
105
+ async getWindows(ids) {
106
+ await this.sync();
107
+ return this.store().getWindows(ids);
108
+ }
109
+ async getDocumentCount() {
110
+ await this.sync();
111
+ return this.store().documentCount();
112
+ }
113
+ async getFileCount() {
114
+ await this.sync();
115
+ return this.store().fileCount();
116
+ }
117
+ async statFiles(paths) {
118
+ await this.sync();
119
+ return this.store().statFiles(paths);
120
+ }
121
+ /** The bytes of the live segments' files. A compaction under the stat makes it read the manifest again. */
122
+ async getSizeBytes() {
123
+ return this.withReload(async () => {
124
+ const sizes = await Promise.all(this.current().manifest.segments.map((name) => segmentBytes(this.dir, name)));
125
+ return sizes.reduce((sum, size) => sum + size, 0);
126
+ });
127
+ }
128
+ // Writing
129
+ /**
130
+ * Under the lock: catch up with other writers, validate the batch against
131
+ * the current state, write its segment, commit the manifest, and only
132
+ * then change memory. A failure before the commit leaves both as they
133
+ * were. A batch that changes nothing, such as a remove of ids the store
134
+ * does not hold, writes nothing.
135
+ */
136
+ async write(batch) {
137
+ await withLock(this.dir, async () => {
138
+ await this.sync();
139
+ const state = this.store();
140
+ const { manifest } = this.current();
141
+ const records = state.prepare(batch);
142
+ if (records.length === 0) {
143
+ return;
144
+ }
145
+ const name = segmentName(manifest.writes + 1);
146
+ await writeSegment(this.dir, name, records);
147
+ await this.commit({ ...manifest, writes: manifest.writes + 1, generation: manifest.generation + 1, segments: [...manifest.segments, name] }, records);
148
+ if (this.needsCompaction()) {
149
+ await this.compact();
150
+ }
151
+ });
152
+ }
153
+ /** Commits a manifest already backed by its segment files, then applies the records to memory. */
154
+ async commit(manifest, records) {
155
+ const stamp = await commitManifest(this.dir, manifest);
156
+ this.store().commit(records);
157
+ this.loaded = { manifest, stamp, replayed: (this.loaded?.replayed ?? 0) + records.length };
158
+ }
159
+ needsCompaction() {
160
+ const { manifest, replayed } = this.current();
161
+ const live = this.liveRecords();
162
+ return manifest.segments.length > MAX_SEGMENTS || replayed - live > COMPACT_WHEN_DEAD_RATIO * live;
163
+ }
164
+ /** One record per document, per document with windows, and per file: what a compacted segment holds. */
165
+ liveRecords() {
166
+ const state = this.store();
167
+ return state.documentCount() + Object.keys(state.windows).length + state.fileCount();
168
+ }
169
+ /**
170
+ * Rewrites the whole store as one segment and deletes the others. Runs
171
+ * under the write lock. Deletes only segment files the new manifest no
172
+ * longer names, inside the segments directory, and only files with a
173
+ * segment's name; a stray file such as .DS_Store is left alone. A
174
+ * segment file that is already gone is not an error.
175
+ */
176
+ async compact() {
177
+ const state = this.store();
178
+ const { manifest } = this.current();
179
+ const records = [
180
+ ...Object.values(state.files).map((file) => ({ kind: "file", file })),
181
+ ...Object.values(state.documents).map((document) => ({ kind: "document", document })),
182
+ ...Object.entries(state.windows).map(([id, windows]) => ({ kind: "windows", id, windows })),
183
+ ];
184
+ const name = segmentName(manifest.writes + 1);
185
+ await writeSegment(this.dir, name, records);
186
+ const compacted = { ...manifest, writes: manifest.writes + 1, generation: manifest.generation + 1, segments: [name] };
187
+ const stamp = await commitManifest(this.dir, compacted);
188
+ this.loaded = { manifest: compacted, stamp, replayed: records.length };
189
+ for (const old of await segmentNamesOnDisk(this.dir)) {
190
+ if (old !== name) {
191
+ deleteSegment(this.dir, old);
192
+ }
193
+ }
194
+ }
195
+ // Searching
196
+ async keywordSearch(terms, filter, limit) {
197
+ await this.sync();
198
+ return this.store().keywordSearch(terms, filter, limit);
199
+ }
200
+ async getNewest(filter, limit) {
201
+ await this.sync();
202
+ return this.store().getNewest(filter, limit);
203
+ }
204
+ async embeddingsSearch(query, filter, limit) {
205
+ await this.sync();
206
+ return this.store().embeddingsSearch(query, filter, limit);
207
+ }
208
+ // Loading
209
+ current() {
210
+ if (this.loaded === undefined) {
211
+ throw new Error("store is not initialized");
212
+ }
213
+ return this.loaded;
214
+ }
215
+ /**
216
+ * Catches up with the manifest on disk when another process changed it.
217
+ * The check is a stat: a commit renames a new file over the manifest, so
218
+ * its inode changes. When the segment list only grew, the new segments
219
+ * are replayed onto the state; otherwise the state is rebuilt. A segment
220
+ * a compaction removed under the load makes the load start again.
221
+ */
222
+ async sync() {
223
+ this.store();
224
+ const stamp = await manifestStamp(this.dir);
225
+ if (stamp === undefined) {
226
+ throw new Error(`store at ${this.dir} has no manifest; was it deleted?`);
227
+ }
228
+ if (this.loaded !== undefined && this.loaded.stamp.ino === stamp.ino && this.loaded.stamp.mtimeMs === stamp.mtimeMs) {
229
+ return;
230
+ }
231
+ await this.withReload(() => Promise.resolve());
232
+ }
233
+ /** Runs `fn` after a load, and again after a fresh load when a segment it read was compacted away under it. */
234
+ async withReload(fn) {
235
+ for (let attempt = 1;; attempt++) {
236
+ try {
237
+ if (attempt > 1 || this.loaded === undefined || !(await this.isCurrent())) {
238
+ await this.load();
239
+ }
240
+ return await fn();
241
+ }
242
+ catch (error) {
243
+ if (error.code !== "ENOENT" || attempt >= RELOAD_ATTEMPTS) {
244
+ throw error;
245
+ }
246
+ }
247
+ }
248
+ }
249
+ async isCurrent() {
250
+ const stamp = await manifestStamp(this.dir);
251
+ const { stamp: known } = this.current();
252
+ return stamp !== undefined && stamp.ino === known.ino && stamp.mtimeMs === known.mtimeMs;
253
+ }
254
+ async load() {
255
+ const stamp = await manifestStamp(this.dir);
256
+ const manifest = await readManifest(this.dir);
257
+ if (stamp === undefined || manifest === undefined) {
258
+ throw new Error(`store at ${this.dir} has no manifest; was it deleted?`);
259
+ }
260
+ await afterManifestRead?.();
261
+ const known = this.loaded?.manifest.segments ?? [];
262
+ const grewOnly = this.loaded !== undefined && manifest.segments.length >= known.length && known.every((name, i) => manifest.segments[i] === name);
263
+ const toRead = grewOnly ? manifest.segments.slice(known.length) : manifest.segments;
264
+ const state = grewOnly ? this.store() : new StoreState();
265
+ let replayed = grewOnly ? this.current().replayed : 0;
266
+ for (const name of toRead) {
267
+ const records = await readSegment(this.dir, name);
268
+ state.commit(records);
269
+ replayed += records.length;
270
+ }
271
+ state.settings = manifest.settings;
272
+ this.state = state;
273
+ this.loaded = { manifest, stamp, replayed };
274
+ }
275
+ // Lifecycle
276
+ async check() {
277
+ await this.sync();
278
+ this.store().check();
279
+ }
280
+ /** Lets the state go. Nothing is held open between calls, so there is nothing to flush. A second call does nothing. */
281
+ async close() {
282
+ this.state = undefined;
283
+ }
284
+ }
@@ -0,0 +1,18 @@
1
+ /** How long a writer waits for another process's write before failing. */
2
+ export declare const BUSY_TIMEOUT_MS = 5000;
3
+ /** What a lock file says: the pid in it, and its inode, so a takeover can tell the same file from a replacement. */
4
+ export type LockFile = {
5
+ pid: number | undefined;
6
+ ino: number;
7
+ };
8
+ export declare function lockPath(dir: string): string;
9
+ /**
10
+ * The guard a takeover of `file` holds while it moves the stale file it
11
+ * read. The name carries that reading, inode and pid, so the guard covers
12
+ * that one file and no other.
13
+ */
14
+ export declare function guardPath(file: string, stale: LockFile): string;
15
+ /** Runs `fn` holding the store's write lock, and releases it afterwards whatever happens. */
16
+ export declare function withLock<T>(dir: string, fn: () => Promise<T>): Promise<T>;
17
+ /** Takes over the lock of `dir` read as `stale`. Exported for the test of a taker whose reading is out of date. */
18
+ export declare function takeOverStaleLock(dir: string, stale: LockFile): Promise<void>;
@@ -0,0 +1,247 @@
1
+ // The write lock of a files store: a file that holds the writer's pid. One
2
+ // writer at a time; readers never take it.
3
+ import { link, open, rename, stat, writeFile } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { setTimeout as sleep } from "node:timers/promises";
6
+ import { LOCK_FILE } from "./manifest.js";
7
+ import { safeDeleteFileWithin } from "./safe-delete.js";
8
+ /** How long a writer waits for another process's write before failing. */
9
+ export const BUSY_TIMEOUT_MS = 5000;
10
+ /** How often a waiting writer looks again. */
11
+ const POLL_MS = 20;
12
+ /** What a guard's name adds to the name of the file it guards. */
13
+ const GUARD_SUFFIX = "takeover";
14
+ /**
15
+ * The lock files this process created and still holds, the lock and the
16
+ * guards of takeovers, by the directory's identity and the file's name,
17
+ * with the inode of each. A file naming this process that is not here was
18
+ * left by an earlier process that had the same pid, so it is stale. The
19
+ * identity is the directory's device and inode, so one directory under
20
+ * any two spellings, through a symlink, a firmlink or a bind mount, is one
21
+ * store.
22
+ */
23
+ const owned = Object.create(null);
24
+ export function lockPath(dir) {
25
+ return path.join(dir, LOCK_FILE);
26
+ }
27
+ /**
28
+ * The guard a takeover of `file` holds while it moves the stale file it
29
+ * read. The name carries that reading, inode and pid, so the guard covers
30
+ * that one file and no other.
31
+ */
32
+ export function guardPath(file, stale) {
33
+ return `${file}.${GUARD_SUFFIX}.${stale.ino}-${stale.pid ?? "empty"}`;
34
+ }
35
+ /** Runs `fn` holding the store's write lock, and releases it afterwards whatever happens. */
36
+ export async function withLock(dir, fn) {
37
+ const where = await lockDir(dir);
38
+ await acquire(where);
39
+ try {
40
+ return await fn();
41
+ }
42
+ finally {
43
+ await release(where, lockPath(dir));
44
+ }
45
+ }
46
+ /** Takes over the lock of `dir` read as `stale`. Exported for the test of a taker whose reading is out of date. */
47
+ export async function takeOverStaleLock(dir, stale) {
48
+ await takeOver(await lockDir(dir), lockPath(dir), stale);
49
+ }
50
+ async function lockDir(dir) {
51
+ const { dev, ino } = await stat(dir);
52
+ return { dir, id: `${dev}:${ino}` };
53
+ }
54
+ /**
55
+ * Takes the lock. The lock file appears with its pid already in it, through
56
+ * a hard link from a temporary file, so no reader ever sees an empty lock.
57
+ * While another process holds it, waits up to BUSY_TIMEOUT_MS and then
58
+ * rejects. A lock is stale when its pid is not running, when it is empty,
59
+ * or when it names this process while this process holds no lock on the
60
+ * directory, as after a restart that got the same pid. Age never makes a
61
+ * lock stale: a live writer may hold it longer than the timeout, during a
62
+ * compaction or while the machine sleeps.
63
+ */
64
+ async function acquire(where) {
65
+ const file = lockPath(where.dir);
66
+ const started = Date.now();
67
+ for (;;) {
68
+ if (await tryCreate(where, file)) {
69
+ return;
70
+ }
71
+ const current = await readLockFile(file);
72
+ // The timeout bounds every wait, including a stale lock another live process is taking over.
73
+ if (Date.now() - started >= BUSY_TIMEOUT_MS) {
74
+ throw new Error(`store at ${where.dir} is locked by process ${current?.pid ?? "unknown"}; waited ${BUSY_TIMEOUT_MS} ms`);
75
+ }
76
+ if (current === undefined) {
77
+ continue;
78
+ }
79
+ if (isStale(where, file, current)) {
80
+ await takeOver(where, file, current);
81
+ continue;
82
+ }
83
+ await sleep(POLL_MS);
84
+ }
85
+ }
86
+ function temporaryName(dir, what) {
87
+ return path.join(dir, `${LOCK_FILE}.${what}.${process.pid}.${Math.random().toString(36).slice(2)}`);
88
+ }
89
+ function ownedKey(where, file) {
90
+ return `${where.id}/${path.basename(file)}`;
91
+ }
92
+ /**
93
+ * Writes our pid to a temporary file and links it to `file`, which fails
94
+ * with EEXIST when the file exists. Records the new file in `owned` with no
95
+ * await between the link and the record; a waiter in this process that
96
+ * read the file in such a gap would take it for stale.
97
+ */
98
+ async function tryCreate(where, file) {
99
+ const temporary = temporaryName(where.dir, "new");
100
+ await writeFile(temporary, String(process.pid));
101
+ const { ino } = await stat(temporary);
102
+ try {
103
+ await link(temporary, file);
104
+ owned[ownedKey(where, file)] = ino;
105
+ return true;
106
+ }
107
+ catch (error) {
108
+ if (error.code === "EEXIST") {
109
+ return false;
110
+ }
111
+ throw error;
112
+ }
113
+ finally {
114
+ deleteWithin(where.dir, temporary);
115
+ }
116
+ }
117
+ /** The lock file as it is now, or undefined when it is gone. Read through one handle, so the pid and the inode are of one file. */
118
+ async function readLockFile(file) {
119
+ const handle = await open(file, "r").catch((error) => {
120
+ if (error.code === "ENOENT") {
121
+ return undefined;
122
+ }
123
+ throw error;
124
+ });
125
+ if (handle === undefined) {
126
+ return undefined;
127
+ }
128
+ try {
129
+ const [contents, info] = await Promise.all([handle.readFile("utf8"), handle.stat()]);
130
+ const pid = Number(contents.trim());
131
+ return { pid: contents.trim() !== "" && Number.isInteger(pid) && pid > 0 ? pid : undefined, ino: info.ino };
132
+ }
133
+ finally {
134
+ await handle.close();
135
+ }
136
+ }
137
+ /** Whether a lock file, the lock or a guard, is left by a process that no longer holds it. */
138
+ function isStale(where, file, lock) {
139
+ if (lock.pid === undefined) {
140
+ return true;
141
+ }
142
+ if (lock.pid === process.pid) {
143
+ return owned[ownedKey(where, file)] !== lock.ino;
144
+ }
145
+ return !isRunning(lock.pid);
146
+ }
147
+ /** True unless the process is gone. A process this user may not signal counts as running. */
148
+ function isRunning(pid) {
149
+ try {
150
+ process.kill(pid, 0);
151
+ return true;
152
+ }
153
+ catch (error) {
154
+ return error.code !== "ESRCH";
155
+ }
156
+ }
157
+ /**
158
+ * Moves a stale file aside: the lock, or the guard of a takeover whose
159
+ * process is gone. Only the holder of the file's guard moves it, and the
160
+ * guard is named after the stale reading. Holding it, the file is read
161
+ * again and moved only while it is still that stale file. A taker whose
162
+ * reading is out of date, because another taker already moved the file and
163
+ * deleted the guard, creates the guard afresh, finds a different file, and
164
+ * leaves it. A guard whose process is gone is stale in turn and is taken
165
+ * over the same way, under a guard of its own.
166
+ */
167
+ async function takeOver(where, file, stale) {
168
+ const guard = guardPath(file, stale);
169
+ if (!(await tryCreate(where, guard))) {
170
+ const holder = await readLockFile(guard);
171
+ if (holder !== undefined && isStale(where, guard, holder)) {
172
+ await takeOver(where, guard, holder);
173
+ }
174
+ else {
175
+ await sleep(POLL_MS);
176
+ }
177
+ return;
178
+ }
179
+ try {
180
+ const current = await readLockFile(file);
181
+ if (current !== undefined && isSameLock(current, stale) && isStale(where, file, current)) {
182
+ await moveAside(where.dir, file, stale);
183
+ }
184
+ }
185
+ finally {
186
+ await release(where, guard);
187
+ }
188
+ }
189
+ /**
190
+ * Whether two readings are of one lock file. The inode alone is not enough:
191
+ * Linux hands a new file the inode a deleted one just had, so a live lock
192
+ * created after the stale one was deleted can carry the stale inode. The
193
+ * pid tells them apart.
194
+ */
195
+ function isSameLock(a, b) {
196
+ return a.ino === b.ino && a.pid === b.pid;
197
+ }
198
+ /**
199
+ * Renames `file` to a unique name and deletes it. The guard makes it the
200
+ * stale file that was read; when it is not, it goes back without replacing
201
+ * anything that appeared since, and the takeover fails loudly.
202
+ */
203
+ async function moveAside(dir, file, expected) {
204
+ const moved = temporaryName(dir, "stale");
205
+ try {
206
+ await rename(file, moved);
207
+ }
208
+ catch (error) {
209
+ if (error.code === "ENOENT") {
210
+ return;
211
+ }
212
+ throw error;
213
+ }
214
+ const taken = await readLockFile(moved);
215
+ if (taken !== undefined && !isSameLock(taken, expected)) {
216
+ await link(moved, file).catch((error) => {
217
+ if (error.code !== "EEXIST") {
218
+ throw error;
219
+ }
220
+ });
221
+ deleteWithin(dir, moved);
222
+ throw new Error(`a takeover at ${file} moved a lock that was not the stale one, and put it back`);
223
+ }
224
+ deleteWithin(dir, moved);
225
+ }
226
+ /**
227
+ * Deletes a lock file this process created, the lock or a guard, when it is
228
+ * still that file, by inode. A file that was taken over is left to its
229
+ * taker. The record in `owned` goes last: while it stands, a waiter in this
230
+ * process sees a live file, not a stale one, and does not take it over
231
+ * during the read here.
232
+ */
233
+ async function release(where, file) {
234
+ const key = ownedKey(where, file);
235
+ const ino = owned[key];
236
+ const current = await readLockFile(file);
237
+ if (ino !== undefined && current !== undefined && current.ino === ino) {
238
+ deleteWithin(where.dir, file);
239
+ }
240
+ delete owned[key];
241
+ }
242
+ function deleteWithin(dir, file) {
243
+ const result = safeDeleteFileWithin(dir, file);
244
+ if (!result.success && !result.message?.includes("does not exist")) {
245
+ throw new Error(result.message);
246
+ }
247
+ }
@@ -0,0 +1,43 @@
1
+ import type { StoreSettings } from "../types.ts";
2
+ export declare const MANIFEST_FILE = "manifest.json";
3
+ export declare const SEGMENTS_DIR = "segments";
4
+ export declare const LOCK_FILE = "lock";
5
+ /** The files engine's layout version, checked before anything else is read. */
6
+ export declare const SCHEMA_VERSION = 1;
7
+ export type Manifest = {
8
+ schemaVersion: number;
9
+ settings: StoreSettings;
10
+ /** Grows by one on every commit. Readers compare it to what they loaded. */
11
+ generation: number;
12
+ /** Grows by one on every write, and names its segment. Never reused, even after a compaction. */
13
+ writes: number;
14
+ /** The live segments, oldest first. */
15
+ segments: string[];
16
+ };
17
+ /** What a reader keeps to tell whether the manifest changed: the file's inode and modification time. A rename changes the inode. */
18
+ export type ManifestStamp = {
19
+ ino: number;
20
+ mtimeMs: number;
21
+ };
22
+ export declare function manifestPath(dir: string): string;
23
+ /** The manifest, or undefined when the directory has none. Rejects another layout version, and a directory holding other files. */
24
+ export declare function readManifest(dir: string): Promise<Manifest | undefined>;
25
+ /** True when the directory holds files that are not a files store's: a store built by an earlier Memento, or someone's own directory. */
26
+ export declare function hasForeignFiles(dir: string): Promise<boolean>;
27
+ export declare function checkSchemaVersion(dir: string, found: number): void;
28
+ /** The manifest file's stamp, or undefined when there is none. */
29
+ export declare function manifestStamp(dir: string): Promise<ManifestStamp | undefined>;
30
+ /**
31
+ * The commit: writes the manifest to a temporary name, syncs it, renames it
32
+ * over the live one, and syncs the directory so the rename is durable. The
33
+ * caller has synced the segment files first.
34
+ */
35
+ export declare function commitManifest(dir: string, manifest: Manifest): Promise<ManifestStamp>;
36
+ /** Writes a file and waits for its bytes to reach the disk. */
37
+ export declare function writeSynced(file: string, contents: string | Uint8Array): Promise<void>;
38
+ /**
39
+ * Syncs a directory, so renames and new names in it are durable. Some file
40
+ * systems refuse to sync a directory handle; the rename itself is still
41
+ * atomic there, so that refusal is not an error for the store.
42
+ */
43
+ export declare function syncDirectory(dir: string): Promise<void>;