@cloudbitmaps/core 0.9.0 → 0.11.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.
- package/NOTICE +4 -4
- package/README.md +33 -16
- package/dist/chunk-5OMC5U7U.js +508 -0
- package/dist/chunk-5OMC5U7U.js.map +7 -0
- package/dist/core/audit.d.ts +128 -0
- package/dist/core/bit-route.d.ts +21 -0
- package/dist/core/blob.d.ts +34 -0
- package/dist/core/budget.d.ts +68 -0
- package/dist/core/codec.d.ts +122 -0
- package/dist/core/concurrency.d.ts +15 -0
- package/dist/core/consistency.d.ts +73 -0
- package/dist/core/cooperative.d.ts +78 -0
- package/dist/core/cost.d.ts +254 -0
- package/dist/core/crbm/crc32c.d.ts +10 -0
- package/dist/core/crbm/format.d.ts +114 -0
- package/dist/core/crbm/reader.d.ts +86 -0
- package/dist/core/crbm/varint.d.ts +13 -0
- package/dist/core/crbm/writer.d.ts +39 -0
- package/dist/core/crbm-storage-source.d.ts +522 -0
- package/dist/core/crypto.d.ts +80 -0
- package/dist/core/determinism.d.ts +42 -0
- package/dist/core/discover.d.ts +77 -0
- package/dist/core/due-index.d.ts +53 -0
- package/dist/core/engine.d.ts +246 -0
- package/dist/core/erase-id.d.ts +176 -0
- package/dist/core/erasure.d.ts +185 -0
- package/dist/core/errors.d.ts +113 -0
- package/dist/core/generation-gc.d.ts +56 -0
- package/dist/core/keys.d.ts +23 -0
- package/dist/core/load.d.ts +121 -0
- package/dist/core/lru.d.ts +69 -0
- package/dist/core/metrics.d.ts +136 -0
- package/dist/core/name-codec.d.ts +69 -0
- package/dist/core/pinned-storage-source.d.ts +90 -0
- package/dist/core/ports.d.ts +423 -0
- package/dist/core/reader-defaults.d.ts +18 -0
- package/dist/core/registry-scan.d.ts +47 -0
- package/dist/core/retention-sweep.d.ts +198 -0
- package/dist/core/retention.d.ts +67 -0
- package/dist/core/retry.d.ts +69 -0
- package/dist/core/rollback.d.ts +75 -0
- package/dist/core/validate.d.ts +44 -0
- package/dist/driver-kit.d.ts +9 -0
- package/dist/driver-kit.js +275 -0
- package/dist/driver-kit.js.map +7 -0
- package/dist/drivers/_shared/keys.d.ts +26 -0
- package/dist/drivers/_shared/object-registry-keys.d.ts +28 -0
- package/dist/drivers/_shared/object-registry.d.ts +89 -0
- package/dist/drivers/_shared/registry.d.ts +66 -0
- package/dist/drivers/backends.d.ts +43 -0
- package/dist/drivers/crypto.d.ts +38 -0
- package/dist/drivers/localfs/fs-util.d.ts +21 -0
- package/dist/drivers/localfs/paths.d.ts +33 -0
- package/dist/drivers/localfs/registry.d.ts +28 -0
- package/dist/drivers/localfs/storage.d.ts +19 -0
- package/dist/drivers/memory.d.ts +49 -0
- package/dist/drivers/retry/retrying-chunk-source.d.ts +59 -0
- package/dist/export/index.d.ts +93 -0
- package/dist/index.d.ts +76 -2760
- package/dist/index.js +3527 -3133
- package/dist/index.js.map +7 -1
- package/dist/testing/fuzz-core.d.ts +14 -0
- package/package.json +19 -115
- package/dist/azure/index.cjs +0 -368
- package/dist/azure/index.cjs.map +0 -1
- package/dist/azure/index.d.cts +0 -48
- package/dist/azure/index.d.ts +0 -48
- package/dist/azure/index.js +0 -304
- package/dist/azure/index.js.map +0 -1
- package/dist/cassandra/index.cjs +0 -265
- package/dist/cassandra/index.cjs.map +0 -1
- package/dist/cassandra/index.d.cts +0 -52
- package/dist/cassandra/index.d.ts +0 -52
- package/dist/cassandra/index.js +0 -204
- package/dist/cassandra/index.js.map +0 -1
- package/dist/chunk-7LMLYSVJ.js +0 -43
- package/dist/chunk-7LMLYSVJ.js.map +0 -1
- package/dist/chunk-BD22WDAN.js +0 -230
- package/dist/chunk-BD22WDAN.js.map +0 -1
- package/dist/chunk-NUIDEEFZ.js +0 -91
- package/dist/chunk-NUIDEEFZ.js.map +0 -1
- package/dist/chunk-OZ6LAFV4.js +0 -6
- package/dist/chunk-OZ6LAFV4.js.map +0 -1
- package/dist/chunk-SNJVZ227.js +0 -35
- package/dist/chunk-SNJVZ227.js.map +0 -1
- package/dist/dynamodb/index.cjs +0 -767
- package/dist/dynamodb/index.cjs.map +0 -1
- package/dist/dynamodb/index.d.cts +0 -106
- package/dist/dynamodb/index.d.ts +0 -106
- package/dist/dynamodb/index.js +0 -469
- package/dist/dynamodb/index.js.map +0 -1
- package/dist/gcs/index.cjs +0 -343
- package/dist/gcs/index.cjs.map +0 -1
- package/dist/gcs/index.d.cts +0 -46
- package/dist/gcs/index.d.ts +0 -46
- package/dist/gcs/index.js +0 -279
- package/dist/gcs/index.js.map +0 -1
- package/dist/index.cjs +0 -4990
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -2761
- package/dist/mongodb/index.cjs +0 -260
- package/dist/mongodb/index.cjs.map +0 -1
- package/dist/mongodb/index.d.cts +0 -45
- package/dist/mongodb/index.d.ts +0 -45
- package/dist/mongodb/index.js +0 -199
- package/dist/mongodb/index.js.map +0 -1
- package/dist/mysql/index.cjs +0 -281
- package/dist/mysql/index.cjs.map +0 -1
- package/dist/mysql/index.d.cts +0 -56
- package/dist/mysql/index.d.ts +0 -56
- package/dist/mysql/index.js +0 -211
- package/dist/mysql/index.js.map +0 -1
- package/dist/ports-CvcvJWf6.d.cts +0 -395
- package/dist/ports-CvcvJWf6.d.ts +0 -395
- package/dist/postgres/index.cjs +0 -273
- package/dist/postgres/index.cjs.map +0 -1
- package/dist/postgres/index.d.cts +0 -54
- package/dist/postgres/index.d.ts +0 -54
- package/dist/postgres/index.js +0 -203
- package/dist/postgres/index.js.map +0 -1
- package/dist/redis/index.cjs +0 -257
- package/dist/redis/index.cjs.map +0 -1
- package/dist/redis/index.d.cts +0 -42
- package/dist/redis/index.d.ts +0 -42
- package/dist/redis/index.js +0 -197
- package/dist/redis/index.js.map +0 -1
- package/dist/s3/index.cjs +0 -918
- package/dist/s3/index.cjs.map +0 -1
- package/dist/s3/index.d.cts +0 -112
- package/dist/s3/index.d.ts +0 -112
- package/dist/s3/index.js +0 -555
- package/dist/s3/index.js.map +0 -1
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_NAMESPACE,
|
|
3
|
+
IntegrityError,
|
|
4
|
+
NotFoundError,
|
|
5
|
+
STORAGE_BACKEND,
|
|
6
|
+
TransientError,
|
|
7
|
+
ValidationError,
|
|
8
|
+
WriteConflictError,
|
|
9
|
+
applyRegistryPatch,
|
|
10
|
+
brandAsBackend,
|
|
11
|
+
decodeNameFromKey,
|
|
12
|
+
encodeNameForKey,
|
|
13
|
+
encodeNameForPath,
|
|
14
|
+
isNotFoundError,
|
|
15
|
+
isValidationError,
|
|
16
|
+
isWriteConflictError,
|
|
17
|
+
mapWithConcurrency,
|
|
18
|
+
namespaceKeyPart,
|
|
19
|
+
namespacePathPart,
|
|
20
|
+
parseRegistryEnvelope,
|
|
21
|
+
recordFromNew,
|
|
22
|
+
registryCounterOf,
|
|
23
|
+
serializeRegistryEnvelope,
|
|
24
|
+
validateNewRegistryRecord,
|
|
25
|
+
validateRegistryPatch,
|
|
26
|
+
validateSegmentRef
|
|
27
|
+
} from "./chunk-5OMC5U7U.js";
|
|
28
|
+
|
|
29
|
+
// src/drivers/_shared/object-registry-keys.ts
|
|
30
|
+
var REGISTRY_SUFFIX = ".reg";
|
|
31
|
+
function prefixPart(prefix) {
|
|
32
|
+
if (prefix === void 0) return "";
|
|
33
|
+
const trimmed = prefix.replace(/^\/+|\/+$/g, "");
|
|
34
|
+
return trimmed === "" ? "" : `${trimmed}/`;
|
|
35
|
+
}
|
|
36
|
+
function normalizeObjectPrefix(prefix) {
|
|
37
|
+
if (prefix === void 0) return void 0;
|
|
38
|
+
for (const ch of prefix) {
|
|
39
|
+
const code = ch.charCodeAt(0);
|
|
40
|
+
if (code < 32 || code === 127) {
|
|
41
|
+
throw new ValidationError("prefix must not contain control characters");
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (prefix.includes("\\")) {
|
|
45
|
+
throw new ValidationError(
|
|
46
|
+
`prefix must not contain backslashes (a path separator on some backends): ${JSON.stringify(prefix)}`
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
let decoded;
|
|
50
|
+
try {
|
|
51
|
+
decoded = decodeURIComponent(prefix);
|
|
52
|
+
} catch {
|
|
53
|
+
decoded = prefix;
|
|
54
|
+
}
|
|
55
|
+
for (const source of decoded === prefix ? [prefix] : [prefix, decoded]) {
|
|
56
|
+
for (const segment of source.split("/")) {
|
|
57
|
+
if (segment === "." || segment === "..") {
|
|
58
|
+
throw new ValidationError(
|
|
59
|
+
`prefix must not contain "." or ".." path segments: ${JSON.stringify(prefix)}`
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return prefix;
|
|
65
|
+
}
|
|
66
|
+
function registryPrefix(prefix) {
|
|
67
|
+
return `${prefixPart(prefix)}registry/`;
|
|
68
|
+
}
|
|
69
|
+
function registryObjectKey(prefix, ref) {
|
|
70
|
+
validateSegmentRef(ref);
|
|
71
|
+
return `${registryPrefix(prefix)}${namespaceKeyPart(ref.namespace)}/${encodeNameForKey(ref.segment)}${REGISTRY_SUFFIX}`;
|
|
72
|
+
}
|
|
73
|
+
function registryListPrefix(prefix, namespace) {
|
|
74
|
+
const base = registryPrefix(prefix);
|
|
75
|
+
return namespace === void 0 ? base : `${base}${namespaceKeyPart(namespace)}/`;
|
|
76
|
+
}
|
|
77
|
+
function parseRegistryKey(prefix, objectKey) {
|
|
78
|
+
const base = registryPrefix(prefix);
|
|
79
|
+
if (!objectKey.startsWith(base) || !objectKey.endsWith(REGISTRY_SUFFIX)) return null;
|
|
80
|
+
const rest = objectKey.slice(base.length, objectKey.length - REGISTRY_SUFFIX.length);
|
|
81
|
+
const slash = rest.indexOf("/");
|
|
82
|
+
if (slash < 0) return null;
|
|
83
|
+
const nsPart = rest.slice(0, slash);
|
|
84
|
+
const encodedSegment = rest.slice(slash + 1);
|
|
85
|
+
if (encodedSegment.length === 0 || encodedSegment.includes("/")) return null;
|
|
86
|
+
const segment = decodeNameFromKey(encodedSegment);
|
|
87
|
+
const namespace = nsPart === DEFAULT_NAMESPACE ? void 0 : decodeNameFromKey(nsPart);
|
|
88
|
+
if (encodeNameForKey(segment) !== encodedSegment) return null;
|
|
89
|
+
if (namespace !== void 0 && encodeNameForKey(namespace) !== nsPart) return null;
|
|
90
|
+
const ref = { segment, namespace };
|
|
91
|
+
try {
|
|
92
|
+
validateSegmentRef(ref);
|
|
93
|
+
} catch {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
return ref;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// src/drivers/_shared/object-registry.ts
|
|
100
|
+
var MAX_ROW_BYTES = 1 * 1024 * 1024;
|
|
101
|
+
var MAX_DELETE_ATTEMPTS = 8;
|
|
102
|
+
var MAX_READ_ATTEMPTS = 8;
|
|
103
|
+
var LIST_READ_CONCURRENCY = 16;
|
|
104
|
+
var ObjectVersionRaced = class extends Error {
|
|
105
|
+
constructor(objectKey) {
|
|
106
|
+
super(`registry object was overwritten mid-read: ${objectKey}`);
|
|
107
|
+
this.name = "ObjectVersionRaced";
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
var ObjectStoreRegistry = class {
|
|
111
|
+
constructor(store, prefix, now) {
|
|
112
|
+
this.store = store;
|
|
113
|
+
this.prefix = prefix;
|
|
114
|
+
this.now = now;
|
|
115
|
+
}
|
|
116
|
+
store;
|
|
117
|
+
prefix;
|
|
118
|
+
now;
|
|
119
|
+
capabilities() {
|
|
120
|
+
return { strongRead: true };
|
|
121
|
+
}
|
|
122
|
+
async get(ref) {
|
|
123
|
+
const current = await this.readRow(registryObjectKey(this.prefix, ref));
|
|
124
|
+
return current && !current.env.deleted ? current.env.record : null;
|
|
125
|
+
}
|
|
126
|
+
async create(ref, record) {
|
|
127
|
+
validateNewRegistryRecord(record);
|
|
128
|
+
const key = registryObjectKey(this.prefix, ref);
|
|
129
|
+
const current = await this.readRow(key);
|
|
130
|
+
if (current !== null && !current.env.deleted) {
|
|
131
|
+
throw new WriteConflictError(`registry row already exists for segment ${ref.segment}`);
|
|
132
|
+
}
|
|
133
|
+
const token = String(current ? registryCounterOf(current.env.record) + 1 : 0);
|
|
134
|
+
const env = {
|
|
135
|
+
deleted: false,
|
|
136
|
+
record: recordFromNew(ref, record, this.now(), token)
|
|
137
|
+
};
|
|
138
|
+
await this.putRow(key, env, current ? { version: current.version } : "absent");
|
|
139
|
+
return { token };
|
|
140
|
+
}
|
|
141
|
+
async compareAndSwap(ref, expected, patch) {
|
|
142
|
+
validateRegistryPatch(patch);
|
|
143
|
+
const key = registryObjectKey(this.prefix, ref);
|
|
144
|
+
const current = await this.readRow(key);
|
|
145
|
+
if (current === null || current.env.deleted || current.env.record.token !== expected) {
|
|
146
|
+
throw new WriteConflictError(`OCC token mismatch for registry row ${ref.segment}`);
|
|
147
|
+
}
|
|
148
|
+
const token = String(registryCounterOf(current.env.record) + 1);
|
|
149
|
+
const env = {
|
|
150
|
+
deleted: false,
|
|
151
|
+
record: applyRegistryPatch(current.env.record, patch, this.now(), token)
|
|
152
|
+
};
|
|
153
|
+
await this.putRow(key, env, { version: current.version });
|
|
154
|
+
return { token };
|
|
155
|
+
}
|
|
156
|
+
async *list(namespace) {
|
|
157
|
+
const prefix = registryListPrefix(this.prefix, namespace);
|
|
158
|
+
let page = [];
|
|
159
|
+
const flush = async function* (keys) {
|
|
160
|
+
const rows = await mapWithConcurrency(
|
|
161
|
+
keys,
|
|
162
|
+
LIST_READ_CONCURRENCY,
|
|
163
|
+
(key) => this.readRow(key)
|
|
164
|
+
);
|
|
165
|
+
for (const current of rows) {
|
|
166
|
+
if (current && !current.env.deleted) yield current.env.record;
|
|
167
|
+
}
|
|
168
|
+
}.bind(this);
|
|
169
|
+
for await (const key of this.store.listKeys(prefix)) {
|
|
170
|
+
if (parseRegistryKey(this.prefix, key) === null) continue;
|
|
171
|
+
page.push(key);
|
|
172
|
+
if (page.length >= LIST_READ_CONCURRENCY) {
|
|
173
|
+
yield* flush(page);
|
|
174
|
+
page = [];
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (page.length > 0) yield* flush(page);
|
|
178
|
+
}
|
|
179
|
+
async delete(ref, expected) {
|
|
180
|
+
const key = registryObjectKey(this.prefix, ref);
|
|
181
|
+
for (let attempt = 0; attempt < MAX_DELETE_ATTEMPTS; attempt++) {
|
|
182
|
+
const current = await this.readRow(key);
|
|
183
|
+
if (expected !== void 0) {
|
|
184
|
+
if (current === null || current.env.deleted || current.env.record.token !== expected) {
|
|
185
|
+
throw new WriteConflictError(`OCC token mismatch for registry row ${ref.segment}`);
|
|
186
|
+
}
|
|
187
|
+
} else if (current === null || current.env.deleted) {
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
const token = String(registryCounterOf(current.env.record) + 1);
|
|
191
|
+
const env = {
|
|
192
|
+
deleted: true,
|
|
193
|
+
record: { ...current.env.record, token, updatedAt: this.now() }
|
|
194
|
+
};
|
|
195
|
+
try {
|
|
196
|
+
await this.putRow(key, env, { version: current.version });
|
|
197
|
+
return;
|
|
198
|
+
} catch (err) {
|
|
199
|
+
if (isWriteConflictError(err)) continue;
|
|
200
|
+
throw err;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
throw new WriteConflictError(
|
|
204
|
+
`registry delete: contention tombstoning "${ref.segment}" \u2014 retry`
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Read + parse a registry object, returning its envelope and version fence, or null if absent.
|
|
209
|
+
*
|
|
210
|
+
* A store that pins a version to read consistently ({@link ObjectVersionRaced}) loses that pin whenever a
|
|
211
|
+
* concurrent writer lands mid-read. Re-reading is the whole answer — the next read simply observes the
|
|
212
|
+
* newer version — and it is bounded so a row under permanent write saturation fails typed instead of
|
|
213
|
+
* spinning. Only a store racing itself gets here; S3 never does.
|
|
214
|
+
*/
|
|
215
|
+
async readRow(objectKey) {
|
|
216
|
+
const row = await this.readRaced(objectKey);
|
|
217
|
+
if (row === null) return null;
|
|
218
|
+
if (row.bytes.length > MAX_ROW_BYTES) {
|
|
219
|
+
throw new IntegrityError(
|
|
220
|
+
`registry object ${row.bytes.length}B exceeds cap ${MAX_ROW_BYTES}B`
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
if (row.version.length === 0) {
|
|
224
|
+
throw new IntegrityError(
|
|
225
|
+
`registry object has no version fence (needed for compare-and-swap): ${objectKey}`
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
const env = parseRegistryEnvelope(new TextDecoder().decode(row.bytes), objectKey);
|
|
229
|
+
return { env, version: row.version };
|
|
230
|
+
}
|
|
231
|
+
/** {@link ObjectRegistryStore.read}, retrying the bounded number of times a mid-read overwrite allows. */
|
|
232
|
+
async readRaced(objectKey) {
|
|
233
|
+
for (let attempt = 0; attempt < MAX_READ_ATTEMPTS; attempt++) {
|
|
234
|
+
try {
|
|
235
|
+
return await this.store.read(objectKey);
|
|
236
|
+
} catch (err) {
|
|
237
|
+
if (!(err instanceof ObjectVersionRaced)) throw err;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
throw new TransientError(
|
|
241
|
+
`registry read: ${this.store.label} object "${objectKey}" was overwritten on every one of ${MAX_READ_ATTEMPTS} attempts \u2014 retry`
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
/** Conditional write of an envelope. The store maps a lost precondition to {@link WriteConflictError}. */
|
|
245
|
+
async putRow(objectKey, env, expect) {
|
|
246
|
+
const body = new TextEncoder().encode(serializeRegistryEnvelope(env));
|
|
247
|
+
if (body.length > MAX_ROW_BYTES) {
|
|
248
|
+
throw new ValidationError(`registry object ${body.length}B exceeds cap ${MAX_ROW_BYTES}B`);
|
|
249
|
+
}
|
|
250
|
+
await this.store.write(objectKey, body, expect);
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
export {
|
|
254
|
+
IntegrityError,
|
|
255
|
+
MAX_ROW_BYTES,
|
|
256
|
+
NotFoundError,
|
|
257
|
+
ObjectStoreRegistry,
|
|
258
|
+
ObjectVersionRaced,
|
|
259
|
+
STORAGE_BACKEND,
|
|
260
|
+
TransientError,
|
|
261
|
+
ValidationError,
|
|
262
|
+
WriteConflictError,
|
|
263
|
+
brandAsBackend,
|
|
264
|
+
encodeNameForKey,
|
|
265
|
+
encodeNameForPath,
|
|
266
|
+
isNotFoundError,
|
|
267
|
+
isValidationError,
|
|
268
|
+
isWriteConflictError,
|
|
269
|
+
namespaceKeyPart,
|
|
270
|
+
namespacePathPart,
|
|
271
|
+
normalizeObjectPrefix,
|
|
272
|
+
prefixPart,
|
|
273
|
+
validateSegmentRef
|
|
274
|
+
};
|
|
275
|
+
//# sourceMappingURL=driver-kit.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/drivers/_shared/object-registry-keys.ts", "../src/drivers/_shared/object-registry.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * The registry object layout, shared by every object-store registry (S3, GCS, Azure Blob).\n *\n * One tiny JSON object per segment at `<prefix>registry/<ns>/<segment>.reg`, **registry-first** \u2014 separate\n * from the namespace-first storage layout (`<prefix><ns>/segments/\u2026`) \u2014 so discovery is a single list over\n * `registry/` for all namespaces, or `registry/<ns>/` for one, never entangled with the `.crbm` payloads.\n *\n * It lives here rather than in a driver because all three object stores encode names the same way\n * (`encodeNameForKey`, `namespaceKeyPart`) and build byte-identical keys. Three copies of this would be\n * three chances for one cloud's layout to drift from the others \u2014 and a drifted key is not a visible bug, it\n * is a segment that quietly cannot be found by a store pointed at the same bucket.\n */\nimport { ValidationError } from '@/core/errors';\nimport { validateSegmentRef } from '@/core/validate';\nimport type { SegmentRef } from '@/core/ports';\nimport { DEFAULT_NAMESPACE, decodeNameFromKey, encodeNameForKey, namespaceKeyPart } from './keys';\n\nconst REGISTRY_SUFFIX = '.reg';\n\n/** Normalize an optional caller prefix to either `''` or `trimmed/` (no leading/trailing slashes). */\nexport function prefixPart(prefix: string | undefined): string {\n if (prefix === undefined) return '';\n const trimmed = prefix.replace(/^\\/+|\\/+$/g, '');\n return trimmed === '' ? '' : `${trimmed}/`;\n}\n\n/**\n * Validate a caller-supplied key prefix (trusted config, but make it a real containment boundary): reject\n * control characters and `.`/`..` path segments so a prefix cannot traverse out of its intended space.\n * Returns it unchanged \u2014 the key builders normalize slashes.\n *\n * The traversal check covers three spellings, because the tools that walk these buckets do. A bare `..` is\n * the obvious one. A **backslash** segment matters on ADLS Gen2 and to Windows-side tooling, which treat it\n * as a separator this code otherwise would not. And a percent-encoded `..` matters because `gsutil`,\n * `s3fs`, `gcsfuse` and `azcopy` decode a key on their way to a local path \u2014 the same reasoning\n * `name-codec.ts` already applies to segment names, which a prefix has no reason to be exempt from.\n */\nexport function normalizeObjectPrefix(prefix: string | undefined): string | undefined {\n if (prefix === undefined) return undefined;\n for (const ch of prefix) {\n const code = ch.charCodeAt(0);\n // C0 plus DEL: a bare `< 0x20` lets U+007F through, and it is as unprintable as the rest.\n if (code < 0x20 || code === 0x7f) {\n throw new ValidationError('prefix must not contain control characters');\n }\n }\n if (prefix.includes('\\\\')) {\n throw new ValidationError(\n `prefix must not contain backslashes (a path separator on some backends): ${JSON.stringify(prefix)}`,\n );\n }\n // Check the decoded spelling too, so an encoded `..` cannot slip past the literal comparison.\n let decoded: string;\n try {\n decoded = decodeURIComponent(prefix);\n } catch {\n decoded = prefix; // not valid percent-encoding; the literal check still applies\n }\n for (const source of decoded === prefix ? [prefix] : [prefix, decoded]) {\n for (const segment of source.split('/')) {\n if (segment === '.' || segment === '..') {\n throw new ValidationError(\n `prefix must not contain \".\" or \"..\" path segments: ${JSON.stringify(prefix)}`,\n );\n }\n }\n }\n return prefix;\n}\n\n/** The key prefix under which every registry object lives: `<prefix>registry/`. */\nexport function registryPrefix(prefix: string | undefined): string {\n return `${prefixPart(prefix)}registry/`;\n}\n\n/** The full key of one segment's registry object: `<prefix>registry/<ns>/<segment>.reg`. */\nexport function registryObjectKey(prefix: string | undefined, ref: SegmentRef): string {\n validateSegmentRef(ref);\n return `${registryPrefix(prefix)}${namespaceKeyPart(ref.namespace)}/${encodeNameForKey(ref.segment)}${REGISTRY_SUFFIX}`;\n}\n\n/** The list prefix for discovery: registry-wide, or scoped to one namespace. */\nexport function registryListPrefix(prefix: string | undefined, namespace?: string): string {\n const base = registryPrefix(prefix);\n return namespace === undefined ? base : `${base}${namespaceKeyPart(namespace)}/`;\n}\n\n/**\n * Parse a `<prefix>registry/<ns>/<segment>.reg` key back to its {@link SegmentRef}, or `null` if it does not\n * match \u2014 a stray or foreign object under the prefix, or one whose parsed ref fails the round-trip check.\n * `_default` maps back to the absent namespace. A name is percent-encoded on the way in, so no encoded name\n * can contain `/` and the split stays unambiguous whatever the caller named their segment.\n */\nexport function parseRegistryKey(prefix: string | undefined, objectKey: string): SegmentRef | null {\n const base = registryPrefix(prefix);\n if (!objectKey.startsWith(base) || !objectKey.endsWith(REGISTRY_SUFFIX)) return null;\n const rest = objectKey.slice(base.length, objectKey.length - REGISTRY_SUFFIX.length);\n const slash = rest.indexOf('/');\n if (slash < 0) return null;\n const nsPart = rest.slice(0, slash);\n const encodedSegment = rest.slice(slash + 1);\n if (encodedSegment.length === 0 || encodedSegment.includes('/')) return null;\n const segment = decodeNameFromKey(encodedSegment);\n const namespace = nsPart === DEFAULT_NAMESPACE ? undefined : decodeNameFromKey(nsPart);\n // The encoding must ROUND-TRIP, not merely decode: a foreign object placed under our prefix could spell a\n // name two ways, and reporting both would hand a sweep one segment under two identities.\n if (encodeNameForKey(segment) !== encodedSegment) return null;\n if (namespace !== undefined && encodeNameForKey(namespace) !== nsPart) return null;\n const ref: SegmentRef = { segment, namespace };\n try {\n validateSegmentRef(ref); // reject a hostile/foreign key that isn't a valid ref\n } catch {\n return null;\n }\n return ref;\n}\n", "/**\n * `ObjectStoreRegistry` \u2014 an {@link IRegistryDriver} over any object store with conditional writes.\n *\n * Lets a **read-mostly deployment run on one bucket alone** \u2014 storage `.crbm` generations plus the registry in\n * the same place, with no separate database. One tiny JSON object per segment at\n * `<prefix>registry/<ns>/<segment>.reg` holding the `{ deleted, record }` envelope (the same shape LocalFs\n * persists). The OCC token is a monotonic counter, advanced on every mutation and even across a `delete`\n * (which **tombstones** rather than removes the object) so a deleted-then-recreated row never re-issues an\n * old token (ABA-safe) \u2014 identical semantics to the LocalFs registry, so it passes the same conformance suite.\n *\n * **The atomic swap is offloaded to the store's conditional writes.** `create` writes only if absent (or\n * over a tombstone under its version), and `compareAndSwap`/`delete` write only if the object still carries\n * the version we read \u2014 so a concurrent writer between our read and our write loses, and the loss surfaces\n * as {@link WriteConflictError}. No in-process lock is needed (unlike LocalFs): the precondition fences\n * writers *across processes*.\n *\n * **Why this is shared rather than written per cloud.** Every object store worth using has the same two\n * primitives under different names \u2014 S3 `If-None-Match: *` / `If-Match: <etag>`, GCS `ifGenerationMatch: 0`\n * / `ifGenerationMatch: <generation>`, Azure `If-None-Match: *` / `If-Match: <etag>` \u2014 so the only thing\n * that differs is three I/O calls, which is what {@link ObjectRegistryStore} abstracts. The parts that are\n * genuinely hard (the ABA-safe counter, the tombstone, the bounded delete retry, the round-trip key check)\n * exist once. Three copies would be three chances for one cloud to drift, and a drifted registry is not a\n * visible bug \u2014 it is a lost `currentGen` swap.\n *\n * **Deployment requirements** (a backend that violates these silently corrupts the registry):\n * - The store **must honor the conditional write**. One that accepts the precondition header and ignores it\n * degrades compare-and-swap to last-write-wins \u2192 lost `currentGen` swaps.\n * - Reads must be **strongly consistent** \u2014 true of S3 (since 2020), GCS and Azure Blob \u2014 since the registry\n * advertises `strongRead` and generation resolution depends on it.\n * - **Do not apply a lifecycle-expiration rule to the `registry/` prefix that expires a current version.**\n * `delete` tombstones (keeps the object with an advanced counter) for ABA-safety; expiring a tombstone would let a recreate reset the\n * token to 0 and re-issue a stale one.\n *\n * **`list()` is fail-closed, and one bad object stops it for everyone.** An object under the `registry/`\n * prefix whose key parses but whose body does not aborts the whole enumeration \u2014 every namespace, not just\n * the affected segment \u2014 and it stays that way until an operator removes the object. The error names the\n * offending key.\n *\n * That is the deliberate choice, and it is the *safer* one rather than the more convenient one. Skipping the\n * unreadable row would keep discovery running, but `list()` is what tells orphan generation collection which\n * segments exist: a row missing from the enumeration makes its storage `.crbm` generations look unreferenced,\n * and the next GC pass would delete them. Silently skipping turns a parse error into data loss. Refusing to\n * enumerate keeps every sweep off a set it cannot vouch for (invariant 5 \u2014 bytes from the tier are\n * untrusted). **Recovery:** read the named object, and either restore a valid envelope or delete it; nothing\n * else is damaged, and discovery resumes on its own.\n */\nimport {\n IntegrityError,\n TransientError,\n ValidationError,\n WriteConflictError,\n isWriteConflictError,\n} from '@/core/errors';\nimport type {\n IRegistryDriver,\n NewRegistryRecord,\n RegCaps,\n RegistryPatch,\n RegistryRecord,\n SegmentRef,\n Token,\n} from '@/core/ports';\nimport { mapWithConcurrency } from '@/core/concurrency';\nimport {\n applyRegistryPatch,\n parseRegistryEnvelope,\n recordFromNew,\n registryCounterOf,\n serializeRegistryEnvelope,\n validateNewRegistryRecord,\n validateRegistryPatch,\n type RegistryEnvelope,\n} from './registry';\nimport { parseRegistryKey, registryListPrefix, registryObjectKey } from './object-registry-keys';\n\n/** Defensive cap on a single registry object read from storage, before allocation (rows are tiny; ~1 KB). */\nexport const MAX_ROW_BYTES = 1 * 1024 * 1024;\n/** Bounded retry for `delete`'s read\u2192tombstone under cross-process contention (converges; then fails typed). */\nconst MAX_DELETE_ATTEMPTS = 8;\n/** Bounded re-read when a store's pinned version is overwritten mid-read (see {@link ObjectVersionRaced}). */\nconst MAX_READ_ATTEMPTS = 8;\n/** In-flight reads per `list()` page \u2014 turns the serial N+1 into one list plus bounded parallel reads. */\nconst LIST_READ_CONCURRENCY = 16;\n\n/**\n * Raised by a store when the version it pinned for a read vanished before it could fetch the bytes \u2014\n * a concurrent writer overwrote or deleted the object in between.\n *\n * This is deliberately **neither** of the two things it superficially resembles. It is not absence: the row\n * is very likely still live, just one version further on. And it is not a write conflict: the caller may be\n * a read-only `get()`, which has nothing to conflict with. Either is an easy misreading for a store that reads a\n * row in two calls, as the GCS and Azure Blob stores do, which is why the signal is part of the port rather than\n * left to each store's judgement. {@link ObjectStoreRegistry} answers it the only way that is correct for every\n * caller: it reads again.\n *\n * Stores whose read is atomic (S3 serves bytes and `ETag` from one `GetObject`) can never raise it.\n */\nexport class ObjectVersionRaced extends Error {\n constructor(objectKey: string) {\n super(`registry object was overwritten mid-read: ${objectKey}`);\n this.name = 'ObjectVersionRaced';\n }\n}\n\n/** One object as read, with the opaque version that fences a later conditional write. */\nexport interface ObjectRow {\n readonly bytes: Uint8Array;\n /** The store's version fence \u2014 an S3/Azure ETag, a GCS generation. Opaque to this class. */\n readonly version: string;\n}\n\n/**\n * The three I/O calls an object store must provide to host a registry. Everything else \u2014 the OCC counter,\n * tombstones, the delete retry, key parsing \u2014 is implemented once above.\n */\nexport interface ObjectRegistryStore {\n /** A label for error messages, e.g. `GCS` or `Azure Blob`. */\n readonly label: string;\n /**\n * Read one object, or `null` when it is absent.\n *\n * **`null` means the object does not exist** \u2014 nothing weaker. A store that reads in two round trips\n * (metadata for the version fence, then the bytes pinned to it) can find that version already gone; it\n * MUST report that with {@link ObjectVersionRaced} rather than `null` or {@link WriteConflictError}, and\n * the caller re-reads. Retryable faults throw {@link TransientError}.\n *\n * `bytes` and `version` MUST describe the **same** observation of the object: `version` is the fence a\n * later conditional write is conditioned on, so a pair drawn from two different versions would either\n * fail a write that should have succeeded or, worse, pass one that should not.\n */\n read(key: string): Promise<ObjectRow | null>;\n /**\n * Write one object under a precondition: `'absent'` means create-only, a version means\n * compare-and-swap against exactly that version. A lost race MUST throw {@link WriteConflictError}.\n *\n * A store must not replay this write after a lost response without telling the replay apart: the replay meets\n * the row it just wrote and its precondition fails, which would read as a lost race. Send it once, or store a\n * write id with the row and treat a conflict whose stored row carries it as success. Retryable faults throw\n * {@link TransientError}.\n */\n write(key: string, body: Uint8Array, expect: 'absent' | { version: string }): Promise<void>;\n /** Every object key under `prefix`, paginated internally. */\n listKeys(prefix: string): AsyncIterable<string>;\n}\n\nexport class ObjectStoreRegistry implements IRegistryDriver {\n constructor(\n private readonly store: ObjectRegistryStore,\n private readonly prefix: string | undefined,\n private readonly now: () => number,\n ) {}\n\n capabilities(): RegCaps {\n return { strongRead: true };\n }\n\n async get(ref: SegmentRef): Promise<RegistryRecord | null> {\n const current = await this.readRow(registryObjectKey(this.prefix, ref));\n return current && !current.env.deleted ? current.env.record : null;\n }\n\n async create(ref: SegmentRef, record: NewRegistryRecord): Promise<{ token: Token }> {\n validateNewRegistryRecord(record);\n const key = registryObjectKey(this.prefix, ref);\n const current = await this.readRow(key);\n if (current !== null && !current.env.deleted) {\n throw new WriteConflictError(`registry row already exists for segment ${ref.segment}`);\n }\n // Advance across a tombstone so a recreate never re-issues an old token (ABA-safe).\n const token = String(current ? registryCounterOf(current.env.record) + 1 : 0);\n const env: RegistryEnvelope = {\n deleted: false,\n record: recordFromNew(ref, record, this.now(), token),\n };\n // Create-only when truly absent; overwrite the tombstone under its version when recreating. Either way\n // a concurrent create loses the precondition and surfaces as a conflict.\n await this.putRow(key, env, current ? { version: current.version } : 'absent');\n return { token };\n }\n\n async compareAndSwap(\n ref: SegmentRef,\n expected: Token,\n patch: RegistryPatch,\n ): Promise<{ token: Token }> {\n validateRegistryPatch(patch);\n const key = registryObjectKey(this.prefix, ref);\n const current = await this.readRow(key);\n if (current === null || current.env.deleted || current.env.record.token !== expected) {\n throw new WriteConflictError(`OCC token mismatch for registry row ${ref.segment}`);\n }\n const token = String(registryCounterOf(current.env.record) + 1);\n const env: RegistryEnvelope = {\n deleted: false,\n record: applyRegistryPatch(current.env.record, patch, this.now(), token),\n };\n // The version we read fences a concurrent writer between that read and this write.\n await this.putRow(key, env, { version: current.version });\n return { token };\n }\n\n async *list(namespace?: string): AsyncIterable<RegistryRecord> {\n const prefix = registryListPrefix(this.prefix, namespace);\n // One list plus bounded parallel reads. A serial await-in-loop made this O(N) sequential round trips.\n let page: string[] = [];\n const flush = async function* (\n this: ObjectStoreRegistry,\n keys: string[],\n ): AsyncIterable<RegistryRecord> {\n const rows = await mapWithConcurrency(keys, LIST_READ_CONCURRENCY, (key) =>\n this.readRow(key),\n );\n for (const current of rows) {\n if (current && !current.env.deleted) yield current.env.record;\n }\n }.bind(this);\n\n for await (const key of this.store.listKeys(prefix)) {\n if (parseRegistryKey(this.prefix, key) === null) continue; // stray or foreign object\n page.push(key);\n if (page.length >= LIST_READ_CONCURRENCY) {\n yield* flush(page);\n page = [];\n }\n }\n if (page.length > 0) yield* flush(page);\n }\n\n async delete(ref: SegmentRef, expected?: Token): Promise<void> {\n const key = registryObjectKey(this.prefix, ref);\n // Tombstone (advance the counter) rather than remove the object \u2014 keeps the token monotonic for\n // ABA-safety. Retry the read\u2192tombstone on a cross-process race; it converges, then fails typed rather\n // than silently leaving the row live.\n for (let attempt = 0; attempt < MAX_DELETE_ATTEMPTS; attempt++) {\n const current = await this.readRow(key);\n if (expected !== undefined) {\n // Fenced: the row must still carry the token the caller read. Re-checked on every attempt, so a row\n // that was swapped, or deleted and re-created, between two attempts is refused rather than tombstoned.\n if (current === null || current.env.deleted || current.env.record.token !== expected) {\n throw new WriteConflictError(`OCC token mismatch for registry row ${ref.segment}`);\n }\n } else if (current === null || current.env.deleted) {\n return; // idempotent \u2014 already gone\n }\n const token = String(registryCounterOf(current.env.record) + 1);\n const env: RegistryEnvelope = {\n deleted: true,\n record: { ...current.env.record, token, updatedAt: this.now() },\n };\n try {\n await this.putRow(key, env, { version: current.version });\n return;\n } catch (err) {\n if (isWriteConflictError(err)) continue; // raced \u2014 re-read and re-tombstone\n throw err;\n }\n }\n throw new WriteConflictError(\n `registry delete: contention tombstoning \"${ref.segment}\" \u2014 retry`,\n );\n }\n\n /**\n * Read + parse a registry object, returning its envelope and version fence, or null if absent.\n *\n * A store that pins a version to read consistently ({@link ObjectVersionRaced}) loses that pin whenever a\n * concurrent writer lands mid-read. Re-reading is the whole answer \u2014 the next read simply observes the\n * newer version \u2014 and it is bounded so a row under permanent write saturation fails typed instead of\n * spinning. Only a store racing itself gets here; S3 never does.\n */\n private async readRow(\n objectKey: string,\n ): Promise<{ env: RegistryEnvelope; version: string } | null> {\n const row = await this.readRaced(objectKey);\n if (row === null) return null;\n if (row.bytes.length > MAX_ROW_BYTES) {\n throw new IntegrityError(\n `registry object ${row.bytes.length}B exceeds cap ${MAX_ROW_BYTES}B`,\n );\n }\n if (row.version.length === 0) {\n // The version is the OCC fence for CAS; a backend that omits it cannot be used safely as a registry.\n throw new IntegrityError(\n `registry object has no version fence (needed for compare-and-swap): ${objectKey}`,\n );\n }\n const env = parseRegistryEnvelope(new TextDecoder().decode(row.bytes), objectKey);\n return { env, version: row.version };\n }\n\n /** {@link ObjectRegistryStore.read}, retrying the bounded number of times a mid-read overwrite allows. */\n private async readRaced(objectKey: string): Promise<ObjectRow | null> {\n for (let attempt = 0; attempt < MAX_READ_ATTEMPTS; attempt++) {\n try {\n return await this.store.read(objectKey);\n } catch (err) {\n if (!(err instanceof ObjectVersionRaced)) throw err;\n }\n }\n throw new TransientError(\n `registry read: ${this.store.label} object \"${objectKey}\" was overwritten on every one of ` +\n `${MAX_READ_ATTEMPTS} attempts \u2014 retry`,\n );\n }\n\n /** Conditional write of an envelope. The store maps a lost precondition to {@link WriteConflictError}. */\n private async putRow(\n objectKey: string,\n env: RegistryEnvelope,\n expect: 'absent' | { version: string },\n ): Promise<void> {\n const body = new TextEncoder().encode(serializeRegistryEnvelope(env));\n if (body.length > MAX_ROW_BYTES) {\n // Belt-and-braces: the governance/DEK fields are already capped by validate*, so this cannot fire for\n // valid input \u2014 but never write a row that would later be unreadable.\n throw new ValidationError(`registry object ${body.length}B exceeds cap ${MAX_ROW_BYTES}B`);\n }\n await this.store.write(objectKey, body, expect);\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,IAAM,kBAAkB;A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AAY,EAAE,OAAO,0BAA0B,GAAG,CAAC;AACpE,QAAI,KAAK,SAAS,eAAe;AAG/B,YAAM,IAAI,gBAAgB,mBAAmB,KAAK,MAAM,iBAAiB,aAAa,GAAG;AAAA,IAC3F;AACA,UAAM,KAAK,MAAM,MAAM,WAAW,MAAM,MAAM;AAAA,EAChD;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared key-grammar fragments used by every driver's logical-ref → physical-key mapping.
|
|
3
|
+
*
|
|
4
|
+
* One copy of the `_default` namespace sentinel for every driver that maps a namespace to a key or a path. Pure
|
|
5
|
+
* string logic, no SDK, no I/O — it lives in the SDK-free `_shared` bundle so any driver may import it.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* The physical stand-in for an **absent** namespace. A caller MAY name a namespace `_default`; it simply does not collide, because
|
|
9
|
+
* `namespaceKeyPart`/`namespacePathPart` encode the caller's namespace (to `%5Fdefault`) and emit this
|
|
10
|
+
* sentinel literally. The separation is a property of the encoding, not of a grammar; reading it as a grammar is
|
|
11
|
+
* exactly what would make the collision easy to reintroduce.
|
|
12
|
+
*/
|
|
13
|
+
export declare const DEFAULT_NAMESPACE = "_default";
|
|
14
|
+
/**
|
|
15
|
+
* The physical namespace component of an **object key**: the caller's namespace encoded, or the sentinel.
|
|
16
|
+
*
|
|
17
|
+
* The sentinel is emitted **literally, never encoded**, and that asymmetry is the whole point. Encoding it too
|
|
18
|
+
* would send an absent namespace to `%5Fdefault` — exactly where a caller who names their namespace `_default`
|
|
19
|
+
* already goes, since the encoder escapes their leading underscore. Both would land in one place and read each
|
|
20
|
+
* other's data. Encoding only the caller's side means `_default` (ours) and `%5Fdefault` (theirs) are two
|
|
21
|
+
* different strings, and no caller can produce the first.
|
|
22
|
+
*/
|
|
23
|
+
export declare function namespaceKeyPart(namespace: string | undefined): string;
|
|
24
|
+
/** As {@link namespaceKeyPart}, for a filesystem path component. */
|
|
25
|
+
export declare function namespacePathPart(namespace: string | undefined): string;
|
|
26
|
+
export { encodeNameForKey, decodeNameFromKey, encodeNameForPath, decodeNameFromPath, } from '../../core/name-codec.js';
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { SegmentRef } from '../../core/ports.js';
|
|
2
|
+
/** Normalize an optional caller prefix to either `''` or `trimmed/` (no leading/trailing slashes). */
|
|
3
|
+
export declare function prefixPart(prefix: string | undefined): string;
|
|
4
|
+
/**
|
|
5
|
+
* Validate a caller-supplied key prefix (trusted config, but make it a real containment boundary): reject
|
|
6
|
+
* control characters and `.`/`..` path segments so a prefix cannot traverse out of its intended space.
|
|
7
|
+
* Returns it unchanged — the key builders normalize slashes.
|
|
8
|
+
*
|
|
9
|
+
* The traversal check covers three spellings, because the tools that walk these buckets do. A bare `..` is
|
|
10
|
+
* the obvious one. A **backslash** segment matters on ADLS Gen2 and to Windows-side tooling, which treat it
|
|
11
|
+
* as a separator this code otherwise would not. And a percent-encoded `..` matters because `gsutil`,
|
|
12
|
+
* `s3fs`, `gcsfuse` and `azcopy` decode a key on their way to a local path — the same reasoning
|
|
13
|
+
* `name-codec.ts` already applies to segment names, which a prefix has no reason to be exempt from.
|
|
14
|
+
*/
|
|
15
|
+
export declare function normalizeObjectPrefix(prefix: string | undefined): string | undefined;
|
|
16
|
+
/** The key prefix under which every registry object lives: `<prefix>registry/`. */
|
|
17
|
+
export declare function registryPrefix(prefix: string | undefined): string;
|
|
18
|
+
/** The full key of one segment's registry object: `<prefix>registry/<ns>/<segment>.reg`. */
|
|
19
|
+
export declare function registryObjectKey(prefix: string | undefined, ref: SegmentRef): string;
|
|
20
|
+
/** The list prefix for discovery: registry-wide, or scoped to one namespace. */
|
|
21
|
+
export declare function registryListPrefix(prefix: string | undefined, namespace?: string): string;
|
|
22
|
+
/**
|
|
23
|
+
* Parse a `<prefix>registry/<ns>/<segment>.reg` key back to its {@link SegmentRef}, or `null` if it does not
|
|
24
|
+
* match — a stray or foreign object under the prefix, or one whose parsed ref fails the round-trip check.
|
|
25
|
+
* `_default` maps back to the absent namespace. A name is percent-encoded on the way in, so no encoded name
|
|
26
|
+
* can contain `/` and the split stays unambiguous whatever the caller named their segment.
|
|
27
|
+
*/
|
|
28
|
+
export declare function parseRegistryKey(prefix: string | undefined, objectKey: string): SegmentRef | null;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import type { IRegistryDriver, NewRegistryRecord, RegCaps, RegistryPatch, RegistryRecord, SegmentRef, Token } from '../../core/ports.js';
|
|
2
|
+
/** Defensive cap on a single registry object read from storage, before allocation (rows are tiny; ~1 KB). */
|
|
3
|
+
export declare const MAX_ROW_BYTES: number;
|
|
4
|
+
/**
|
|
5
|
+
* Raised by a store when the version it pinned for a read vanished before it could fetch the bytes —
|
|
6
|
+
* a concurrent writer overwrote or deleted the object in between.
|
|
7
|
+
*
|
|
8
|
+
* This is deliberately **neither** of the two things it superficially resembles. It is not absence: the row
|
|
9
|
+
* is very likely still live, just one version further on. And it is not a write conflict: the caller may be
|
|
10
|
+
* a read-only `get()`, which has nothing to conflict with. Either is an easy misreading for a store that reads a
|
|
11
|
+
* row in two calls, as the GCS and Azure Blob stores do, which is why the signal is part of the port rather than
|
|
12
|
+
* left to each store's judgement. {@link ObjectStoreRegistry} answers it the only way that is correct for every
|
|
13
|
+
* caller: it reads again.
|
|
14
|
+
*
|
|
15
|
+
* Stores whose read is atomic (S3 serves bytes and `ETag` from one `GetObject`) can never raise it.
|
|
16
|
+
*/
|
|
17
|
+
export declare class ObjectVersionRaced extends Error {
|
|
18
|
+
constructor(objectKey: string);
|
|
19
|
+
}
|
|
20
|
+
/** One object as read, with the opaque version that fences a later conditional write. */
|
|
21
|
+
export interface ObjectRow {
|
|
22
|
+
readonly bytes: Uint8Array;
|
|
23
|
+
/** The store's version fence — an S3/Azure ETag, a GCS generation. Opaque to this class. */
|
|
24
|
+
readonly version: string;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The three I/O calls an object store must provide to host a registry. Everything else — the OCC counter,
|
|
28
|
+
* tombstones, the delete retry, key parsing — is implemented once above.
|
|
29
|
+
*/
|
|
30
|
+
export interface ObjectRegistryStore {
|
|
31
|
+
/** A label for error messages, e.g. `GCS` or `Azure Blob`. */
|
|
32
|
+
readonly label: string;
|
|
33
|
+
/**
|
|
34
|
+
* Read one object, or `null` when it is absent.
|
|
35
|
+
*
|
|
36
|
+
* **`null` means the object does not exist** — nothing weaker. A store that reads in two round trips
|
|
37
|
+
* (metadata for the version fence, then the bytes pinned to it) can find that version already gone; it
|
|
38
|
+
* MUST report that with {@link ObjectVersionRaced} rather than `null` or {@link WriteConflictError}, and
|
|
39
|
+
* the caller re-reads. Retryable faults throw {@link TransientError}.
|
|
40
|
+
*
|
|
41
|
+
* `bytes` and `version` MUST describe the **same** observation of the object: `version` is the fence a
|
|
42
|
+
* later conditional write is conditioned on, so a pair drawn from two different versions would either
|
|
43
|
+
* fail a write that should have succeeded or, worse, pass one that should not.
|
|
44
|
+
*/
|
|
45
|
+
read(key: string): Promise<ObjectRow | null>;
|
|
46
|
+
/**
|
|
47
|
+
* Write one object under a precondition: `'absent'` means create-only, a version means
|
|
48
|
+
* compare-and-swap against exactly that version. A lost race MUST throw {@link WriteConflictError}.
|
|
49
|
+
*
|
|
50
|
+
* A store must not replay this write after a lost response without telling the replay apart: the replay meets
|
|
51
|
+
* the row it just wrote and its precondition fails, which would read as a lost race. Send it once, or store a
|
|
52
|
+
* write id with the row and treat a conflict whose stored row carries it as success. Retryable faults throw
|
|
53
|
+
* {@link TransientError}.
|
|
54
|
+
*/
|
|
55
|
+
write(key: string, body: Uint8Array, expect: 'absent' | {
|
|
56
|
+
version: string;
|
|
57
|
+
}): Promise<void>;
|
|
58
|
+
/** Every object key under `prefix`, paginated internally. */
|
|
59
|
+
listKeys(prefix: string): AsyncIterable<string>;
|
|
60
|
+
}
|
|
61
|
+
export declare class ObjectStoreRegistry implements IRegistryDriver {
|
|
62
|
+
private readonly store;
|
|
63
|
+
private readonly prefix;
|
|
64
|
+
private readonly now;
|
|
65
|
+
constructor(store: ObjectRegistryStore, prefix: string | undefined, now: () => number);
|
|
66
|
+
capabilities(): RegCaps;
|
|
67
|
+
get(ref: SegmentRef): Promise<RegistryRecord | null>;
|
|
68
|
+
create(ref: SegmentRef, record: NewRegistryRecord): Promise<{
|
|
69
|
+
token: Token;
|
|
70
|
+
}>;
|
|
71
|
+
compareAndSwap(ref: SegmentRef, expected: Token, patch: RegistryPatch): Promise<{
|
|
72
|
+
token: Token;
|
|
73
|
+
}>;
|
|
74
|
+
list(namespace?: string): AsyncIterable<RegistryRecord>;
|
|
75
|
+
delete(ref: SegmentRef, expected?: Token): Promise<void>;
|
|
76
|
+
/**
|
|
77
|
+
* Read + parse a registry object, returning its envelope and version fence, or null if absent.
|
|
78
|
+
*
|
|
79
|
+
* A store that pins a version to read consistently ({@link ObjectVersionRaced}) loses that pin whenever a
|
|
80
|
+
* concurrent writer lands mid-read. Re-reading is the whole answer — the next read simply observes the
|
|
81
|
+
* newer version — and it is bounded so a row under permanent write saturation fails typed instead of
|
|
82
|
+
* spinning. Only a store racing itself gets here; S3 never does.
|
|
83
|
+
*/
|
|
84
|
+
private readRow;
|
|
85
|
+
/** {@link ObjectRegistryStore.read}, retrying the bounded number of times a mid-read overwrite allows. */
|
|
86
|
+
private readRaced;
|
|
87
|
+
/** Conditional write of an envelope. The store maps a lost precondition to {@link WriteConflictError}. */
|
|
88
|
+
private putRow;
|
|
89
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { NewRegistryRecord, RegistryPatch, RegistryRecord, SegmentRef, Token } from '../../core/ports.js';
|
|
2
|
+
/**
|
|
3
|
+
* The fields a stored record may carry: {@link RegistryRecord}'s, and nothing else. A field no reader resolves
|
|
4
|
+
* through is refused on read-back like any other corruption (invariant 5), rather than ignored.
|
|
5
|
+
*/
|
|
6
|
+
export declare const RECORD_FIELDS: readonly ["namespace", "segment", "currentGen", "wrappedDeks", "keyId", "status", "retention", "residency", "createdAt", "updatedAt", "token"];
|
|
7
|
+
/** Validate the caller-settable fields at `create`. */
|
|
8
|
+
export declare function validateNewRegistryRecord(rec: NewRegistryRecord): void;
|
|
9
|
+
/** Validate the caller-settable fields in a `compareAndSwap` patch. */
|
|
10
|
+
export declare function validateRegistryPatch(patch: RegistryPatch): void;
|
|
11
|
+
/**
|
|
12
|
+
* The persisted envelope for a registry row: the record plus a tombstone flag. A **deleted** row keeps its
|
|
13
|
+
* record (with an advanced counter) rather than being removed, so the monotonic token survives a
|
|
14
|
+
* delete→recreate — ABA-safety. Shared by the persistent drivers (LocalFs file, S3 object).
|
|
15
|
+
*
|
|
16
|
+
* `schemaVersion` is a wire-only concern — it stamps the persisted bytes, not the in-memory domain object —
|
|
17
|
+
* so it lives on the serialize/parse boundary ({@link serializeRegistryEnvelope} /
|
|
18
|
+
* {@link parseRegistryEnvelope}), never on this interface.
|
|
19
|
+
*/
|
|
20
|
+
export interface RegistryEnvelope {
|
|
21
|
+
readonly deleted: boolean;
|
|
22
|
+
readonly record: RegistryRecord;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Current registry-row schema version — a pre-1.0 format-freeze prerequisite. Every persistent
|
|
26
|
+
* registry driver — every one of which persists the `{ deleted, record }` envelope — stamps its rows
|
|
27
|
+
* with this so a reader can fail-closed on a future, incompatible layout instead of misparsing it. Bump only
|
|
28
|
+
* on a backward-incompatible change. Policy: a **higher** stamp than this build knows → `UnsupportedError`
|
|
29
|
+
* (fail-closed); an **absent** or malformed stamp → `IntegrityError`, since every row this build writes has one.
|
|
30
|
+
*/
|
|
31
|
+
export declare const REGISTRY_SCHEMA_VERSION = 1;
|
|
32
|
+
/**
|
|
33
|
+
* Validate a persisted registry row's `schemaVersion` (untrusted bytes, invariant 5): an absent or malformed value
|
|
34
|
+
* → `IntegrityError`; a version newer than this build → `UnsupportedError` (fail-closed rather than misread a
|
|
35
|
+
* format we don't understand).
|
|
36
|
+
*/
|
|
37
|
+
export declare function assertRegistrySchemaVersion(raw: unknown, ctx: string): void;
|
|
38
|
+
/** Serialize a registry envelope for persistence, stamping the current {@link REGISTRY_SCHEMA_VERSION}. */
|
|
39
|
+
export declare function serializeRegistryEnvelope(env: RegistryEnvelope): string;
|
|
40
|
+
/**
|
|
41
|
+
* The OCC counter encoded in a record's token. A published row always has a **canonical decimal** token
|
|
42
|
+
* (`String(counter)`), so anything else (`"1e3"`, `"0x10"`, `" 5 "`, `""`, a >2^53 value) is corruption /
|
|
43
|
+
* tampering — reject it (invariant 5) rather than let `Number()` coerce it and silently break monotonicity.
|
|
44
|
+
*/
|
|
45
|
+
export declare function registryCounterOf(record: RegistryRecord): number;
|
|
46
|
+
/**
|
|
47
|
+
* Parse + structurally validate a persisted `{ deleted, record }` envelope from stored bytes. A published row
|
|
48
|
+
* is always whole (atomic write), so a parse failure or a missing/mistyped field means corruption/tampering —
|
|
49
|
+
* fail fast (invariant 5), never silently report "absent". `ctx` names the source (path/key) for the message.
|
|
50
|
+
*/
|
|
51
|
+
export declare function parseRegistryEnvelope(text: string, ctx: string): RegistryEnvelope;
|
|
52
|
+
/** Build a full record from a {@link NewRegistryRecord} plus identity, audit timestamps, and an OCC token. */
|
|
53
|
+
export declare function recordFromNew(ref: SegmentRef, rec: NewRegistryRecord, now: number, token: Token): RegistryRecord;
|
|
54
|
+
/**
|
|
55
|
+
* Fail-fast structural check on a record read back from a persistent tier (untrusted bytes, invariant 5):
|
|
56
|
+
* a published row is always whole, so a missing/mistyped required field means corruption/tampering — reject
|
|
57
|
+
* it rather than silently report "absent". `token` is checked by the caller (its source differs per backend:
|
|
58
|
+
* an in-body field vs a derived OCC counter).
|
|
59
|
+
*/
|
|
60
|
+
export declare function assertStoredRecordShape(r: Record<string, unknown>, ctx: string): void;
|
|
61
|
+
/**
|
|
62
|
+
* Apply a patch to an existing record, returning a new one with a fresh `updatedAt` + `token` (identity and
|
|
63
|
+
* `createdAt` are preserved). Optional fields use `'k' in patch` so a patch can *clear* them (set to
|
|
64
|
+
* `undefined`, e.g. dropping `keyId` on crypto-shred); required fields use `??` (they always have a value).
|
|
65
|
+
*/
|
|
66
|
+
export declare function applyRegistryPatch(prev: RegistryRecord, patch: RegistryPatch, now: number, token: Token): RegistryRecord;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { STORAGE_BACKEND } from '../core/ports.js';
|
|
2
|
+
import type { IRegistryDriver, IStorageDriver, StorageBackend } from '../core/ports.js';
|
|
3
|
+
export interface MemoryStorageOptions {
|
|
4
|
+
/** Injected clock for the registry's `createdAt`/`updatedAt`; defaults to `Date.now`. */
|
|
5
|
+
readonly now?: () => number;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* An in-process backend — nothing to install, nothing to clean up, and it disappears with the process.
|
|
9
|
+
*
|
|
10
|
+
* This is the one to reach for in tests and in the first five minutes. It is **not** a cache in front of
|
|
11
|
+
* anything: it is the whole store, held in RAM, so a restart is a data loss.
|
|
12
|
+
*/
|
|
13
|
+
export declare class MemoryStorage implements StorageBackend {
|
|
14
|
+
/** Cross-bundle brand, stamped non-enumerably in the constructor so a spread cannot carry it. */
|
|
15
|
+
readonly [STORAGE_BACKEND]: true;
|
|
16
|
+
readonly storage: IStorageDriver;
|
|
17
|
+
readonly registry: IRegistryDriver;
|
|
18
|
+
constructor(options?: MemoryStorageOptions);
|
|
19
|
+
}
|
|
20
|
+
export interface LocalFsStorageOptions {
|
|
21
|
+
/** Injected clock for the registry's `createdAt`/`updatedAt`; defaults to `Date.now`. */
|
|
22
|
+
readonly now?: () => number;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* A local-filesystem backend rooted at one directory: generations under `<root>/storage`, pointers under
|
|
26
|
+
* `<root>/registry`.
|
|
27
|
+
*
|
|
28
|
+
* The layout is stated here rather than by the caller, which is the point — two paths a caller wrote out
|
|
29
|
+
* separately could name different roots, and nothing would stop them. It is also the layout
|
|
30
|
+
* the `export-segments` CLI expects, so a store built this way can be ejected without being told where to look.
|
|
31
|
+
*
|
|
32
|
+
* A root is for **one process**. Every instance in a process that names the same root shares one lock per
|
|
33
|
+
* registry row, however the root is spelled (relative path, symlink), so they cannot both advance a row from
|
|
34
|
+
* one token. Two processes on one root are **not** fenced from each other.
|
|
35
|
+
*/
|
|
36
|
+
export declare class LocalFsStorage implements StorageBackend {
|
|
37
|
+
readonly root: string;
|
|
38
|
+
/** Cross-bundle brand, stamped non-enumerably in the constructor so a spread cannot carry it. */
|
|
39
|
+
readonly [STORAGE_BACKEND]: true;
|
|
40
|
+
readonly storage: IStorageDriver;
|
|
41
|
+
readonly registry: IRegistryDriver;
|
|
42
|
+
constructor(root: string, options?: LocalFsStorageOptions);
|
|
43
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { Aead, AeadSealed, IKeystore, WrappedDek } from '../core/crypto.js';
|
|
2
|
+
/** AES-256-GCM AEAD bound to one 32-byte key. A fresh CSPRNG 96-bit nonce per `seal`; `aad` is authenticated,
|
|
3
|
+
* never stored. Nonce-reuse safety: the random-96-bit birthday bound is ~q²/2⁹⁷, negligible below ~2³² seals
|
|
4
|
+
* under one key. A per-segment DEK is **reused across all generations** (every load and rewrite encrypts under it), so
|
|
5
|
+
* seal count is cumulative over the segment's life — a segment approaching ~2³² lifetime chunk-seals should be
|
|
6
|
+
* re-seeded (a fresh segment ⇒ fresh DEK). Far beyond any realistic workload; noted for completeness. */
|
|
7
|
+
export declare class NodeAead implements Aead {
|
|
8
|
+
private readonly key;
|
|
9
|
+
constructor(key: Uint8Array);
|
|
10
|
+
seal(plaintext: Uint8Array, aad: Uint8Array): AeadSealed;
|
|
11
|
+
open(sealed: AeadSealed, aad: Uint8Array): Uint8Array;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Options for {@link InProcessKeystore}. `keys` maps a `keyId` → its 32-byte KEK; `activeKeyId` names the KEK
|
|
15
|
+
* new DEKs are wrapped under; an optional `recoveryKeyId` additionally wraps each new DEK under a second
|
|
16
|
+
* (e.g. offline) KEK, so losing the active KEK isn't fatal. Rotating the active KEK needs no data
|
|
17
|
+
* re-encryption: add the new KEK, point `activeKeyId` at it, keep the old one to unwrap existing segments.
|
|
18
|
+
*/
|
|
19
|
+
export interface InProcessKeystoreOptions {
|
|
20
|
+
readonly keys: Readonly<Record<string, Uint8Array>>;
|
|
21
|
+
readonly activeKeyId: string;
|
|
22
|
+
readonly recoveryKeyId?: string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Dependency-free BYOK keystore: envelope-wraps a fresh random per-segment DEK under the active (and optional
|
|
26
|
+
* recovery) KEK using `node:crypto`. No external service. The raw DEK never leaves a returned {@link NodeAead}.
|
|
27
|
+
*/
|
|
28
|
+
export declare class InProcessKeystore implements IKeystore {
|
|
29
|
+
private readonly keys;
|
|
30
|
+
private readonly activeKeyId;
|
|
31
|
+
private readonly recoveryKeyId;
|
|
32
|
+
constructor(options: InProcessKeystoreOptions);
|
|
33
|
+
createDek(): Promise<{
|
|
34
|
+
wrapped: WrappedDek[];
|
|
35
|
+
aead: Aead;
|
|
36
|
+
}>;
|
|
37
|
+
openDek(wrapped: readonly WrappedDek[]): Promise<Aead>;
|
|
38
|
+
}
|