@unieai/rabi-storage-json 0.0.0-stage → 0.2.1-rc.3
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/LICENSE +21 -0
- package/README.md +7 -2
- package/lib/index.js +610 -0
- package/lib/types/atomic.d.ts +20 -0
- package/lib/types/format.d.ts +54 -0
- package/lib/types/index.d.ts +44 -0
- package/lib/types/per-record-unit.d.ts +82 -0
- package/lib/types/single-unit.d.ts +21 -0
- package/locale/en.json +5 -0
- package/locale/zh.json +6 -0
- package/package.json +32 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DeepSeek
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @unieai/rabi-storage-json
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
JSON file KV storage backend for the Rabi Harness storage hub
|
|
4
|
+
|
|
5
|
+
Part of Rabi, the agent harness UnieAI Code runs on. Installed as a dependency of `@unieai/rabi`;
|
|
6
|
+
not meant to be used on its own.
|
|
7
|
+
|
|
8
|
+
See LICENSE for the license and copyright of this package.
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,610 @@
|
|
|
1
|
+
import { mkdir, open, readFile, readdir, rename, rm } from "node:fs/promises";
|
|
2
|
+
import z from "@unieai/schemastery";
|
|
3
|
+
import { StorageError, UNIT_NAME_RE, storageBackendServiceKey } from "@unieai/rabi-storage";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
//#region lib/types/atomic.js
|
|
7
|
+
/**
|
|
8
|
+
* Atomic whole-file replacement for the JSON backend.
|
|
9
|
+
*
|
|
10
|
+
* Publish protocol: write a same-directory temp file, fsync it, then
|
|
11
|
+
* `rename()` over the target. Rename is an atomic replace on POSIX and on
|
|
12
|
+
* Windows (libuv maps it to `MoveFileExW(..., MOVEFILE_REPLACE_EXISTING)`),
|
|
13
|
+
* and replacement is the intended semantic here — unlike the session-log
|
|
14
|
+
* backend's link()+unlink() no-clobber protocol, a unit file has exactly one
|
|
15
|
+
* writer per process and last-write-wins is correct. After the rename the
|
|
16
|
+
* parent directory is fsynced on POSIX so the new entry is crash-durable.
|
|
17
|
+
* @module @unieai/rabi-storage-json/src/atomic
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
* Durably replace `path` with `data`.
|
|
21
|
+
* @param path - Absolute target file path.
|
|
22
|
+
* @param data - Full new file content.
|
|
23
|
+
* @returns resolution after the replacement is crash-durable.
|
|
24
|
+
*/
|
|
25
|
+
async function writeAtomic(path, data) {
|
|
26
|
+
const tmp = join(dirname(path), `.${randomUUID()}.tmp`);
|
|
27
|
+
try {
|
|
28
|
+
const handle = await open(tmp, "wx", 384);
|
|
29
|
+
try {
|
|
30
|
+
await handle.writeFile(data, "utf8");
|
|
31
|
+
await handle.sync();
|
|
32
|
+
} finally {
|
|
33
|
+
await handle.close();
|
|
34
|
+
}
|
|
35
|
+
await rename(tmp, path);
|
|
36
|
+
await fsyncDirectory(dirname(path));
|
|
37
|
+
} catch (error) {
|
|
38
|
+
await rm(tmp, { force: true });
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** fsync a POSIX directory so a just-renamed entry is crash-durable. */
|
|
43
|
+
/* v8 ignore start -- Windows rejects O_RDONLY directory opens; POSIX coverage exercises this. */
|
|
44
|
+
async function fsyncDirectory(path) {
|
|
45
|
+
if (process.platform === "win32") return;
|
|
46
|
+
const handle = await open(path, "r");
|
|
47
|
+
try {
|
|
48
|
+
await handle.sync();
|
|
49
|
+
} finally {
|
|
50
|
+
await handle.close();
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/* v8 ignore stop */
|
|
54
|
+
//#endregion
|
|
55
|
+
//#region lib/types/format.js
|
|
56
|
+
/**
|
|
57
|
+
* On-disk JSON unit format: the file is always the current net state, kept
|
|
58
|
+
* human-readable (pretty-printed, stable key order from insertion) — that
|
|
59
|
+
* legibility is this backend's reason to exist. `single`-layout units are
|
|
60
|
+
* one document with a unit header; `per-record`-layout units are a directory
|
|
61
|
+
* with one version-stamped document per record (`<table>/<key>.json`) plus a
|
|
62
|
+
* `global.json` for the global slot, so a write rewrites one record instead
|
|
63
|
+
* of the whole unit.
|
|
64
|
+
* @module @unieai/rabi-storage-json/src/format
|
|
65
|
+
*/
|
|
66
|
+
/**
|
|
67
|
+
* Serialize a unit state to file content.
|
|
68
|
+
* @param name - Unit name, stamped into the header.
|
|
69
|
+
* @param state - Authoritative in-memory state.
|
|
70
|
+
* @returns pretty-printed JSON document with a trailing newline.
|
|
71
|
+
*/
|
|
72
|
+
function serialize(name, state) {
|
|
73
|
+
const tables = {};
|
|
74
|
+
for (const [table, records] of state.tables) tables[table] = Object.fromEntries(records);
|
|
75
|
+
const document = {
|
|
76
|
+
unit: {
|
|
77
|
+
name,
|
|
78
|
+
version: state.version
|
|
79
|
+
},
|
|
80
|
+
global: state.global,
|
|
81
|
+
tables
|
|
82
|
+
};
|
|
83
|
+
return `${JSON.stringify(document, null, 2)}\n`;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Parse file content into unit state, validating shape and version.
|
|
87
|
+
* @param text - Raw file content.
|
|
88
|
+
* @param descriptor - Expected identity; version mismatch rejects.
|
|
89
|
+
* @returns the parsed state.
|
|
90
|
+
*/
|
|
91
|
+
function parse(text, descriptor) {
|
|
92
|
+
let document;
|
|
93
|
+
try {
|
|
94
|
+
document = JSON.parse(text);
|
|
95
|
+
} catch (error) {
|
|
96
|
+
throw new StorageError("malformed-medium", `unit '${descriptor.name}': file is not valid JSON`, { cause: error });
|
|
97
|
+
}
|
|
98
|
+
if (typeof document !== "object" || document === null) throw new StorageError("malformed-medium", `unit '${descriptor.name}': file is not a JSON object`);
|
|
99
|
+
const { unit, global: globalValue, tables } = document;
|
|
100
|
+
if (typeof unit !== "object" || unit === null || unit["name"] !== descriptor.name || typeof unit["version"] !== "number") throw new StorageError("malformed-medium", `unit '${descriptor.name}': missing or foreign unit header`);
|
|
101
|
+
const version = unit["version"];
|
|
102
|
+
if (version !== descriptor.version) throw new StorageError("version-mismatch", `unit '${descriptor.name}': stored version ${version} != expected ${descriptor.version}`);
|
|
103
|
+
if (typeof tables !== "object" || tables === null || Array.isArray(tables)) throw new StorageError("malformed-medium", `unit '${descriptor.name}': tables is not an object`);
|
|
104
|
+
const state = {
|
|
105
|
+
version,
|
|
106
|
+
global: globalValue ?? null,
|
|
107
|
+
tables: /* @__PURE__ */ new Map()
|
|
108
|
+
};
|
|
109
|
+
for (const table of descriptor.tables) {
|
|
110
|
+
const records = tables[table];
|
|
111
|
+
if (records === void 0) {
|
|
112
|
+
state.tables.set(table, /* @__PURE__ */ new Map());
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (typeof records !== "object" || records === null || Array.isArray(records)) throw new StorageError("malformed-medium", `unit '${descriptor.name}': table '${table}' is not an object`);
|
|
116
|
+
state.tables.set(table, new Map(Object.entries(records)));
|
|
117
|
+
}
|
|
118
|
+
return state;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Serialize one per-record document: the unit's version stamp plus the
|
|
122
|
+
* record value, pretty-printed like the whole-unit document.
|
|
123
|
+
* @param version - Unit format version, stamped into the header.
|
|
124
|
+
* @param value - The record value (or the global singleton value).
|
|
125
|
+
* @returns pretty-printed JSON document with a trailing newline.
|
|
126
|
+
*/
|
|
127
|
+
function serializeRecord(version, value) {
|
|
128
|
+
return `${JSON.stringify({
|
|
129
|
+
version,
|
|
130
|
+
record: value
|
|
131
|
+
}, null, 2)}\n`;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Parse one per-record document, validating its version stamp. A document
|
|
135
|
+
* that is malformed or stamped with an unaccepted version is FOREIGN and
|
|
136
|
+
* reads as absent — the per-record contract: one bad or stale record file
|
|
137
|
+
* must not brick the whole unit, and an unaccepted version stamp discards the
|
|
138
|
+
* record instead of migrating it (the whole-unit format rejects instead,
|
|
139
|
+
* because there is exactly one document).
|
|
140
|
+
* @param text - Raw per-record document content.
|
|
141
|
+
* @param versions - Accepted unit versions (the current one plus the
|
|
142
|
+
* descriptor's compatibleVersions); any other stamp discards the
|
|
143
|
+
* document.
|
|
144
|
+
* @returns the record value, or `undefined` for a foreign document.
|
|
145
|
+
*/
|
|
146
|
+
function parseRecord(text, versions) {
|
|
147
|
+
let document;
|
|
148
|
+
try {
|
|
149
|
+
document = JSON.parse(text);
|
|
150
|
+
} catch {
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
if (typeof document !== "object" || document === null) return void 0;
|
|
154
|
+
const { version: stamped, record } = document;
|
|
155
|
+
if (typeof stamped !== "number" || !versions.includes(stamped)) return void 0;
|
|
156
|
+
return record;
|
|
157
|
+
}
|
|
158
|
+
//#endregion
|
|
159
|
+
//#region lib/types/single-unit.js
|
|
160
|
+
/**
|
|
161
|
+
* One opened JSON unit in `single` layout: the whole unit is one document at
|
|
162
|
+
* `<root>/<name>.json`. The in-memory state is authoritative; every write
|
|
163
|
+
* primitive mutates it and republishes the whole file atomically. Writes are
|
|
164
|
+
* NOT queued here — per the backend contract, write ordering belongs to the
|
|
165
|
+
* caller (the domain layer's write chain); this unit only guarantees that
|
|
166
|
+
* each single call publishes a complete, durable file. The `per-record`
|
|
167
|
+
* layout is a separate unit class in `per-record-unit.ts`.
|
|
168
|
+
* @module @unieai/rabi-storage-json/src/single-unit
|
|
169
|
+
*/
|
|
170
|
+
/**
|
|
171
|
+
* Open (load or lazily create) one `single`-layout unit under `root`: the
|
|
172
|
+
* unit file is `<root>/<name>.json`.
|
|
173
|
+
* @param descriptor - Static identity and shape of the unit.
|
|
174
|
+
* @param root - Absolute backend root directory.
|
|
175
|
+
* @param onClose - Backend callback releasing the unit's open-slot.
|
|
176
|
+
* @returns the opened unit.
|
|
177
|
+
*/
|
|
178
|
+
async function openSingleUnit(descriptor, root, onClose) {
|
|
179
|
+
const path = join(root, `${descriptor.name}.json`);
|
|
180
|
+
let text;
|
|
181
|
+
try {
|
|
182
|
+
text = await readFile(path, "utf8");
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (error.code !== "ENOENT") throw error;
|
|
185
|
+
}
|
|
186
|
+
return new SingleJsonUnit(descriptor, path, text === void 0 ? {
|
|
187
|
+
version: descriptor.version,
|
|
188
|
+
global: null,
|
|
189
|
+
tables: new Map(descriptor.tables.map((table) => [table, /* @__PURE__ */ new Map()]))
|
|
190
|
+
} : parse(text, descriptor), onClose);
|
|
191
|
+
}
|
|
192
|
+
var SingleJsonUnit = class {
|
|
193
|
+
descriptor;
|
|
194
|
+
path;
|
|
195
|
+
state;
|
|
196
|
+
onClose;
|
|
197
|
+
closed = false;
|
|
198
|
+
/** In-flight publishes; close() drains them before releasing the unit. */
|
|
199
|
+
inFlight = /* @__PURE__ */ new Set();
|
|
200
|
+
constructor(descriptor, path, state, onClose) {
|
|
201
|
+
this.descriptor = descriptor;
|
|
202
|
+
this.path = path;
|
|
203
|
+
this.state = state;
|
|
204
|
+
this.onClose = onClose;
|
|
205
|
+
}
|
|
206
|
+
async loadAll() {
|
|
207
|
+
this.assertOpen();
|
|
208
|
+
const tables = {};
|
|
209
|
+
for (const [table, records] of this.state.tables) tables[table] = Object.fromEntries(records);
|
|
210
|
+
return {
|
|
211
|
+
tables,
|
|
212
|
+
global: this.state.global
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
async putRecord(table, key, value) {
|
|
216
|
+
this.assertOpen();
|
|
217
|
+
const records = this.records(table);
|
|
218
|
+
const hadKey = records.has(key);
|
|
219
|
+
const previous = records.get(key);
|
|
220
|
+
records.set(key, value);
|
|
221
|
+
await this.publish().catch((error) => {
|
|
222
|
+
if (hadKey) records.set(key, previous);
|
|
223
|
+
else records.delete(key);
|
|
224
|
+
throw error;
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
async deleteRecord(table, key) {
|
|
228
|
+
this.assertOpen();
|
|
229
|
+
const records = this.records(table);
|
|
230
|
+
if (!records.has(key)) return;
|
|
231
|
+
const previous = records.get(key);
|
|
232
|
+
records.delete(key);
|
|
233
|
+
await this.publish().catch((error) => {
|
|
234
|
+
records.set(key, previous);
|
|
235
|
+
throw error;
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
async setGlobal(value) {
|
|
239
|
+
this.assertOpen();
|
|
240
|
+
if (!this.descriptor.hasGlobal) throw new Error(`unit '${this.descriptor.name}' does not declare a global slot`);
|
|
241
|
+
const previous = this.state.global;
|
|
242
|
+
this.state.global = value;
|
|
243
|
+
await this.publish().catch((error) => {
|
|
244
|
+
this.state.global = previous;
|
|
245
|
+
throw error;
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
async close() {
|
|
249
|
+
if (this.closed) {
|
|
250
|
+
await Promise.allSettled(this.inFlight);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
this.closed = true;
|
|
254
|
+
await Promise.allSettled(this.inFlight);
|
|
255
|
+
this.onClose();
|
|
256
|
+
}
|
|
257
|
+
assertOpen() {
|
|
258
|
+
if (this.closed) throw new StorageError("closed", `unit '${this.descriptor.name}' is closed`);
|
|
259
|
+
}
|
|
260
|
+
records(table) {
|
|
261
|
+
const records = this.state.tables.get(table);
|
|
262
|
+
if (!records) throw new Error(`unit '${this.descriptor.name}' does not declare table '${table}'`);
|
|
263
|
+
return records;
|
|
264
|
+
}
|
|
265
|
+
publish() {
|
|
266
|
+
const write = writeAtomic(this.path, serialize(this.descriptor.name, this.state));
|
|
267
|
+
this.inFlight.add(write);
|
|
268
|
+
write.catch(() => {}).finally(() => this.inFlight.delete(write));
|
|
269
|
+
return write;
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
//#endregion
|
|
273
|
+
//#region lib/types/per-record-unit.js
|
|
274
|
+
/**
|
|
275
|
+
* One opened JSON unit in `per-record` layout: the unit is a directory at
|
|
276
|
+
* `dir`, holding one document per record under `<dir>/<table>/<key>.json`
|
|
277
|
+
* plus `global.json` for the global slot. The directory is the state — this
|
|
278
|
+
* unit holds NO in-memory state of its own: `loadAll` re-reads the tree and
|
|
279
|
+
* every write is one durable file operation. The domain layer owns the live
|
|
280
|
+
* in-memory tables (seeded by the open-time `loadAll`) and serializes writes
|
|
281
|
+
* through its write chain, so this unit never mutates memory and needs no
|
|
282
|
+
* rollback — a failed write simply leaves both the file and the domain's
|
|
283
|
+
* memory unchanged.
|
|
284
|
+
*
|
|
285
|
+
* Per-record contract: a record document that is malformed or stamped with a
|
|
286
|
+
* version outside the accepted set (the descriptor's current version plus
|
|
287
|
+
* its `compatibleVersions`) reads as an absent record — one bad or stale
|
|
288
|
+
* file never bricks the whole unit, and an unaccepted version stamp discards
|
|
289
|
+
* the record instead of migrating it. Record keys become path segments, so
|
|
290
|
+
* they must be path-safe (`[a-zA-Z0-9_-]+`); an unsafe key rejects at write.
|
|
291
|
+
*
|
|
292
|
+
* Legacy bootstrap: when the new tree has no document path, a legacy
|
|
293
|
+
* whole-unit file `<root>/<name>.json` (the pre-per-record layout) seeds
|
|
294
|
+
* per-record documents, provided its stored unit version is in the accepted
|
|
295
|
+
* set — a legacy file stamped with any other version is left alone and reads
|
|
296
|
+
* as the empty unit. Any new document path, including one whose contents are
|
|
297
|
+
* unreadable or stale, suppresses the bootstrap for the whole unit. The
|
|
298
|
+
* legacy file is never changed or deleted.
|
|
299
|
+
* @module @unieai/rabi-storage-json/src/per-record-unit
|
|
300
|
+
*/
|
|
301
|
+
/** Keys become path segments in this layout; this set is path-safe on every OS. */
|
|
302
|
+
const SAFE_KEY_RE = /^[a-zA-Z0-9_-]+$/;
|
|
303
|
+
/**
|
|
304
|
+
* Open one `per-record`-layout unit under `root`: the unit directory is
|
|
305
|
+
* `<root>/<name>/`. Loads lazily on the first `loadAll` — this unit holds no
|
|
306
|
+
* state, so opening touches nothing on the medium.
|
|
307
|
+
* @param descriptor - Static identity and shape of the unit.
|
|
308
|
+
* @param root - Absolute backend root directory.
|
|
309
|
+
* @param onClose - Backend callback releasing the unit's open-slot.
|
|
310
|
+
* @returns the opened unit.
|
|
311
|
+
*/
|
|
312
|
+
async function openPerRecordUnit(descriptor, root, onClose) {
|
|
313
|
+
return new PerRecordJsonUnit(descriptor, join(root, descriptor.name), onClose);
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Read every record document under the unit directory: each declared table's
|
|
317
|
+
* `<key>.json` files plus `global.json`. A missing directory is the empty
|
|
318
|
+
* unit (materialization defers to the first write); a foreign document
|
|
319
|
+
* (missing, malformed, or stamped with an unaccepted version) reads as an absent
|
|
320
|
+
* record, per the per-record contract.
|
|
321
|
+
* @param descriptor - Static identity and shape of the unit.
|
|
322
|
+
* @param dir - Absolute unit directory path.
|
|
323
|
+
* @returns the authoritative state reconstructed from the tree.
|
|
324
|
+
*/
|
|
325
|
+
async function loadPerRecordState(descriptor, dir) {
|
|
326
|
+
const versions = acceptedStamps(descriptor);
|
|
327
|
+
const state = {
|
|
328
|
+
version: descriptor.version,
|
|
329
|
+
global: null,
|
|
330
|
+
tables: new Map(descriptor.tables.map((table) => [table, /* @__PURE__ */ new Map()]))
|
|
331
|
+
};
|
|
332
|
+
let entries;
|
|
333
|
+
try {
|
|
334
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
335
|
+
} catch (error) {
|
|
336
|
+
if (error.code !== "ENOENT") throw error;
|
|
337
|
+
}
|
|
338
|
+
if (!(entries === void 0 ? false : (await Promise.all(entries.map(async (entry) => {
|
|
339
|
+
if (entry.isDirectory()) {
|
|
340
|
+
const records = state.tables.get(entry.name);
|
|
341
|
+
if (records !== void 0) return loadTableRecords(records, versions, join(dir, entry.name));
|
|
342
|
+
}
|
|
343
|
+
if (entry.name === "global.json" && descriptor.hasGlobal) {
|
|
344
|
+
const global = await readRecord(join(dir, entry.name), versions);
|
|
345
|
+
if (global !== void 0) state.global = global;
|
|
346
|
+
return true;
|
|
347
|
+
}
|
|
348
|
+
return false;
|
|
349
|
+
}))).some(Boolean))) await bootstrapLegacyUnit(descriptor, dir, state);
|
|
350
|
+
return state;
|
|
351
|
+
}
|
|
352
|
+
/** The version stamps this unit reads as its own: current plus declared compatible versions. */
|
|
353
|
+
function acceptedStamps(descriptor) {
|
|
354
|
+
return [descriptor.version, ...descriptor.compatibleVersions ?? []];
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Bootstrap an empty per-record tree from a legacy whole-unit file
|
|
358
|
+
* (`<root>/<name>.json`, the pre-per-record layout). Every declared-table
|
|
359
|
+
* record is copied into a current-version document, while the legacy file is
|
|
360
|
+
* retained unchanged. A missing, foreign (another unit's name), malformed,
|
|
361
|
+
* or non-unit legacy file is left alone, and so is one whose stored unit
|
|
362
|
+
* version is outside the accepted set — migrating records the owner never
|
|
363
|
+
* vouched for would stamp them with the current version and turn a
|
|
364
|
+
* discardable stale cache into schema failures at the domain layer. Other
|
|
365
|
+
* read failures propagate.
|
|
366
|
+
* @param descriptor - Static identity and shape of the unit.
|
|
367
|
+
* @param dir - The per-record unit directory (`<root>/<name>`).
|
|
368
|
+
* @param state - The empty tree state; bootstrapped records are added.
|
|
369
|
+
*/
|
|
370
|
+
async function bootstrapLegacyUnit(descriptor, dir, state) {
|
|
371
|
+
const legacyPath = join(dirname(dir), `${descriptor.name}.json`);
|
|
372
|
+
let text;
|
|
373
|
+
try {
|
|
374
|
+
text = await readFile(legacyPath, "utf8");
|
|
375
|
+
} catch (error) {
|
|
376
|
+
if (error.code !== "ENOENT") throw error;
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
let document;
|
|
380
|
+
try {
|
|
381
|
+
document = JSON.parse(text);
|
|
382
|
+
} catch {
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
if (document.unit?.name !== descriptor.name) return;
|
|
386
|
+
const stamped = document.unit.version;
|
|
387
|
+
if (typeof stamped !== "number" || !acceptedStamps(descriptor).includes(stamped)) return;
|
|
388
|
+
const tables = document.tables;
|
|
389
|
+
if (typeof tables !== "object" || tables === null) return;
|
|
390
|
+
const recordsByTable = tables;
|
|
391
|
+
for (const [table, records] of Object.entries(recordsByTable)) {
|
|
392
|
+
const target = state.tables.get(table);
|
|
393
|
+
if (target === void 0) continue;
|
|
394
|
+
for (const [key, value] of Object.entries(records)) {
|
|
395
|
+
const path = join(dir, table, `${key}.json`);
|
|
396
|
+
await mkdir(dirname(path), {
|
|
397
|
+
recursive: true,
|
|
398
|
+
mode: 448
|
|
399
|
+
});
|
|
400
|
+
await writeAtomic(path, serializeRecord(descriptor.version, value));
|
|
401
|
+
target.set(key, value);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Read one declared table's record documents into `records`.
|
|
407
|
+
* @returns whether the directory contains any `.json` document path,
|
|
408
|
+
* independently of key safety, readability, or stored version.
|
|
409
|
+
*/
|
|
410
|
+
async function loadTableRecords(records, versions, dir) {
|
|
411
|
+
const files = await readdir(dir, { withFileTypes: true });
|
|
412
|
+
const hasDocuments = files.some((file) => file.name.endsWith(".json"));
|
|
413
|
+
const loaded = await Promise.all(files.map(async (file) => {
|
|
414
|
+
if (!file.name.endsWith(".json")) return;
|
|
415
|
+
const key = file.name.slice(0, -5);
|
|
416
|
+
if (!SAFE_KEY_RE.test(key)) return;
|
|
417
|
+
const record = await readRecord(join(dir, file.name), versions);
|
|
418
|
+
if (record !== void 0) return [key, record];
|
|
419
|
+
}));
|
|
420
|
+
for (const record of loaded) if (record !== void 0) records.set(...record);
|
|
421
|
+
return hasDocuments;
|
|
422
|
+
}
|
|
423
|
+
/** Read one record document; a foreign (unreadable or stale) one reads as absent. */
|
|
424
|
+
async function readRecord(path, versions) {
|
|
425
|
+
try {
|
|
426
|
+
return parseRecord(await readFile(path, "utf8"), versions);
|
|
427
|
+
} catch {
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* One opened `per-record`-layout unit. Stateless by design: the directory is
|
|
433
|
+
* the medium, the domain layer owns the live memory, and each method here is
|
|
434
|
+
* a single durable file operation. Write ordering belongs to the caller (the
|
|
435
|
+
* domain layer's write chain), exactly like the `single`-layout unit.
|
|
436
|
+
*/
|
|
437
|
+
var PerRecordJsonUnit = class {
|
|
438
|
+
descriptor;
|
|
439
|
+
dir;
|
|
440
|
+
onClose;
|
|
441
|
+
closed = false;
|
|
442
|
+
/** In-flight durable writes; close() drains them before releasing the unit. */
|
|
443
|
+
inFlight = /* @__PURE__ */ new Set();
|
|
444
|
+
constructor(descriptor, dir, onClose) {
|
|
445
|
+
this.descriptor = descriptor;
|
|
446
|
+
this.dir = dir;
|
|
447
|
+
this.onClose = onClose;
|
|
448
|
+
}
|
|
449
|
+
/** Re-read the tree: the directory is the authoritative state. */
|
|
450
|
+
async loadAll() {
|
|
451
|
+
this.assertOpen();
|
|
452
|
+
const state = await loadPerRecordState(this.descriptor, this.dir);
|
|
453
|
+
const tables = {};
|
|
454
|
+
for (const [table, records] of state.tables) tables[table] = Object.fromEntries(records);
|
|
455
|
+
return {
|
|
456
|
+
tables,
|
|
457
|
+
global: state.global
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
/** Durably replace one record: its own document, atomically. */
|
|
461
|
+
async putRecord(table, key, value) {
|
|
462
|
+
this.assertOpen();
|
|
463
|
+
assertSafeKey(this.descriptor.name, key);
|
|
464
|
+
await this.tracked(this.writeDocument(join(this.tableDir(table), `${key}.json`), value));
|
|
465
|
+
}
|
|
466
|
+
/** Durably delete one record. Idempotent: a missing key is a no-op. */
|
|
467
|
+
async deleteRecord(table, key) {
|
|
468
|
+
this.assertOpen();
|
|
469
|
+
assertSafeKey(this.descriptor.name, key);
|
|
470
|
+
await this.tracked(rm(join(this.tableDir(table), `${key}.json`), { force: true }));
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* Move one record's document aside as `<key>.json.bak.<YYYYMMDDHHmm>`. The
|
|
474
|
+
* moved file no longer ends in `.json`, so every later read ignores it; the
|
|
475
|
+
* bytes stay on disk for inspection. A same-minute backup of the same
|
|
476
|
+
* key overwrites the previous backup (the newer bytes are the ones worth
|
|
477
|
+
* keeping).
|
|
478
|
+
*/
|
|
479
|
+
async backupRecord(table, key) {
|
|
480
|
+
this.assertOpen();
|
|
481
|
+
assertSafeKey(this.descriptor.name, key);
|
|
482
|
+
const path = join(this.tableDir(table), `${key}.json`);
|
|
483
|
+
const moved = `${path}.bak.${backupStamp(/* @__PURE__ */ new Date())}`;
|
|
484
|
+
await this.tracked(rename(path, moved));
|
|
485
|
+
return moved;
|
|
486
|
+
}
|
|
487
|
+
/** Durably replace the global singleton. Only valid when declared. */
|
|
488
|
+
async setGlobal(value) {
|
|
489
|
+
this.assertOpen();
|
|
490
|
+
if (!this.descriptor.hasGlobal) throw new Error(`unit '${this.descriptor.name}' does not declare a global slot`);
|
|
491
|
+
await this.tracked(this.writeDocument(join(this.dir, "global.json"), value));
|
|
492
|
+
}
|
|
493
|
+
/** Drain in-flight writes and release the unit. Idempotent. */
|
|
494
|
+
async close() {
|
|
495
|
+
if (this.closed) {
|
|
496
|
+
await Promise.allSettled(this.inFlight);
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
this.closed = true;
|
|
500
|
+
await Promise.allSettled(this.inFlight);
|
|
501
|
+
this.onClose();
|
|
502
|
+
}
|
|
503
|
+
assertOpen() {
|
|
504
|
+
if (this.closed) throw new StorageError("closed", `unit '${this.descriptor.name}' is closed`);
|
|
505
|
+
}
|
|
506
|
+
/** Resolve a declared table's directory; an undeclared table is a caller bug and throws. */
|
|
507
|
+
tableDir(table) {
|
|
508
|
+
if (!this.descriptor.tables.includes(table)) throw new Error(`unit '${this.descriptor.name}' does not declare table '${table}'`);
|
|
509
|
+
return join(this.dir, table);
|
|
510
|
+
}
|
|
511
|
+
/** Durably replace one document, creating its parent directory. */
|
|
512
|
+
writeDocument(path, value) {
|
|
513
|
+
return (async () => {
|
|
514
|
+
await mkdir(dirname(path), {
|
|
515
|
+
recursive: true,
|
|
516
|
+
mode: 448
|
|
517
|
+
});
|
|
518
|
+
await writeAtomic(path, serializeRecord(this.descriptor.version, value));
|
|
519
|
+
})();
|
|
520
|
+
}
|
|
521
|
+
/** Track one durable write so close() drains it. */
|
|
522
|
+
tracked(write) {
|
|
523
|
+
this.inFlight.add(write);
|
|
524
|
+
write.catch(() => {}).finally(() => this.inFlight.delete(write));
|
|
525
|
+
return write;
|
|
526
|
+
}
|
|
527
|
+
};
|
|
528
|
+
/** Local-time `YYYYMMDDHHmm` suffix for backed-up documents. */
|
|
529
|
+
function backupStamp(now) {
|
|
530
|
+
const pad = (value) => String(value).padStart(2, "0");
|
|
531
|
+
return `${String(now.getFullYear())}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}`;
|
|
532
|
+
}
|
|
533
|
+
/** Reject a record key that would be unsafe as a path segment. */
|
|
534
|
+
function assertSafeKey(unit, key) {
|
|
535
|
+
if (!SAFE_KEY_RE.test(key)) throw new Error(`unit '${unit}': per-record key '${key}' is not path-safe (must match ${SAFE_KEY_RE})`);
|
|
536
|
+
}
|
|
537
|
+
//#endregion
|
|
538
|
+
//#region lib/types/index.js
|
|
539
|
+
/**
|
|
540
|
+
* JSON storage backend: one human-readable document per unit under a
|
|
541
|
+
* configured root — a whole-unit file (`single` layout) or one document per
|
|
542
|
+
* record (`per-record` layout), published by atomic rewrite. Registers as
|
|
543
|
+
* backend `json` on the storage hub.
|
|
544
|
+
* @module @unieai/rabi-storage-json
|
|
545
|
+
*/
|
|
546
|
+
/** Cordis plugin name. */
|
|
547
|
+
const name = "storage-json";
|
|
548
|
+
/** The hub must exist before the backend can register. */
|
|
549
|
+
const inject = ["storage"];
|
|
550
|
+
/** Config schema. */
|
|
551
|
+
const Config = z.object({ root: z.string().required() });
|
|
552
|
+
/** JSON backend: owns the file-tree root and serves the `kv` facet. */
|
|
553
|
+
var JsonStorageBackend = class {
|
|
554
|
+
root;
|
|
555
|
+
open = /* @__PURE__ */ new Map();
|
|
556
|
+
opening = /* @__PURE__ */ new Map();
|
|
557
|
+
closed = false;
|
|
558
|
+
constructor(root) {
|
|
559
|
+
this.root = root;
|
|
560
|
+
}
|
|
561
|
+
kv = { open: async (descriptor) => {
|
|
562
|
+
if (this.closed) throw new StorageError("closed", "json backend is closed");
|
|
563
|
+
validateDescriptor(descriptor);
|
|
564
|
+
if (this.open.has(descriptor.name) || this.opening.has(descriptor.name)) throw new Error(`unit '${descriptor.name}' is already open; a unit has exactly one live handle`);
|
|
565
|
+
const opening = this.openUnit(descriptor);
|
|
566
|
+
this.opening.set(descriptor.name, opening);
|
|
567
|
+
return opening.finally(() => this.opening.delete(descriptor.name));
|
|
568
|
+
} };
|
|
569
|
+
async openUnit(descriptor) {
|
|
570
|
+
await mkdir(this.root, {
|
|
571
|
+
recursive: true,
|
|
572
|
+
mode: 448
|
|
573
|
+
});
|
|
574
|
+
const onClose = () => this.open.delete(descriptor.name);
|
|
575
|
+
const unit = descriptor.layout === "per-record" ? await openPerRecordUnit(descriptor, this.root, onClose) : await openSingleUnit(descriptor, this.root, onClose);
|
|
576
|
+
if (this.closed) {
|
|
577
|
+
await unit.close();
|
|
578
|
+
throw new StorageError("closed", "json backend is closed");
|
|
579
|
+
}
|
|
580
|
+
this.open.set(descriptor.name, unit);
|
|
581
|
+
return unit;
|
|
582
|
+
}
|
|
583
|
+
async close() {
|
|
584
|
+
if (!this.closed) this.closed = true;
|
|
585
|
+
await Promise.allSettled([...this.opening.values()]);
|
|
586
|
+
for (const unit of [...this.open.values()]) await unit.close();
|
|
587
|
+
}
|
|
588
|
+
};
|
|
589
|
+
function validateDescriptor(descriptor) {
|
|
590
|
+
if (!UNIT_NAME_RE.test(descriptor.name)) throw new StorageError("malformed-medium", `invalid unit name '${descriptor.name}'`);
|
|
591
|
+
for (const table of descriptor.tables) if (!UNIT_NAME_RE.test(table)) throw new StorageError("malformed-medium", `invalid table name '${table}' in unit '${descriptor.name}'`);
|
|
592
|
+
}
|
|
593
|
+
/**
|
|
594
|
+
* Register the `json` backend on the storage hub.
|
|
595
|
+
* @param ctx - Plugin context.
|
|
596
|
+
* @param config - Validated configuration.
|
|
597
|
+
*/
|
|
598
|
+
function apply(ctx, config) {
|
|
599
|
+
const backend = new JsonStorageBackend(config.root);
|
|
600
|
+
ctx.effect(() => {
|
|
601
|
+
const unregister = ctx.storage.backend.register("json", backend);
|
|
602
|
+
return async () => {
|
|
603
|
+
unregister();
|
|
604
|
+
await backend.close();
|
|
605
|
+
};
|
|
606
|
+
});
|
|
607
|
+
ctx.provide(storageBackendServiceKey("json"), backend);
|
|
608
|
+
}
|
|
609
|
+
//#endregion
|
|
610
|
+
export { Config, JsonStorageBackend, apply, inject, name };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Atomic whole-file replacement for the JSON backend.
|
|
3
|
+
*
|
|
4
|
+
* Publish protocol: write a same-directory temp file, fsync it, then
|
|
5
|
+
* `rename()` over the target. Rename is an atomic replace on POSIX and on
|
|
6
|
+
* Windows (libuv maps it to `MoveFileExW(..., MOVEFILE_REPLACE_EXISTING)`),
|
|
7
|
+
* and replacement is the intended semantic here — unlike the session-log
|
|
8
|
+
* backend's link()+unlink() no-clobber protocol, a unit file has exactly one
|
|
9
|
+
* writer per process and last-write-wins is correct. After the rename the
|
|
10
|
+
* parent directory is fsynced on POSIX so the new entry is crash-durable.
|
|
11
|
+
* @module @unieai/rabi-storage-json/src/atomic
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Durably replace `path` with `data`.
|
|
15
|
+
* @param path - Absolute target file path.
|
|
16
|
+
* @param data - Full new file content.
|
|
17
|
+
* @returns resolution after the replacement is crash-durable.
|
|
18
|
+
*/
|
|
19
|
+
export declare function writeAtomic(path: string, data: string): Promise<void>;
|
|
20
|
+
//# sourceMappingURL=atomic.d.ts.map
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* On-disk JSON unit format: the file is always the current net state, kept
|
|
3
|
+
* human-readable (pretty-printed, stable key order from insertion) — that
|
|
4
|
+
* legibility is this backend's reason to exist. `single`-layout units are
|
|
5
|
+
* one document with a unit header; `per-record`-layout units are a directory
|
|
6
|
+
* with one version-stamped document per record (`<table>/<key>.json`) plus a
|
|
7
|
+
* `global.json` for the global slot, so a write rewrites one record instead
|
|
8
|
+
* of the whole unit.
|
|
9
|
+
* @module @unieai/rabi-storage-json/src/format
|
|
10
|
+
*/
|
|
11
|
+
import type { KvUnitDescriptor } from '@unieai/rabi-storage';
|
|
12
|
+
/** In-memory authoritative state of one unit; the file is its projection. `global` is `null` until first written. */
|
|
13
|
+
export interface UnitState {
|
|
14
|
+
version: number;
|
|
15
|
+
global: unknown;
|
|
16
|
+
tables: Map<string, Map<string, unknown>>;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Serialize a unit state to file content.
|
|
20
|
+
* @param name - Unit name, stamped into the header.
|
|
21
|
+
* @param state - Authoritative in-memory state.
|
|
22
|
+
* @returns pretty-printed JSON document with a trailing newline.
|
|
23
|
+
*/
|
|
24
|
+
export declare function serialize(name: string, state: UnitState): string;
|
|
25
|
+
/**
|
|
26
|
+
* Parse file content into unit state, validating shape and version.
|
|
27
|
+
* @param text - Raw file content.
|
|
28
|
+
* @param descriptor - Expected identity; version mismatch rejects.
|
|
29
|
+
* @returns the parsed state.
|
|
30
|
+
*/
|
|
31
|
+
export declare function parse(text: string, descriptor: KvUnitDescriptor): UnitState;
|
|
32
|
+
/**
|
|
33
|
+
* Serialize one per-record document: the unit's version stamp plus the
|
|
34
|
+
* record value, pretty-printed like the whole-unit document.
|
|
35
|
+
* @param version - Unit format version, stamped into the header.
|
|
36
|
+
* @param value - The record value (or the global singleton value).
|
|
37
|
+
* @returns pretty-printed JSON document with a trailing newline.
|
|
38
|
+
*/
|
|
39
|
+
export declare function serializeRecord(version: number, value: unknown): string;
|
|
40
|
+
/**
|
|
41
|
+
* Parse one per-record document, validating its version stamp. A document
|
|
42
|
+
* that is malformed or stamped with an unaccepted version is FOREIGN and
|
|
43
|
+
* reads as absent — the per-record contract: one bad or stale record file
|
|
44
|
+
* must not brick the whole unit, and an unaccepted version stamp discards the
|
|
45
|
+
* record instead of migrating it (the whole-unit format rejects instead,
|
|
46
|
+
* because there is exactly one document).
|
|
47
|
+
* @param text - Raw per-record document content.
|
|
48
|
+
* @param versions - Accepted unit versions (the current one plus the
|
|
49
|
+
* descriptor's compatibleVersions); any other stamp discards the
|
|
50
|
+
* document.
|
|
51
|
+
* @returns the record value, or `undefined` for a foreign document.
|
|
52
|
+
*/
|
|
53
|
+
export declare function parseRecord(text: string, versions: readonly number[]): unknown;
|
|
54
|
+
//# sourceMappingURL=format.d.ts.map
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSON storage backend: one human-readable document per unit under a
|
|
3
|
+
* configured root — a whole-unit file (`single` layout) or one document per
|
|
4
|
+
* record (`per-record` layout), published by atomic rewrite. Registers as
|
|
5
|
+
* backend `json` on the storage hub.
|
|
6
|
+
* @module @unieai/rabi-storage-json
|
|
7
|
+
*/
|
|
8
|
+
import type { Context } from '@unieai/cordis';
|
|
9
|
+
import z from '@unieai/schemastery';
|
|
10
|
+
import type { KvFacet, StorageBackend } from '@unieai/rabi-storage';
|
|
11
|
+
/** Cordis plugin name. */
|
|
12
|
+
export declare const name = "storage-json";
|
|
13
|
+
/** The hub must exist before the backend can register. */
|
|
14
|
+
export declare const inject: string[];
|
|
15
|
+
/**
|
|
16
|
+
* Plugin configuration.
|
|
17
|
+
* `root` has NO default on purpose: a `process.cwd()` fallback would scatter
|
|
18
|
+
* unit files wherever the process happens to start; assemblies state the
|
|
19
|
+
* location explicitly.
|
|
20
|
+
*/
|
|
21
|
+
export interface Config {
|
|
22
|
+
/** Directory holding one `<unit>.json` file (or `<unit>/` tree) per unit. */
|
|
23
|
+
root: string;
|
|
24
|
+
}
|
|
25
|
+
/** Config schema. */
|
|
26
|
+
export declare const Config: z<Config>;
|
|
27
|
+
/** JSON backend: owns the file-tree root and serves the `kv` facet. */
|
|
28
|
+
export declare class JsonStorageBackend implements StorageBackend {
|
|
29
|
+
private readonly root;
|
|
30
|
+
private readonly open;
|
|
31
|
+
private readonly opening;
|
|
32
|
+
private closed;
|
|
33
|
+
constructor(root: string);
|
|
34
|
+
readonly kv: KvFacet;
|
|
35
|
+
private openUnit;
|
|
36
|
+
close(): Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Register the `json` backend on the storage hub.
|
|
40
|
+
* @param ctx - Plugin context.
|
|
41
|
+
* @param config - Validated configuration.
|
|
42
|
+
*/
|
|
43
|
+
export declare function apply(ctx: Context, config: Config): void;
|
|
44
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One opened JSON unit in `per-record` layout: the unit is a directory at
|
|
3
|
+
* `dir`, holding one document per record under `<dir>/<table>/<key>.json`
|
|
4
|
+
* plus `global.json` for the global slot. The directory is the state — this
|
|
5
|
+
* unit holds NO in-memory state of its own: `loadAll` re-reads the tree and
|
|
6
|
+
* every write is one durable file operation. The domain layer owns the live
|
|
7
|
+
* in-memory tables (seeded by the open-time `loadAll`) and serializes writes
|
|
8
|
+
* through its write chain, so this unit never mutates memory and needs no
|
|
9
|
+
* rollback — a failed write simply leaves both the file and the domain's
|
|
10
|
+
* memory unchanged.
|
|
11
|
+
*
|
|
12
|
+
* Per-record contract: a record document that is malformed or stamped with a
|
|
13
|
+
* version outside the accepted set (the descriptor's current version plus
|
|
14
|
+
* its `compatibleVersions`) reads as an absent record — one bad or stale
|
|
15
|
+
* file never bricks the whole unit, and an unaccepted version stamp discards
|
|
16
|
+
* the record instead of migrating it. Record keys become path segments, so
|
|
17
|
+
* they must be path-safe (`[a-zA-Z0-9_-]+`); an unsafe key rejects at write.
|
|
18
|
+
*
|
|
19
|
+
* Legacy bootstrap: when the new tree has no document path, a legacy
|
|
20
|
+
* whole-unit file `<root>/<name>.json` (the pre-per-record layout) seeds
|
|
21
|
+
* per-record documents, provided its stored unit version is in the accepted
|
|
22
|
+
* set — a legacy file stamped with any other version is left alone and reads
|
|
23
|
+
* as the empty unit. Any new document path, including one whose contents are
|
|
24
|
+
* unreadable or stale, suppresses the bootstrap for the whole unit. The
|
|
25
|
+
* legacy file is never changed or deleted.
|
|
26
|
+
* @module @unieai/rabi-storage-json/src/per-record-unit
|
|
27
|
+
*/
|
|
28
|
+
import type { KvUnit, KvUnitDescriptor } from '@unieai/rabi-storage';
|
|
29
|
+
/**
|
|
30
|
+
* Open one `per-record`-layout unit under `root`: the unit directory is
|
|
31
|
+
* `<root>/<name>/`. Loads lazily on the first `loadAll` — this unit holds no
|
|
32
|
+
* state, so opening touches nothing on the medium.
|
|
33
|
+
* @param descriptor - Static identity and shape of the unit.
|
|
34
|
+
* @param root - Absolute backend root directory.
|
|
35
|
+
* @param onClose - Backend callback releasing the unit's open-slot.
|
|
36
|
+
* @returns the opened unit.
|
|
37
|
+
*/
|
|
38
|
+
export declare function openPerRecordUnit(descriptor: KvUnitDescriptor, root: string, onClose: () => void): Promise<KvUnit>;
|
|
39
|
+
/**
|
|
40
|
+
* One opened `per-record`-layout unit. Stateless by design: the directory is
|
|
41
|
+
* the medium, the domain layer owns the live memory, and each method here is
|
|
42
|
+
* a single durable file operation. Write ordering belongs to the caller (the
|
|
43
|
+
* domain layer's write chain), exactly like the `single`-layout unit.
|
|
44
|
+
*/
|
|
45
|
+
export declare class PerRecordJsonUnit implements KvUnit {
|
|
46
|
+
private readonly descriptor;
|
|
47
|
+
private readonly dir;
|
|
48
|
+
private readonly onClose;
|
|
49
|
+
private closed;
|
|
50
|
+
/** In-flight durable writes; close() drains them before releasing the unit. */
|
|
51
|
+
private readonly inFlight;
|
|
52
|
+
constructor(descriptor: KvUnitDescriptor, dir: string, onClose: () => void);
|
|
53
|
+
/** Re-read the tree: the directory is the authoritative state. */
|
|
54
|
+
loadAll(): Promise<{
|
|
55
|
+
tables: Record<string, Record<string, unknown>>;
|
|
56
|
+
global: unknown;
|
|
57
|
+
}>;
|
|
58
|
+
/** Durably replace one record: its own document, atomically. */
|
|
59
|
+
putRecord(table: string, key: string, value: unknown): Promise<void>;
|
|
60
|
+
/** Durably delete one record. Idempotent: a missing key is a no-op. */
|
|
61
|
+
deleteRecord(table: string, key: string): Promise<void>;
|
|
62
|
+
/**
|
|
63
|
+
* Move one record's document aside as `<key>.json.bak.<YYYYMMDDHHmm>`. The
|
|
64
|
+
* moved file no longer ends in `.json`, so every later read ignores it; the
|
|
65
|
+
* bytes stay on disk for inspection. A same-minute backup of the same
|
|
66
|
+
* key overwrites the previous backup (the newer bytes are the ones worth
|
|
67
|
+
* keeping).
|
|
68
|
+
*/
|
|
69
|
+
backupRecord(table: string, key: string): Promise<string>;
|
|
70
|
+
/** Durably replace the global singleton. Only valid when declared. */
|
|
71
|
+
setGlobal(value: unknown): Promise<void>;
|
|
72
|
+
/** Drain in-flight writes and release the unit. Idempotent. */
|
|
73
|
+
close(): Promise<void>;
|
|
74
|
+
private assertOpen;
|
|
75
|
+
/** Resolve a declared table's directory; an undeclared table is a caller bug and throws. */
|
|
76
|
+
private tableDir;
|
|
77
|
+
/** Durably replace one document, creating its parent directory. */
|
|
78
|
+
private writeDocument;
|
|
79
|
+
/** Track one durable write so close() drains it. */
|
|
80
|
+
private tracked;
|
|
81
|
+
}
|
|
82
|
+
//# sourceMappingURL=per-record-unit.d.ts.map
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One opened JSON unit in `single` layout: the whole unit is one document at
|
|
3
|
+
* `<root>/<name>.json`. The in-memory state is authoritative; every write
|
|
4
|
+
* primitive mutates it and republishes the whole file atomically. Writes are
|
|
5
|
+
* NOT queued here — per the backend contract, write ordering belongs to the
|
|
6
|
+
* caller (the domain layer's write chain); this unit only guarantees that
|
|
7
|
+
* each single call publishes a complete, durable file. The `per-record`
|
|
8
|
+
* layout is a separate unit class in `per-record-unit.ts`.
|
|
9
|
+
* @module @unieai/rabi-storage-json/src/single-unit
|
|
10
|
+
*/
|
|
11
|
+
import type { KvUnit, KvUnitDescriptor } from '@unieai/rabi-storage';
|
|
12
|
+
/**
|
|
13
|
+
* Open (load or lazily create) one `single`-layout unit under `root`: the
|
|
14
|
+
* unit file is `<root>/<name>.json`.
|
|
15
|
+
* @param descriptor - Static identity and shape of the unit.
|
|
16
|
+
* @param root - Absolute backend root directory.
|
|
17
|
+
* @param onClose - Backend callback releasing the unit's open-slot.
|
|
18
|
+
* @returns the opened unit.
|
|
19
|
+
*/
|
|
20
|
+
export declare function openSingleUnit(descriptor: KvUnitDescriptor, root: string, onClose: () => void): Promise<KvUnit>;
|
|
21
|
+
//# sourceMappingURL=single-unit.d.ts.map
|
package/locale/en.json
ADDED
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@unieai/rabi-storage-json",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"description": "JSON file KV storage backend for the Rabi Harness storage hub",
|
|
4
|
+
"version": "0.2.1-rc.3",
|
|
5
|
+
"publishConfig": {
|
|
6
|
+
"access": "public"
|
|
7
|
+
},
|
|
8
|
+
"type": "module",
|
|
9
|
+
"main": "lib/index.js",
|
|
10
|
+
"types": "lib/types/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./lib/types/index.d.ts",
|
|
14
|
+
"default": "./lib/index.js"
|
|
15
|
+
},
|
|
16
|
+
"./src/*": "./src/*",
|
|
17
|
+
"./package.json": "./package.json",
|
|
18
|
+
"./locale/*.json": "./locale/*.json"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"locale/*.json",
|
|
22
|
+
"lib/index.js",
|
|
23
|
+
"lib/types/**/*.d.ts",
|
|
24
|
+
"README.md"
|
|
25
|
+
],
|
|
26
|
+
"license": "MIT",
|
|
27
|
+
"peerDependencies": {
|
|
28
|
+
"@unieai/rabi-storage": "0.2.1-rc.3",
|
|
29
|
+
"@unieai/cordis": "4.0.5"
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"@unieai/schemastery": "3.18.5"
|
|
33
|
+
}
|
|
34
|
+
}
|