@git-stunts/git-cas 6.5.7 → 6.5.9
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/ARCHITECTURE.md +9 -0
- package/CHANGELOG.md +39 -0
- package/GUIDE.md +54 -0
- package/README.md +17 -9
- package/UPGRADING.md +68 -0
- package/build-info.json +2 -2
- package/docs/API.md +115 -12
- package/docs/releases/v6.5.8.md +89 -0
- package/docs/releases/v6.5.9.md +119 -0
- package/index.d.ts +75 -0
- package/index.js +19 -1
- package/package.json +4 -2
- package/src/domain/services/AssetService.js +201 -10
- package/src/domain/services/BoundedWriteWavePersistence.js +235 -0
- package/src/domain/services/BundleBatchPlanner.js +349 -0
- package/src/domain/services/BundleService.js +225 -2
- package/src/domain/services/CasService.d.ts +16 -0
- package/src/domain/services/CasService.js +9 -18
- package/src/domain/services/ManifestRepository.js +129 -50
- package/src/domain/services/ManifestTreeService.js +47 -0
- package/src/domain/services/PageService.js +36 -10
- package/src/domain/services/RootSet.js +32 -0
- package/src/domain/services/RootSetPersistence.js +58 -1
- package/src/domain/services/StagedTarget.js +19 -0
- package/src/domain/services/StagingWorkspace.js +95 -20
- package/src/domain/services/StagingWorkspaceRegistry.js +9 -4
- package/src/domain/services/WorkspaceCompoundAdmission.js +61 -0
- package/src/domain/services/WorkspaceCompoundScope.js +193 -0
- package/src/domain/services/forkCasPersistence.js +20 -0
- package/src/infrastructure/adapters/GitObjectSessionPool.js +47 -5
- package/src/infrastructure/adapters/GitPersistenceAdapter.js +169 -0
- package/src/infrastructure/adapters/GitPersistenceWriteScope.js +154 -0
- package/src/infrastructure/adapters/GitRefAdapter.js +38 -3
- package/src/infrastructure/adapters/GitUpdateRefSessionPool.js +115 -0
- package/src/package-version.js +1 -1
- package/src/ports/GitPersistencePort.js +43 -0
- package/src/ports/GitRefPort.js +8 -0
|
@@ -9,13 +9,19 @@ import normalizeBundlePath from '../value-objects/BundlePath.js';
|
|
|
9
9
|
import StagedBundle from '../value-objects/StagedBundle.js';
|
|
10
10
|
import BoundedPromiseCache from '../../helpers/boundedPromiseCache.js';
|
|
11
11
|
import BundleDescriptorCodec, { BUNDLE_INDEX_ENTRY } from './BundleDescriptorCodec.js';
|
|
12
|
+
import BundleBatchPlanner from './BundleBatchPlanner.js';
|
|
12
13
|
import BundleFanoutBuilder from './BundleFanoutBuilder.js';
|
|
13
14
|
import StagingEvidence from './StagingEvidence.js';
|
|
15
|
+
import { recordStagedTarget } from './StagedTarget.js';
|
|
14
16
|
|
|
15
17
|
const DEFAULT_CLOCK = Object.freeze({ now: () => new Date() });
|
|
16
18
|
const DEFAULT_MAX_NESTING_DEPTH = 32;
|
|
17
19
|
const DESCRIPTOR_CACHE_ENTRIES = 1_024;
|
|
18
20
|
const DESCRIPTOR_CACHE_BYTES = 16 * 1024 * 1024;
|
|
21
|
+
export const DEFAULT_BUNDLE_WRITE_BATCH_BUNDLES = 64;
|
|
22
|
+
export const DEFAULT_BUNDLE_WRITE_BATCH_MEMBERS = 8_192;
|
|
23
|
+
export const DEFAULT_BUNDLE_WRITE_BATCH_OBJECTS = 256;
|
|
24
|
+
export const DEFAULT_BUNDLE_WRITE_BATCH_BYTES = 64 * 1024 * 1024;
|
|
19
25
|
|
|
20
26
|
/**
|
|
21
27
|
* Builds and traverses deterministic, targeted structured bundle trees.
|
|
@@ -92,6 +98,32 @@ export default class BundleService {
|
|
|
92
98
|
return await this.#putOrdered(members, limits);
|
|
93
99
|
}
|
|
94
100
|
|
|
101
|
+
/**
|
|
102
|
+
* Builds an explicitly bounded group of ordered bundles through shared
|
|
103
|
+
* descriptor and tree dependency waves.
|
|
104
|
+
*/
|
|
105
|
+
async putOrderedBatch(options = {}) {
|
|
106
|
+
return await withWriteScope(
|
|
107
|
+
this.#persistence,
|
|
108
|
+
async (persistence) => await this.putOrderedBatchWithPersistence(options, persistence),
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** @internal Builds a bounded bundle group through an operation-owned persistence view. */
|
|
113
|
+
async putOrderedBatchWithPersistence(options = {}, persistence) {
|
|
114
|
+
const batch = BundleService.#batchOptions(options);
|
|
115
|
+
const staging = new StagingEvidence();
|
|
116
|
+
try {
|
|
117
|
+
const admitted = await this.#admitOrderedBatch(batch.bundles, batch.maxBatchMembers);
|
|
118
|
+
if (admitted.length === 0) {
|
|
119
|
+
return Object.freeze([]);
|
|
120
|
+
}
|
|
121
|
+
return await this.#writeAdmittedBatch({ admitted, batch, persistence, staging });
|
|
122
|
+
} catch (error) {
|
|
123
|
+
throw augmentError(error, { staging: staging.snapshot() });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
95
127
|
/** @internal Builds from handles whose complete support graphs were already validated. */
|
|
96
128
|
async putOrderedReferences({ members, limits }) {
|
|
97
129
|
if (!isIterable(members)) {
|
|
@@ -327,19 +359,129 @@ export default class BundleService {
|
|
|
327
359
|
previousPath = path;
|
|
328
360
|
}
|
|
329
361
|
const result = await builder.finish();
|
|
330
|
-
return new StagedBundle({
|
|
362
|
+
return recordStagedTarget(new StagedBundle({
|
|
331
363
|
handle: new BundleHandle({ codec: this.#codec.extension, oid: result.oid }),
|
|
332
364
|
memberCount: result.memberCount,
|
|
333
365
|
indexDepth: result.indexDepth,
|
|
334
366
|
descriptorBytes: result.descriptorBytes,
|
|
335
367
|
limits,
|
|
336
368
|
observedAt,
|
|
337
|
-
});
|
|
369
|
+
}));
|
|
338
370
|
} catch (error) {
|
|
339
371
|
throw augmentError(error, { staging: staging.snapshot() });
|
|
340
372
|
}
|
|
341
373
|
}
|
|
342
374
|
|
|
375
|
+
async #admitOrderedBatch(requests, maxBatchMembers) {
|
|
376
|
+
const admitted = [];
|
|
377
|
+
let aggregateMembers = 0;
|
|
378
|
+
for (const request of requests) {
|
|
379
|
+
if (!request || typeof request !== 'object' || !isIterable(request.members)) {
|
|
380
|
+
throw createCasError(
|
|
381
|
+
'Ordered bundle batch entries must provide iterable members',
|
|
382
|
+
ErrorCodes.INVALID_OPTIONS,
|
|
383
|
+
);
|
|
384
|
+
}
|
|
385
|
+
const limits = this.#limits.lower(request.limits);
|
|
386
|
+
const members = [];
|
|
387
|
+
let previousPath = null;
|
|
388
|
+
for await (const pair of request.members) {
|
|
389
|
+
const [rawPath, value] = BundleService.#memberPair(pair);
|
|
390
|
+
const path = normalizeBundlePath(rawPath, limits.maxMemberPathBytes);
|
|
391
|
+
BundleService.#assertOrder(path, previousPath);
|
|
392
|
+
aggregateMembers += 1;
|
|
393
|
+
BundleService.#assertMemberCounts(members.length + 1, aggregateMembers, {
|
|
394
|
+
maxMembers: limits.maxMembers,
|
|
395
|
+
maxBatchMembers,
|
|
396
|
+
});
|
|
397
|
+
members.push({ path, value, inline: inlinePageOptions(value) });
|
|
398
|
+
previousPath = path;
|
|
399
|
+
}
|
|
400
|
+
admitted.push({ members, limits, observedAt: this.#observedAt() });
|
|
401
|
+
}
|
|
402
|
+
return admitted;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
async #writeAdmittedBatch({ admitted, batch, persistence, staging }) {
|
|
406
|
+
const inlinePages = admitted.flatMap((request) =>
|
|
407
|
+
request.members.filter((member) => member.inline).map((member) => member.inline)
|
|
408
|
+
);
|
|
409
|
+
const plannedObjects = BundleBatchPlanner.estimateObjectCount(admitted);
|
|
410
|
+
BundleService.#assertBatchObjects(plannedObjects + inlinePages.length, batch.maxBatchObjects);
|
|
411
|
+
const pages = await this.#writeInlinePageBatch(inlinePages, {
|
|
412
|
+
batch,
|
|
413
|
+
persistence,
|
|
414
|
+
staging,
|
|
415
|
+
});
|
|
416
|
+
const prepared = await this.#prepareAdmittedBatch(admitted, pages);
|
|
417
|
+
const pageBytes = pages.reduce((total, page) => total + page.page.size, 0);
|
|
418
|
+
const planner = new BundleBatchPlanner({
|
|
419
|
+
persistence,
|
|
420
|
+
codec: this.#codec,
|
|
421
|
+
staging,
|
|
422
|
+
maxBatchObjects: batch.maxBatchObjects - pages.length,
|
|
423
|
+
maxBatchBytes: batch.maxBatchBytes - pageBytes,
|
|
424
|
+
});
|
|
425
|
+
const plans = prepared.map((request) => planner.create(request));
|
|
426
|
+
const results = await planner.write(plans);
|
|
427
|
+
return Object.freeze(results.map((result) => this.#stagedBatchBundle(result)));
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
async #writeInlinePageBatch(inlinePages, { batch, staging, persistence }) {
|
|
431
|
+
if (inlinePages.length === 0) {
|
|
432
|
+
return [];
|
|
433
|
+
}
|
|
434
|
+
if (typeof this.#pages.putBatch !== 'function') {
|
|
435
|
+
throw createCasError('Bundle batching requires page batch support', ErrorCodes.INVALID_OPTIONS);
|
|
436
|
+
}
|
|
437
|
+
const options = {
|
|
438
|
+
pages: inlinePages,
|
|
439
|
+
maxBatchBytes: batch.maxBatchBytes,
|
|
440
|
+
maxBatchPages: batch.maxBatchObjects,
|
|
441
|
+
};
|
|
442
|
+
const pages = typeof this.#pages.putBatchWithPersistence === 'function'
|
|
443
|
+
? await this.#pages.putBatchWithPersistence(options, persistence)
|
|
444
|
+
: await this.#pages.putBatch(options);
|
|
445
|
+
for (const page of pages) {
|
|
446
|
+
staging.record(page.handle.oid, 'blob');
|
|
447
|
+
staging.recordHandle(page.handle);
|
|
448
|
+
}
|
|
449
|
+
return pages;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
async #prepareAdmittedBatch(admitted, pages) {
|
|
453
|
+
const validation = { active: new Set(), cache: new Map() };
|
|
454
|
+
const prepared = [];
|
|
455
|
+
let pageIndex = 0;
|
|
456
|
+
for (const request of admitted) {
|
|
457
|
+
const members = [];
|
|
458
|
+
for (const member of request.members) {
|
|
459
|
+
if (member.inline) {
|
|
460
|
+
members.push(preparedPageMember(member.path, pages[pageIndex]));
|
|
461
|
+
pageIndex += 1;
|
|
462
|
+
} else {
|
|
463
|
+
members.push(await this.#prepareHandleMember(member.path, member.value, {
|
|
464
|
+
validation,
|
|
465
|
+
validateTargets: true,
|
|
466
|
+
}));
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
prepared.push({ ...request, members });
|
|
470
|
+
}
|
|
471
|
+
return prepared;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
#stagedBatchBundle(result) {
|
|
475
|
+
return recordStagedTarget(new StagedBundle({
|
|
476
|
+
handle: new BundleHandle({ codec: this.#codec.extension, oid: result.oid }),
|
|
477
|
+
memberCount: result.memberCount,
|
|
478
|
+
indexDepth: result.indexDepth,
|
|
479
|
+
descriptorBytes: result.descriptorBytes,
|
|
480
|
+
limits: result.limits,
|
|
481
|
+
observedAt: result.observedAt,
|
|
482
|
+
}));
|
|
483
|
+
}
|
|
484
|
+
|
|
343
485
|
async #prepareMember(path, value, { staging, validation, validateTargets }) {
|
|
344
486
|
const inline = inlinePageOptions(value);
|
|
345
487
|
if (inline) {
|
|
@@ -693,6 +835,54 @@ export default class BundleService {
|
|
|
693
835
|
);
|
|
694
836
|
}
|
|
695
837
|
|
|
838
|
+
static #batchOptions(options) {
|
|
839
|
+
if (!options || typeof options !== 'object' || !Array.isArray(options.bundles)) {
|
|
840
|
+
throw createCasError('Bundle batch must provide a bundle array', ErrorCodes.INVALID_OPTIONS);
|
|
841
|
+
}
|
|
842
|
+
const batch = {
|
|
843
|
+
bundles: options.bundles,
|
|
844
|
+
maxBatchBundles: options.maxBatchBundles ?? DEFAULT_BUNDLE_WRITE_BATCH_BUNDLES,
|
|
845
|
+
maxBatchMembers: options.maxBatchMembers ?? DEFAULT_BUNDLE_WRITE_BATCH_MEMBERS,
|
|
846
|
+
maxBatchObjects: options.maxBatchObjects ?? DEFAULT_BUNDLE_WRITE_BATCH_OBJECTS,
|
|
847
|
+
maxBatchBytes: options.maxBatchBytes ?? DEFAULT_BUNDLE_WRITE_BATCH_BYTES,
|
|
848
|
+
};
|
|
849
|
+
assertBatchLimit(batch.maxBatchBundles, 'bundle count', DEFAULT_BUNDLE_WRITE_BATCH_OBJECTS);
|
|
850
|
+
assertBatchLimit(batch.maxBatchMembers, 'member count', 100_000);
|
|
851
|
+
assertBatchLimit(batch.maxBatchObjects, 'object count', DEFAULT_BUNDLE_WRITE_BATCH_OBJECTS);
|
|
852
|
+
assertBatchLimit(batch.maxBatchBytes, 'byte count', DEFAULT_BUNDLE_WRITE_BATCH_BYTES);
|
|
853
|
+
if (batch.bundles.length > batch.maxBatchBundles) {
|
|
854
|
+
throw createCasError('Bundle batch exceeds its configured bundle limit', ErrorCodes.INVALID_OPTIONS, {
|
|
855
|
+
observedBundles: batch.bundles.length,
|
|
856
|
+
maxBatchBundles: batch.maxBatchBundles,
|
|
857
|
+
});
|
|
858
|
+
}
|
|
859
|
+
return batch;
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
static #assertBatchObjects(observedObjects, maxBatchObjects) {
|
|
863
|
+
if (observedObjects > maxBatchObjects) {
|
|
864
|
+
throw createCasError('Bundle batch exceeds its configured object limit', ErrorCodes.INVALID_OPTIONS, {
|
|
865
|
+
observedObjects,
|
|
866
|
+
maxBatchObjects,
|
|
867
|
+
});
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
static #assertMemberCounts(bundleMembers, batchMembers, limits) {
|
|
872
|
+
if (bundleMembers > limits.maxMembers) {
|
|
873
|
+
throw createCasError('Bundle exceeds its member limit', ErrorCodes.BUNDLE_MEMBER_LIMIT, {
|
|
874
|
+
observedMembers: bundleMembers,
|
|
875
|
+
maxMembers: limits.maxMembers,
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
if (batchMembers > limits.maxBatchMembers) {
|
|
879
|
+
throw createCasError('Bundle batch exceeds its member limit', ErrorCodes.BUNDLE_MEMBER_LIMIT, {
|
|
880
|
+
observedMembers: batchMembers,
|
|
881
|
+
maxBatchMembers: limits.maxBatchMembers,
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
|
|
696
886
|
static #assertDependencies({ persistence, codec, pages, resolveHandle, openHandle, clock }) {
|
|
697
887
|
BundleService.#assertPersistence(persistence);
|
|
698
888
|
BundleService.#assertCodecDependency(codec);
|
|
@@ -746,6 +936,33 @@ function inlinePageOptions(value) {
|
|
|
746
936
|
return null;
|
|
747
937
|
}
|
|
748
938
|
|
|
939
|
+
function preparedPageMember(path, staged) {
|
|
940
|
+
if (!staged?.handle) {
|
|
941
|
+
throw createCasError(
|
|
942
|
+
'Page batch did not return a staged handle for every inline member',
|
|
943
|
+
ErrorCodes.GIT_ERROR,
|
|
944
|
+
{ path },
|
|
945
|
+
);
|
|
946
|
+
}
|
|
947
|
+
return Object.freeze({
|
|
948
|
+
path,
|
|
949
|
+
handle: staged.handle,
|
|
950
|
+
oid: staged.handle.oid,
|
|
951
|
+
type: 'blob',
|
|
952
|
+
size: staged.page.size,
|
|
953
|
+
});
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
function assertBatchLimit(value, label, maximum) {
|
|
957
|
+
if (!Number.isSafeInteger(value) || value < 1 || value > maximum) {
|
|
958
|
+
throw createCasError(
|
|
959
|
+
`Bundle batch ${label} must be a positive safe integer within its supported maximum`,
|
|
960
|
+
ErrorCodes.INVALID_OPTIONS,
|
|
961
|
+
{ label, value, maximum },
|
|
962
|
+
);
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
|
|
749
966
|
function bundleReference(value) {
|
|
750
967
|
if (value && typeof value === 'object' &&
|
|
751
968
|
Object.hasOwn(value, 'handle') && Object.hasOwn(value, 'size')) {
|
|
@@ -854,6 +1071,12 @@ function compareText(left, right) {
|
|
|
854
1071
|
return left < right ? -1 : left > right ? 1 : 0;
|
|
855
1072
|
}
|
|
856
1073
|
|
|
1074
|
+
async function withWriteScope(persistence, operation) {
|
|
1075
|
+
return typeof persistence.withWriteScope === 'function'
|
|
1076
|
+
? await persistence.withWriteScope(operation)
|
|
1077
|
+
: await operation(persistence);
|
|
1078
|
+
}
|
|
1079
|
+
|
|
857
1080
|
function augmentError(error, meta) {
|
|
858
1081
|
if (error && typeof error === 'object') {
|
|
859
1082
|
error.meta = { ...error.meta, ...meta };
|
|
@@ -65,7 +65,9 @@ export interface CodecPort {
|
|
|
65
65
|
/** Port interface for persisting data to Git's object database. */
|
|
66
66
|
export interface GitPersistencePort {
|
|
67
67
|
writeBlob(content: Uint8Array): Promise<string>;
|
|
68
|
+
writeBlobs?(contents: Iterable<Uint8Array>): Promise<string[]>;
|
|
68
69
|
writeTree(entries: string[]): Promise<string>;
|
|
70
|
+
writeTrees?(trees: Iterable<string[]>): Promise<string[]>;
|
|
69
71
|
readBlob(oid: string, maxBytes?: number): Promise<Uint8Array>;
|
|
70
72
|
readBlobStream(oid: string): Promise<AsyncIterable<Uint8Array>>;
|
|
71
73
|
readTree(
|
|
@@ -80,6 +82,12 @@ export interface GitPersistencePort {
|
|
|
80
82
|
): AsyncIterable<{ mode: string; type: string; oid: string; name: string }>;
|
|
81
83
|
readObjectType(oid: string): Promise<string>;
|
|
82
84
|
readObjectSize(oid: string): Promise<number>;
|
|
85
|
+
readObjectInfos?(
|
|
86
|
+
oids: Iterable<string>
|
|
87
|
+
): Promise<Array<{ oid: string; type: string; size: number }>>;
|
|
88
|
+
withWriteScope?<T>(
|
|
89
|
+
operation: (persistence: GitPersistencePort) => Promise<T>
|
|
90
|
+
): Promise<T>;
|
|
83
91
|
setMaxBlobSize?(maxBlobSize: number): void;
|
|
84
92
|
}
|
|
85
93
|
|
|
@@ -173,7 +181,11 @@ export interface FileRestorePlan {
|
|
|
173
181
|
export default class CasService {
|
|
174
182
|
readonly persistence: GitPersistencePort;
|
|
175
183
|
readonly codec: CodecPort;
|
|
184
|
+
readonly compressionAdapter: CompressionPort;
|
|
176
185
|
readonly crypto: CryptoPort;
|
|
186
|
+
readonly chunker: ChunkingPort;
|
|
187
|
+
readonly formatVersion?: string;
|
|
188
|
+
readonly legacyMode: boolean;
|
|
177
189
|
readonly observability: ObservabilityPort;
|
|
178
190
|
readonly chunkSize: number;
|
|
179
191
|
readonly merkleThreshold: number;
|
|
@@ -210,6 +222,10 @@ export default class CasService {
|
|
|
210
222
|
|
|
211
223
|
createTree(options: { manifest: Manifest; merkleThreshold?: number }): Promise<string>;
|
|
212
224
|
|
|
225
|
+
createTrees(
|
|
226
|
+
requests: Array<{ manifest: Manifest; merkleThreshold?: number }>,
|
|
227
|
+
): Promise<string[]>;
|
|
228
|
+
|
|
213
229
|
restore(options: {
|
|
214
230
|
manifest: Manifest;
|
|
215
231
|
encryptionKey?: Uint8Array;
|
|
@@ -26,6 +26,7 @@ import RestoreFramed from '../strategies/RestoreFramed.js';
|
|
|
26
26
|
import RestoreWhole from '../strategies/RestoreWhole.js';
|
|
27
27
|
import RestoreStrategy from '../strategies/RestoreStrategy.js';
|
|
28
28
|
import ManifestRepository from './ManifestRepository.js';
|
|
29
|
+
import ManifestTreeService from './ManifestTreeService.js';
|
|
29
30
|
import RecipientService from './RecipientService.js';
|
|
30
31
|
import IntegrityVerifier from './IntegrityVerifier.js';
|
|
31
32
|
import RestoreSuccess from '../outcomes/RestoreSuccess.js';
|
|
@@ -43,11 +44,10 @@ export default class CasService {
|
|
|
43
44
|
#integrityVerifier;
|
|
44
45
|
#keyResolver;
|
|
45
46
|
#manifestRepository;
|
|
46
|
-
#
|
|
47
|
+
#manifestTrees;
|
|
47
48
|
#recipientService;
|
|
48
49
|
#restoreStrategies;
|
|
49
50
|
#storeStrategies;
|
|
50
|
-
|
|
51
51
|
/**
|
|
52
52
|
* @param {Object} options
|
|
53
53
|
* @param {import('../../ports/GitPersistencePort.js').default} options.persistence
|
|
@@ -81,6 +81,7 @@ export default class CasService {
|
|
|
81
81
|
this.chunker = chunker;
|
|
82
82
|
this.compressionAdapter = compressionAdapter;
|
|
83
83
|
this.formatVersion = formatVersion;
|
|
84
|
+
this.legacyMode = legacyMode;
|
|
84
85
|
this.merkleThreshold = merkleThreshold;
|
|
85
86
|
this.concurrency = concurrency;
|
|
86
87
|
this.maxRestoreBufferSize = maxRestoreBufferSize;
|
|
@@ -106,6 +107,7 @@ export default class CasService {
|
|
|
106
107
|
});
|
|
107
108
|
this.#framed = new FramedRecordCodec({ crypto, observability: safeObservability });
|
|
108
109
|
this.#manifestRepository = new ManifestRepository({ codec, crypto, legacyMode, merkleThreshold, persistence });
|
|
110
|
+
this.#manifestTrees = new ManifestTreeService({ repository: this.#manifestRepository });
|
|
109
111
|
this.#storeStrategies = this.#buildStoreStrategies({ crypto });
|
|
110
112
|
this.#restoreStrategies = this.#buildRestoreStrategies({ crypto, maxRestoreBufferSize });
|
|
111
113
|
this.#recipientService = new RecipientService({ crypto, keyResolver: this.#keyResolver });
|
|
@@ -313,7 +315,7 @@ export default class CasService {
|
|
|
313
315
|
|
|
314
316
|
#finalizeStore({ manifestData, merkleThreshold, keyInfo, slug }) {
|
|
315
317
|
const manifest = new Manifest(manifestData);
|
|
316
|
-
this.#
|
|
318
|
+
this.#manifestTrees.remember(manifest, merkleThreshold);
|
|
317
319
|
this.observability.metric('file', {
|
|
318
320
|
action: 'stored',
|
|
319
321
|
slug,
|
|
@@ -328,16 +330,6 @@ export default class CasService {
|
|
|
328
330
|
return StoreEncryptionConfig.resolve({ encryption, hasEncryptionKey, chunker, observability: this.observability });
|
|
329
331
|
}
|
|
330
332
|
|
|
331
|
-
/**
|
|
332
|
-
* @param {Manifest} manifest
|
|
333
|
-
* @param {number|undefined} merkleThreshold
|
|
334
|
-
*/
|
|
335
|
-
#rememberMerkleThreshold(manifest, merkleThreshold) {
|
|
336
|
-
if (merkleThreshold !== undefined) {
|
|
337
|
-
this.#merkleThresholdByManifest.set(manifest, merkleThreshold);
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
|
|
341
333
|
async _dispatchStore({ processedSource, manifestData, keyInfo, encryptionConfig, chunker = this.chunker }) {
|
|
342
334
|
const strategy = StoreStrategy.for({
|
|
343
335
|
keyInfo,
|
|
@@ -368,13 +360,12 @@ export default class CasService {
|
|
|
368
360
|
}
|
|
369
361
|
|
|
370
362
|
async createTree({ manifest, merkleThreshold }) {
|
|
371
|
-
|
|
372
|
-
return await this.#manifestRepository.createTree({
|
|
373
|
-
manifest,
|
|
374
|
-
merkleThreshold: merkleThreshold ?? this.#merkleThresholdByManifest.get(manifest),
|
|
375
|
-
});
|
|
363
|
+
return await this.#manifestTrees.createTree({ manifest, merkleThreshold });
|
|
376
364
|
}
|
|
377
365
|
|
|
366
|
+
async createTrees(requests) {
|
|
367
|
+
return await this.#manifestTrees.createTrees(requests);
|
|
368
|
+
}
|
|
378
369
|
async restore({ manifest, encryptionKey, passphrase }) {
|
|
379
370
|
const chunks = [];
|
|
380
371
|
for await (const chunk of this.restoreStream({ manifest, encryptionKey, passphrase })) {
|
|
@@ -49,25 +49,32 @@ export default class ManifestRepository {
|
|
|
49
49
|
* @returns {Promise<string>}
|
|
50
50
|
*/
|
|
51
51
|
async createTree({ manifest, merkleThreshold }) {
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
return await this.#createMerkleTree({ manifest, merkleThreshold: effectiveThreshold });
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
const manifestData = manifest.toJSON();
|
|
59
|
-
const hashableBytes = encodeForHash(manifestData, this.#codec);
|
|
60
|
-
manifestData.manifestHash = await this.#crypto.sha256(hashableBytes);
|
|
61
|
-
const serializedManifest = normalizeCodecBytes(this.#codec.encode(manifestData));
|
|
62
|
-
const manifestOid = await this.#persistence.writeBlob(serializedManifest);
|
|
63
|
-
|
|
64
|
-
const treeEntries = buildFlatManifestTreeEntries({
|
|
65
|
-
manifestOid,
|
|
66
|
-
chunks,
|
|
67
|
-
extension: this.#codec.extension,
|
|
68
|
-
});
|
|
52
|
+
const roots = await this.createTrees([{ manifest, merkleThreshold }]);
|
|
53
|
+
return roots[0];
|
|
54
|
+
}
|
|
69
55
|
|
|
70
|
-
|
|
56
|
+
/**
|
|
57
|
+
* Creates an explicitly bounded ordered manifest-tree wave. Flat manifest
|
|
58
|
+
* blobs and Merkle sub-manifests share the first blob phase, Merkle roots
|
|
59
|
+
* share the second, and all complete trees share one final tree phase.
|
|
60
|
+
*
|
|
61
|
+
* @param {Array<{ manifest: Manifest, merkleThreshold?: number }>} requests
|
|
62
|
+
* @returns {Promise<string[]>}
|
|
63
|
+
*/
|
|
64
|
+
async createTrees(requests) {
|
|
65
|
+
const plans = await Promise.all(requests.map((request) => this.#planTree(request)));
|
|
66
|
+
const firstBlobs = plans.flatMap((plan) => plan.firstBlobs);
|
|
67
|
+
const firstOids = await this.#writeBlobs(firstBlobs);
|
|
68
|
+
let firstIndex = 0;
|
|
69
|
+
for (const plan of plans) {
|
|
70
|
+
plan.acceptFirstOids(firstOids.slice(firstIndex, firstIndex + plan.firstBlobs.length));
|
|
71
|
+
firstIndex += plan.firstBlobs.length;
|
|
72
|
+
}
|
|
73
|
+
const merklePlans = plans.filter((plan) => plan.kind === 'merkle');
|
|
74
|
+
const rootBytes = await Promise.all(merklePlans.map((plan) => plan.rootBytes()));
|
|
75
|
+
const rootOids = await this.#writeBlobs(rootBytes);
|
|
76
|
+
merklePlans.forEach((plan, index) => plan.acceptRootOid(rootOids[index]));
|
|
77
|
+
return await this.#writeTrees(plans.map((plan) => plan.treeEntries()));
|
|
71
78
|
}
|
|
72
79
|
|
|
73
80
|
/**
|
|
@@ -121,43 +128,97 @@ export default class ManifestRepository {
|
|
|
121
128
|
return original === undefined || isLegacyNoAad(original);
|
|
122
129
|
}
|
|
123
130
|
|
|
124
|
-
async #
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
for (let i = 0; i < chunks.length; i += merkleThreshold) {
|
|
129
|
-
const group = chunks.slice(i, i + merkleThreshold);
|
|
130
|
-
const subManifestData = { chunks: group.map((c) => ({ index: c.index, size: c.size, digest: c.digest, blob: c.blob })) };
|
|
131
|
-
const serialized = normalizeCodecBytes(this.#codec.encode(subManifestData));
|
|
132
|
-
const oid = await this.#persistence.writeBlob(serialized);
|
|
133
|
-
|
|
134
|
-
subManifestRefs.push({
|
|
135
|
-
oid,
|
|
136
|
-
chunkCount: group.length,
|
|
137
|
-
startIndex: i,
|
|
138
|
-
});
|
|
131
|
+
async #planTree({ manifest, merkleThreshold }) {
|
|
132
|
+
const effectiveThreshold = merkleThreshold ?? this.#merkleThreshold;
|
|
133
|
+
if (manifest.chunks.length > effectiveThreshold) {
|
|
134
|
+
return this.#planMerkleTree(manifest, effectiveThreshold);
|
|
139
135
|
}
|
|
140
|
-
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
136
|
+
const manifestData = manifest.toJSON();
|
|
137
|
+
const hashableBytes = encodeForHash(manifestData, this.#codec);
|
|
138
|
+
manifestData.manifestHash = await this.#crypto.sha256(hashableBytes);
|
|
139
|
+
const serialized = normalizeCodecBytes(this.#codec.encode(manifestData));
|
|
140
|
+
let manifestOid;
|
|
141
|
+
return {
|
|
142
|
+
kind: 'flat',
|
|
143
|
+
firstBlobs: [serialized],
|
|
144
|
+
acceptFirstOids: ([oid]) => { manifestOid = oid; },
|
|
145
|
+
rootBytes: async () => null,
|
|
146
|
+
acceptRootOid: () => {},
|
|
147
|
+
treeEntries: () => buildFlatManifestTreeEntries({
|
|
148
|
+
manifestOid,
|
|
149
|
+
chunks: manifest.chunks,
|
|
150
|
+
extension: this.#codec.extension,
|
|
151
|
+
}),
|
|
146
152
|
};
|
|
147
|
-
|
|
148
|
-
rootManifestData.manifestHash = await this.#crypto.sha256(rootHashableBytes);
|
|
153
|
+
}
|
|
149
154
|
|
|
150
|
-
|
|
151
|
-
const
|
|
155
|
+
#planMerkleTree(manifest, merkleThreshold) {
|
|
156
|
+
const chunks = [...manifest.chunks];
|
|
157
|
+
const groups = [];
|
|
158
|
+
for (let index = 0; index < chunks.length; index += merkleThreshold) {
|
|
159
|
+
groups.push({ index, chunks: chunks.slice(index, index + merkleThreshold) });
|
|
160
|
+
}
|
|
161
|
+
const firstBlobs = groups.map(({ chunks: group }) => normalizeCodecBytes(this.#codec.encode({
|
|
162
|
+
chunks: group.map((chunk) => ({
|
|
163
|
+
index: chunk.index,
|
|
164
|
+
size: chunk.size,
|
|
165
|
+
digest: chunk.digest,
|
|
166
|
+
blob: chunk.blob,
|
|
167
|
+
})),
|
|
168
|
+
})));
|
|
169
|
+
let subManifestRefs;
|
|
170
|
+
let rootManifestOid;
|
|
171
|
+
return {
|
|
172
|
+
kind: 'merkle',
|
|
173
|
+
firstBlobs,
|
|
174
|
+
acceptFirstOids: (oids) => {
|
|
175
|
+
subManifestRefs = groups.map((group, index) => ({
|
|
176
|
+
oid: oids[index],
|
|
177
|
+
chunkCount: group.chunks.length,
|
|
178
|
+
startIndex: group.index,
|
|
179
|
+
}));
|
|
180
|
+
},
|
|
181
|
+
rootBytes: async () => {
|
|
182
|
+
const rootManifestData = {
|
|
183
|
+
...manifest.toJSON(),
|
|
184
|
+
version: 2,
|
|
185
|
+
chunks: [],
|
|
186
|
+
subManifests: subManifestRefs,
|
|
187
|
+
};
|
|
188
|
+
const hashableBytes = encodeForHash(rootManifestData, this.#codec);
|
|
189
|
+
rootManifestData.manifestHash = await this.#crypto.sha256(hashableBytes);
|
|
190
|
+
return normalizeCodecBytes(this.#codec.encode(rootManifestData));
|
|
191
|
+
},
|
|
192
|
+
acceptRootOid: (oid) => { rootManifestOid = oid; },
|
|
193
|
+
treeEntries: () => buildMerkleTreeEntries({
|
|
194
|
+
rootManifestOid,
|
|
195
|
+
subManifests: subManifestRefs,
|
|
196
|
+
chunks,
|
|
197
|
+
extension: this.#codec.extension,
|
|
198
|
+
}),
|
|
199
|
+
};
|
|
200
|
+
}
|
|
152
201
|
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
202
|
+
async #writeBlobs(contents) {
|
|
203
|
+
if (contents.length === 0) {
|
|
204
|
+
return [];
|
|
205
|
+
}
|
|
206
|
+
const oids = typeof this.#persistence.writeBlobs === 'function'
|
|
207
|
+
? await this.#persistence.writeBlobs(contents)
|
|
208
|
+
: await writeIndividually(contents, (content) => this.#persistence.writeBlob(content));
|
|
209
|
+
ManifestRepository.#assertCardinality('blob', contents, oids);
|
|
210
|
+
return oids;
|
|
211
|
+
}
|
|
159
212
|
|
|
160
|
-
|
|
213
|
+
async #writeTrees(trees) {
|
|
214
|
+
if (trees.length === 0) {
|
|
215
|
+
return [];
|
|
216
|
+
}
|
|
217
|
+
const oids = typeof this.#persistence.writeTrees === 'function'
|
|
218
|
+
? await this.#persistence.writeTrees(trees)
|
|
219
|
+
: await writeIndividually(trees, (entries) => this.#persistence.writeTree(entries));
|
|
220
|
+
ManifestRepository.#assertCardinality('tree', trees, oids);
|
|
221
|
+
return oids;
|
|
161
222
|
}
|
|
162
223
|
|
|
163
224
|
async #readManifestBlob(treeOid) {
|
|
@@ -266,6 +327,16 @@ export default class ManifestRepository {
|
|
|
266
327
|
return allChunks;
|
|
267
328
|
}
|
|
268
329
|
|
|
330
|
+
static #assertCardinality(kind, input, output) {
|
|
331
|
+
if (output.length !== input.length) {
|
|
332
|
+
throw createCasError(
|
|
333
|
+
`Persistence returned the wrong number of manifest ${kind} identifiers`,
|
|
334
|
+
ErrorCodes.GIT_ERROR,
|
|
335
|
+
{ expected: input.length, actual: output.length },
|
|
336
|
+
);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
269
340
|
async #readSubManifestBlob(oid, treeOid) {
|
|
270
341
|
const subManifestOid = Oid.from(oid).toString();
|
|
271
342
|
const normalizedTreeOid = Oid.from(treeOid).toString();
|
|
@@ -284,3 +355,11 @@ export default class ManifestRepository {
|
|
|
284
355
|
}
|
|
285
356
|
}
|
|
286
357
|
}
|
|
358
|
+
|
|
359
|
+
async function writeIndividually(values, write) {
|
|
360
|
+
const results = [];
|
|
361
|
+
for (const value of values) {
|
|
362
|
+
results.push(await write(value));
|
|
363
|
+
}
|
|
364
|
+
return results;
|
|
365
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import createCasError from '../errors/createCasError.js';
|
|
2
|
+
import { ErrorCodes } from '../errors/index.js';
|
|
3
|
+
|
|
4
|
+
/** Validates manifest-tree requests and retains per-manifest threshold choices. */
|
|
5
|
+
export default class ManifestTreeService {
|
|
6
|
+
#repository;
|
|
7
|
+
#thresholds = new WeakMap();
|
|
8
|
+
|
|
9
|
+
constructor({ repository }) {
|
|
10
|
+
this.#repository = repository;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
remember(manifest, merkleThreshold) {
|
|
14
|
+
if (merkleThreshold !== undefined) {
|
|
15
|
+
this.#thresholds.set(manifest, merkleThreshold);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async createTree({ manifest, merkleThreshold }) {
|
|
20
|
+
return await this.#repository.createTree(
|
|
21
|
+
this.#validated({ manifest, merkleThreshold })
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async createTrees(requests) {
|
|
26
|
+
return await this.#repository.createTrees(
|
|
27
|
+
requests.map((request) => this.#validated(request))
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
#validated({ manifest, merkleThreshold }) {
|
|
32
|
+
if (
|
|
33
|
+
merkleThreshold !== undefined &&
|
|
34
|
+
(!Number.isSafeInteger(merkleThreshold) || merkleThreshold < 1)
|
|
35
|
+
) {
|
|
36
|
+
throw createCasError(
|
|
37
|
+
'merkleThreshold must be a positive safe integer',
|
|
38
|
+
ErrorCodes.INVALID_OPTIONS,
|
|
39
|
+
{ merkleThreshold },
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
return {
|
|
43
|
+
manifest,
|
|
44
|
+
merkleThreshold: merkleThreshold ?? this.#thresholds.get(manifest),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
}
|