@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.
@@ -0,0 +1,151 @@
1
+ import createCasError from '../errors/createCasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+ import CollectionNamespace from './CollectionNamespace.js';
4
+
5
+ export const WORKSPACE_REF_PREFIX = 'refs/cas/workspaces/';
6
+ const WORKSPACE_ID = /^v1-([a-z0-9]+)-([a-f0-9]{32})$/;
7
+ const NONCE_BYTES = 16;
8
+
9
+ /** Immutable ref identifying one scoped staging workspace. */
10
+ export default class WorkspaceRef {
11
+ #createdAt;
12
+ #id;
13
+ #namespace;
14
+ #value;
15
+
16
+ constructor(value) {
17
+ const parsed = WorkspaceRef.#parse(value);
18
+ this.#namespace = parsed.namespace;
19
+ this.#id = parsed.id;
20
+ this.#createdAt = parsed.createdAt;
21
+ this.#value = parsed.value;
22
+ Object.freeze(this);
23
+ }
24
+
25
+ static from(value) {
26
+ return value instanceof WorkspaceRef ? value : new WorkspaceRef(value);
27
+ }
28
+
29
+ static create({ namespace: value, createdAt, nonce }) {
30
+ const namespace = CollectionNamespace.from(value).toString();
31
+ const created = WorkspaceRef.#canonicalTimestamp(createdAt);
32
+ if (!(nonce instanceof Uint8Array) || nonce.length !== NONCE_BYTES) {
33
+ throw WorkspaceRef.#invalid('Workspace nonce must contain exactly 16 bytes', {
34
+ nonceLength: nonce?.length,
35
+ });
36
+ }
37
+ const epoch = String(created.getTime().toString(36));
38
+ const nonceHex = [...nonce]
39
+ .map((byte) => byte.toString(16).padStart(2, '0'))
40
+ .join('');
41
+ const id = `v1-${epoch}-${nonceHex}`;
42
+ return new WorkspaceRef(
43
+ `${WORKSPACE_REF_PREFIX}${WorkspaceRef.#encodeNamespace(namespace)}/${id}`,
44
+ );
45
+ }
46
+
47
+ static prefixForNamespace(value) {
48
+ const namespace = CollectionNamespace.from(value).toString();
49
+ return `${WORKSPACE_REF_PREFIX}${WorkspaceRef.#encodeNamespace(namespace)}/`;
50
+ }
51
+
52
+ get namespace() {
53
+ return this.#namespace;
54
+ }
55
+
56
+ get id() {
57
+ return this.#id;
58
+ }
59
+
60
+ get createdAt() {
61
+ return this.#createdAt;
62
+ }
63
+
64
+ toString() {
65
+ return this.#value;
66
+ }
67
+
68
+ static #parse(value) {
69
+ const [encodedNamespace, id] = WorkspaceRef.#split(value);
70
+ const namespace = WorkspaceRef.#decodeNamespace(encodedNamespace, value);
71
+ const createdAt = WorkspaceRef.#createdAtFromId(id, value);
72
+ return { namespace, id, createdAt, value };
73
+ }
74
+
75
+ static #split(value) {
76
+ if (typeof value !== 'string' || !value.startsWith(WORKSPACE_REF_PREFIX)) {
77
+ throw WorkspaceRef.#invalid(`Workspace ref must be below ${WORKSPACE_REF_PREFIX}`, {
78
+ ref: value,
79
+ });
80
+ }
81
+ const fields = value.slice(WORKSPACE_REF_PREFIX.length).split('/');
82
+ if (fields.length !== 2 || fields.some((field) => field.length === 0)) {
83
+ throw WorkspaceRef.#invalid('Workspace ref must contain one encoded namespace and ID', {
84
+ ref: value,
85
+ });
86
+ }
87
+ return fields;
88
+ }
89
+
90
+ static #decodeNamespace(encodedNamespace, value) {
91
+ if (encodedNamespace.includes('++')) {
92
+ throw WorkspaceRef.#invalid('Workspace ref contains a malformed encoded namespace', {
93
+ ref: value,
94
+ });
95
+ }
96
+ let namespace;
97
+ try {
98
+ namespace = CollectionNamespace.from(encodedNamespace.replaceAll('+', '/')).toString();
99
+ } catch (error) {
100
+ throw WorkspaceRef.#invalid('Workspace ref contains an invalid encoded namespace', {
101
+ ref: value,
102
+ originalError: error,
103
+ });
104
+ }
105
+ if (WorkspaceRef.#encodeNamespace(namespace) !== encodedNamespace) {
106
+ throw WorkspaceRef.#invalid('Workspace ref namespace is not canonical', { ref: value });
107
+ }
108
+ return namespace;
109
+ }
110
+
111
+ static #createdAtFromId(id, value) {
112
+ const idMatch = WORKSPACE_ID.exec(id);
113
+ if (!idMatch) {
114
+ throw WorkspaceRef.#invalid('Workspace ref contains an invalid workspace ID', { ref: value });
115
+ }
116
+ const epoch = Number.parseInt(idMatch[1], 36);
117
+ if (!Number.isSafeInteger(epoch) || epoch < 0 || epoch.toString(36) !== idMatch[1]) {
118
+ throw WorkspaceRef.#invalid('Workspace ref contains an invalid creation epoch', { ref: value });
119
+ }
120
+ const createdAt = new Date(epoch);
121
+ if (Number.isNaN(createdAt.getTime())) {
122
+ throw WorkspaceRef.#invalid('Workspace ref creation epoch is outside the Date range', {
123
+ ref: value,
124
+ });
125
+ }
126
+ return createdAt.toISOString();
127
+ }
128
+
129
+ static #canonicalTimestamp(value) {
130
+ if (typeof value !== 'string') {
131
+ throw WorkspaceRef.#invalid('Workspace creation time must be a canonical timestamp', {
132
+ createdAt: value,
133
+ });
134
+ }
135
+ const date = new Date(value);
136
+ if (Number.isNaN(date.getTime()) || date.toISOString() !== value) {
137
+ throw WorkspaceRef.#invalid('Workspace creation time must be a canonical timestamp', {
138
+ createdAt: value,
139
+ });
140
+ }
141
+ return date;
142
+ }
143
+
144
+ static #encodeNamespace(namespace) {
145
+ return namespace.replaceAll('/', '+');
146
+ }
147
+
148
+ static #invalid(message, meta) {
149
+ return createCasError(message, ErrorCodes.WORKSPACE_REF_INVALID, meta);
150
+ }
151
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Fixed-residency LRU for in-flight and completed immutable reads.
3
+ * Rejected promises remove themselves so transient failures remain retryable.
4
+ */
5
+ export default class BoundedPromiseCache {
6
+ /** @type {Map<string, { promise: Promise<unknown>, weight: number }>} */
7
+ #entries = new Map();
8
+ #maxEntries;
9
+ #maxWeight;
10
+ #totalWeight = 0;
11
+ #weightOf;
12
+
13
+ /**
14
+ * @param {number} maxEntries
15
+ * @param {object} [options]
16
+ * @param {number} [options.maxWeight=Infinity]
17
+ * @param {(value: unknown) => number} [options.weightOf]
18
+ */
19
+ constructor(maxEntries, { maxWeight = Number.POSITIVE_INFINITY, weightOf = () => 0 } = {}) {
20
+ if (!Number.isSafeInteger(maxEntries) || maxEntries < 1) {
21
+ throw new TypeError('maxEntries must be a positive safe integer');
22
+ }
23
+ if (
24
+ maxWeight !== Number.POSITIVE_INFINITY &&
25
+ (!Number.isSafeInteger(maxWeight) || maxWeight < 0)
26
+ ) {
27
+ throw new TypeError('maxWeight must be a non-negative safe integer or Infinity');
28
+ }
29
+ if (typeof weightOf !== 'function') {
30
+ throw new TypeError('weightOf must be a function');
31
+ }
32
+ this.#maxEntries = maxEntries;
33
+ this.#maxWeight = maxWeight;
34
+ this.#weightOf = weightOf;
35
+ }
36
+
37
+ /**
38
+ * @template T
39
+ * @param {string} key
40
+ * @param {() => Promise<T>|T} factory
41
+ * @returns {Promise<T>}
42
+ */
43
+ getOrCreate(key, factory) {
44
+ const cached = this.#entries.get(key);
45
+ if (cached !== undefined) {
46
+ this.#entries.delete(key);
47
+ this.#entries.set(key, cached);
48
+ return cached.promise;
49
+ }
50
+
51
+ const source = Promise.resolve().then(factory);
52
+ const entry = { promise: source, weight: 0 };
53
+ const tracked = source.then(
54
+ (value) => {
55
+ if (this.#entries.get(key) === entry) {
56
+ let weight;
57
+ try {
58
+ weight = this.#resolvedWeight(value);
59
+ } catch (error) {
60
+ this.#remove(key, entry);
61
+ throw error;
62
+ }
63
+ if (weight > this.#maxWeight) {
64
+ this.#remove(key, entry);
65
+ return value;
66
+ }
67
+ entry.weight = weight;
68
+ this.#totalWeight += entry.weight;
69
+ this.#evict();
70
+ }
71
+ return value;
72
+ },
73
+ (error) => {
74
+ if (this.#entries.get(key) === entry) {
75
+ this.#remove(key, entry);
76
+ }
77
+ throw error;
78
+ },
79
+ );
80
+ entry.promise = tracked;
81
+ this.#entries.set(key, entry);
82
+ this.#evict();
83
+ return tracked;
84
+ }
85
+
86
+ #resolvedWeight(value) {
87
+ const weight = this.#weightOf(value);
88
+ if (!Number.isSafeInteger(weight) || weight < 0) {
89
+ throw new TypeError('weightOf must return a non-negative safe integer');
90
+ }
91
+ return weight;
92
+ }
93
+
94
+ #evict() {
95
+ while (this.#entries.size > this.#maxEntries || this.#totalWeight > this.#maxWeight) {
96
+ const oldestKey = this.#entries.keys().next().value;
97
+ const oldest = this.#entries.get(oldestKey);
98
+ this.#remove(oldestKey, oldest);
99
+ }
100
+ }
101
+
102
+ #remove(key, entry) {
103
+ if (entry === undefined || !this.#entries.delete(key)) {
104
+ return;
105
+ }
106
+ this.#totalWeight -= entry.weight;
107
+ }
108
+ }
@@ -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 BoundedPromiseCache from '../../helpers/boundedPromiseCache.js';
7
8
 
8
9
  /**
9
10
  * Default resilience policy: 30 s timeout (no retry).
@@ -15,8 +16,10 @@ import { CasError, createCasError, ErrorCodes } from '../../domain/errors/index.
15
16
  */
16
17
  const DEFAULT_POLICY = Policy.timeout(30_000);
17
18
  export const DEFAULT_MAX_BLOB_SIZE = 10 * 1024 * 1024;
19
+ const DEFAULT_METADATA_CACHE_ENTRIES = 2_048;
18
20
  const MIN_READ_BLOB_LIMIT = 1;
19
21
  const MIN_MAX_BLOB_SIZE = 1024;
22
+ const MIN_METADATA_CACHE_ENTRIES = 1;
20
23
  const MAX_BLOB_SIZE_LIMIT = Number.MAX_SAFE_INTEGER;
21
24
  const OBJECT_INFO_ARGUMENT = '--batch-check=%(objectname) %(objecttype) %(objectsize)';
22
25
  const GIT_OBJECT_TYPES = new Set(['blob', 'tree', 'commit', 'tag']);
@@ -25,19 +28,25 @@ const GIT_OBJECT_TYPES = new Set(['blob', 'tree', 'commit', 'tag']);
25
28
  * {@link GitPersistencePort} implementation backed by `@git-stunts/plumbing`.
26
29
  *
27
30
  * All Git I/O is wrapped with a configurable resilience {@link Policy}
28
- * (30 s timeout by default).
31
+ * (30 s timeout by default). Successful metadata reads assume referenced roots
32
+ * remain retained while this adapter is in use; destructive external pruning
33
+ * must not race active operations.
29
34
  */
30
35
  export default class GitPersistenceAdapter extends GitPersistencePort {
31
36
  #maxBlobSize = DEFAULT_MAX_BLOB_SIZE;
37
+ #metadataCache;
32
38
  /**
33
39
  * @param {Object} options
34
40
  * @param {import('@git-stunts/plumbing').default} options.plumbing - GitPlumbing instance.
35
41
  * @param {import('@git-stunts/alfred').Policy} [options.policy] - Resilience policy (defaults to 30 s timeout, no retry).
42
+ * @param {number} [options.metadataCacheEntries=2048] - Maximum immutable metadata entries retained by this adapter.
36
43
  */
37
- constructor({ plumbing, policy }) {
44
+ constructor({ plumbing, policy, metadataCacheEntries = DEFAULT_METADATA_CACHE_ENTRIES }) {
38
45
  super();
46
+ GitPersistenceAdapter.#assertMetadataCacheEntries(metadataCacheEntries);
39
47
  this.plumbing = plumbing;
40
48
  this.policy = policy ?? DEFAULT_POLICY;
49
+ this.#metadataCache = new BoundedPromiseCache(metadataCacheEntries);
41
50
  }
42
51
 
43
52
  /**
@@ -145,12 +154,15 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
145
154
  * @returns {Promise<{ mode: string, type: string, oid: string, name: string }|null>}
146
155
  */
147
156
  async readTreeEntry(treeOid, treePath) {
148
- return this.policy.execute(async () => {
157
+ const key = `tree\0${treeOid}\0${treePath}`;
158
+ const entry = await this.#metadataCache.getOrCreate(key, () => this.policy.execute(async () => {
149
159
  const output = await this.plumbing.execute({
150
160
  args: ['ls-tree', '-z', treeOid, '--', treePath],
151
161
  });
152
- return GitPersistenceAdapter.#parseTreeOutput(output)[0] || null;
153
- });
162
+ const found = GitPersistenceAdapter.#parseTreeOutput(output)[0] || null;
163
+ return found === null ? null : Object.freeze(found);
164
+ }));
165
+ return entry === null ? null : { ...entry };
154
166
  }
155
167
 
156
168
  /**
@@ -209,32 +221,51 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
209
221
  * @returns {Promise<{ oid: string, type: string, size: number }>} Object metadata.
210
222
  */
211
223
  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
- }
224
+ return this.#metadataCache.getOrCreate(`object\0${oid}`, async () => {
225
+ const rawOutput = await this.policy.execute(() => this.plumbing.execute({
226
+ args: ['cat-file', OBJECT_INFO_ARGUMENT],
227
+ input: `${oid}\n`,
228
+ }));
229
+ const output = typeof rawOutput === 'string' ? rawOutput.trim() : '';
230
+ if (output === `${oid} missing`) {
231
+ throw new CasError(`Git object not found: ${oid}`, ErrorCodes.GIT_OBJECT_NOT_FOUND, {
232
+ oid,
233
+ });
234
+ }
222
235
 
223
- const fields = output.split(' ');
224
- const size = Number(fields[2]);
236
+ const fields = output.split(' ');
237
+ const size = Number(fields[2]);
238
+ if (
239
+ fields.length !== 3 ||
240
+ fields[0] !== oid ||
241
+ !GIT_OBJECT_TYPES.has(fields[1]) ||
242
+ !Number.isSafeInteger(size) ||
243
+ size < 0
244
+ ) {
245
+ throw new CasError(`Git object has invalid metadata: ${oid}`, ErrorCodes.GIT_ERROR, {
246
+ oid,
247
+ output: rawOutput,
248
+ });
249
+ }
250
+ return Object.freeze({ oid: fields[0], type: fields[1], size });
251
+ });
252
+ }
253
+
254
+ /**
255
+ * @param {number} metadataCacheEntries
256
+ */
257
+ static #assertMetadataCacheEntries(metadataCacheEntries) {
225
258
  if (
226
- fields.length !== 3 ||
227
- fields[0] !== oid ||
228
- !GIT_OBJECT_TYPES.has(fields[1]) ||
229
- !Number.isSafeInteger(size) ||
230
- size < 0
259
+ Number.isSafeInteger(metadataCacheEntries) &&
260
+ metadataCacheEntries >= MIN_METADATA_CACHE_ENTRIES
231
261
  ) {
232
- throw new CasError(`Git object has invalid metadata: ${oid}`, ErrorCodes.GIT_ERROR, {
233
- oid,
234
- output: rawOutput,
235
- });
262
+ return;
236
263
  }
237
- return Object.freeze({ oid: fields[0], type: fields[1], size });
264
+ throw createCasError(
265
+ 'Git metadata cache entries must be a positive safe integer',
266
+ ErrorCodes.INVALID_OPTIONS,
267
+ { option: 'metadataCacheEntries', metadataCacheEntries },
268
+ );
238
269
  }
239
270
 
240
271
  /**
@@ -15,6 +15,7 @@ import Oid from '../../domain/value-objects/Oid.js';
15
15
  const DEFAULT_POLICY = Policy.timeout(30_000);
16
16
  const FORBIDDEN_REF_CHARACTERS = new Set(['~', '^', ':', '?', '*', '[', '\\']);
17
17
  const MAX_REF_ITERATION_LIMIT = 1001;
18
+ const REF_NAME_ENCODER = new globalThis.TextEncoder();
18
19
 
19
20
  /**
20
21
  * {@link GitRefPort} implementation backed by `@git-stunts/plumbing`.
@@ -216,8 +217,9 @@ export default class GitRefAdapter extends GitRefPort {
216
217
  }
217
218
 
218
219
  /** @override */
219
- async *iterateRefs({ prefix = 'refs/', limit } = {}) {
220
+ async *iterateRefs({ prefix = 'refs/', after = null, limit } = {}) {
220
221
  assertRefPrefix(prefix);
222
+ assertRefCursor(prefix, after);
221
223
  assertRefIterationLimit(limit);
222
224
  if (typeof this.plumbing?.executeStream !== 'function') {
223
225
  throw new CasError(
@@ -226,19 +228,9 @@ export default class GitRefAdapter extends GitRefPort {
226
228
  { prefix },
227
229
  );
228
230
  }
229
- const stream = await this.policy.execute(() =>
230
- this.plumbing.executeStream({
231
- args: [
232
- 'for-each-ref',
233
- '--format=%(refname)%09%(objectname)%09%(symref)',
234
- `--count=${limit}`,
235
- prefix,
236
- ],
237
- }),
238
- );
239
- for await (const line of consumeRefLines(stream)) {
240
- yield parseIteratedRef(prefix, line);
241
- }
231
+ const args = refInventoryArgs({ prefix, after, limit });
232
+ const stream = await this.policy.execute(() => this.plumbing.executeStream({ args }));
233
+ yield* paginatedRefRecords({ stream, prefix, after, limit });
242
234
  }
243
235
 
244
236
  async #inspectDirectRef(ref) {
@@ -296,6 +288,16 @@ function assertRefName(ref) {
296
288
  assertRefSyntax(ref, { allowTrailingSlash: false });
297
289
  }
298
290
 
291
+ function assertRefCursor(prefix, after) {
292
+ if (after === null) {
293
+ return;
294
+ }
295
+ assertRefName(after);
296
+ if (!after.startsWith(prefix)) {
297
+ throw invalidRefName(after);
298
+ }
299
+ }
300
+
299
301
  function assertRefIterationLimit(limit) {
300
302
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_REF_ITERATION_LIMIT) {
301
303
  throw new CasError(
@@ -330,6 +332,46 @@ function isInvalidRefSegment(part) {
330
332
  return part.length === 0 || part.startsWith('.') || part.endsWith('.lock');
331
333
  }
332
334
 
335
+ function compareRefNames(left, right) {
336
+ const leftBytes = REF_NAME_ENCODER.encode(left);
337
+ const rightBytes = REF_NAME_ENCODER.encode(right);
338
+ const sharedLength = Math.min(leftBytes.length, rightBytes.length);
339
+ for (let index = 0; index < sharedLength; index += 1) {
340
+ if (leftBytes[index] !== rightBytes[index]) {
341
+ return leftBytes[index] - rightBytes[index];
342
+ }
343
+ }
344
+ return leftBytes.length - rightBytes.length;
345
+ }
346
+
347
+ function refInventoryArgs({ prefix, after, limit }) {
348
+ const args = [
349
+ 'for-each-ref',
350
+ '--format=%(refname)%09%(objectname)%09%(symref)',
351
+ '--sort=refname',
352
+ ];
353
+ if (after === null) {
354
+ args.push(`--count=${limit}`);
355
+ }
356
+ args.push(prefix);
357
+ return args;
358
+ }
359
+
360
+ async function* paginatedRefRecords({ stream, prefix, after, limit }) {
361
+ let returned = 0;
362
+ for await (const line of consumeRefLines(stream)) {
363
+ const record = parseIteratedRef(prefix, line);
364
+ if (after !== null && compareRefNames(record.ref, after) <= 0) {
365
+ continue;
366
+ }
367
+ yield record;
368
+ returned += 1;
369
+ if (after !== null && returned >= limit) {
370
+ return;
371
+ }
372
+ }
373
+ }
374
+
333
375
  function hasForbiddenRefCharacter(value) {
334
376
  return typeof value === 'string' && [...value].some((character) => {
335
377
  const code = character.codePointAt(0);
@@ -1 +1 @@
1
- export const PACKAGE_VERSION = '6.3.0';
1
+ export const PACKAGE_VERSION = '6.5.0';
@@ -86,6 +86,7 @@ export default class GitRefPort {
86
86
  * Streams refs below a canonical Git ref prefix.
87
87
  * @param {Object} _options
88
88
  * @param {string} [_options.prefix]
89
+ * @param {string|null} [_options.after] Exclusive ref-name continuation cursor.
89
90
  * @param {number} _options.limit Maximum records to request from Git.
90
91
  * @returns {AsyncIterable<{ref: string, oid: string, symref: string|null}>}
91
92
  */