@git-stunts/git-cas 6.0.1 → 6.2.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.
Files changed (70) hide show
  1. package/ARCHITECTURE.md +120 -6
  2. package/CHANGELOG.md +98 -1
  3. package/GUIDE.md +114 -13
  4. package/README.md +60 -4
  5. package/UPGRADING.md +71 -1
  6. package/build-info.json +2 -2
  7. package/docs/API.md +934 -7
  8. package/docs/WALKTHROUGH.md +46 -0
  9. package/docs/releases/v6.1.0.md +75 -0
  10. package/docs/releases/v6.2.0.md +131 -0
  11. package/index.d.ts +974 -1
  12. package/index.js +354 -1
  13. package/package.json +8 -6
  14. package/src/domain/errors/Codes.js +48 -0
  15. package/src/domain/helpers/assertCanonicalTimestamp.js +15 -0
  16. package/src/domain/helpers/handleTarget.js +48 -0
  17. package/src/domain/helpers/isCanonicalCollectionKey.js +35 -0
  18. package/src/domain/services/AssetService.js +213 -0
  19. package/src/domain/services/BundleDescriptorCodec.js +286 -0
  20. package/src/domain/services/BundleFanoutBuilder.js +247 -0
  21. package/src/domain/services/BundleService.js +848 -0
  22. package/src/domain/services/CacheCandidateHeap.js +71 -0
  23. package/src/domain/services/CacheIndex.js +362 -0
  24. package/src/domain/services/CacheMetadataCodec.js +164 -0
  25. package/src/domain/services/CachePolicyEnforcer.js +144 -0
  26. package/src/domain/services/CacheSet.js +703 -0
  27. package/src/domain/services/CacheSetRegistry.js +88 -0
  28. package/src/domain/services/CasService.d.ts +3 -1
  29. package/src/domain/services/ExpiringSet.js +496 -0
  30. package/src/domain/services/ExpiringSetIndex.js +254 -0
  31. package/src/domain/services/ExpiringSetMetadataCodec.js +160 -0
  32. package/src/domain/services/ExpiringSetRegistry.js +101 -0
  33. package/src/domain/services/PageService.js +175 -0
  34. package/src/domain/services/PublicationService.js +315 -0
  35. package/src/domain/services/RepositoryDoctor.js +649 -0
  36. package/src/domain/services/RetentionService.js +120 -0
  37. package/src/domain/services/RootSet.js +281 -0
  38. package/src/domain/services/RootSetMetadataCodec.js +259 -0
  39. package/src/domain/services/RootSetPersistence.js +335 -0
  40. package/src/domain/services/RootSetRegistry.js +44 -0
  41. package/src/domain/services/RootSetRetryPolicy.js +87 -0
  42. package/src/domain/services/RootSetTreeCodec.js +95 -0
  43. package/src/domain/services/StagingEvidence.js +39 -0
  44. package/src/domain/value-objects/ApplicationHandle.js +40 -0
  45. package/src/domain/value-objects/AssetHandle.js +163 -0
  46. package/src/domain/value-objects/BundleHandle.js +32 -0
  47. package/src/domain/value-objects/BundleLimits.js +80 -0
  48. package/src/domain/value-objects/BundlePath.js +78 -0
  49. package/src/domain/value-objects/CacheHit.js +93 -0
  50. package/src/domain/value-objects/CacheKey.js +32 -0
  51. package/src/domain/value-objects/CachePolicy.js +59 -0
  52. package/src/domain/value-objects/CacheSetRef.js +40 -0
  53. package/src/domain/value-objects/CollectionNamespace.js +54 -0
  54. package/src/domain/value-objects/ExpiringMarker.js +81 -0
  55. package/src/domain/value-objects/ExpiringSetKey.js +28 -0
  56. package/src/domain/value-objects/ExpiringSetRef.js +42 -0
  57. package/src/domain/value-objects/OpaqueHandle.js +171 -0
  58. package/src/domain/value-objects/PageHandle.js +34 -0
  59. package/src/domain/value-objects/RetentionWitness.js +101 -0
  60. package/src/domain/value-objects/RootSetRef.js +88 -0
  61. package/src/domain/value-objects/StagedAsset.js +63 -0
  62. package/src/domain/value-objects/StagedBundle.js +66 -0
  63. package/src/domain/value-objects/StagedPage.js +47 -0
  64. package/src/infrastructure/adapters/GitPersistenceAdapter.js +57 -0
  65. package/src/infrastructure/adapters/GitRefAdapter.js +26 -5
  66. package/src/infrastructure/adapters/GitRepositoryInspectionAdapter.js +164 -0
  67. package/src/package-version.js +1 -1
  68. package/src/ports/GitPersistencePort.js +20 -1
  69. package/src/ports/GitRefPort.js +10 -0
  70. package/src/ports/RepositoryInspectionPort.js +33 -0
@@ -0,0 +1,47 @@
1
+ import createCasError from '../errors/createCasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+ import assertCanonicalTimestamp from '../helpers/assertCanonicalTimestamp.js';
4
+ import PageHandle from './PageHandle.js';
5
+
6
+ /**
7
+ * Immutable result for a page blob written without a reachability root.
8
+ */
9
+ export default class StagedPage {
10
+ /** @param {{ handle: PageHandle|string|object, size: number, observedAt: string }} value */
11
+ constructor({ handle, size, observedAt }) {
12
+ if (!Number.isSafeInteger(size) || size < 0) {
13
+ throw StagedPage.#invalid('Staged page size must be a non-negative safe integer', { size });
14
+ }
15
+ assertCanonicalTimestamp(observedAt, {
16
+ invalid: StagedPage.#invalid,
17
+ message: 'Staged page observation time must be a canonical UTC timestamp',
18
+ });
19
+ this.version = 1;
20
+ this.state = 'staged';
21
+ this.handle = PageHandle.from(handle);
22
+ this.page = Object.freeze({ size });
23
+ this.retention = Object.freeze({
24
+ policy: null,
25
+ reachability: 'unanchored',
26
+ protection: 'not-established',
27
+ });
28
+ this.observedAt = observedAt;
29
+ Object.freeze(this);
30
+ }
31
+
32
+ /** @returns {object} */
33
+ toJSON() {
34
+ return {
35
+ version: this.version,
36
+ state: this.state,
37
+ handle: this.handle.toString(),
38
+ page: { ...this.page },
39
+ retention: { ...this.retention },
40
+ observedAt: this.observedAt,
41
+ };
42
+ }
43
+
44
+ static #invalid(message, meta) {
45
+ return createCasError(message, ErrorCodes.HANDLE_INVALID, meta);
46
+ }
47
+ }
@@ -18,6 +18,8 @@ export const DEFAULT_MAX_BLOB_SIZE = 10 * 1024 * 1024;
18
18
  const MIN_READ_BLOB_LIMIT = 1;
19
19
  const MIN_MAX_BLOB_SIZE = 1024;
20
20
  const MAX_BLOB_SIZE_LIMIT = Number.MAX_SAFE_INTEGER;
21
+ const OBJECT_INFO_ARGUMENT = '--batch-check=%(objectname) %(objecttype) %(objectsize)';
22
+ const GIT_OBJECT_TYPES = new Set(['blob', 'tree', 'commit', 'tag']);
21
23
 
22
24
  /**
23
25
  * {@link GitPersistencePort} implementation backed by `@git-stunts/plumbing`.
@@ -180,6 +182,61 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
180
182
  }
181
183
  }
182
184
 
185
+ /**
186
+ * @override
187
+ * @param {string} oid - Git object ID.
188
+ * @returns {Promise<string>} Git object type.
189
+ */
190
+ async readObjectType(oid) {
191
+ return (await this.#readObjectInfo(oid)).type;
192
+ }
193
+
194
+ /**
195
+ * @override
196
+ * @param {string} oid - Git object ID.
197
+ * @returns {Promise<number>} Git object size in bytes.
198
+ */
199
+ async readObjectSize(oid) {
200
+ return (await this.#readObjectInfo(oid)).size;
201
+ }
202
+
203
+ /**
204
+ * Reads object metadata through Git's structured batch protocol. Missing
205
+ * objects are reported on stdout with exit zero, avoiding runtime-specific
206
+ * stderr capture while preserving genuine command failures.
207
+ *
208
+ * @param {string} oid - Git object ID.
209
+ * @returns {Promise<{ oid: string, type: string, size: number }>} Object metadata.
210
+ */
211
+ async #readObjectInfo(oid) {
212
+ const rawOutput = await this.policy.execute(() => this.plumbing.execute({
213
+ args: ['cat-file', OBJECT_INFO_ARGUMENT],
214
+ input: `${oid}\n`,
215
+ }));
216
+ const output = typeof rawOutput === 'string' ? rawOutput.trim() : '';
217
+ if (output === `${oid} missing`) {
218
+ throw new CasError(`Git object not found: ${oid}`, ErrorCodes.GIT_OBJECT_NOT_FOUND, {
219
+ oid,
220
+ });
221
+ }
222
+
223
+ const fields = output.split(' ');
224
+ const size = Number(fields[2]);
225
+ if (
226
+ fields.length !== 3 ||
227
+ fields[0] !== oid ||
228
+ !GIT_OBJECT_TYPES.has(fields[1]) ||
229
+ !Number.isSafeInteger(size) ||
230
+ size < 0
231
+ ) {
232
+ throw new CasError(`Git object has invalid metadata: ${oid}`, ErrorCodes.GIT_ERROR, {
233
+ oid,
234
+ output: rawOutput,
235
+ });
236
+ }
237
+ return Object.freeze({ oid: fields[0], type: fields[1], size });
238
+ }
239
+
183
240
  /**
184
241
  * Bun can surface unhandled EPIPE writes when large buffers are fed through
185
242
  * `git hash-object --stdin`. Write the blob to a temp file and hash the file
@@ -12,7 +12,6 @@ import { isGitMissingRefError } from '../../domain/helpers/gitRefErrors.js';
12
12
  * an unref'd timer that allows Node to exit before the next attempt starts.
13
13
  */
14
14
  const DEFAULT_POLICY = Policy.timeout(30_000);
15
- const GIT_NULL_OID = '0'.repeat(40);
16
15
 
17
16
  /**
18
17
  * {@link GitRefPort} implementation backed by `@git-stunts/plumbing`.
@@ -64,18 +63,40 @@ export default class GitRefAdapter extends GitRefPort {
64
63
  );
65
64
  }
66
65
 
66
+ /**
67
+ * @override
68
+ * @param {string} commitOid - Git commit OID.
69
+ * @returns {Promise<string[]>} Direct parent OIDs.
70
+ */
71
+ async resolveParents(commitOid) {
72
+ const line = await this.policy.execute(() =>
73
+ this.plumbing.execute({ args: ['rev-list', '--parents', '-n', '1', commitOid] }),
74
+ );
75
+ const [resolvedCommit, ...parents] = line.trim().split(/\s+/u);
76
+ if (!resolvedCommit) {
77
+ throw new CasError(
78
+ `Git commit not found: ${commitOid}`,
79
+ ErrorCodes.GIT_ERROR,
80
+ { commitOid },
81
+ );
82
+ }
83
+ return parents;
84
+ }
85
+
67
86
  /**
68
87
  * @override
69
88
  * @param {Object} options
70
89
  * @param {string} options.treeOid - Tree OID for the commit.
71
90
  * @param {string|null} [options.parentOid] - Parent commit OID.
91
+ * @param {string[]} [options.parentOids] - Ordered parent commit OIDs.
72
92
  * @param {string} options.message - Commit message.
73
93
  * @returns {Promise<string>} The new commit OID.
74
94
  */
75
- async createCommit({ treeOid, parentOid, message }) {
95
+ async createCommit({ treeOid, parentOid, parentOids, message }) {
76
96
  const args = ['commit-tree', treeOid, '-m', message];
77
- if (parentOid) {
78
- args.push('-p', parentOid);
97
+ const parents = parentOids ?? (parentOid ? [parentOid] : []);
98
+ for (const parent of parents) {
99
+ args.push('-p', parent);
79
100
  }
80
101
  return this.policy.execute(() =>
81
102
  this.plumbing.execute({ args }),
@@ -93,7 +114,7 @@ export default class GitRefAdapter extends GitRefPort {
93
114
  async updateRef({ ref, newOid, expectedOldOid }) {
94
115
  const args = ['update-ref', ref, newOid];
95
116
  if (expectedOldOid !== undefined) {
96
- args.push(expectedOldOid ?? GIT_NULL_OID);
117
+ args.push(expectedOldOid ?? '0'.repeat(newOid.length));
97
118
  }
98
119
  await this.policy.execute(() =>
99
120
  this.plumbing.execute({ args }),
@@ -0,0 +1,164 @@
1
+ import { Policy } from '@git-stunts/alfred';
2
+ import { CasError, ErrorCodes } from '../../domain/errors/index.js';
3
+ import Oid from '../../domain/value-objects/Oid.js';
4
+ import RepositoryInspectionPort from '../../ports/RepositoryInspectionPort.js';
5
+
6
+ const DEFAULT_POLICY = Policy.timeout(30_000);
7
+ const DEFAULT_FULL_SCAN_POLICY = Policy.timeout(5 * 60_000);
8
+ const OBJECT_TYPES = new Set(['blob', 'tree', 'commit', 'tag']);
9
+ const OBJECT_FORMAT = '--batch-check=%(objectname) %(objecttype) %(objectsize) %(objectsize:disk)';
10
+
11
+ /** Non-mutating repository inspection backed by safe Git plumbing commands. */
12
+ export default class GitRepositoryInspectionAdapter extends RepositoryInspectionPort {
13
+ constructor({ plumbing, policy }) {
14
+ super();
15
+ if (
16
+ typeof plumbing?.execute !== 'function' ||
17
+ typeof plumbing?.executeStream !== 'function' ||
18
+ typeof plumbing?.inspectPrunableObjects !== 'function'
19
+ ) {
20
+ throw new CasError(
21
+ 'Repository inspection requires GitPlumbing 3.1.0 or newer',
22
+ ErrorCodes.REPOSITORY_INSPECTION_INVALID
23
+ );
24
+ }
25
+ this.plumbing = plumbing;
26
+ this.policy = policy ?? DEFAULT_POLICY;
27
+ this.fullScanPolicy = policy ?? DEFAULT_FULL_SCAN_POLICY;
28
+ Object.freeze(this);
29
+ }
30
+
31
+ async *iterateObjects() {
32
+ const stream = await this.#stream({
33
+ args: ['cat-file', '--batch-all-objects', OBJECT_FORMAT],
34
+ });
35
+ for await (const line of consumeLines(stream, 'object inventory')) {
36
+ const fields = line.split(' ');
37
+ if (fields.length !== 4) {
38
+ throw invalidOutput('object inventory', line);
39
+ }
40
+ const [oid, type] = fields;
41
+ yield Object.freeze({
42
+ oid: parseOid(oid, 'object inventory', line),
43
+ type: parseType(type, 'object inventory', line),
44
+ logicalBytes: parseBytes(fields[2], 'object inventory', line),
45
+ physicalBytes: parseBytes(fields[3], 'object inventory', line),
46
+ });
47
+ }
48
+ }
49
+
50
+ async *iterateReachableObjectIds() {
51
+ const stream = await this.#stream({
52
+ args: ['rev-list', '--all', '--reflog', '--objects', '--no-object-names'],
53
+ });
54
+ for await (const line of consumeLines(stream, 'reachable object inventory')) {
55
+ yield parseOid(line, 'reachable object inventory', line);
56
+ }
57
+ }
58
+
59
+ async *iteratePrunableObjects({ expiresBefore }) {
60
+ const stream = await this.policy.execute(() =>
61
+ this.plumbing.inspectPrunableObjects({ expiresBefore })
62
+ );
63
+ for await (const line of consumeLines(stream, 'prunable object inspection')) {
64
+ const fields = line.trim().split(/\s+/u);
65
+ if (fields.length !== 2) {
66
+ throw invalidOutput('prunable object inspection', line);
67
+ }
68
+ yield Object.freeze({
69
+ oid: parseOid(fields[0], 'prunable object inspection', line),
70
+ type: parseType(fields[1], 'prunable object inspection', line),
71
+ });
72
+ }
73
+ }
74
+
75
+ async *iterateRefs() {
76
+ const stream = await this.#stream({
77
+ args: ['for-each-ref', '--format=%(refname)%09%(objectname)', 'refs/'],
78
+ });
79
+ for await (const line of consumeLines(stream, 'ref inventory')) {
80
+ const fields = line.split('\t');
81
+ if (fields.length !== 2 || !fields[0].startsWith('refs/')) {
82
+ throw invalidOutput('ref inventory', line);
83
+ }
84
+ yield Object.freeze({
85
+ ref: fields[0],
86
+ oid: parseOid(fields[1], 'ref inventory', line),
87
+ });
88
+ }
89
+ }
90
+
91
+ async reachablePhysicalBytes() {
92
+ const output = await this.fullScanPolicy.execute(() =>
93
+ this.plumbing.execute({
94
+ args: ['rev-list', '--all', '--reflog', '--objects', '--disk-usage'],
95
+ })
96
+ );
97
+ return parseBytes(String(output).trim(), 'reachable disk usage', output);
98
+ }
99
+
100
+ async #stream(options) {
101
+ return await this.policy.execute(() => this.plumbing.executeStream(options));
102
+ }
103
+ }
104
+
105
+ async function* consumeLines(stream, operation) {
106
+ const decoder = new globalThis.TextDecoder();
107
+ let pending = '';
108
+ for await (const chunk of stream) {
109
+ pending += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
110
+ let newline = pending.indexOf('\n');
111
+ while (newline !== -1) {
112
+ const line = pending.slice(0, newline).replace(/\r$/u, '');
113
+ pending = pending.slice(newline + 1);
114
+ if (line.length > 0) {
115
+ yield line;
116
+ }
117
+ newline = pending.indexOf('\n');
118
+ }
119
+ }
120
+ pending += decoder.decode();
121
+ if (pending.length > 0) {
122
+ yield pending.replace(/\r$/u, '');
123
+ }
124
+ const result = await stream.finished;
125
+ if (result?.code !== 0) {
126
+ throw new CasError(`Git ${operation} failed`, ErrorCodes.REPOSITORY_INSPECTION_INVALID, {
127
+ operation,
128
+ stderr: result?.stderr,
129
+ });
130
+ }
131
+ }
132
+
133
+ function parseOid(value, operation, output) {
134
+ if (!Oid.isValid(value)) {
135
+ throw invalidOutput(operation, output);
136
+ }
137
+ return Oid.from(value).toString();
138
+ }
139
+
140
+ function parseType(value, operation, output) {
141
+ if (!OBJECT_TYPES.has(value)) {
142
+ throw invalidOutput(operation, output);
143
+ }
144
+ return value;
145
+ }
146
+
147
+ function parseBytes(value, operation, output) {
148
+ if (!/^\d+$/u.test(String(value))) {
149
+ throw invalidOutput(operation, output);
150
+ }
151
+ const bytes = Number(value);
152
+ if (!Number.isSafeInteger(bytes)) {
153
+ throw invalidOutput(operation, output);
154
+ }
155
+ return bytes;
156
+ }
157
+
158
+ function invalidOutput(operation, output) {
159
+ return new CasError(
160
+ `Git ${operation} returned invalid structured output`,
161
+ ErrorCodes.REPOSITORY_INSPECTION_INVALID,
162
+ { operation, output: String(output) }
163
+ );
164
+ }
@@ -1 +1 @@
1
- export const PACKAGE_VERSION = '6.0.1';
1
+ export const PACKAGE_VERSION = '6.2.0';
@@ -24,9 +24,10 @@ export default class GitPersistencePort {
24
24
  /**
25
25
  * Reads a Git blob by its OID.
26
26
  * @param {string} _oid - Git object ID.
27
+ * @param {number} [_maxBytes] - Maximum bytes the adapter may materialize.
27
28
  * @returns {Promise<Uint8Array>} The blob content.
28
29
  */
29
- async readBlob(_oid) {
30
+ async readBlob(_oid, _maxBytes) {
30
31
  throw new Error('Not implemented');
31
32
  }
32
33
 
@@ -68,4 +69,22 @@ export default class GitPersistencePort {
68
69
  iterateTree(_treeOid) {
69
70
  throw new Error('Not implemented');
70
71
  }
72
+
73
+ /**
74
+ * Reads the Git object type without materializing object content.
75
+ * @param {string} _oid - Git object ID.
76
+ * @returns {Promise<string>} Git object type such as `blob`, `tree`, or `commit`.
77
+ */
78
+ async readObjectType(_oid) {
79
+ throw new Error('Not implemented');
80
+ }
81
+
82
+ /**
83
+ * Reads the Git object size without materializing object content.
84
+ * @param {string} _oid - Git object ID.
85
+ * @returns {Promise<number>} Object size in bytes.
86
+ */
87
+ async readObjectSize(_oid) {
88
+ throw new Error('Not implemented');
89
+ }
71
90
  }
@@ -22,11 +22,21 @@ export default class GitRefPort {
22
22
  throw new Error('Not implemented');
23
23
  }
24
24
 
25
+ /**
26
+ * Resolves the direct parent OIDs from a commit OID.
27
+ * @param {string} _commitOid - Git commit OID.
28
+ * @returns {Promise<string[]>} Direct parent OIDs; empty for a root commit.
29
+ */
30
+ async resolveParents(_commitOid) {
31
+ throw new Error('Not implemented');
32
+ }
33
+
25
34
  /**
26
35
  * Creates a Git commit object.
27
36
  * @param {Object} _options
28
37
  * @param {string} _options.treeOid - Tree OID for the commit.
29
38
  * @param {string|null} [_options.parentOid] - Parent commit OID (null for root commit).
39
+ * @param {string[]} [_options.parentOids] - Ordered parent commit OIDs.
30
40
  * @param {string} _options.message - Commit message.
31
41
  * @returns {Promise<string>} The new commit OID.
32
42
  */
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Abstract port for non-mutating, repository-wide Git object inspection.
3
+ * @abstract
4
+ */
5
+ export default class RepositoryInspectionPort {
6
+ /** @returns {AsyncIterable<{ oid: string, type: string, logicalBytes: number, physicalBytes: number }>} */
7
+ iterateObjects() {
8
+ throw new Error('Not implemented');
9
+ }
10
+
11
+ /** @returns {AsyncIterable<string>} */
12
+ iterateReachableObjectIds() {
13
+ throw new Error('Not implemented');
14
+ }
15
+
16
+ /**
17
+ * @param {{ expiresBefore: string }} _options
18
+ * @returns {AsyncIterable<{ oid: string, type: string }>}
19
+ */
20
+ iteratePrunableObjects(_options) {
21
+ throw new Error('Not implemented');
22
+ }
23
+
24
+ /** @returns {AsyncIterable<{ ref: string, oid: string }>} */
25
+ iterateRefs() {
26
+ throw new Error('Not implemented');
27
+ }
28
+
29
+ /** @returns {Promise<number>} */
30
+ async reachablePhysicalBytes() {
31
+ throw new Error('Not implemented');
32
+ }
33
+ }