@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.
Files changed (37) hide show
  1. package/ARCHITECTURE.md +9 -0
  2. package/CHANGELOG.md +39 -0
  3. package/GUIDE.md +54 -0
  4. package/README.md +17 -9
  5. package/UPGRADING.md +68 -0
  6. package/build-info.json +2 -2
  7. package/docs/API.md +115 -12
  8. package/docs/releases/v6.5.8.md +89 -0
  9. package/docs/releases/v6.5.9.md +119 -0
  10. package/index.d.ts +75 -0
  11. package/index.js +19 -1
  12. package/package.json +4 -2
  13. package/src/domain/services/AssetService.js +201 -10
  14. package/src/domain/services/BoundedWriteWavePersistence.js +235 -0
  15. package/src/domain/services/BundleBatchPlanner.js +349 -0
  16. package/src/domain/services/BundleService.js +225 -2
  17. package/src/domain/services/CasService.d.ts +16 -0
  18. package/src/domain/services/CasService.js +9 -18
  19. package/src/domain/services/ManifestRepository.js +129 -50
  20. package/src/domain/services/ManifestTreeService.js +47 -0
  21. package/src/domain/services/PageService.js +36 -10
  22. package/src/domain/services/RootSet.js +32 -0
  23. package/src/domain/services/RootSetPersistence.js +58 -1
  24. package/src/domain/services/StagedTarget.js +19 -0
  25. package/src/domain/services/StagingWorkspace.js +95 -20
  26. package/src/domain/services/StagingWorkspaceRegistry.js +9 -4
  27. package/src/domain/services/WorkspaceCompoundAdmission.js +61 -0
  28. package/src/domain/services/WorkspaceCompoundScope.js +193 -0
  29. package/src/domain/services/forkCasPersistence.js +20 -0
  30. package/src/infrastructure/adapters/GitObjectSessionPool.js +47 -5
  31. package/src/infrastructure/adapters/GitPersistenceAdapter.js +169 -0
  32. package/src/infrastructure/adapters/GitPersistenceWriteScope.js +154 -0
  33. package/src/infrastructure/adapters/GitRefAdapter.js +38 -3
  34. package/src/infrastructure/adapters/GitUpdateRefSessionPool.js +115 -0
  35. package/src/package-version.js +1 -1
  36. package/src/ports/GitPersistencePort.js +43 -0
  37. package/src/ports/GitRefPort.js +8 -0
@@ -0,0 +1,119 @@
1
+ # git-cas v6.5.9 Release Notes
2
+
3
+ v6.5.9 adds bounded compound staging-workspace admission for applications that
4
+ construct dependency-ordered page and bundle graphs. It replaces one temporary
5
+ retention publication per construction wave with one exact final workspace
6
+ generation, without changing application handles, stored object bytes,
7
+ workspace descriptors, ref layout or namespaces, readers, or existing
8
+ workspace methods. Successful compound admission deliberately reduces
9
+ workspace-ref update frequency.
10
+
11
+ ## Compound Workspace Admission
12
+
13
+ `workspace.batch()` owns one bounded callback and one operation-scoped Git
14
+ persistence view:
15
+
16
+ ```js
17
+ const admitted = await workspace.batch({
18
+ maxOperations: 3,
19
+ operation: async (scope) => {
20
+ const pages = await scope.pages.putBatch({ pages: pageRequests });
21
+ const leaves = await scope.bundles.putOrderedBatch({
22
+ bundles: buildLeafRequests(pages),
23
+ });
24
+ return (
25
+ await scope.bundles.putOrderedBatch({
26
+ bundles: [buildRootRequest(leaves)],
27
+ })
28
+ )[0];
29
+ },
30
+ });
31
+
32
+ admitted.value;
33
+ admitted.retention;
34
+ ```
35
+
36
+ The scope exposes only the existing bounded page-batch and ordered-bundle-batch
37
+ operations. Calls serialize by invocation order and return frozen handle
38
+ arrays for later dependency waves. The default scope limit is 64 operations;
39
+ the exported hard limit is 1,024. Every call also retains its existing page,
40
+ bundle, member, object, and byte ceilings.
41
+
42
+ Success installs the union of previously retained workspace targets and every
43
+ new compound target exactly once. The callback value becomes caller-visible
44
+ only after scoped Git resources close and the paired retention result names the
45
+ exact final generation. Existing staging methods continue to retain their
46
+ result independently and remain appropriate when an intermediate handle must
47
+ leave private construction code.
48
+
49
+ ## Failure and Trust Boundary
50
+
51
+ Invalid bounds, empty operations, callback failure, staged-write failure,
52
+ session-close failure, and checked final-retention failure return no admitted
53
+ value and do not move the prior workspace generation. The first failure stops
54
+ later queued work. Distinct callback/write and operation/close failures remain
55
+ available through `AggregateError`. Immutable objects written before refusal
56
+ may remain unreachable for Git's ordinary reclamation.
57
+
58
+ The callback is trusted JavaScript. git-cas closes an escaped scope and never
59
+ returns the callback value before retention, but it cannot prevent callback
60
+ code from assigning a provisional handle into external state as a side effect.
61
+ Such a leaked handle has no compound retention witness and is outside the
62
+ contract.
63
+
64
+ ## Process-Topology Witness
65
+
66
+ The committed five-sample witness compares the same 33-operation graph under
67
+ independent per-wave retention and compound admission. Each mode produces 64
68
+ pages, 16 leaf bundles, one root bundle, and the same ordered sequence of 81
69
+ application handles in fresh SHA-1 and SHA-256 bare repositories.
70
+
71
+ | Format | Mode | Git children | Git interactions | Median wall ms | Worker CPU ms |
72
+ | ------- | -------- | -----------: | ---------------: | -------------: | ------------: |
73
+ | SHA-1 | per-wave | 200 | 380 | 3763.820 | 370.336 |
74
+ | SHA-1 | compound | 23 | 238 | 733.116 | 113.672 |
75
+ | SHA-256 | per-wave | 200 | 380 | 3709.930 | 373.898 |
76
+ | SHA-256 | compound | 23 | 238 | 726.976 | 114.407 |
77
+
78
+ Both formats reduced Git child creation by 88.5% and median wall time by about
79
+ 80.5% on the measured host: 200 to 23 Git children and 33 retained generations
80
+ to one. `fast-import`, `commit-tree`, symbolic-ref containment checks, and
81
+ checked ref updates fell from one per wave to one per compound admission. The
82
+ semantic handle digests matched exactly.
83
+
84
+ The remaining 18 `mktree` children preserve validation across interdependent
85
+ descriptor-pack visibility boundaries. Further reduction requires a separately
86
+ proved typed tree-writing protocol or equivalent deterministic construction;
87
+ this release does not bypass Git's object validation.
88
+
89
+ See the [machine witness](https://github.com/git-stunts/git-cas/blob/main/docs/design/0060-compound-workspace-admission/witness/compound-workspace-admission.json)
90
+ and [verification narrative](https://github.com/git-stunts/git-cas/blob/main/docs/design/0060-compound-workspace-admission/witness/verification.md)
91
+ for the exact source, environment, counts, digests, and method.
92
+
93
+ ## Reachability Proof
94
+
95
+ Real-Git integration tests cover SHA-1 and SHA-256 success and refusal. They
96
+ verify one checked publication, zero active scoped fast-import sessions after
97
+ settlement, immediate-prune readability while retained, reclamation after
98
+ checked release, and no workspace generation after a dependent wave fails.
99
+
100
+ ## Verification
101
+
102
+ Implementation review #124 merged normally as
103
+ `eb8d617620fa8f401fb887f5b1bbc341d4746b0a`; its exact reviewed head
104
+ `29ba6e88c787a5e54c95a554e9166fd21aae31c0` passed all 14 release-verifier
105
+ stages with 7,141 observed tests across Node, Bun, Deno, and all three real-Git
106
+ integration suites. Exact versioned candidate
107
+ `5512acd477bc5e5a11339d6027a03631d1a3544a` then passed the same 14-stage
108
+ method with 7,147 observed tests: 2,179 Node, 2,178 Bun, 2,169 Deno, and 207
109
+ integration tests in each runtime. No tag, npm artifact, or GitHub Release is
110
+ claimed by this candidate.
111
+
112
+ ## Compatibility
113
+
114
+ This release is additive and requires no application or stored-data migration.
115
+ Existing repositories open in place. It introduces no new object format,
116
+ descriptor version, ref namespace, reader, transaction log, authority cutover,
117
+ or mixed-version rewrite. Applications may leave every existing workspace call
118
+ unchanged and adopt `workspace.batch()` only where intermediate handles remain
119
+ private to one bounded construction.
package/index.d.ts CHANGED
@@ -515,6 +515,7 @@ export declare class GitPersistencePortBase {
515
515
  writeBlob(content: Uint8Array): Promise<string>;
516
516
  writeBlobs?(contents: Iterable<Uint8Array>): Promise<string[]>;
517
517
  writeTree(entries: string[]): Promise<string>;
518
+ writeTrees?(trees: Iterable<string[]>): Promise<string[]>;
518
519
  readBlob(oid: string, maxBytes?: number): Promise<Uint8Array>;
519
520
  readBlobStream(oid: string): Promise<AsyncIterable<Uint8Array>>;
520
521
  readTree(
@@ -529,6 +530,12 @@ export declare class GitPersistencePortBase {
529
530
  ): AsyncIterable<{ mode: string; type: string; oid: string; name: string }>;
530
531
  readObjectType(oid: string): Promise<string>;
531
532
  readObjectSize(oid: string): Promise<number>;
533
+ readObjectInfos?(
534
+ oids: Iterable<string>
535
+ ): Promise<Array<{ oid: string; type: string; size: number }>>;
536
+ withWriteScope?<T>(
537
+ operation: (persistence: GitPersistencePortBase) => Promise<T>
538
+ ): Promise<T>;
532
539
  setMaxBlobSize?(maxBlobSize: number): void;
533
540
  close?(): Promise<void>;
534
541
  [Symbol.asyncDispose]?(): Promise<void>;
@@ -563,6 +570,8 @@ export declare class GitRefPortBase {
563
570
  after?: string | null;
564
571
  limit: number;
565
572
  }): AsyncIterable<{ ref: string; oid: string; symref: string | null }>;
573
+ close?(): Promise<void>;
574
+ [Symbol.asyncDispose]?(): Promise<void>;
566
575
  }
567
576
 
568
577
  /** Git-backed implementation of the persistence port. */
@@ -576,6 +585,13 @@ export declare class GitPersistenceAdapter extends GitPersistencePortBase {
576
585
  treeCacheBytes?: number;
577
586
  });
578
587
  writeBlobs(contents: Iterable<Uint8Array>): Promise<string[]>;
588
+ writeTrees(trees: Iterable<string[]>): Promise<string[]>;
589
+ readObjectInfos(
590
+ oids: Iterable<string>
591
+ ): Promise<Array<{ oid: string; type: string; size: number }>>;
592
+ withWriteScope<T>(
593
+ operation: (persistence: GitPersistencePortBase) => Promise<T>
594
+ ): Promise<T>;
579
595
  setMaxBlobSize(maxBlobSize: number): void;
580
596
  close(): Promise<void>;
581
597
  [Symbol.asyncDispose](): Promise<void>;
@@ -596,6 +612,8 @@ export declare class GitRefAdapter extends GitRefPortBase {
596
612
  after?: string | null;
597
613
  limit: number;
598
614
  }): AsyncIterable<{ ref: string; oid: string; symref: string | null }>;
615
+ close(): Promise<void>;
616
+ [Symbol.asyncDispose](): Promise<void>;
599
617
  }
600
618
 
601
619
  export type RepositoryObjectType = 'blob' | 'tree' | 'commit' | 'tag';
@@ -816,6 +834,10 @@ export declare class RootSet {
816
834
  entries: Iterable<RootSetEntry>;
817
835
  expectedHeadOid?: string | null;
818
836
  }): Promise<RootSetMutationResult>;
837
+ replaceExact(options: {
838
+ entries: Iterable<RootSetEntry>;
839
+ expectedHeadOid: string | null;
840
+ }): Promise<RootSetMutationResult>;
819
841
  mutate(
820
842
  mutator: (
821
843
  entries: ReadonlyArray<Readonly<RootSetEntry>>,
@@ -1449,6 +1471,12 @@ export interface AssetPutOptions {
1449
1471
 
1450
1472
  export interface AssetCapability {
1451
1473
  put(options: AssetPutOptions): Promise<StagedAsset>;
1474
+ putBatch(options: {
1475
+ assets: AssetPutOptions[];
1476
+ maxBatchAssets?: number;
1477
+ maxBatchObjects?: number;
1478
+ maxBatchBytes?: number;
1479
+ }): Promise<ReadonlyArray<StagedAsset>>;
1452
1480
  adopt(options: { treeOid: string }): Promise<StagedAsset>;
1453
1481
  open(options: {
1454
1482
  handle: AssetHandleInput;
@@ -1504,6 +1532,18 @@ export interface BundleCapability {
1504
1532
  | AsyncIterable<[string, BundleMemberInput]>;
1505
1533
  limits?: Partial<BundleLimits>;
1506
1534
  }): Promise<StagedBundle>;
1535
+ putOrderedBatch(options: {
1536
+ bundles: Array<{
1537
+ members:
1538
+ | Iterable<[string, BundleMemberInput]>
1539
+ | AsyncIterable<[string, BundleMemberInput]>;
1540
+ limits?: Partial<BundleLimits>;
1541
+ }>;
1542
+ maxBatchBundles?: number;
1543
+ maxBatchMembers?: number;
1544
+ maxBatchObjects?: number;
1545
+ maxBatchBytes?: number;
1546
+ }): Promise<ReadonlyArray<StagedBundle>>;
1507
1547
  getMember(options: {
1508
1548
  handle: BundleHandleInput;
1509
1549
  path: string;
@@ -1574,6 +1614,27 @@ export interface WorkspaceCheckpointResult {
1574
1614
  readonly witnesses: ReadonlyArray<RetentionWitness>;
1575
1615
  }
1576
1616
 
1617
+ export const DEFAULT_WORKSPACE_COMPOUND_OPERATIONS: 64;
1618
+ export const MAX_WORKSPACE_COMPOUND_OPERATIONS: 1024;
1619
+
1620
+ export interface WorkspaceCompoundScope {
1621
+ readonly pages: {
1622
+ putBatch(
1623
+ options: Parameters<PageCapability['putBatch']>[0],
1624
+ ): Promise<ReadonlyArray<PageHandle>>;
1625
+ };
1626
+ readonly bundles: {
1627
+ putOrderedBatch(
1628
+ options: Parameters<BundleCapability['putOrderedBatch']>[0],
1629
+ ): Promise<ReadonlyArray<BundleHandle>>;
1630
+ };
1631
+ }
1632
+
1633
+ export interface WorkspaceCompoundResult<T> {
1634
+ readonly value: T;
1635
+ readonly retention: WorkspaceCheckpointResult;
1636
+ }
1637
+
1577
1638
  export interface WorkspaceReleaseResult {
1578
1639
  readonly changed: boolean;
1579
1640
  readonly ref: string;
@@ -1633,6 +1694,9 @@ export declare class StagingWorkspace {
1633
1694
  readonly expiresAt: string | null;
1634
1695
  readonly assets: {
1635
1696
  put(options: AssetPutOptions): Promise<WorkspaceRetainedAsset>;
1697
+ putBatch(
1698
+ options: Parameters<AssetCapability['putBatch']>[0],
1699
+ ): Promise<ReadonlyArray<WorkspaceRetainedAsset>>;
1636
1700
  adopt(options: { treeOid: string }): Promise<WorkspaceRetainedAsset>;
1637
1701
  };
1638
1702
  readonly pages: {
@@ -1644,7 +1708,14 @@ export declare class StagingWorkspace {
1644
1708
  readonly bundles: {
1645
1709
  put(options: Parameters<BundleCapability['put']>[0]): Promise<WorkspaceRetainedBundle>;
1646
1710
  putOrdered(options: Parameters<BundleCapability['putOrdered']>[0]): Promise<WorkspaceRetainedBundle>;
1711
+ putOrderedBatch(
1712
+ options: Parameters<BundleCapability['putOrderedBatch']>[0],
1713
+ ): Promise<ReadonlyArray<WorkspaceRetainedBundle>>;
1647
1714
  };
1715
+ batch<T>(options: {
1716
+ operation(scope: WorkspaceCompoundScope): T | Promise<T>;
1717
+ maxOperations?: number;
1718
+ }): Promise<Readonly<WorkspaceCompoundResult<T>>>;
1648
1719
  checkpoint(options: { handles: Iterable<ApplicationHandleInput> }): Promise<WorkspaceCheckpointResult>;
1649
1720
  renew(): Promise<WorkspaceCheckpointResult>;
1650
1721
  promoteToCache(options: {
@@ -1813,6 +1884,10 @@ export default class ContentAddressableStore {
1813
1884
 
1814
1885
  createTree(options: { manifest: Manifest; merkleThreshold?: number }): Promise<string>;
1815
1886
 
1887
+ createTrees(
1888
+ requests: Array<{ manifest: Manifest; merkleThreshold?: number }>,
1889
+ ): Promise<string[]>;
1890
+
1816
1891
  verifyIntegrity(manifest: Manifest, options?: VerifyIntegrityOptions): Promise<boolean>;
1817
1892
 
1818
1893
  readManifest(options: { treeOid: string }): Promise<Manifest>;
package/index.js CHANGED
@@ -110,6 +110,10 @@ export { default as RepositoryInspectionPort } from './src/ports/RepositoryInspe
110
110
  export { default as NodeCompressionAdapter } from './src/infrastructure/adapters/NodeCompressionAdapter.js';
111
111
  export { default as diffManifests } from './src/domain/services/ManifestDiff.js';
112
112
  export { SCHEME_WHOLE, SCHEME_FRAMED, SCHEME_CONVERGENT } from './src/domain/encryption/schemes.js';
113
+ export {
114
+ DEFAULT_WORKSPACE_COMPOUND_OPERATIONS,
115
+ MAX_WORKSPACE_COMPOUND_OPERATIONS,
116
+ } from './src/domain/services/WorkspaceCompoundScope.js';
113
117
 
114
118
  /**
115
119
  * High-level facade for the Content Addressable Store library.
@@ -210,6 +214,7 @@ export default class ContentAddressableStore {
210
214
  });
211
215
  this.assets = Object.freeze({
212
216
  put: async (options) => (await this.#getAssetService()).put(options),
217
+ putBatch: async (options) => (await this.#getAssetService()).putBatch(options),
213
218
  adopt: async (options) => (await this.#getAssetService()).adopt(options),
214
219
  open: (options) => this.#openAsset(options),
215
220
  });
@@ -222,6 +227,7 @@ export default class ContentAddressableStore {
222
227
  this.bundles = Object.freeze({
223
228
  put: async (options) => (await this.#getBundleService()).put(options),
224
229
  putOrdered: async (options) => (await this.#getBundleService()).putOrdered(options),
230
+ putOrderedBatch: async (options) => (await this.#getBundleService()).putOrderedBatch(options),
225
231
  getMember: async (options) => (await this.#getBundleService()).getMember(options),
226
232
  getMemberReference: async (options) => (
227
233
  await this.#getBundleService()
@@ -262,6 +268,8 @@ export default class ContentAddressableStore {
262
268
  #stagingWorkspaceRegistry = null;
263
269
  /** @type {RepositoryDoctor|null} */
264
270
  #repositoryDoctor = null;
271
+ /** @type {GitRefAdapter|null} */
272
+ #ref = null;
265
273
  #closePromise = null;
266
274
  #closed = false;
267
275
  #servicePromise = null;
@@ -314,6 +322,7 @@ export default class ContentAddressableStore {
314
322
  plumbing: cfg.plumbing,
315
323
  policy: cfg.policy,
316
324
  });
325
+ this.#ref = ref;
317
326
  this.#vault = new VaultService({
318
327
  persistence,
319
328
  ref,
@@ -627,7 +636,16 @@ export default class ContentAddressableStore {
627
636
  return;
628
637
  }
629
638
  const service = await this.#servicePromise;
630
- await service.persistence.close();
639
+ const results = await Promise.allSettled([
640
+ service.persistence.close(),
641
+ this.#ref?.close(),
642
+ ]);
643
+ const failures = results
644
+ .filter((result) => result.status === 'rejected')
645
+ .map((result) => result.reason);
646
+ if (failures.length > 0) {
647
+ throw new AggregateError(failures, 'Content-addressable store failed to close cleanly');
648
+ }
631
649
  })();
632
650
  return await this.#closePromise;
633
651
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@git-stunts/git-cas",
3
- "version": "6.5.7",
3
+ "version": "6.5.9",
4
4
  "description": "Content-addressed storage backed by Git's object database, with optional encryption and pluggable codecs",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -44,6 +44,8 @@
44
44
  "docs/releases/v6.5.5.md",
45
45
  "docs/releases/v6.5.6.md",
46
46
  "docs/releases/v6.5.7.md",
47
+ "docs/releases/v6.5.8.md",
48
+ "docs/releases/v6.5.9.md",
47
49
  "docs/THREAT_MODEL.md",
48
50
  "docs/VAULT_INTERNALS.md",
49
51
  "docs/WALKTHROUGH.md",
@@ -109,7 +111,7 @@
109
111
  "@flyingrobots/bijou-tui": "^7.2.0",
110
112
  "@flyingrobots/bijou-tui-app": "^7.2.0",
111
113
  "@git-stunts/alfred": "^0.10.0",
112
- "@git-stunts/plumbing": "^3.2.0",
114
+ "@git-stunts/plumbing": "^3.3.0",
113
115
  "@git-stunts/vault": "^1.0.1",
114
116
  "cbor-x": "^1.6.0",
115
117
  "commander": "14.0.3",
@@ -2,8 +2,14 @@ import createCasError from '../errors/createCasError.js';
2
2
  import { ErrorCodes } from '../errors/index.js';
3
3
  import AssetHandle from '../value-objects/AssetHandle.js';
4
4
  import StagedAsset from '../value-objects/StagedAsset.js';
5
+ import BoundedWriteWavePersistence from './BoundedWriteWavePersistence.js';
6
+ import forkCasPersistence from './forkCasPersistence.js';
7
+ import { recordStagedTarget } from './StagedTarget.js';
5
8
 
6
9
  const DEFAULT_CLOCK = Object.freeze({ now: () => new Date() });
10
+ export const DEFAULT_ASSET_WRITE_BATCH_ASSETS = 4;
11
+ export const DEFAULT_ASSET_WRITE_BATCH_OBJECTS = 4_096;
12
+ export const DEFAULT_ASSET_WRITE_BATCH_BYTES = 256 * 1024 * 1024;
7
13
 
8
14
  /**
9
15
  * High-level asset handle boundary over the existing streaming CAS pipeline.
@@ -30,15 +36,91 @@ export default class AssetService {
30
36
  * @returns {Promise<StagedAsset>}
31
37
  */
32
38
  async put(options) {
33
- const filename = options?.filename ?? options?.slug;
34
- const manifest = await this.#cas.store({ ...options, filename });
35
- const oid = await this.#cas.createTree({
39
+ return await this.#putWith(this.#cas, options);
40
+ }
41
+
42
+ /** Stores an input-ordered group with bounded concurrent CAS pipelines. */
43
+ async putBatch(options = {}) {
44
+ const batch = AssetService.#batchOptions(options);
45
+ return await withWriteScope(
46
+ this.#cas.persistence,
47
+ async (persistence) => await this.#putBatch(batch, persistence)
48
+ );
49
+ }
50
+
51
+ async #putBatch(batch, scopedPersistence) {
52
+ const persistence = new BoundedWriteWavePersistence({
53
+ persistence: scopedPersistence,
54
+ maxBatchObjects: batch.maxBatchObjects,
55
+ maxBatchBytes: batch.maxBatchBytes,
56
+ });
57
+ const cas = forkCasPersistence(this.#cas, persistence);
58
+ const manifests = new Array(batch.assets.length);
59
+ const state = { next: 0, error: null, errorIndex: null };
60
+ const workers = Array.from(
61
+ { length: Math.min(batch.maxBatchAssets, batch.assets.length) },
62
+ () => this.#storeBatchWorker({ batch, cas, manifests, state })
63
+ );
64
+ await Promise.allSettled(workers);
65
+ if (state.error !== null) {
66
+ throw AssetService.#batchFailure(state.error, persistence, {
67
+ stagedAssetCount: 0,
68
+ batchIndex: state.errorIndex,
69
+ });
70
+ }
71
+ let oids;
72
+ try {
73
+ oids = await cas.createTrees(
74
+ manifests.map((manifest, index) => ({
75
+ manifest,
76
+ merkleThreshold: batch.assets[index]?.merkleThreshold,
77
+ }))
78
+ );
79
+ } catch (error) {
80
+ throw AssetService.#batchFailure(error, persistence, { stagedAssetCount: 0 });
81
+ }
82
+ const results = manifests.map((manifest, index) =>
83
+ this.#staged({ manifest, oid: oids[index] })
84
+ );
85
+ return Object.freeze(results);
86
+ }
87
+
88
+ async #putWith(cas, options) {
89
+ const manifest = await this.#storeWith(cas, options);
90
+ const oid = await cas.createTree({
36
91
  manifest,
37
92
  merkleThreshold: options?.merkleThreshold,
38
93
  });
39
94
  return this.#staged({ manifest, oid });
40
95
  }
41
96
 
97
+ async #storeBatchWorker({ batch, cas, manifests, state }) {
98
+ while (state.error === null) {
99
+ const index = state.next;
100
+ if (index >= batch.assets.length) {
101
+ return;
102
+ }
103
+ state.next += 1;
104
+ try {
105
+ manifests[index] = await this.#storeWith(cas, batch.assets[index], state);
106
+ } catch (error) {
107
+ if (state.error === null) {
108
+ state.error = error;
109
+ state.errorIndex = index;
110
+ }
111
+ }
112
+ }
113
+ }
114
+
115
+ async #storeWith(cas, options, batchState = null) {
116
+ const filename = options?.filename ?? options?.slug;
117
+ const source =
118
+ batchState !== null && options?.source?.[Symbol.asyncIterator]
119
+ ? cancelAfterBatchFailure(options.source, batchState)
120
+ : options?.source;
121
+ return await cas.store({ ...options, source, filename });
122
+ }
123
+
42
124
  /**
43
125
  * Adopts a validated existing git-cas manifest tree into an asset handle.
44
126
  *
@@ -172,13 +254,15 @@ export default class AssetService {
172
254
  }
173
255
 
174
256
  #staged({ manifest, oid }) {
175
- return new StagedAsset({
176
- handle: new AssetHandle({ codec: this.#cas.codec.extension, oid }),
177
- slug: manifest.slug,
178
- filename: manifest.filename,
179
- size: manifest.size,
180
- observedAt: this.#observedAt(),
181
- });
257
+ return recordStagedTarget(
258
+ new StagedAsset({
259
+ handle: new AssetHandle({ codec: this.#cas.codec.extension, oid }),
260
+ slug: manifest.slug,
261
+ filename: manifest.filename,
262
+ size: manifest.size,
263
+ observedAt: this.#observedAt(),
264
+ })
265
+ );
182
266
  }
183
267
 
184
268
  #observedAt() {
@@ -210,4 +294,111 @@ export default class AssetService {
210
294
  throw createCasError('AssetService clock must provide now()', ErrorCodes.INVALID_OPTIONS);
211
295
  }
212
296
  }
297
+
298
+ static #batchOptions(options) {
299
+ if (!options || typeof options !== 'object' || !Array.isArray(options.assets)) {
300
+ throw createCasError('Asset batch must provide an asset array', ErrorCodes.INVALID_OPTIONS);
301
+ }
302
+ const batch = {
303
+ assets: options.assets,
304
+ maxBatchAssets: options.maxBatchAssets ?? DEFAULT_ASSET_WRITE_BATCH_ASSETS,
305
+ maxBatchObjects: options.maxBatchObjects ?? DEFAULT_ASSET_WRITE_BATCH_OBJECTS,
306
+ maxBatchBytes: options.maxBatchBytes ?? DEFAULT_ASSET_WRITE_BATCH_BYTES,
307
+ };
308
+ AssetService.#assertBatchLimit(batch.maxBatchAssets, 'assets', 64);
309
+ AssetService.#assertBatchLimit(batch.maxBatchObjects, 'objects', 100_000);
310
+ AssetService.#assertBatchLimit(batch.maxBatchBytes, 'bytes', 1024 * 1024 * 1024);
311
+ return batch;
312
+ }
313
+
314
+ static #assertBatchLimit(value, label, maximum) {
315
+ if (!Number.isSafeInteger(value) || value < 1 || value > maximum) {
316
+ throw createCasError(
317
+ `Asset batch ${label} limit is outside its supported range`,
318
+ ErrorCodes.INVALID_OPTIONS,
319
+ { label, value, maximum }
320
+ );
321
+ }
322
+ }
323
+
324
+ static #batchFailure(error, persistence, { stagedAssetCount, batchIndex = null }) {
325
+ const sourceMeta = batchErrorMeta(error);
326
+ const failure = createCasError({
327
+ message: error instanceof Error ? error.message : String(error),
328
+ code: batchErrorCode(error),
329
+ documentationUrl: batchErrorDocumentation(error),
330
+ meta: {
331
+ ...sourceMeta,
332
+ originalError: sourceMeta.originalError ?? error,
333
+ ...(batchIndex === null ? {} : { batchIndex }),
334
+ staging: {
335
+ ...persistence.snapshot(),
336
+ stagedAssetCount,
337
+ },
338
+ },
339
+ });
340
+ failure.cause = error;
341
+ return failure;
342
+ }
343
+ }
344
+
345
+ function batchErrorCode(error) {
346
+ return error && typeof error === 'object' && typeof error.code === 'string'
347
+ ? error.code
348
+ : ErrorCodes.GIT_ERROR;
349
+ }
350
+
351
+ function batchErrorMeta(error) {
352
+ return error && typeof error === 'object' && error.meta && typeof error.meta === 'object'
353
+ ? error.meta
354
+ : {};
355
+ }
356
+
357
+ function batchErrorDocumentation(error) {
358
+ return error && typeof error === 'object' && typeof error.documentationUrl === 'string'
359
+ ? error.documentationUrl
360
+ : undefined;
361
+ }
362
+
363
+ function cancelAfterBatchFailure(source, state) {
364
+ return {
365
+ async *[Symbol.asyncIterator]() {
366
+ const iterator = source[Symbol.asyncIterator]();
367
+ let complete = false;
368
+ try {
369
+ while (state.error === null) {
370
+ const next = await iterator.next();
371
+ if (next.done) {
372
+ complete = true;
373
+ return;
374
+ }
375
+ if (state.error !== null) {
376
+ return;
377
+ }
378
+ yield next.value;
379
+ }
380
+ } finally {
381
+ if (!complete) {
382
+ await closeAsyncIterator(iterator);
383
+ }
384
+ }
385
+ },
386
+ };
387
+ }
388
+
389
+ async function closeAsyncIterator(iterator) {
390
+ if (typeof iterator.return !== 'function') {
391
+ return;
392
+ }
393
+ try {
394
+ await iterator.return();
395
+ } catch {
396
+ // Preserve the first batch failure; iterator cleanup is best effort.
397
+ }
398
+ }
399
+
400
+ async function withWriteScope(persistence, operation) {
401
+ return typeof persistence.withWriteScope === 'function'
402
+ ? await persistence.withWriteScope(operation)
403
+ : await operation(persistence);
213
404
  }