@git-stunts/git-cas 6.3.0 → 6.5.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.
@@ -7,12 +7,15 @@ import BundleHandle from '../value-objects/BundleHandle.js';
7
7
  import BundleLimits from '../value-objects/BundleLimits.js';
8
8
  import normalizeBundlePath from '../value-objects/BundlePath.js';
9
9
  import StagedBundle from '../value-objects/StagedBundle.js';
10
+ import BoundedPromiseCache from '../../helpers/boundedPromiseCache.js';
10
11
  import BundleDescriptorCodec, { BUNDLE_INDEX_ENTRY } from './BundleDescriptorCodec.js';
11
12
  import BundleFanoutBuilder from './BundleFanoutBuilder.js';
12
13
  import StagingEvidence from './StagingEvidence.js';
13
14
 
14
15
  const DEFAULT_CLOCK = Object.freeze({ now: () => new Date() });
15
16
  const DEFAULT_MAX_NESTING_DEPTH = 32;
17
+ const DESCRIPTOR_CACHE_ENTRIES = 1_024;
18
+ const DESCRIPTOR_CACHE_BYTES = 16 * 1024 * 1024;
16
19
 
17
20
  /**
18
21
  * Builds and traverses deterministic, targeted structured bundle trees.
@@ -20,6 +23,10 @@ const DEFAULT_MAX_NESTING_DEPTH = 32;
20
23
  export default class BundleService {
21
24
  #clock;
22
25
  #codec;
26
+ #descriptorBlobs = new BoundedPromiseCache(DESCRIPTOR_CACHE_ENTRIES, {
27
+ maxWeight: DESCRIPTOR_CACHE_BYTES,
28
+ weightOf: (value) => value.byteLength,
29
+ });
23
30
  #limits;
24
31
  #maxNestingDepth;
25
32
  #openHandle;
@@ -104,14 +111,30 @@ export default class BundleService {
104
111
  return member === null ? null : await this.#resolveMemberReference(member, BundleHandle.from(value));
105
112
  }
106
113
 
107
- /** @internal Returns one descriptor after validating only its direct Git edge. */
114
+ /** Returns one descriptor after validating the bundle structure and direct Git edge. */
108
115
  async getMemberReference({ handle: value, path: rawPath }) {
109
116
  const handle = BundleHandle.from(value);
110
117
  const path = normalizeBundlePath(rawPath, this.#limits.maxMemberPathBytes);
111
118
  const root = await this.#readRoot(handle);
112
119
  let nodeOid = root.index.oid;
120
+ let expectedSummary = null;
121
+ let parentTreeOid = handle.oid;
122
+ let descriptorBytes = root.descriptorBytes;
113
123
  while (true) {
114
124
  const node = await this.#readNode(nodeOid, root.descriptor.limits);
125
+ descriptorBytes += node.descriptorBytes;
126
+ if (descriptorBytes > root.descriptor.limits.maxDescriptorBytes) {
127
+ throw corrupt('Bundle descriptors exceed their persisted byte limit', {
128
+ descriptorBytes,
129
+ maxDescriptorBytes: root.descriptor.limits.maxDescriptorBytes,
130
+ });
131
+ }
132
+ const actualSummary = summaryOf(node.descriptor, nodeOid);
133
+ if (expectedSummary === null) {
134
+ assertSummary(root.descriptor, actualSummary);
135
+ } else {
136
+ assertChildSummary(expectedSummary, actualSummary, parentTreeOid);
137
+ }
115
138
  if (node.descriptor.kind === 'leaf') {
116
139
  return await this.#referenceFromLeaf({
117
140
  bundleHandle: handle,
@@ -125,6 +148,8 @@ export default class BundleService {
125
148
  return null;
126
149
  }
127
150
  const edge = await this.#requiredEdge(nodeOid, child.slot, 'tree');
151
+ expectedSummary = child;
152
+ parentTreeOid = nodeOid;
128
153
  nodeOid = edge.oid;
129
154
  }
130
155
  }
@@ -206,7 +231,7 @@ export default class BundleService {
206
231
  yield* this.#iterateMemberReferences(value, { validateTargets: true });
207
232
  }
208
233
 
209
- /** @internal Streams descriptors after validating only their direct Git edges. */
234
+ /** Streams descriptors after validating bundle structure and direct Git edges. */
210
235
  async *iterateMemberReferences({ handle: value }) {
211
236
  yield* this.#iterateMemberReferences(value, { validateTargets: false });
212
237
  }
@@ -587,7 +612,11 @@ export default class BundleService {
587
612
 
588
613
  async #readDescriptorBlob(oid, meta, maxBytes) {
589
614
  try {
590
- return await this.#persistence.readBlob(oid, maxBytes);
615
+ const bytes = await this.#descriptorBlobs.getOrCreate(
616
+ `${oid}\0${maxBytes}`,
617
+ () => this.#persistence.readBlob(oid, maxBytes),
618
+ );
619
+ return Uint8Array.from(bytes);
591
620
  } catch (error) {
592
621
  throw corrupt('Bundle descriptor blob is missing or unreadable', { ...meta, oid, originalError: error });
593
622
  }
@@ -4,6 +4,7 @@ import { CACHE_ACQUISITION_REF_PREFIX } from '../value-objects/CacheAcquisitionR
4
4
  import { CACHE_SET_REF_PREFIX } from '../value-objects/CacheSetRef.js';
5
5
  import { EXPIRING_SET_REF_PREFIX } from '../value-objects/ExpiringSetRef.js';
6
6
  import { ROOT_SET_REF_PREFIX } from '../value-objects/RootSetRef.js';
7
+ import { WORKSPACE_REF_PREFIX } from '../value-objects/WorkspaceRef.js';
7
8
  import { VAULT_REF } from './VaultPersistence.js';
8
9
  import {
9
10
  cacheAcquisitionGroup,
@@ -17,12 +18,13 @@ const MAX_COLLECTIONS_PER_KIND = 1_000;
17
18
 
18
19
  /** Composes bounded, non-mutating repository and managed-collection evidence. */
19
20
  export default class RepositoryDoctor {
20
- constructor({ repository, rootSets, caches, expiringSets, vault, clock }) {
21
- assertDependencies({ repository, rootSets, caches, expiringSets, vault });
21
+ constructor({ repository, rootSets, caches, expiringSets, workspaces, vault, clock }) {
22
+ assertDependencies({ repository, rootSets, caches, expiringSets, workspaces, vault });
22
23
  this.repository = repository;
23
24
  this.rootSets = rootSets;
24
25
  this.caches = caches;
25
26
  this.expiringSets = expiringSets;
27
+ this.workspaces = workspaces;
26
28
  this.vault = vault;
27
29
  this.clock = clock ?? { now: () => new Date() };
28
30
  Object.freeze(this);
@@ -130,6 +132,9 @@ export default class RepositoryDoctor {
130
132
  } else if (record.ref.startsWith(EXPIRING_SET_REF_PREFIX)) {
131
133
  result.expiringSets.observed += 1;
132
134
  recordExpiringSet(result.expiringSets, await this.#inspectExpiringSet(record));
135
+ } else if (record.ref.startsWith(WORKSPACE_REF_PREFIX)) {
136
+ result.workspaces.observed += 1;
137
+ recordWorkspace(result.workspaces, await this.#inspectWorkspace(record));
133
138
  } else if (record.ref === VAULT_REF) {
134
139
  result.vault = record;
135
140
  }
@@ -141,6 +146,7 @@ export default class RepositoryDoctor {
141
146
  caches: collectionGroup(result.caches),
142
147
  rootSets: collectionGroup(result.rootSets),
143
148
  expiringSets: collectionGroup(result.expiringSets),
149
+ workspaces: collectionGroup(result.workspaces),
144
150
  vault: await this.#inspectVault(result.vault, limitations),
145
151
  },
146
152
  };
@@ -175,6 +181,23 @@ export default class RepositoryDoctor {
175
181
  }
176
182
  }
177
183
 
184
+ async #inspectWorkspace(record) {
185
+ if (!this.workspaces) {
186
+ return unhealthyWorkspaceUsage({
187
+ record,
188
+ error: createCasError(
189
+ 'Workspace diagnostics are unavailable for this direct RepositoryDoctor construction',
190
+ ErrorCodes.REPOSITORY_INSPECTION_INVALID,
191
+ ),
192
+ });
193
+ }
194
+ try {
195
+ return workspaceUsage(await this.workspaces.inspectRecord(record));
196
+ } catch (error) {
197
+ return unhealthyWorkspaceUsage({ record, error });
198
+ }
199
+ }
200
+
178
201
  async #inspectVault(record, limitations) {
179
202
  if (record === null) {
180
203
  return {
@@ -392,6 +415,33 @@ function expiringSetUsageWithoutState(record, namespace, report) {
392
415
  };
393
416
  }
394
417
 
418
+ function workspaceUsage(report) {
419
+ const healthy = report.posture !== 'invalid' && report.issue === null;
420
+ return {
421
+ namespace: report.namespace,
422
+ ref: report.ref,
423
+ generation: report.generation,
424
+ healthy,
425
+ entryCount: report.rootCount,
426
+ logicalBytes: report.logicalBytes,
427
+ rootObjectBytes: report.rootObjectBytes,
428
+ physicalBytes: null,
429
+ retention: report.rootCount === null
430
+ ? null
431
+ : { pinnedEntries: 0, evictableEntries: report.rootCount },
432
+ reachability: 'anchored',
433
+ age: {
434
+ createdAt: report.createdAt,
435
+ ageMs: report.ageMs,
436
+ },
437
+ expiry: {
438
+ expiresAt: report.expiresAt,
439
+ posture: report.posture,
440
+ },
441
+ issues: report.issue ? [report.issue] : [],
442
+ };
443
+ }
444
+
395
445
  function rootGeneration(report, fallback) {
396
446
  return report.root?.headOid ?? fallback;
397
447
  }
@@ -435,6 +485,16 @@ function usageInventory(detailLimit) {
435
485
  { entryCount: 0, liveEntries: 0, expiredEntries: 0 },
436
486
  detailLimit
437
487
  ),
488
+ workspaces: collectionInventory(
489
+ {
490
+ entryCount: 0,
491
+ logicalBytes: 0,
492
+ rootObjectBytes: 0,
493
+ activeWorkspaces: 0,
494
+ expiredWorkspaces: 0,
495
+ },
496
+ detailLimit
497
+ ),
438
498
  vault: null,
439
499
  };
440
500
  }
@@ -474,6 +534,16 @@ function recordExpiringSet(inventory, entry) {
474
534
  });
475
535
  }
476
536
 
537
+ function recordWorkspace(inventory, entry) {
538
+ recordCollection(inventory, entry, {
539
+ entryCount: entry.entryCount,
540
+ logicalBytes: entry.logicalBytes,
541
+ rootObjectBytes: entry.rootObjectBytes,
542
+ activeWorkspaces: entry.expiry?.posture === 'active' ? 1 : 0,
543
+ expiredWorkspaces: entry.expiry?.posture === 'expired' ? 1 : 0,
544
+ });
545
+ }
546
+
477
547
  function recordCollection(inventory, entry, values) {
478
548
  inventory.inspected += 1;
479
549
  inventory.healthy &&= entry.healthy;
@@ -522,6 +592,7 @@ function usageHealthy(usage) {
522
592
  usage.acquisitions.healthy &&
523
593
  usage.rootSets.healthy &&
524
594
  usage.expiringSets.healthy &&
595
+ usage.workspaces.healthy &&
525
596
  usage.vault.healthy
526
597
  );
527
598
  }
@@ -558,6 +629,18 @@ function unhealthyExpiringSetUsage(options) {
558
629
  return { ...unhealthyBase(options), age: null, expiry: null };
559
630
  }
560
631
 
632
+ function unhealthyWorkspaceUsage(options) {
633
+ return {
634
+ ...unhealthyBase(options),
635
+ namespace: options.namespace ?? null,
636
+ logicalBytes: null,
637
+ rootObjectBytes: null,
638
+ retention: null,
639
+ age: null,
640
+ expiry: null,
641
+ };
642
+ }
643
+
561
644
  function publicError(error) {
562
645
  return {
563
646
  code: error?.code ?? ErrorCodes.REPOSITORY_INSPECTION_INVALID,
@@ -621,6 +704,18 @@ function addTruncationLimitations(refs, limitations) {
621
704
  });
622
705
  }
623
706
  }
707
+ const workspaces = refs.workspaces;
708
+ if (workspaces.observed > workspaces.entries.length) {
709
+ limitations.push({
710
+ ...limitation(
711
+ 'WORKSPACE_DETAILS_TRUNCATED',
712
+ 'Workspace detail exceeded maxCollectionsPerKind.'
713
+ ),
714
+ observed: workspaces.observed,
715
+ inspected: workspaces.inspected,
716
+ detailed: workspaces.entries.length,
717
+ });
718
+ }
624
719
  }
625
720
 
626
721
  function limitation(code, message) {
@@ -1,6 +1,7 @@
1
1
  import CasError from '../errors/CasError.js';
2
2
  import { ErrorCodes } from '../errors/index.js';
3
3
  import { errorDetailsText, isGitMissingRefError } from '../helpers/gitRefErrors.js';
4
+ import Oid from '../value-objects/Oid.js';
4
5
  import RootSetRef from '../value-objects/RootSetRef.js';
5
6
  import RootSetMetadataCodec, { ROOT_SET_METADATA_ENTRY } from './RootSetMetadataCodec.js';
6
7
  import RootSetTreeCodec from './RootSetTreeCodec.js';
@@ -10,6 +11,70 @@ const UPDATE_REF_CONFLICT_MARKERS = Object.freeze({
10
11
  cannotLockRef: 'cannot lock ref',
11
12
  referenceAlreadyExists: 'reference already exists',
12
13
  });
14
+ const GIT_REPOSITORY_LOCKED = 'GIT_REPOSITORY_LOCKED';
15
+ const GIT_FATAL_EXIT_CODE = 128;
16
+
17
+ function hasExactUpdateRefArgs(err, {
18
+ rootSetRef,
19
+ newCommit,
20
+ expectedHeadOid,
21
+ }) {
22
+ const details = err?.details && typeof err.details === 'object' ? err.details : {};
23
+ if (!Array.isArray(details.args)) {
24
+ return false;
25
+ }
26
+ const expectedArgs = [
27
+ 'update-ref',
28
+ '--no-deref',
29
+ rootSetRef,
30
+ newCommit,
31
+ expectedHeadOid ?? '0'.repeat(newCommit.length),
32
+ ];
33
+ return details.args.length === expectedArgs.length &&
34
+ expectedArgs.every((arg, index) => details.args[index] === arg);
35
+ }
36
+
37
+ function classifyStructuredUpdateRefConflict(err, {
38
+ rootSetRef,
39
+ newCommit,
40
+ expectedHeadOid,
41
+ }) {
42
+ const details = err?.details && typeof err.details === 'object' ? err.details : {};
43
+ if (details.code !== GIT_REPOSITORY_LOCKED) {
44
+ return null;
45
+ }
46
+ return hasExactUpdateRefArgs(err, { rootSetRef, newCommit, expectedHeadOid });
47
+ }
48
+
49
+ function isObservedUpdateRefConflict(err, {
50
+ rootSetRef,
51
+ newCommit,
52
+ expectedHeadOid,
53
+ actualHeadOid,
54
+ }) {
55
+ const details = err?.details && typeof err.details === 'object' ? err.details : {};
56
+ if (!Oid.isValid(actualHeadOid)) {
57
+ return false;
58
+ }
59
+ const canonicalActualHeadOid = Oid.from(actualHeadOid).toString();
60
+ const canonicalExpectedHeadOid = Oid.isValid(expectedHeadOid)
61
+ ? Oid.from(expectedHeadOid).toString()
62
+ : expectedHeadOid;
63
+ return details.code === GIT_FATAL_EXIT_CODE &&
64
+ canonicalActualHeadOid !== canonicalExpectedHeadOid &&
65
+ hasExactUpdateRefArgs(err, { rootSetRef, newCommit, expectedHeadOid });
66
+ }
67
+
68
+ function hasTextualUpdateRefConflict(err, rootSetRef) {
69
+ const normalized = errorDetailsText(err).toLowerCase();
70
+ if (!normalized.includes(rootSetRef.toLowerCase())) {
71
+ return false;
72
+ }
73
+ return normalized.includes(UPDATE_REF_CONFLICT_MARKERS.cannotLockRef) && (
74
+ normalized.includes(UPDATE_REF_CONFLICT_MARKERS.butExpected) ||
75
+ normalized.includes(UPDATE_REF_CONFLICT_MARKERS.referenceAlreadyExists)
76
+ );
77
+ }
13
78
 
14
79
  /**
15
80
  * Stateless persistence boundary for one root-set ref and snapshot format.
@@ -214,7 +279,11 @@ export default class RootSetPersistence {
214
279
  });
215
280
  } catch (err) {
216
281
  const meta = await this.#updateFailureMeta(err, commitOid, expectedHeadOid);
217
- if (this.#isConflict(err)) {
282
+ if (this.#isConflict(err, {
283
+ newCommit: commitOid,
284
+ expectedHeadOid,
285
+ actualHeadOid: meta.actualHeadOid,
286
+ })) {
218
287
  throw new CasError(
219
288
  'Concurrent root-set update detected',
220
289
  ErrorCodes.ROOT_SET_CONFLICT,
@@ -248,19 +317,30 @@ export default class RootSetPersistence {
248
317
  };
249
318
  }
250
319
 
251
- #isConflict(err) {
320
+ #isConflict(err, { newCommit, expectedHeadOid, actualHeadOid }) {
252
321
  const meta = err?.meta && typeof err.meta === 'object' ? err.meta : {};
253
322
  if (Object.hasOwn(meta, 'expectedOldOid') && Object.hasOwn(meta, 'actualOldOid')) {
254
323
  return true;
255
324
  }
256
- const normalized = errorDetailsText(err).toLowerCase();
257
- if (!normalized.includes(this.rootSetRef.toLowerCase())) {
258
- return false;
325
+ const structuredConflict = classifyStructuredUpdateRefConflict(err, {
326
+ rootSetRef: this.rootSetRef,
327
+ newCommit,
328
+ expectedHeadOid,
329
+ });
330
+ if (structuredConflict !== null) {
331
+ return structuredConflict;
259
332
  }
260
- return normalized.includes(UPDATE_REF_CONFLICT_MARKERS.cannotLockRef) && (
261
- normalized.includes(UPDATE_REF_CONFLICT_MARKERS.butExpected) ||
262
- normalized.includes(UPDATE_REF_CONFLICT_MARKERS.referenceAlreadyExists)
263
- );
333
+ // A failed exact CAS command plus an independently observed head advance
334
+ // remains sufficient conflict evidence when Git emits no diagnostic text.
335
+ if (isObservedUpdateRefConflict(err, {
336
+ rootSetRef: this.rootSetRef,
337
+ newCommit,
338
+ expectedHeadOid,
339
+ actualHeadOid,
340
+ })) {
341
+ return true;
342
+ }
343
+ return hasTextualUpdateRefConflict(err, this.rootSetRef);
264
344
  }
265
345
 
266
346
  #isMissingRefError(err) {