@cloudbitmaps/core 0.19.1 → 0.20.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/dist/{chunk-RSLVTRJY.js → chunk-YSC7NJWV.js} +314 -216
- package/dist/chunk-YSC7NJWV.js.map +7 -0
- package/dist/core/audit.d.ts +56 -3
- package/dist/core/combine-many.d.ts +9 -6
- package/dist/core/consistency.d.ts +10 -4
- package/dist/core/crbm/fingerprint.d.ts +18 -0
- package/dist/core/crbm/format.d.ts +2 -4
- package/dist/core/crbm/frame.d.ts +10 -0
- package/dist/core/crbm/reader.d.ts +1 -8
- package/dist/core/crbm-storage-source.d.ts +229 -89
- package/dist/core/engine.d.ts +17 -14
- package/dist/core/erase-id.d.ts +62 -27
- package/dist/core/generation-gc.d.ts +2 -1
- package/dist/core/leases.d.ts +7 -0
- package/dist/core/load.d.ts +5 -3
- package/dist/core/metrics.d.ts +5 -5
- package/dist/core/pinned-storage-source.d.ts +3 -3
- package/dist/core/pointer-id.d.ts +19 -0
- package/dist/core/ports.d.ts +127 -35
- package/dist/core/reader-defaults.d.ts +14 -3
- package/dist/core/rollback.d.ts +2 -1
- package/dist/core/summary.d.ts +38 -21
- package/dist/core/token.d.ts +13 -8
- package/dist/driver-kit.d.ts +2 -1
- package/dist/driver-kit.js +11 -4
- package/dist/driver-kit.js.map +2 -2
- package/dist/drivers/_shared/object-registry.d.ts +1 -1
- package/dist/drivers/_shared/registry.d.ts +26 -17
- package/dist/drivers/localfs/storage.d.ts +7 -6
- package/dist/drivers/memory.d.ts +8 -6
- package/dist/drivers/retry/retrying-chunk-source.d.ts +1 -5
- package/dist/export/index.d.ts +16 -0
- package/dist/index.d.ts +2 -5
- package/dist/index.js +1169 -1041
- package/dist/index.js.map +4 -4
- package/package.json +1 -1
- package/dist/chunk-RSLVTRJY.js.map +0 -7
- package/dist/core/cost.d.ts +0 -351
package/dist/core/summary.d.ts
CHANGED
|
@@ -2,15 +2,17 @@
|
|
|
2
2
|
* A generation's summary on its registry row: how a writer builds it, how a reader opens it, and how it is held
|
|
3
3
|
* against the object it describes.
|
|
4
4
|
*
|
|
5
|
-
* The row carries a cached description of the current generation, `{ generation, cardinality, metadata? }`,
|
|
6
|
-
* the same compare-and-swap that moves the pointer.
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
5
|
+
* The row carries a cached description of the current generation, `{ generation, cardinality, fingerprint, metadata? }`,
|
|
6
|
+
* written by the same compare-and-swap that moves the pointer. The fingerprint names the generation's object, by its
|
|
7
|
+
* size and footer checksum, as `CrbmReader.fingerprint` does. On a cleartext segment the values are in the clear. On an
|
|
8
|
+
* encrypted one the row holds `{ generation, sealed }` instead: the cardinality as a fixed-width little-endian u64, the
|
|
9
|
+
* object's size as a u64 and its footer checksum as a u32, then the metadata's canonical JSON if there is any, sealed
|
|
10
|
+
* under the segment's data key with the summary scope of the associated data, which binds it to its namespace, segment
|
|
11
|
+
* and generation. The numbers are fixed-width so the ciphertext's length reveals only the metadata's size, never how
|
|
12
|
+
* many digits the count or the size has. Pure: no I/O.
|
|
11
13
|
*
|
|
12
14
|
* The generation's `.crbm` object stays the truth, and the summary is a copy of it. {@link summaryAgrees} is the
|
|
13
|
-
* comparison of one with the other.
|
|
15
|
+
* comparison of one with the other, and the fingerprint is what a reader holds every object it opens against.
|
|
14
16
|
*/
|
|
15
17
|
import type { Aead } from './crypto.js';
|
|
16
18
|
import type { ClearRegistrySummary, GenerationMetadata, RegistryRecord, RegistrySummary, SealedRegistrySummary, SegmentRef } from './ports.js';
|
|
@@ -19,28 +21,39 @@ export interface GenerationDescription {
|
|
|
19
21
|
readonly cardinality: number;
|
|
20
22
|
readonly metadata?: GenerationMetadata | undefined;
|
|
21
23
|
}
|
|
22
|
-
/**
|
|
23
|
-
export
|
|
24
|
+
/** What a row's summary says: the generation's description, and the fingerprint of the object it describes. */
|
|
25
|
+
export interface SummaryDescription extends GenerationDescription {
|
|
26
|
+
readonly fingerprint: string;
|
|
27
|
+
}
|
|
28
|
+
/** The size of the object a fingerprint names, in bytes: what `stat()` reports from a row's summary. */
|
|
29
|
+
export declare function sizeOfFingerprint(fingerprint: string): number;
|
|
30
|
+
/**
|
|
31
|
+
* The clear summary of a generation on a cleartext segment, naming its object by `fingerprint`. `metadata` is left off
|
|
32
|
+
* when there is none.
|
|
33
|
+
*/
|
|
34
|
+
export declare function clearSummary(generation: number, cardinality: number, fingerprint: string, metadata?: GenerationMetadata): ClearRegistrySummary;
|
|
24
35
|
/**
|
|
25
|
-
* The sealed summary of a generation on an encrypted segment: the cardinality as a u64,
|
|
26
|
-
* JSON, sealed under `aead` and bound to `ref` and
|
|
36
|
+
* The sealed summary of a generation on an encrypted segment: the cardinality as a u64, the object's size as a u64 and
|
|
37
|
+
* its footer checksum as a u32, then the metadata's canonical JSON, sealed under `aead` and bound to `ref` and
|
|
38
|
+
* `generation`.
|
|
27
39
|
*/
|
|
28
|
-
export declare function sealSummary(aead: Aead, ref: SegmentRef, generation: number, cardinality: number, metadata?: GenerationMetadata): SealedRegistrySummary;
|
|
40
|
+
export declare function sealSummary(aead: Aead, ref: SegmentRef, generation: number, cardinality: number, fingerprint: string, metadata?: GenerationMetadata): SealedRegistrySummary;
|
|
29
41
|
/**
|
|
30
42
|
* What a sealed summary says, opened with `aead` under the summary scope of `ref` and the summary's own generation.
|
|
31
43
|
* The bytes are untrusted: a blob that is not base64, is the wrong size, fails its authentication (tampered, or moved
|
|
32
|
-
* from another generation's row), or holds a count outside 0 to 2^32
|
|
33
|
-
* {@link IntegrityError}.
|
|
44
|
+
* from another generation's row), or holds a count outside 0 to 2^32, a size no object can have, or metadata that
|
|
45
|
+
* breaks the rules, is an {@link IntegrityError}.
|
|
34
46
|
*/
|
|
35
|
-
export declare function openSummary(aead: Aead, ref: SegmentRef, summary: SealedRegistrySummary):
|
|
47
|
+
export declare function openSummary(aead: Aead, ref: SegmentRef, summary: SealedRegistrySummary): SummaryDescription;
|
|
36
48
|
/**
|
|
37
49
|
* What a row's summary says of its current generation, or `undefined` when it says nothing a reader may use. It is
|
|
38
50
|
* used only for the generation it names, on an active row, and in the shape the row's keys call for: clear on a row
|
|
39
51
|
* with no wrapped keys, sealed on a row with them. A sealed one is opened with `aead`, and is unusable without it,
|
|
40
|
-
* or when it does not open, so a summary a tamperer moved or rewrote is never believed
|
|
41
|
-
* summary: the row's copy is a cache, and a copy that cannot be
|
|
52
|
+
* or when it does not open, so a summary a tamperer moved or rewrote is never believed; a clear one whose fingerprint
|
|
53
|
+
* names no object is unusable too. Never throws for a bad summary: the row's copy is a cache, and a copy that cannot be
|
|
54
|
+
* used is a copy that is not there.
|
|
42
55
|
*/
|
|
43
|
-
export declare function usableSummary(ref: SegmentRef, row: RegistryRecord, aead: Aead | undefined):
|
|
56
|
+
export declare function usableSummary(ref: SegmentRef, row: Pick<RegistryRecord, 'summary' | 'status' | 'currentGen' | 'wrappedDeks'>, aead: Aead | undefined): SummaryDescription | undefined;
|
|
44
57
|
/**
|
|
45
58
|
* Whether a summary's description of a generation is what its object holds: the same id count and the same metadata,
|
|
46
59
|
* compared in canonical form, so key order never matters. A summary with metadata over an object with none, and the
|
|
@@ -54,8 +67,12 @@ export declare function summaryAgrees(summary: GenerationDescription, object: Ge
|
|
|
54
67
|
* metadata block is not authenticated, so a block stripped from one reads as none, and the sealed summary on the row is
|
|
55
68
|
* the one copy that says there was a block; carrying it keeps the rewrite from erasing the record of what it dropped.
|
|
56
69
|
* Pass `authenticated` only for a summary that was opened (a clear one has no more authority than the block it sits
|
|
57
|
-
* beside). Never refuses
|
|
70
|
+
* beside). Never refuses. The erasure reaches this with a stripped block only past a fingerprint forged to match the
|
|
71
|
+
* row's, since stripping the block changes the object's size and the open is held to the row's fingerprint.
|
|
58
72
|
*/
|
|
59
73
|
export declare function metadataToCarry(object: GenerationMetadata | undefined, authenticated: GenerationDescription | undefined): GenerationMetadata | undefined;
|
|
60
|
-
/**
|
|
61
|
-
|
|
74
|
+
/**
|
|
75
|
+
* The summary of a generation of `ref`, describing the object `description.fingerprint` names, clear or sealed under
|
|
76
|
+
* `aead` as the segment's keys call for.
|
|
77
|
+
*/
|
|
78
|
+
export declare function summaryOf(ref: SegmentRef, generation: number, description: SummaryDescription, aead: Aead | undefined): RegistrySummary;
|
package/dist/core/token.d.ts
CHANGED
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
* A shipped registry gives a row it creates a token `<incarnation>.<counter>.<write>`: 32 lowercase hex digits drawn
|
|
5
5
|
* from injected entropy when the row is created, a decimal counter, and 16 hex digits drawn for each write. Every write
|
|
6
6
|
* of the row keeps the incarnation, and a name created again draws a new one, so two incarnations are told apart by it
|
|
7
|
-
* even when their rows were created in the same millisecond or one is gone. A
|
|
8
|
-
*
|
|
7
|
+
* even when their rows were created in the same millisecond or one is gone. A registry of someone else's issues tokens
|
|
8
|
+
* in any form, and one whose tokens carry no incarnation id is told apart only by the row's creation stamp.
|
|
9
9
|
*
|
|
10
10
|
* This lives in `core/` so the publish can read it, and the registry drivers, which build the tokens, import it from
|
|
11
11
|
* here: the form has one definition.
|
|
@@ -14,18 +14,23 @@ import type { Token } from './ports.js';
|
|
|
14
14
|
/** An incarnation-form token: the incarnation id, the counter and a write part, `.`-separated, in lowercase hex. */
|
|
15
15
|
export declare const INCARNATION_TOKEN: RegExp;
|
|
16
16
|
/**
|
|
17
|
-
* The incarnation id in a token, or `undefined` for one that has none: a
|
|
18
|
-
*
|
|
17
|
+
* The incarnation id in a token, or `undefined` for one that has none: a token a registry of someone else's issues in
|
|
18
|
+
* another form. Two tokens with the same incarnation are writes of one incarnation of a row.
|
|
19
19
|
*/
|
|
20
20
|
export declare function incarnationOf(token: Token): string | undefined;
|
|
21
|
+
/** An audit event's `incarnation`, from the token of the row it is about: absent for a token that carries none. */
|
|
22
|
+
export declare function incarnationField(token: Token | undefined): {
|
|
23
|
+
readonly incarnation?: string;
|
|
24
|
+
};
|
|
21
25
|
/**
|
|
22
26
|
* Whether two reads of one name's row are one incarnation of it.
|
|
23
27
|
*
|
|
24
28
|
* - Both tokens carry an incarnation id: the ids decide, and the clock stamps do not enter.
|
|
25
|
-
* - Only one does: different incarnations. A
|
|
26
|
-
*
|
|
27
|
-
* - Neither does (a
|
|
28
|
-
* is the only signal left. It is a clock reading, so a caller that acts on this answer proves its own object
|
|
29
|
+
* - Only one does: different incarnations. A registry gives its rows one form of token, so a row without an id never
|
|
30
|
+
* becomes a row with one, nor the reverse.
|
|
31
|
+
* - Neither does (a registry of someone else's whose tokens carry none): there is no id to compare, and the creation
|
|
32
|
+
* stamp is the only signal left. It is a clock reading, so a caller that acts on this answer proves its own object
|
|
33
|
+
* too.
|
|
29
34
|
*/
|
|
30
35
|
export declare function sameIncarnation(a: {
|
|
31
36
|
readonly token: Token;
|
package/dist/driver-kit.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
export type { GenKey, IRegistryDriver, IStorageDriver, SegmentRef, StorageBackend, StorageCaps, } from './core/ports.js';
|
|
1
|
+
export type { GenKey, IRegistryDriver, IStorageDriver, SegmentRef, StorageBackend, StorageCaps, StorageDeleteOptions, TailRead, } from './core/ports.js';
|
|
2
2
|
export { brandAsBackend, STORAGE_BACKEND } from './core/ports.js';
|
|
3
3
|
export type { IMetricsSink, MetricEvent } from './core/metrics.js';
|
|
4
4
|
export { IntegrityError, isIntegrityError, isNotFoundError, isTransientError, isValidationError, isWriteConflictError, NotFoundError, TransientError, ValidationError, WriteConflictError, } from './core/errors.js';
|
|
5
|
+
export { RESOLVED_FIELDS, pointerIdOf, renewPointer, renewsPointer } from './core/pointer-id.js';
|
|
5
6
|
export { validateSegmentRef } from './core/validate.js';
|
|
6
7
|
export type { BlobSink } from './core/blob.js';
|
|
7
8
|
export { MAX_ROW_BYTES, ObjectStoreRegistry, ObjectVersionRaced, } from './drivers/_shared/object-registry.js';
|
package/dist/driver-kit.js
CHANGED
|
@@ -2,6 +2,7 @@ import {
|
|
|
2
2
|
DEFAULT_NAMESPACE,
|
|
3
3
|
IntegrityError,
|
|
4
4
|
NotFoundError,
|
|
5
|
+
RESOLVED_FIELDS,
|
|
5
6
|
STORAGE_BACKEND,
|
|
6
7
|
TransientError,
|
|
7
8
|
ValidationError,
|
|
@@ -12,7 +13,6 @@ import {
|
|
|
12
13
|
encodeNameForKey,
|
|
13
14
|
encodeNameForPath,
|
|
14
15
|
entropyIsAvailable,
|
|
15
|
-
incarnationOf,
|
|
16
16
|
isIntegrityError,
|
|
17
17
|
isNotFoundError,
|
|
18
18
|
isTransientError,
|
|
@@ -24,13 +24,16 @@ import {
|
|
|
24
24
|
newIncarnationToken,
|
|
25
25
|
nextRegistryToken,
|
|
26
26
|
parseRegistryEnvelope,
|
|
27
|
+
pointerIdOf,
|
|
27
28
|
recordFromNew,
|
|
29
|
+
renewPointer,
|
|
30
|
+
renewsPointer,
|
|
28
31
|
serializeRegistryEnvelope,
|
|
29
32
|
validateNewRegistryRecord,
|
|
30
33
|
validateRegistryPatch,
|
|
31
34
|
validateSegmentRef,
|
|
32
35
|
webCryptoEntropy
|
|
33
|
-
} from "./chunk-
|
|
36
|
+
} from "./chunk-YSC7NJWV.js";
|
|
34
37
|
|
|
35
38
|
// src/drivers/_shared/object-registry-keys.ts
|
|
36
39
|
var REGISTRY_SUFFIX = ".reg";
|
|
@@ -137,7 +140,7 @@ var ObjectStoreRegistry = class {
|
|
|
137
140
|
const conditionalDelete = this.removesRows();
|
|
138
141
|
return entropyIsAvailable(this.entropy) ? { strongRead: true, conditionalDelete } : { strongRead: true, canWrite: false, conditionalDelete };
|
|
139
142
|
}
|
|
140
|
-
/** Whether a delete removes a row
|
|
143
|
+
/** Whether a delete removes a row: the store has a delete, and vouches for it. */
|
|
141
144
|
removesRows() {
|
|
142
145
|
return this.store.conditionalDelete === true && typeof this.store.delete === "function";
|
|
143
146
|
}
|
|
@@ -242,7 +245,7 @@ var ObjectStoreRegistry = class {
|
|
|
242
245
|
}
|
|
243
246
|
try {
|
|
244
247
|
const remove = this.removesRows() ? this.store.delete : void 0;
|
|
245
|
-
if (remove !== void 0
|
|
248
|
+
if (remove !== void 0) {
|
|
246
249
|
await remove.call(this.store, key, { version: current.version });
|
|
247
250
|
return;
|
|
248
251
|
}
|
|
@@ -316,6 +319,7 @@ export {
|
|
|
316
319
|
NotFoundError,
|
|
317
320
|
ObjectStoreRegistry,
|
|
318
321
|
ObjectVersionRaced,
|
|
322
|
+
RESOLVED_FIELDS,
|
|
319
323
|
STORAGE_BACKEND,
|
|
320
324
|
TransientError,
|
|
321
325
|
ValidationError,
|
|
@@ -331,7 +335,10 @@ export {
|
|
|
331
335
|
namespaceKeyPart,
|
|
332
336
|
namespacePathPart,
|
|
333
337
|
normalizeObjectPrefix,
|
|
338
|
+
pointerIdOf,
|
|
334
339
|
prefixPart,
|
|
340
|
+
renewPointer,
|
|
341
|
+
renewsPointer,
|
|
335
342
|
validateSegmentRef
|
|
336
343
|
};
|
|
337
344
|
//# sourceMappingURL=driver-kit.js.map
|
package/dist/driver-kit.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
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 // Index scans, not a regex: `/\\/+$/` retries from every slash of a run that is not at the end, which is\n // quadratic in the run's length.\n let start = 0;\n let end = prefix.length;\n while (start < end && prefix.charCodeAt(start) === 0x2f) start++;\n while (end > start && prefix.charCodeAt(end - 1) === 0x2f) end--;\n const trimmed = prefix.slice(start, end);\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 random incarnation id drawn when the row is created, a counter advanced on every\n * mutation, and a random part drawn for every write, so with overwhelming probability a deleted-then-recreated row, or\n * one restored from a backup, never re-issues an old token (ABA-safe) \u2014 identical semantics to the LocalFs registry, so it passes the same\n * conformance suite.\n *\n * **`delete` removes a row for good where the store vouches for a conditional delete** (`If-Match: <etag>`,\n * `ifGenerationMatch: <generation>`), and only a row whose token carries an incarnation id: a re-create draws a new\n * incarnation, so nothing of the old row is needed to keep its tokens apart, and a full `list()` no longer reads a\n * row for every name it ever held. Every other row is **tombstoned**: the object stays, its counter advanced, and a\n * re-create carries the counter on. A row a release before 0.12 wrote has a bare decimal token and is always\n * tombstoned, since a process still on that release, re-creating the name over nothing, would start its counter at 0\n * again and issue the old row's tokens.\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 (or delete) only if the object still\n * carries 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 * **A caller that already read the row can spare the read before its write.** `get` remembers the version of the\n * object it read, against the record it returned. A `compareAndSwap` handed that very record as `held` conditions its\n * write on that version and sends it at once, and a `create` handed `null` (the caller found no row) sends its\n * create-only write at once. The store's condition stays the fence: a row that changed since fails the write as a lost\n * race, so a stale `held` can lose a write and never land one. A record this registry did not return (a copy, another\n * registry's) is read for as without the hint.\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 a few I/O calls, which is what {@link ObjectRegistryStore} abstracts. The parts that are\n * genuinely hard (the ABA-safe token, the delete and its 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 * Expiring a live row loses its pointer. A tombstone `delete` left keeps the counter for a re-create; one expired\n * by a rule is no worse than a row removed for good, since a recreate draws a fresh incarnation and its tokens are\n * new but for a collision of probability 2^-128 per pair of incarnations, but a rule cannot tell a tombstone from a\n * live row.\n * - **A store's conditional delete must be honoured by its backend** before the store sets `conditionalDelete`.\n * One that ignores the precondition lets two sweepers and a re-create delete a live row.\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 RegistryWriteOptions,\n SegmentRef,\n Token,\n} from '@/core/ports';\nimport type { Entropy } from '@/core/determinism';\nimport { mapWithConcurrency } from '@/core/concurrency';\nimport {\n applyRegistryPatch,\n incarnationOf,\n newIncarnationToken,\n nextRegistryToken,\n parseRegistryEnvelope,\n recordFromNew,\n serializeRegistryEnvelope,\n validateNewRegistryRecord,\n validateRegistryPatch,\n type RegistryEnvelope,\n} from './registry';\nimport { entropyIsAvailable, webCryptoEntropy } from './entropy';\nimport { parseRegistryKey, registryListPrefix, registryObjectKey } from './object-registry-keys';\nimport { validateSegmentRef } from '@/core/validate';\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 then delete or tombstone, under cross-process contention (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 = 48;\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, metadata and then bytes pinned to it, 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 can never raise it, and every shipped store's is: S3 serves bytes and `ETag` from one\n * `GetObject`, GCS bytes and `generation` from one GET, and Azure Blob bytes and `ETag` from one GET.\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 I/O calls an object store must provide to host a registry: three, and an optional conditional delete. Everything\n * else \u2014 the OCC token, 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 * Optional: delete one object, and only while it is still at exactly `expect.version`, by a precondition the\n * backend applies (`If-Match: <etag>`, `ifGenerationMatch: <generation>`). An object that was overwritten, or is\n * gone, MUST throw {@link WriteConflictError} and delete nothing. Retryable faults throw {@link TransientError}.\n *\n * Sending it again after a lost response is safe, unlike a write: the precondition names one version, so a second\n * copy can remove nothing the first was not allowed to. A copy that meets its own landed delete fails the\n * precondition and reports a conflict; the registry re-reads, and finds the row gone.\n *\n * The registry calls it only when {@link conditionalDelete} is `true`.\n */\n delete?(key: string, expect: { version: string }): Promise<void>;\n /**\n * Whether {@link delete} may be relied on: `true` only where the backend is known to apply the precondition. A\n * backend that accepts the header and ignores it would let a delete remove a row written after the delete read it,\n * a live one included. Absent or `false`, the registry never calls `delete` and tombstones every row instead.\n */\n readonly conditionalDelete?: boolean;\n}\n\n/** A row as read: its envelope, the bytes it was parsed from, and the version that fences a write to it. */\ninterface ReadRow extends ObjectRow {\n readonly env: RegistryEnvelope;\n}\n\n/** What a record `get` returned was read from. */\ninterface ObservedRow extends ObjectRow {\n readonly key: string;\n}\n\nexport class ObjectStoreRegistry implements IRegistryDriver {\n /**\n * `entropy` draws the random parts of every token: a new row's incarnation id, and each write's own part. It\n * defaults to the platform's Web Crypto. Inject one only to make a test replayable: a seeded source in production\n * gives every process the same ids.\n */\n constructor(\n private readonly store: ObjectRegistryStore,\n private readonly prefix: string | undefined,\n private readonly now: () => number,\n private readonly entropy: Entropy = webCryptoEntropy,\n ) {}\n\n capabilities(): RegCaps {\n const conditionalDelete = this.removesRows();\n return entropyIsAvailable(this.entropy)\n ? { strongRead: true, conditionalDelete }\n : { strongRead: true, canWrite: false, conditionalDelete };\n }\n\n /** Whether a delete removes a row born with an incarnation id: the store has a delete, and vouches for it. */\n private removesRows(): boolean {\n return this.store.conditionalDelete === true && typeof this.store.delete === 'function';\n }\n\n /** The object each record `get` returned was read from, to fence a write made against it ({@link RegistryWriteOptions.held}). */\n private readonly observed = new WeakMap<RegistryRecord, ObservedRow>();\n\n async get(ref: SegmentRef): Promise<RegistryRecord | null> {\n const key = registryObjectKey(this.prefix, ref);\n const row = await this.readRow(key);\n if (row === null || row.env.deleted) return null;\n this.observed.set(row.env.record, { key, bytes: row.bytes, version: row.version });\n return row.env.record;\n }\n\n async create(\n ref: SegmentRef,\n record: NewRegistryRecord,\n options?: RegistryWriteOptions,\n ): Promise<{ token: Token }> {\n const checked = validateNewRegistryRecord(record);\n const key = registryObjectKey(this.prefix, ref);\n let lost: unknown;\n if (options?.held === null) {\n // The caller found no row: send the create-only write without reading. One that loses to a row, or to a tombstone\n // (which a create-only write cannot go over), is told apart by the read below.\n try {\n return await this.createOver(key, ref, checked, undefined);\n } catch (err) {\n if (!isWriteConflictError(err)) throw err;\n lost = err;\n }\n }\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 // No row at all now: the create-only write lost to something that has gone since, and it is not sent again.\n if (lost !== undefined && current === null) throw lost;\n return this.createOver(key, ref, checked, current ?? undefined);\n }\n\n /** Write a new incarnation of the row: over `tombstone` under its version, or create-only when there is none. */\n private async createOver(\n key: string,\n ref: SegmentRef,\n checked: NewRegistryRecord,\n tombstone: ReadRow | undefined,\n ): Promise<{ token: Token }> {\n // A new incarnation, whose counter continues across a tombstone, so with overwhelming probability a recreate never re-issues an old token.\n const token = newIncarnationToken(this.entropy, tombstone?.env.record);\n const env: RegistryEnvelope = {\n deleted: false,\n record: recordFromNew(ref, checked, 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, tombstone ? { version: tombstone.version } : 'absent');\n return { token };\n }\n\n async compareAndSwap(\n ref: SegmentRef,\n expected: Token,\n patch: RegistryPatch,\n options?: RegistryWriteOptions,\n ): Promise<{ token: Token }> {\n const checked = validateRegistryPatch(patch);\n const key = registryObjectKey(this.prefix, ref);\n // The row the caller read, as this registry read it, when it is the row `expected` names; otherwise read it now.\n const current = this.observedRow(key, expected, options?.held) ?? (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 = nextRegistryToken(current.env.record, this.entropy);\n const env: RegistryEnvelope = {\n deleted: false,\n record: applyRegistryPatch(current.env.record, checked, 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 /**\n * The row a caller's `held` record was read as, decoded again from the bytes `get` saw so that nothing the caller did\n * to its copy reaches the write, or `undefined` when `held` is not a record this registry returned for this row under\n * the token the write expects. The version it carries is the store's fence, so a row that has moved on since fails\n * the write.\n */\n private observedRow(\n key: string,\n expected: Token,\n held: RegistryRecord | null | undefined,\n ): ReadRow | undefined {\n const seen = held ? this.observed.get(held) : undefined;\n if (seen === undefined || seen.key !== key || held?.token !== expected) return undefined;\n return this.decodeRow(key, seen);\n }\n\n async *list(namespace?: string): AsyncIterable<RegistryRecord> {\n // A namespace that is given is checked as every other name is: `''` names none, and reads as an error, not as empty.\n if (namespace !== undefined) validateSegmentRef({ segment: 'x', namespace });\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 // A row born with an incarnation id is removed from the store, by a delete the store applies only while the\n // object is still the version read here: a later create draws a new incarnation, so nothing of this row is needed\n // to keep its tokens apart. Any other row is tombstoned (the counter advanced, the object kept), so a re-create\n // carries the counter on. Retry the read and the write on a cross-process race; it converges, then fails typed\n // rather 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 try {\n const remove = this.removesRows() ? this.store.delete : undefined;\n if (remove !== undefined && incarnationOf(current.env.record.token) !== undefined) {\n // The version read above is the row the caller's token names, so this removes that row and no later one.\n await remove.call(this.store, key, { version: current.version });\n return;\n }\n const token = nextRegistryToken(current.env.record, this.entropy);\n const env: RegistryEnvelope = {\n deleted: true,\n record: { ...current.env.record, token, updatedAt: this.now() },\n };\n await this.putRow(key, env, { version: current.version });\n return;\n } catch (err) {\n if (isWriteConflictError(err)) continue; // raced \u2014 re-read and try again\n throw err;\n }\n }\n throw new WriteConflictError(`registry delete: contention deleting \"${ref.segment}\" \u2014 retry`);\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 that reads in two calls gets here; none of the shipped stores does.\n */\n private async readRow(objectKey: string): Promise<ReadRow | null> {\n const row = await this.readRaced(objectKey);\n return row === null ? null : this.decodeRow(objectKey, row);\n }\n\n /** Check and parse the bytes of a registry object. */\n private decodeRow(objectKey: string, row: ObjectRow): ReadRow {\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 // The name the key spells is the name the row must carry: a key outside the layout has none to hold it to.\n const stored = parseRegistryKey(this.prefix, objectKey) ?? undefined;\n const env = parseRegistryEnvelope(new TextDecoder().decode(row.bytes), objectKey, stored);\n return { env, bytes: row.bytes, 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": "
|
|
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 // Index scans, not a regex: `/\\/+$/` retries from every slash of a run that is not at the end, which is\n // quadratic in the run's length.\n let start = 0;\n let end = prefix.length;\n while (start < end && prefix.charCodeAt(start) === 0x2f) start++;\n while (end > start && prefix.charCodeAt(end - 1) === 0x2f) end--;\n const trimmed = prefix.slice(start, end);\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 random incarnation id drawn when the row is created, a counter advanced on every\n * mutation, and a random part drawn for every write, so with overwhelming probability a deleted-then-recreated row, or\n * one restored from a backup, never re-issues an old token (ABA-safe) \u2014 identical semantics to the LocalFs registry, so it passes the same\n * conformance suite.\n *\n * **`delete` removes a row for good where the store vouches for a conditional delete** (`If-Match: <etag>`,\n * `ifGenerationMatch: <generation>`): a re-create draws a new incarnation, so nothing of the old row is needed to keep\n * its tokens apart, and a full `list()` no longer reads a row for every name it ever held. On a store that cannot\n * vouch for one, the row is **tombstoned**: the object stays, its counter advanced, and a re-create carries the counter\n * on.\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 (or delete) only if the object still\n * carries 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 * **A caller that already read the row can spare the read before its write.** `get` remembers the version of the\n * object it read, against the record it returned. A `compareAndSwap` handed that very record as `held` conditions its\n * write on that version and sends it at once, and a `create` handed `null` (the caller found no row) sends its\n * create-only write at once. The store's condition stays the fence: a row that changed since fails the write as a lost\n * race, so a stale `held` can lose a write and never land one. A record this registry did not return (a copy, another\n * registry's) is read for as without the hint.\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 a few I/O calls, which is what {@link ObjectRegistryStore} abstracts. The parts that are\n * genuinely hard (the ABA-safe token, the delete and its 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 * Expiring a live row loses its pointer. A tombstone `delete` left keeps the counter for a re-create; one expired\n * by a rule is no worse than a row removed for good, since a recreate draws a fresh incarnation and its tokens are\n * new but for a collision of probability 2^-128 per pair of incarnations, but a rule cannot tell a tombstone from a\n * live row.\n * - **A store's conditional delete must be honoured by its backend** before the store sets `conditionalDelete`.\n * One that ignores the precondition lets two sweepers and a re-create delete a live row.\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 RegistryWriteOptions,\n SegmentRef,\n Token,\n} from '@/core/ports';\nimport type { Entropy } from '@/core/determinism';\nimport { mapWithConcurrency } from '@/core/concurrency';\nimport {\n applyRegistryPatch,\n newIncarnationToken,\n nextRegistryToken,\n parseRegistryEnvelope,\n recordFromNew,\n serializeRegistryEnvelope,\n validateNewRegistryRecord,\n validateRegistryPatch,\n type RegistryEnvelope,\n} from './registry';\nimport { entropyIsAvailable, webCryptoEntropy } from './entropy';\nimport { parseRegistryKey, registryListPrefix, registryObjectKey } from './object-registry-keys';\nimport { validateSegmentRef } from '@/core/validate';\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 then delete or tombstone, under cross-process contention (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 = 48;\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, metadata and then bytes pinned to it, 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 can never raise it, and every shipped store's is: S3 serves bytes and `ETag` from one\n * `GetObject`, GCS bytes and `generation` from one GET, and Azure Blob bytes and `ETag` from one GET.\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 I/O calls an object store must provide to host a registry: three, and an optional conditional delete. Everything\n * else \u2014 the OCC token, 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 * Optional: delete one object, and only while it is still at exactly `expect.version`, by a precondition the\n * backend applies (`If-Match: <etag>`, `ifGenerationMatch: <generation>`). An object that was overwritten, or is\n * gone, MUST throw {@link WriteConflictError} and delete nothing. Retryable faults throw {@link TransientError}.\n *\n * Sending it again after a lost response is safe, unlike a write: the precondition names one version, so a second\n * copy can remove nothing the first was not allowed to. A copy that meets its own landed delete fails the\n * precondition and reports a conflict; the registry re-reads, and finds the row gone.\n *\n * The registry calls it only when {@link conditionalDelete} is `true`.\n */\n delete?(key: string, expect: { version: string }): Promise<void>;\n /**\n * Whether {@link delete} may be relied on: `true` only where the backend is known to apply the precondition. A\n * backend that accepts the header and ignores it would let a delete remove a row written after the delete read it,\n * a live one included. Absent or `false`, the registry never calls `delete` and tombstones every row instead.\n */\n readonly conditionalDelete?: boolean;\n}\n\n/** A row as read: its envelope, the bytes it was parsed from, and the version that fences a write to it. */\ninterface ReadRow extends ObjectRow {\n readonly env: RegistryEnvelope;\n}\n\n/** What a record `get` returned was read from. */\ninterface ObservedRow extends ObjectRow {\n readonly key: string;\n}\n\nexport class ObjectStoreRegistry implements IRegistryDriver {\n /**\n * `entropy` draws the random parts of every token: a new row's incarnation id, and each write's own part. It\n * defaults to the platform's Web Crypto. Inject one only to make a test replayable: a seeded source in production\n * gives every process the same ids.\n */\n constructor(\n private readonly store: ObjectRegistryStore,\n private readonly prefix: string | undefined,\n private readonly now: () => number,\n private readonly entropy: Entropy = webCryptoEntropy,\n ) {}\n\n capabilities(): RegCaps {\n const conditionalDelete = this.removesRows();\n return entropyIsAvailable(this.entropy)\n ? { strongRead: true, conditionalDelete }\n : { strongRead: true, canWrite: false, conditionalDelete };\n }\n\n /** Whether a delete removes a row: the store has a delete, and vouches for it. */\n private removesRows(): boolean {\n return this.store.conditionalDelete === true && typeof this.store.delete === 'function';\n }\n\n /** The object each record `get` returned was read from, to fence a write made against it ({@link RegistryWriteOptions.held}). */\n private readonly observed = new WeakMap<RegistryRecord, ObservedRow>();\n\n async get(ref: SegmentRef): Promise<RegistryRecord | null> {\n const key = registryObjectKey(this.prefix, ref);\n const row = await this.readRow(key);\n if (row === null || row.env.deleted) return null;\n this.observed.set(row.env.record, { key, bytes: row.bytes, version: row.version });\n return row.env.record;\n }\n\n async create(\n ref: SegmentRef,\n record: NewRegistryRecord,\n options?: RegistryWriteOptions,\n ): Promise<{ token: Token }> {\n const checked = validateNewRegistryRecord(record);\n const key = registryObjectKey(this.prefix, ref);\n let lost: unknown;\n if (options?.held === null) {\n // The caller found no row: send the create-only write without reading. One that loses to a row, or to a tombstone\n // (which a create-only write cannot go over), is told apart by the read below.\n try {\n return await this.createOver(key, ref, checked, undefined);\n } catch (err) {\n if (!isWriteConflictError(err)) throw err;\n lost = err;\n }\n }\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 // No row at all now: the create-only write lost to something that has gone since, and it is not sent again.\n if (lost !== undefined && current === null) throw lost;\n return this.createOver(key, ref, checked, current ?? undefined);\n }\n\n /** Write a new incarnation of the row: over `tombstone` under its version, or create-only when there is none. */\n private async createOver(\n key: string,\n ref: SegmentRef,\n checked: NewRegistryRecord,\n tombstone: ReadRow | undefined,\n ): Promise<{ token: Token }> {\n // A new incarnation, whose counter continues across a tombstone, so with overwhelming probability a recreate never re-issues an old token.\n const token = newIncarnationToken(this.entropy, tombstone?.env.record);\n const env: RegistryEnvelope = {\n deleted: false,\n record: recordFromNew(ref, checked, 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, tombstone ? { version: tombstone.version } : 'absent');\n return { token };\n }\n\n async compareAndSwap(\n ref: SegmentRef,\n expected: Token,\n patch: RegistryPatch,\n options?: RegistryWriteOptions,\n ): Promise<{ token: Token }> {\n const checked = validateRegistryPatch(patch);\n const key = registryObjectKey(this.prefix, ref);\n // The row the caller read, as this registry read it, when it is the row `expected` names; otherwise read it now.\n const current = this.observedRow(key, expected, options?.held) ?? (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 = nextRegistryToken(current.env.record, this.entropy);\n const env: RegistryEnvelope = {\n deleted: false,\n record: applyRegistryPatch(current.env.record, checked, 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 /**\n * The row a caller's `held` record was read as, decoded again from the bytes `get` saw so that nothing the caller did\n * to its copy reaches the write, or `undefined` when `held` is not a record this registry returned for this row under\n * the token the write expects. The version it carries is the store's fence, so a row that has moved on since fails\n * the write.\n */\n private observedRow(\n key: string,\n expected: Token,\n held: RegistryRecord | null | undefined,\n ): ReadRow | undefined {\n const seen = held ? this.observed.get(held) : undefined;\n if (seen === undefined || seen.key !== key || held?.token !== expected) return undefined;\n return this.decodeRow(key, seen);\n }\n\n async *list(namespace?: string): AsyncIterable<RegistryRecord> {\n // A namespace that is given is checked as every other name is: `''` names none, and reads as an error, not as empty.\n if (namespace !== undefined) validateSegmentRef({ segment: 'x', namespace });\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 // Where the store vouches for a conditional delete, the row is removed from it, by a delete the store applies only\n // while the object is still the version read here: a later create draws a new incarnation, so nothing of this row\n // is needed to keep its tokens apart. Otherwise it is tombstoned (the counter advanced, the object kept), so a\n // re-create carries the counter on. Retry the read and the write on a cross-process race; it converges, then fails\n // typed rather 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 try {\n const remove = this.removesRows() ? this.store.delete : undefined;\n if (remove !== undefined) {\n // The version read above is the row the caller's token names, so this removes that row and no later one.\n await remove.call(this.store, key, { version: current.version });\n return;\n }\n const token = nextRegistryToken(current.env.record, this.entropy);\n const env: RegistryEnvelope = {\n deleted: true,\n record: { ...current.env.record, token, updatedAt: this.now() },\n };\n await this.putRow(key, env, { version: current.version });\n return;\n } catch (err) {\n if (isWriteConflictError(err)) continue; // raced \u2014 re-read and try again\n throw err;\n }\n }\n throw new WriteConflictError(`registry delete: contention deleting \"${ref.segment}\" \u2014 retry`);\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 that reads in two calls gets here; none of the shipped stores does.\n */\n private async readRow(objectKey: string): Promise<ReadRow | null> {\n const row = await this.readRaced(objectKey);\n return row === null ? null : this.decodeRow(objectKey, row);\n }\n\n /** Check and parse the bytes of a registry object. */\n private decodeRow(objectKey: string, row: ObjectRow): ReadRow {\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 // The name the key spells is the name the row must carry: a key outside the layout has none to hold it to.\n const stored = parseRegistryKey(this.prefix, objectKey) ?? undefined;\n const env = parseRegistryEnvelope(new TextDecoder().decode(row.bytes), objectKey, stored);\n return { env, bytes: row.bytes, 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;AAGjB,SAAS,WAAW,QAAoC;AAC7D,MAAI,WAAW,OAAW,QAAO;AAGjC,MAAI,QAAQ;AACZ,MAAI,MAAM,OAAO;AACjB,SAAO,QAAQ,OAAO,OAAO,WAAW,KAAK,MAAM,GAAM;AACzD,SAAO,MAAM,SAAS,OAAO,WAAW,MAAM,CAAC,MAAM,GAAM;AAC3D,QAAM,UAAU,OAAO,MAAM,OAAO,GAAG;AACvC,SAAO,YAAY,KAAK,KAAK,GAAG,OAAO;AACzC;AAaO,SAAS,sBAAsB,QAAgD;AACpF,MAAI,WAAW,OAAW,QAAO;AACjC,aAAW,MAAM,QAAQ;AACvB,UAAM,OAAO,GAAG,WAAW,CAAC;AAE5B,QAAI,OAAO,MAAQ,SAAS,KAAM;AAChC,YAAM,IAAI,gBAAgB,4CAA4C;AAAA,IACxE;AAAA,EACF;AACA,MAAI,OAAO,SAAS,IAAI,GAAG;AACzB,UAAM,IAAI;AAAA,MACR,4EAA4E,KAAK,UAAU,MAAM,CAAC;AAAA,IACpG;AAAA,EACF;AAEA,MAAI;AACJ,MAAI;AACF,cAAU,mBAAmB,MAAM;AAAA,EACrC,QAAQ;AACN,cAAU;AAAA,EACZ;AACA,aAAW,UAAU,YAAY,SAAS,CAAC,MAAM,IAAI,CAAC,QAAQ,OAAO,GAAG;AACtE,eAAW,WAAW,OAAO,MAAM,GAAG,GAAG;AACvC,UAAI,YAAY,OAAO,YAAY,MAAM;AACv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IAAI,MAAM,MAAM,iBAAiB,aAAa;AAAA,MACnE;AAAA,IACF;AACA,QAAI,IAAI,QAAQ,WAAW,GAAG;AAE5B,YAAM,IAAI;AAAA,QACR,uEAAuE,SAAS;AAAA,MAClF;AAAA,IACF;AAEA,UAAM,SAAS,iBAAiB,KAAK,QAAQ,SAAS,KAAK;AAC3D,UAAM,MAAM,sBAAsB,IAAI,YAAY,EAAE,OAAO,IAAI,KAAK,GAAG,WAAW,MAAM;AACxF,WAAO,EAAE,KAAK,OAAO,IAAI,OAAO,SAAS,IAAI,QAAQ;AAAA,EACvD;AAAA;AAAA,EAGA,MAAc,UAAU,WAA8C;AACpE,aAAS,UAAU,GAAG,UAAU,mBAAmB,WAAW;AAC5D,UAAI;AACF,eAAO,MAAM,KAAK,MAAM,KAAK,SAAS;AAAA,MACxC,SAAS,KAAK;AACZ,YAAI,EAAE,eAAe,oBAAqB,OAAM;AAAA,MAClD;AAAA,IACF;AACA,UAAM,IAAI;AAAA,MACR,kBAAkB,KAAK,MAAM,KAAK,YAAY,SAAS,qCAClD,iBAAiB;AAAA,IACxB;AAAA,EACF;AAAA;AAAA,EAGA,MAAc,OACZ,WACA,KACA,QACe;AACf,UAAM,OAAO,IAAI,YAAY,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
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -92,7 +92,7 @@ export declare class ObjectStoreRegistry implements IRegistryDriver {
|
|
|
92
92
|
*/
|
|
93
93
|
constructor(store: ObjectRegistryStore, prefix: string | undefined, now: () => number, entropy?: Entropy);
|
|
94
94
|
capabilities(): RegCaps;
|
|
95
|
-
/** Whether a delete removes a row
|
|
95
|
+
/** Whether a delete removes a row: the store has a delete, and vouches for it. */
|
|
96
96
|
private removesRows;
|
|
97
97
|
/** The object each record `get` returned was read from, to fence a write made against it ({@link RegistryWriteOptions.held}). */
|
|
98
98
|
private readonly observed;
|
|
@@ -2,7 +2,12 @@ import type { Entropy } from '../../core/determinism.js';
|
|
|
2
2
|
import { incarnationOf } from '../../core/token.js';
|
|
3
3
|
import { usableKeptGens } from '../../core/kept-generations.js';
|
|
4
4
|
import type { NewRegistryRecord, RegistryPatch, RegistryRecord, SegmentRef, Token } from '../../core/ports.js';
|
|
5
|
-
|
|
5
|
+
/**
|
|
6
|
+
* The fields a stored record may carry: {@link RegistryRecord}'s, and nothing else. A field no reader resolves
|
|
7
|
+
* through is refused on read-back like any other corruption (invariant 5), rather than ignored. A field that joins
|
|
8
|
+
* schema 4 before it is released is appended here, with its validator, and needs no new schema version.
|
|
9
|
+
*/
|
|
10
|
+
export declare const RECORD_FIELDS: readonly ["namespace", "segment", "currentGen", "wrappedDeks", "keyId", "status", "retention", "residency", "summary", "createdAt", "updatedAt", "token", "keptGens", "leases", "pointerId"];
|
|
6
11
|
/**
|
|
7
12
|
* Validate the caller-settable fields at `create`, and return the record to store: the caller's, with its summary
|
|
8
13
|
* replaced by the checked, frozen copy {@link validateSummary} builds.
|
|
@@ -33,19 +38,19 @@ export interface RegistryEnvelope {
|
|
|
33
38
|
/**
|
|
34
39
|
* Current registry-row schema version — a pre-1.0 format-freeze prerequisite. Every persistent
|
|
35
40
|
* registry driver — every one of which persists the `{ deleted, record }` envelope — stamps its rows
|
|
36
|
-
* with this so a reader can fail-closed on a
|
|
37
|
-
* on a backward-incompatible change. Policy:
|
|
38
|
-
*
|
|
41
|
+
* with this so a reader can fail-closed on a layout it does not read instead of misparsing it. Bump only
|
|
42
|
+
* on a backward-incompatible change. Policy: any stamp but this one → `UnsupportedError` (fail-closed); an
|
|
43
|
+
* **absent** or malformed stamp → `IntegrityError`, since every row this build writes has one.
|
|
39
44
|
*
|
|
40
|
-
* Schema
|
|
41
|
-
*
|
|
42
|
-
*
|
|
45
|
+
* Schema 4 is the record with `pointerId`, the incarnation-form token and a summary that names its object. This build
|
|
46
|
+
* reads schema 4 and nothing else: a row stamped 1 to 3 carries no `pointerId`, so nothing could say which write set
|
|
47
|
+
* what it resolves to.
|
|
43
48
|
*/
|
|
44
|
-
export declare const REGISTRY_SCHEMA_VERSION =
|
|
49
|
+
export declare const REGISTRY_SCHEMA_VERSION = 4;
|
|
45
50
|
/**
|
|
46
51
|
* Validate a persisted registry row's `schemaVersion` (untrusted bytes, invariant 5) and return it: an absent or
|
|
47
|
-
* malformed value → `IntegrityError`;
|
|
48
|
-
* misread a format
|
|
52
|
+
* malformed value → `IntegrityError`; any version but {@link REGISTRY_SCHEMA_VERSION} → `UnsupportedError`
|
|
53
|
+
* (fail-closed rather than misread a format this build does not read), naming what to do for an earlier one.
|
|
49
54
|
*/
|
|
50
55
|
export declare function assertRegistrySchemaVersion(raw: unknown, ctx: string): number;
|
|
51
56
|
/** Serialize a registry envelope for persistence, stamping the current {@link REGISTRY_SCHEMA_VERSION}. */
|
|
@@ -57,8 +62,8 @@ export declare function drawIncarnation(entropy: Entropy): string;
|
|
|
57
62
|
/** A fresh write part from `entropy`: 64 bits as 16 lowercase hex digits. */
|
|
58
63
|
export declare function drawWrite(entropy: Entropy): string;
|
|
59
64
|
/**
|
|
60
|
-
* The token for the write after `record`'s: the same incarnation,
|
|
61
|
-
*
|
|
65
|
+
* The token for the write after `record`'s: the same incarnation, the counter one on, and a fresh write part. For a
|
|
66
|
+
* compare-and-swap or a tombstone.
|
|
62
67
|
*/
|
|
63
68
|
export declare function nextRegistryToken(record: RegistryRecord, entropy: Entropy): Token;
|
|
64
69
|
/**
|
|
@@ -73,19 +78,23 @@ export declare function newIncarnationToken(entropy: Entropy, tombstone: Registr
|
|
|
73
78
|
* `expected` is the segment the row was read under; a row that names another is refused.
|
|
74
79
|
*/
|
|
75
80
|
export declare function parseRegistryEnvelope(text: string, ctx: string, expected?: SegmentRef): RegistryEnvelope;
|
|
76
|
-
/**
|
|
81
|
+
/**
|
|
82
|
+
* Build a full record from a {@link NewRegistryRecord} plus identity, audit timestamps, and an OCC token. The create
|
|
83
|
+
* sets what the row resolves to, so its `pointerId` is its own token.
|
|
84
|
+
*/
|
|
77
85
|
export declare function recordFromNew(ref: SegmentRef, rec: NewRegistryRecord, now: number, token: Token): RegistryRecord;
|
|
78
86
|
/**
|
|
79
87
|
* Fail-fast structural check on a record read back from a persistent tier (untrusted bytes, invariant 5):
|
|
80
88
|
* a published row is always whole, so a missing/mistyped required field means corruption/tampering — reject
|
|
81
|
-
* it rather than silently report "absent".
|
|
82
|
-
*
|
|
89
|
+
* it rather than silently report "absent". The form of `token` and `pointerId`, and how the two relate, is checked by
|
|
90
|
+
* the caller.
|
|
83
91
|
*/
|
|
84
|
-
export declare function assertStoredRecordShape(r: Record<string, unknown>, ctx: string
|
|
92
|
+
export declare function assertStoredRecordShape(r: Record<string, unknown>, ctx: string): void;
|
|
85
93
|
/**
|
|
86
94
|
* Apply a patch to an existing record, returning a new one with a fresh `updatedAt` + `token` (identity and
|
|
87
95
|
* `createdAt` are preserved). Optional fields use `'k' in patch` so a patch can *clear* them (set to
|
|
88
|
-
* `undefined`, e.g. dropping `keyId` on crypto-shred); required fields use `??` (they always have a value).
|
|
96
|
+
* `undefined`, e.g. dropping `keyId` on crypto-shred); required fields use `??` (they always have a value). A patch
|
|
97
|
+
* that names a resolved field ({@link renewsPointer}) sets `pointerId` to this write's token; any other keeps it.
|
|
89
98
|
*
|
|
90
99
|
* `summary` describes the current generation, so it follows the pointer and the keys: a patch that moves
|
|
91
100
|
* `currentGen`, or changes `wrappedDeks` so the summary's shape no longer agrees, without mentioning `summary` drops
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { BlobSink } from '../../core/blob.js';
|
|
2
|
-
import type { StorageCaps, GenKey, IStorageDriver, SegmentRef } from '../../core/ports.js';
|
|
2
|
+
import type { StorageCaps, GenKey, IStorageDriver, SegmentRef, StorageDeleteOptions, TailRead } from '../../core/ports.js';
|
|
3
3
|
export declare class LocalFsStorageDriver implements IStorageDriver {
|
|
4
4
|
private readonly root;
|
|
5
5
|
private readonly exactCase;
|
|
@@ -10,11 +10,12 @@ export declare class LocalFsStorageDriver implements IStorageDriver {
|
|
|
10
10
|
sha256: string;
|
|
11
11
|
}>;
|
|
12
12
|
getRange(key: GenKey, offset: number, length: number): Promise<Uint8Array>;
|
|
13
|
-
getTail(key: GenKey, maxBytes: number): Promise<
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
13
|
+
getTail(key: GenKey, maxBytes: number): Promise<TailRead>;
|
|
14
|
+
/**
|
|
15
|
+
* Idempotent. Ignores `options.ifVersion`, as `conditionalDelete: false` says: see the note on the class for why it
|
|
16
|
+
* cannot apply one. The parameter is declared so that a wrapper of this driver can hand the port's options on.
|
|
17
|
+
*/
|
|
18
|
+
delete(key: GenKey, options?: StorageDeleteOptions): Promise<void>;
|
|
18
19
|
list(ref: SegmentRef): AsyncIterable<GenKey>;
|
|
19
20
|
private openRead;
|
|
20
21
|
}
|
package/dist/drivers/memory.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { BlobSink } from '../core/blob.js';
|
|
2
2
|
import type { Entropy } from '../core/determinism.js';
|
|
3
|
-
import type { StorageCaps, GenKey, IStorageDriver, IRegistryDriver, NewRegistryRecord, RegCaps, RegistryPatch, RegistryRecord, SegmentRef, Token } from '../core/ports.js';
|
|
3
|
+
import type { StorageCaps, StorageDeleteOptions, TailRead, GenKey, IStorageDriver, IRegistryDriver, NewRegistryRecord, RegCaps, RegistryPatch, RegistryRecord, SegmentRef, Token } from '../core/ports.js';
|
|
4
4
|
export interface MemoryRegistryDriverOptions {
|
|
5
5
|
/** Injected clock for `createdAt`/`updatedAt`; defaults to `Date.now` (drivers may use ambient time). */
|
|
6
6
|
readonly now?: () => number;
|
|
@@ -40,20 +40,22 @@ export declare class MemoryRegistryDriver implements IRegistryDriver {
|
|
|
40
40
|
* In-memory {@link IStorageDriver} — write-once immutable generation objects as opaque bytes. A "dumb byte
|
|
41
41
|
* mover" (understands neither roaring nor `.crbm`), so it's a faithful storage backend for tests and a zero-setup
|
|
42
42
|
* local storage tier. Mirrors the LocalFs/S3 contract (write-once, range/tail reads).
|
|
43
|
+
*
|
|
44
|
+
* Every object stored gets a version from a counter the driver never reuses, so two objects stored one after the other
|
|
45
|
+
* under one key never share one, whatever their bytes. A delete given `ifVersion` compares it with the stored object's
|
|
46
|
+
* and removes it in the same step, with no await between them: `conditionalDelete` is `true`.
|
|
43
47
|
*/
|
|
44
48
|
export declare class MemoryStorageDriver implements IStorageDriver {
|
|
45
49
|
private readonly objects;
|
|
50
|
+
private stored;
|
|
46
51
|
capabilities(): StorageCaps;
|
|
47
52
|
putImmutable(key: GenKey, write: (sink: BlobSink) => Promise<void>): Promise<{
|
|
48
53
|
size: number;
|
|
49
54
|
sha256: string;
|
|
50
55
|
}>;
|
|
51
56
|
getRange(key: GenKey, offset: number, length: number): Promise<Uint8Array>;
|
|
52
|
-
getTail(key: GenKey, maxBytes: number): Promise<
|
|
53
|
-
|
|
54
|
-
size: number;
|
|
55
|
-
}>;
|
|
56
|
-
delete(key: GenKey): Promise<void>;
|
|
57
|
+
getTail(key: GenKey, maxBytes: number): Promise<TailRead>;
|
|
58
|
+
delete(key: GenKey, options?: StorageDeleteOptions): Promise<void>;
|
|
57
59
|
list(ref: SegmentRef): AsyncIterable<GenKey>;
|
|
58
60
|
private require;
|
|
59
61
|
}
|
|
@@ -46,15 +46,11 @@ export declare class RetryingStorageChunkSource implements StorageChunkSource {
|
|
|
46
46
|
readonly getChunks?: (ref: SegmentRef, keys: readonly number[], options?: ReadChunksOptions) => AsyncIterable<ChunkRead>;
|
|
47
47
|
readonly cardinalities?: (ref: SegmentRef) => Promise<ReadonlyMap<number, number> | null>;
|
|
48
48
|
readonly summary?: (ref: SegmentRef) => Promise<GenerationSummary | null>;
|
|
49
|
+
readonly stat?: (ref: SegmentRef) => Promise<(GenerationSummary & SegmentSize) | null>;
|
|
49
50
|
readonly currentGeneration?: (ref: SegmentRef) => Promise<number | null>;
|
|
50
51
|
readonly invalidate?: (ref: SegmentRef) => void;
|
|
51
52
|
readonly exists?: (ref: SegmentRef) => Promise<boolean>;
|
|
52
53
|
readonly currentVersion?: (ref: SegmentRef) => Promise<string | null>;
|
|
53
|
-
/**
|
|
54
|
-
* Forwarded, not retried: a property, with no request behind it. Without it the grounded cost report priced a
|
|
55
|
-
* retrying store's refresh at the default TTL whatever the store was configured with.
|
|
56
|
-
*/
|
|
57
|
-
get pointerRefreshMs(): number | undefined;
|
|
58
54
|
constructor(inner: StorageChunkSource, opts: RetryingOptions);
|
|
59
55
|
getChunk(ref: ChunkRef): Promise<Uint8Array | null>;
|
|
60
56
|
listChunkKeys(ref: SegmentRef): Promise<number[]>;
|