@git-stunts/git-cas 6.5.7 → 6.5.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/GUIDE.md +29 -0
  3. package/README.md +11 -7
  4. package/UPGRADING.md +29 -0
  5. package/build-info.json +2 -2
  6. package/docs/API.md +66 -12
  7. package/docs/releases/v6.5.8.md +89 -0
  8. package/index.d.ts +50 -0
  9. package/index.js +15 -1
  10. package/package.json +3 -2
  11. package/src/domain/services/AssetService.js +201 -10
  12. package/src/domain/services/BoundedWriteWavePersistence.js +235 -0
  13. package/src/domain/services/BundleBatchPlanner.js +349 -0
  14. package/src/domain/services/BundleService.js +225 -2
  15. package/src/domain/services/CasService.d.ts +16 -0
  16. package/src/domain/services/CasService.js +9 -18
  17. package/src/domain/services/ManifestRepository.js +129 -50
  18. package/src/domain/services/ManifestTreeService.js +47 -0
  19. package/src/domain/services/PageService.js +26 -9
  20. package/src/domain/services/RootSet.js +32 -0
  21. package/src/domain/services/RootSetPersistence.js +58 -1
  22. package/src/domain/services/StagedTarget.js +19 -0
  23. package/src/domain/services/StagingWorkspace.js +21 -7
  24. package/src/domain/services/forkCasPersistence.js +20 -0
  25. package/src/infrastructure/adapters/GitObjectSessionPool.js +47 -5
  26. package/src/infrastructure/adapters/GitPersistenceAdapter.js +169 -0
  27. package/src/infrastructure/adapters/GitPersistenceWriteScope.js +154 -0
  28. package/src/infrastructure/adapters/GitRefAdapter.js +38 -3
  29. package/src/infrastructure/adapters/GitUpdateRefSessionPool.js +115 -0
  30. package/src/package-version.js +1 -1
  31. package/src/ports/GitPersistencePort.js +43 -0
  32. package/src/ports/GitRefPort.js +8 -0
@@ -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
- #merkleThresholdByManifest = new WeakMap();
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.#rememberMerkleThreshold(manifest, merkleThreshold);
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
- CasService.#validateMerkleThreshold(merkleThreshold);
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 chunks = manifest.chunks;
53
- const effectiveThreshold = merkleThreshold ?? this.#merkleThreshold;
54
- if (chunks.length > effectiveThreshold) {
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
- return await this.#persistence.writeTree(treeEntries);
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 #createMerkleTree({ manifest, merkleThreshold }) {
125
- const chunks = [...manifest.chunks];
126
- const subManifestRefs = [];
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 rootManifestData = {
142
- ...manifest.toJSON(),
143
- version: 2,
144
- chunks: [],
145
- subManifests: subManifestRefs,
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
- const rootHashableBytes = encodeForHash(rootManifestData, this.#codec);
148
- rootManifestData.manifestHash = await this.#crypto.sha256(rootHashableBytes);
153
+ }
149
154
 
150
- const serializedRoot = normalizeCodecBytes(this.#codec.encode(rootManifestData));
151
- const rootManifestOid = await this.#persistence.writeBlob(serializedRoot);
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
- const treeEntries = buildMerkleTreeEntries({
154
- rootManifestOid,
155
- subManifests: subManifestRefs,
156
- chunks,
157
- extension: this.#codec.extension,
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
- return await this.#persistence.writeTree(treeEntries);
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
+ }
@@ -5,6 +5,7 @@ import { assertHandleObjectType, mapHandleTargetError } from '../helpers/handleT
5
5
  import PageHandle from '../value-objects/PageHandle.js';
6
6
  import StagedPage from '../value-objects/StagedPage.js';
7
7
  import BoundedPromiseCache from '../../helpers/boundedPromiseCache.js';
8
+ import { recordStagedTarget } from './StagedTarget.js';
8
9
 
9
10
  export const DEFAULT_MAX_PAGE_SIZE = 16 * 1024 * 1024;
10
11
  const DEFAULT_PAGE_CACHE_ENTRIES = 128;
@@ -59,11 +60,11 @@ export default class PageService {
59
60
  const observedAt = this.#observedAt();
60
61
  const bytes = await PageService.#collect(source, limit);
61
62
  const oid = await this.#persistence.writeBlob(bytes);
62
- return new StagedPage({
63
+ return recordStagedTarget(new StagedPage({
63
64
  handle: new PageHandle({ oid }),
64
65
  size: bytes.length,
65
66
  observedAt,
66
- });
67
+ }));
67
68
  }
68
69
 
69
70
  /**
@@ -80,6 +81,19 @@ export default class PageService {
80
81
  maxBatchBytes = DEFAULT_PAGE_WRITE_BATCH_BYTES,
81
82
  maxBatchPages = DEFAULT_PAGE_WRITE_BATCH_PAGES,
82
83
  }) {
84
+ return await this.#putBatch({ pages, maxBatchBytes, maxBatchPages }, this.#persistence);
85
+ }
86
+
87
+ /** @internal Stores a page batch through an operation-owned persistence view. */
88
+ async putBatchWithPersistence({
89
+ pages,
90
+ maxBatchBytes = DEFAULT_PAGE_WRITE_BATCH_BYTES,
91
+ maxBatchPages = DEFAULT_PAGE_WRITE_BATCH_PAGES,
92
+ }, persistence) {
93
+ return await this.#putBatch({ pages, maxBatchBytes, maxBatchPages }, persistence);
94
+ }
95
+
96
+ async #putBatch({ pages, maxBatchBytes, maxBatchPages }, persistence) {
83
97
  PageService.#assertBatch(pages, maxBatchBytes, maxBatchPages);
84
98
  const prepared = [];
85
99
  let totalBytes = 0;
@@ -107,7 +121,10 @@ export default class PageService {
107
121
  if (prepared.length === 0) {
108
122
  return Object.freeze([]);
109
123
  }
110
- const oids = await this.#writeBlobs(prepared.map((page) => page.bytes));
124
+ const oids = await this.#writeBlobs(
125
+ prepared.map((page) => page.bytes),
126
+ persistence,
127
+ );
111
128
  if (oids.length !== prepared.length) {
112
129
  throw createCasError(
113
130
  'Persistence returned the wrong number of page object identifiers',
@@ -115,11 +132,11 @@ export default class PageService {
115
132
  { expected: prepared.length, actual: oids.length },
116
133
  );
117
134
  }
118
- return Object.freeze(oids.map((oid, index) => new StagedPage({
135
+ return Object.freeze(oids.map((oid, index) => recordStagedTarget(new StagedPage({
119
136
  handle: new PageHandle({ oid }),
120
137
  size: prepared[index].bytes.length,
121
138
  observedAt: prepared[index].observedAt,
122
- })));
139
+ }))));
123
140
  }
124
141
 
125
142
  /**
@@ -218,13 +235,13 @@ export default class PageService {
218
235
  return now.toISOString();
219
236
  }
220
237
 
221
- async #writeBlobs(contents) {
222
- if (typeof this.#persistence.writeBlobs === 'function') {
223
- return await this.#persistence.writeBlobs(contents);
238
+ async #writeBlobs(contents, persistence = this.#persistence) {
239
+ if (typeof persistence.writeBlobs === 'function') {
240
+ return await persistence.writeBlobs(contents);
224
241
  }
225
242
  const oids = [];
226
243
  for (const content of contents) {
227
- oids.push(await this.#persistence.writeBlob(content));
244
+ oids.push(await persistence.writeBlob(content));
228
245
  }
229
246
  return oids;
230
247
  }
@@ -108,6 +108,31 @@ export default class RootSet {
108
108
  );
109
109
  }
110
110
 
111
+ /**
112
+ * Replaces the current generation under caller-supplied exact head
113
+ * authority. Unlike replace(), this path deliberately does not read or
114
+ * retry: the checked ref update is the authority test.
115
+ *
116
+ * @param {{ entries: Iterable<object>, expectedHeadOid: string|null }} options
117
+ * @returns {Promise<object>}
118
+ */
119
+ async replaceExact(options) {
120
+ if (!RootSet.#hasExpectedHead(options)) {
121
+ throw new CasError(
122
+ 'Exact root-set replacement requires expectedHeadOid authority',
123
+ ErrorCodes.INVALID_OPTIONS,
124
+ );
125
+ }
126
+ const entries = this.#metadataCodec.normalizeEntries(options.entries);
127
+ const expectedHeadOid = RootSet.#normalizeExpectedHead(options.expectedHeadOid);
128
+ const written = await this.persistence.write({
129
+ entries,
130
+ expectedHeadOid,
131
+ message: 'root-set: replace exact current roots',
132
+ });
133
+ return { changed: true, ...written };
134
+ }
135
+
111
136
  /**
112
137
  * @param {(entries: ReadonlyArray<object>, state: Readonly<object>) => Iterable<object>|Promise<Iterable<object>>} mutator
113
138
  * @param {{ expectedHeadOid?: string|null }} [options]
@@ -250,6 +275,13 @@ export default class RootSet {
250
275
  return Oid.from(expectedHeadOid).toString();
251
276
  }
252
277
 
278
+ static #hasExpectedHead(options) {
279
+ return typeof options === 'object' &&
280
+ options !== null &&
281
+ Object.hasOwn(options, 'expectedHeadOid') &&
282
+ options.expectedHeadOid !== undefined;
283
+ }
284
+
253
285
  static #entriesEqual(left, right) {
254
286
  return JSON.stringify(left) === JSON.stringify(right);
255
287
  }
@@ -396,7 +396,50 @@ export default class RootSetPersistence {
396
396
  }
397
397
 
398
398
  async #assertTargets(entries) {
399
- const report = await this.inspectTargets(entries);
399
+ if (typeof this.persistence.readObjectInfos === 'function') {
400
+ try {
401
+ const infos = await this.persistence.readObjectInfos(entries.map((entry) => entry.oid));
402
+ this.#assertBatchTargetInfos(entries, infos);
403
+ return;
404
+ } catch (err) {
405
+ if (err?.code === ErrorCodes.ROOT_SET_TARGET_TYPE_MISMATCH) {
406
+ throw err;
407
+ }
408
+ if (err?.code !== ErrorCodes.GIT_OBJECT_NOT_FOUND) {
409
+ throw this.#targetUnreadable(entries[0], err);
410
+ }
411
+ }
412
+ }
413
+ this.#assertTargetReport(await this.inspectTargets(entries));
414
+ }
415
+
416
+ #assertBatchTargetInfos(entries, infos) {
417
+ if (infos.length !== entries.length) {
418
+ throw new CasError(
419
+ 'Root-set target metadata count does not match the entry count',
420
+ ErrorCodes.GIT_ERROR,
421
+ { expectedCount: entries.length, actualCount: infos.length },
422
+ );
423
+ }
424
+ const mismatchIndex = infos.findIndex((info, index) => info.type !== entries[index].type);
425
+ if (mismatchIndex === -1) {
426
+ return;
427
+ }
428
+ const entry = entries[mismatchIndex];
429
+ throw new CasError(
430
+ `Root-set target type mismatch for ${entry.oid}`,
431
+ ErrorCodes.ROOT_SET_TARGET_TYPE_MISMATCH,
432
+ {
433
+ ref: this.rootSetRef,
434
+ name: entry.name,
435
+ oid: entry.oid,
436
+ expectedType: entry.type,
437
+ actualType: infos[mismatchIndex].type,
438
+ },
439
+ );
440
+ }
441
+
442
+ #assertTargetReport(report) {
400
443
  const issue = report.issues[0];
401
444
  if (!issue) {
402
445
  return;
@@ -412,4 +455,18 @@ export default class RootSetPersistence {
412
455
  ...issue,
413
456
  });
414
457
  }
458
+
459
+ #targetUnreadable(entry, originalError) {
460
+ return new CasError(
461
+ `Root-set target could not be inspected: ${entry?.oid ?? 'unknown'}`,
462
+ ErrorCodes.ROOT_SET_TARGET_UNREADABLE,
463
+ {
464
+ ref: this.rootSetRef,
465
+ name: entry?.name,
466
+ oid: entry?.oid,
467
+ expectedType: entry?.type,
468
+ originalError,
469
+ },
470
+ );
471
+ }
415
472
  }
@@ -0,0 +1,19 @@
1
+ import parseApplicationHandle from '../value-objects/ApplicationHandle.js';
2
+
3
+ const TARGETS = new WeakMap();
4
+
5
+ /** Records the direct Git target proven by an internal staged constructor. */
6
+ export function recordStagedTarget(staged) {
7
+ const handle = parseApplicationHandle(staged.handle);
8
+ TARGETS.set(staged, Object.freeze({
9
+ handle,
10
+ oid: handle.oid,
11
+ type: handle.kind === 'page' ? 'blob' : 'tree',
12
+ }));
13
+ return staged;
14
+ }
15
+
16
+ /** Returns private construction evidence, never serialized public metadata. */
17
+ export function stagedTargetOf(staged) {
18
+ return TARGETS.get(staged) ?? null;
19
+ }
@@ -4,6 +4,7 @@ import parseApplicationHandle from '../value-objects/ApplicationHandle.js';
4
4
  import RetentionWitness from '../value-objects/RetentionWitness.js';
5
5
  import WorkspaceRef from '../value-objects/WorkspaceRef.js';
6
6
  import RootSetMetadataCodec from './RootSetMetadataCodec.js';
7
+ import { stagedTargetOf } from './StagedTarget.js';
7
8
  import {
8
9
  MAX_WORKSPACE_TARGETS,
9
10
  WORKSPACE_DESCRIPTOR_ENTRY,
@@ -57,6 +58,9 @@ export default class StagingWorkspace {
57
58
 
58
59
  this.assets = Object.freeze({
59
60
  put: (options) => this.#enqueue(() => this.#stage(this.#assets, 'put', options)),
61
+ putBatch: (options) => (
62
+ this.#enqueue(() => this.#stageBatch(this.#assets, 'putBatch', options))
63
+ ),
60
64
  adopt: (options) => this.#enqueue(() => this.#stage(this.#assets, 'adopt', options)),
61
65
  });
62
66
  this.pages = Object.freeze({
@@ -68,6 +72,9 @@ export default class StagingWorkspace {
68
72
  putOrdered: (options) => (
69
73
  this.#enqueue(() => this.#stage(this.#bundles, 'putOrdered', options))
70
74
  ),
75
+ putOrderedBatch: (options) => (
76
+ this.#enqueue(() => this.#stageBatch(this.#bundles, 'putOrderedBatch', options))
77
+ ),
71
78
  });
72
79
  Object.freeze(this);
73
80
  }
@@ -172,7 +179,7 @@ export default class StagingWorkspace {
172
179
  );
173
180
  }
174
181
  try {
175
- const target = await this.#resolveTarget(staged.handle);
182
+ const target = stagedTargetOf(staged) ?? await this.#resolveTarget(staged.handle);
176
183
  const targets = new Map(this.#targets);
177
184
  targets.set(target.handle.toString(), target);
178
185
  const installation = await this.#install([...targets.values()]);
@@ -208,6 +215,13 @@ export default class StagingWorkspace {
208
215
 
209
216
  async #stageBatch(service, method, options) {
210
217
  this.#assertActive();
218
+ if (typeof service[method] !== 'function') {
219
+ throw createCasError(
220
+ `Workspace ${method}() is unavailable on the configured service`,
221
+ ErrorCodes.INVALID_OPTIONS,
222
+ { method },
223
+ );
224
+ }
211
225
  const staged = await service[method](options);
212
226
  if (!Array.isArray(staged) || staged.some((page) => !page?.handle)) {
213
227
  throw createCasError(
@@ -245,8 +259,8 @@ export default class StagingWorkspace {
245
259
  async #retainBatch(staged) {
246
260
  const resolved = [];
247
261
  const targets = new Map(this.#targets);
248
- for (const page of staged) {
249
- const target = await this.#resolveTarget(page.handle);
262
+ for (const artifact of staged) {
263
+ const target = stagedTargetOf(artifact) ?? await this.#resolveTarget(artifact.handle);
250
264
  resolved.push(target);
251
265
  targets.set(target.handle.toString(), target);
252
266
  }
@@ -254,7 +268,7 @@ export default class StagingWorkspace {
254
268
  const witnesses = new Map(
255
269
  installation.witnesses.map((witness) => [witness.handle.toString(), witness]),
256
270
  );
257
- return Object.freeze(staged.map((page, index) => {
271
+ return Object.freeze(staged.map((artifact, index) => {
258
272
  const handle = resolved[index].handle.toString();
259
273
  const witness = witnesses.get(handle);
260
274
  if (!witness) {
@@ -264,7 +278,7 @@ export default class StagingWorkspace {
264
278
  { handle, generation: installation.generation },
265
279
  );
266
280
  }
267
- return StagingWorkspace.#retainedStage(page, witness);
281
+ return StagingWorkspace.#retainedStage(artifact, witness);
268
282
  }));
269
283
  }
270
284
 
@@ -295,7 +309,7 @@ export default class StagingWorkspace {
295
309
  },
296
310
  ...targets.map(StagingWorkspace.#targetEntry),
297
311
  ];
298
- const mutation = await this.#rootSet.replace({
312
+ const mutation = await this.#rootSet.replaceExact({
299
313
  entries,
300
314
  expectedHeadOid: this.#generation,
301
315
  });
@@ -569,7 +583,7 @@ export default class StagingWorkspace {
569
583
  static #assertDependencies({ rootSet, refs, assets, pages, bundles, resolveHandle,
570
584
  descriptorCodec, clock }) {
571
585
  const missing = [
572
- ['rootSet', StagingWorkspace.#hasMethods(rootSet, ['replace'])],
586
+ ['rootSet', StagingWorkspace.#hasMethods(rootSet, ['replaceExact'])],
573
587
  ['refs', StagingWorkspace.#hasMethods(refs, ['deleteRef'])],
574
588
  ['assets', StagingWorkspace.#hasMethods(assets, ['put', 'adopt'])],
575
589
  ['pages', StagingWorkspace.#hasMethods(pages, ['put', 'putBatch'])],
@@ -0,0 +1,20 @@
1
+ import CasService from './CasService.js';
2
+
3
+ /** Creates an operation-local CAS facade over another persistence port. */
4
+ export default function forkCasPersistence(cas, persistence) {
5
+ return new CasService({
6
+ persistence,
7
+ codec: cas.codec,
8
+ crypto: cas.crypto,
9
+ observability: cas.observability,
10
+ chunkSize: cas.chunkSize,
11
+ merkleThreshold: cas.merkleThreshold,
12
+ concurrency: cas.concurrency,
13
+ chunker: cas.chunker,
14
+ maxRestoreBufferSize: cas.maxRestoreBufferSize,
15
+ maxBlobSize: cas.maxBlobSize,
16
+ compressionAdapter: cas.compressionAdapter,
17
+ formatVersion: cas.formatVersion,
18
+ legacyMode: cas.legacyMode,
19
+ });
20
+ }