@git-stunts/git-cas 6.0.1 → 6.1.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.
@@ -0,0 +1,87 @@
1
+ import CasError from '../errors/CasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+
4
+ export const DEFAULT_ROOT_SET_RETRY_MAX_ATTEMPTS = 3;
5
+ export const DEFAULT_ROOT_SET_RETRY_BASE_DELAY_MS = 25;
6
+
7
+ /**
8
+ * Retry policy for optimistic root-set mutations.
9
+ */
10
+ export default class RootSetRetryPolicy {
11
+ #maxAttempts;
12
+ #baseDelayMs;
13
+ #random;
14
+ #sleep;
15
+
16
+ /**
17
+ * @param {object} [options]
18
+ * @param {number} [options.maxAttempts]
19
+ * @param {number} [options.baseDelayMs]
20
+ * @param {() => number} [options.random]
21
+ * @param {(delayMs: number) => Promise<void>} [options.sleep]
22
+ */
23
+ constructor({
24
+ maxAttempts = DEFAULT_ROOT_SET_RETRY_MAX_ATTEMPTS,
25
+ baseDelayMs = DEFAULT_ROOT_SET_RETRY_BASE_DELAY_MS,
26
+ random = Math.random,
27
+ sleep = (delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs)),
28
+ } = {}) {
29
+ RootSetRetryPolicy.#assertPositiveInteger('maxAttempts', maxAttempts);
30
+ RootSetRetryPolicy.#assertNonNegativeNumber('baseDelayMs', baseDelayMs);
31
+ RootSetRetryPolicy.#assertFunction('random', random);
32
+ RootSetRetryPolicy.#assertFunction('sleep', sleep);
33
+ this.#maxAttempts = maxAttempts;
34
+ this.#baseDelayMs = baseDelayMs;
35
+ this.#random = random;
36
+ this.#sleep = sleep;
37
+ Object.freeze(this);
38
+ }
39
+
40
+ get maxAttempts() {
41
+ return this.#maxAttempts;
42
+ }
43
+
44
+ /**
45
+ * @param {unknown} err
46
+ * @returns {boolean}
47
+ */
48
+ isRetryable(err) {
49
+ return err instanceof CasError && err.code === ErrorCodes.ROOT_SET_CONFLICT;
50
+ }
51
+
52
+ /**
53
+ * @param {number} attempt
54
+ * @returns {Promise<void>}
55
+ */
56
+ async waitBeforeRetry(attempt) {
57
+ const exponentialDelay = this.#baseDelayMs * (2 ** attempt);
58
+ const jitter = Math.floor(this.#random() * (exponentialDelay / 2));
59
+ await this.#sleep(exponentialDelay + jitter);
60
+ }
61
+
62
+ static #assertPositiveInteger(label, value) {
63
+ if (!Number.isInteger(value) || value < 1) {
64
+ throw RootSetRetryPolicy.#invalid(label, value, 'a positive integer');
65
+ }
66
+ }
67
+
68
+ static #assertNonNegativeNumber(label, value) {
69
+ if (!Number.isFinite(value) || value < 0) {
70
+ throw RootSetRetryPolicy.#invalid(label, value, 'a non-negative number');
71
+ }
72
+ }
73
+
74
+ static #assertFunction(label, value) {
75
+ if (typeof value !== 'function') {
76
+ throw RootSetRetryPolicy.#invalid(label, value, 'a function');
77
+ }
78
+ }
79
+
80
+ static #invalid(label, value, expectation) {
81
+ return new CasError(
82
+ `Root-set retry ${label} must be ${expectation}`,
83
+ ErrorCodes.ROOT_SET_RETRY_POLICY_INVALID,
84
+ { [label]: value },
85
+ );
86
+ }
87
+ }
@@ -0,0 +1,95 @@
1
+ import CasError from '../errors/CasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+ import { ROOT_SET_METADATA_ENTRY } from './RootSetMetadataCodec.js';
4
+
5
+ const GIT_TREE_MODE = '040000';
6
+ const GIT_BLOB_MODE = '100644';
7
+
8
+ /**
9
+ * Encodes and validates the Git tree that provides root-set reachability.
10
+ */
11
+ export default class RootSetTreeCodec {
12
+ /**
13
+ * @param {object} metadata
14
+ * @param {string} metadataBlobOid
15
+ * @returns {string[]}
16
+ */
17
+ toTreeLines(metadata, metadataBlobOid) {
18
+ const lines = [`${GIT_BLOB_MODE} blob ${metadataBlobOid}\t${ROOT_SET_METADATA_ENTRY}`];
19
+ for (const entry of metadata.entries) {
20
+ const mode = entry.type === 'tree' ? GIT_TREE_MODE : GIT_BLOB_MODE;
21
+ lines.push(`${mode} ${entry.type} ${entry.oid}\t${entry.slot}`);
22
+ }
23
+ return lines;
24
+ }
25
+
26
+ /**
27
+ * @param {Array<object>} rawEntries
28
+ * @param {object} metadata
29
+ */
30
+ validate(rawEntries, metadata) {
31
+ if (!Array.isArray(rawEntries)) {
32
+ throw this.#treeError('Root-set tree entries must be an array', { rawEntries });
33
+ }
34
+ const { actual, metadataCount } = this.#indexTreeEntries(rawEntries);
35
+ this.#assertEntryCounts(actual, metadataCount, metadata);
36
+ this.#assertReachabilityEdges(actual, metadata.entries);
37
+ }
38
+
39
+ #indexTreeEntries(rawEntries) {
40
+ const actual = new Map();
41
+ let metadataCount = 0;
42
+ for (const entry of rawEntries) {
43
+ if (entry.name === ROOT_SET_METADATA_ENTRY) {
44
+ metadataCount++;
45
+ if (entry.type !== 'blob' || entry.mode !== GIT_BLOB_MODE) {
46
+ throw this.#treeError('Root-set metadata entry must be a regular blob', { entry });
47
+ }
48
+ continue;
49
+ }
50
+ if (actual.has(entry.name)) {
51
+ throw this.#treeError('Root-set tree contains duplicate entry slots', {
52
+ slot: entry.name,
53
+ });
54
+ }
55
+ actual.set(entry.name, entry);
56
+ }
57
+ return { actual, metadataCount };
58
+ }
59
+
60
+ #assertEntryCounts(actual, metadataCount, metadata) {
61
+ if (metadataCount !== 1) {
62
+ throw this.#treeError('Root-set tree must contain exactly one metadata blob', {
63
+ metadataCount,
64
+ });
65
+ }
66
+ if (actual.size !== metadata.entries.length) {
67
+ throw this.#treeError('Root-set metadata and tree entry counts differ', {
68
+ metadataEntryCount: metadata.entries.length,
69
+ treeEntryCount: actual.size,
70
+ });
71
+ }
72
+ }
73
+
74
+ #assertReachabilityEdges(actual, expectedEntries) {
75
+ for (const expected of expectedEntries) {
76
+ const entry = actual.get(expected.slot);
77
+ const mode = expected.type === 'tree' ? GIT_TREE_MODE : GIT_BLOB_MODE;
78
+ if (!entry || entry.oid !== expected.oid || entry.type !== expected.type || entry.mode !== mode) {
79
+ throw this.#treeError('Root-set metadata does not match its Git reachability edge', {
80
+ expected,
81
+ actual: entry ?? null,
82
+ });
83
+ }
84
+ }
85
+ }
86
+
87
+ /**
88
+ * @param {string} message
89
+ * @param {object} meta
90
+ * @returns {CasError}
91
+ */
92
+ #treeError(message, meta) {
93
+ return new CasError(message, ErrorCodes.ROOT_SET_TREE_INVALID, meta);
94
+ }
95
+ }
@@ -0,0 +1,88 @@
1
+ import CasError from '../errors/CasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+
4
+ export const ROOT_SET_REF_PREFIX = 'refs/cas/rootsets/';
5
+ const FORBIDDEN_REF_CHARS = '~^:?*[\\';
6
+
7
+ /**
8
+ * Immutable, validated ref in the git-cas root-set namespace.
9
+ */
10
+ export default class RootSetRef {
11
+ #value;
12
+
13
+ /**
14
+ * @param {string} value
15
+ */
16
+ constructor(value) {
17
+ if (!RootSetRef.isValid(value)) {
18
+ throw new CasError(
19
+ `Root-set ref must be a valid ref below ${ROOT_SET_REF_PREFIX}`,
20
+ ErrorCodes.ROOT_SET_REF_INVALID,
21
+ { ref: value, prefix: ROOT_SET_REF_PREFIX },
22
+ );
23
+ }
24
+ this.#value = value;
25
+ Object.freeze(this);
26
+ }
27
+
28
+ /**
29
+ * @param {string|RootSetRef} value
30
+ * @returns {RootSetRef}
31
+ */
32
+ static from(value) {
33
+ return value instanceof RootSetRef ? value : new RootSetRef(value);
34
+ }
35
+
36
+ /**
37
+ * @param {unknown} value
38
+ * @returns {boolean}
39
+ */
40
+ static isValid(value) {
41
+ if (typeof value !== 'string' || !value.startsWith(ROOT_SET_REF_PREFIX)) {
42
+ return false;
43
+ }
44
+ const suffix = value.slice(ROOT_SET_REF_PREFIX.length);
45
+ if (RootSetRef.#hasInvalidSuffixShape(suffix) || RootSetRef.#hasForbiddenChar(suffix)) {
46
+ return false;
47
+ }
48
+ return suffix.split('/').every(RootSetRef.#isValidComponent);
49
+ }
50
+
51
+ static #hasInvalidSuffixShape(suffix) {
52
+ return [
53
+ suffix.length === 0,
54
+ suffix.startsWith('/'),
55
+ suffix.endsWith('/'),
56
+ suffix.endsWith('.'),
57
+ suffix.includes('//'),
58
+ suffix.includes('..'),
59
+ suffix.includes('@{'),
60
+ ].some(Boolean);
61
+ }
62
+
63
+ static #hasForbiddenChar(value) {
64
+ for (const character of value) {
65
+ const codePoint = character.codePointAt(0);
66
+ if (codePoint <= 0x20 || codePoint === 0x7f || FORBIDDEN_REF_CHARS.includes(character)) {
67
+ return true;
68
+ }
69
+ }
70
+ return false;
71
+ }
72
+
73
+ static #isValidComponent(component) {
74
+ return [
75
+ component.length > 0,
76
+ component !== '.',
77
+ component !== '..',
78
+ !component.endsWith('.lock'),
79
+ ].every(Boolean);
80
+ }
81
+
82
+ /**
83
+ * @returns {string}
84
+ */
85
+ toString() {
86
+ return this.#value;
87
+ }
88
+ }
@@ -4,6 +4,7 @@ import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import GitPersistencePort from '../../ports/GitPersistencePort.js';
6
6
  import { CasError, createCasError, ErrorCodes } from '../../domain/errors/index.js';
7
+ import { errorDetailsText } from '../../domain/helpers/gitRefErrors.js';
7
8
 
8
9
  /**
9
10
  * Default resilience policy: 30 s timeout (no retry).
@@ -180,6 +181,27 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
180
181
  }
181
182
  }
182
183
 
184
+ /**
185
+ * @override
186
+ * @param {string} oid - Git object ID.
187
+ * @returns {Promise<string>} Git object type.
188
+ */
189
+ async readObjectType(oid) {
190
+ try {
191
+ return await this.policy.execute(() =>
192
+ this.plumbing.execute({ args: ['cat-file', '-t', oid] }),
193
+ );
194
+ } catch (err) {
195
+ if (isMissingGitObjectError(err)) {
196
+ throw new CasError(`Git object not found: ${oid}`, ErrorCodes.GIT_OBJECT_NOT_FOUND, {
197
+ oid,
198
+ originalError: err,
199
+ });
200
+ }
201
+ throw err;
202
+ }
203
+ }
204
+
183
205
  /**
184
206
  * Bun can surface unhandled EPIPE writes when large buffers are fed through
185
207
  * `git hash-object --stdin`. Write the blob to a temp file and hash the file
@@ -310,3 +332,10 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
310
332
  };
311
333
  }
312
334
  }
335
+
336
+ function isMissingGitObjectError(err) {
337
+ const message = errorDetailsText(err).toLowerCase();
338
+ return message.includes('could not get object info') ||
339
+ message.includes('not a valid object name') ||
340
+ message.includes('bad object');
341
+ }
@@ -64,6 +64,26 @@ export default class GitRefAdapter extends GitRefPort {
64
64
  );
65
65
  }
66
66
 
67
+ /**
68
+ * @override
69
+ * @param {string} commitOid - Git commit OID.
70
+ * @returns {Promise<string[]>} Direct parent OIDs.
71
+ */
72
+ async resolveParents(commitOid) {
73
+ const line = await this.policy.execute(() =>
74
+ this.plumbing.execute({ args: ['rev-list', '--parents', '-n', '1', commitOid] }),
75
+ );
76
+ const [resolvedCommit, ...parents] = line.trim().split(/\s+/u);
77
+ if (!resolvedCommit) {
78
+ throw new CasError(
79
+ `Git commit not found: ${commitOid}`,
80
+ ErrorCodes.GIT_ERROR,
81
+ { commitOid },
82
+ );
83
+ }
84
+ return parents;
85
+ }
86
+
67
87
  /**
68
88
  * @override
69
89
  * @param {Object} options
@@ -1 +1 @@
1
- export const PACKAGE_VERSION = '6.0.1';
1
+ export const PACKAGE_VERSION = '6.1.0';
@@ -68,4 +68,13 @@ export default class GitPersistencePort {
68
68
  iterateTree(_treeOid) {
69
69
  throw new Error('Not implemented');
70
70
  }
71
+
72
+ /**
73
+ * Reads the Git object type without materializing object content.
74
+ * @param {string} _oid - Git object ID.
75
+ * @returns {Promise<string>} Git object type such as `blob`, `tree`, or `commit`.
76
+ */
77
+ async readObjectType(_oid) {
78
+ throw new Error('Not implemented');
79
+ }
71
80
  }
@@ -22,6 +22,15 @@ 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