@git-stunts/git-cas 6.5.1 → 6.5.3

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.
@@ -2,9 +2,12 @@ import { Policy } from '@git-stunts/alfred';
2
2
  import { mkdtemp, rm, writeFile } from 'node:fs/promises';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
+ import { GitObjectMissingError } from '@git-stunts/plumbing';
5
6
  import GitPersistencePort from '../../ports/GitPersistencePort.js';
6
7
  import { CasError, createCasError, ErrorCodes } from '../../domain/errors/index.js';
7
8
  import BoundedPromiseCache from '../../helpers/boundedPromiseCache.js';
9
+ import GitTreeObjectCodec from '../codecs/GitTreeObjectCodec.js';
10
+ import GitObjectSessionPool from './GitObjectSessionPool.js';
8
11
 
9
12
  /**
10
13
  * Default resilience policy: 30 s timeout (no retry).
@@ -17,6 +20,9 @@ import BoundedPromiseCache from '../../helpers/boundedPromiseCache.js';
17
20
  const DEFAULT_POLICY = Policy.timeout(30_000);
18
21
  export const DEFAULT_MAX_BLOB_SIZE = 10 * 1024 * 1024;
19
22
  const DEFAULT_METADATA_CACHE_ENTRIES = 2_048;
23
+ const DEFAULT_SESSION_IDLE_TIMEOUT_MS = 1_000;
24
+ const DEFAULT_TREE_CACHE_BYTES = 8 * 1024 * 1024;
25
+ const DEFAULT_TREE_CACHE_ENTRIES = 256;
20
26
  const MIN_READ_BLOB_LIMIT = 1;
21
27
  const MIN_MAX_BLOB_SIZE = 1024;
22
28
  const MIN_METADATA_CACHE_ENTRIES = 1;
@@ -33,20 +39,46 @@ const GIT_OBJECT_TYPES = new Set(['blob', 'tree', 'commit', 'tag']);
33
39
  * must not race active operations.
34
40
  */
35
41
  export default class GitPersistenceAdapter extends GitPersistencePort {
42
+ #activeOperations = new Set();
43
+ #activeStreams = new Set();
44
+ #closePromise = null;
45
+ #closed = false;
36
46
  #maxBlobSize = DEFAULT_MAX_BLOB_SIZE;
37
47
  #metadataCache;
48
+ #sessions;
49
+ #treeCache;
50
+ #treeReadMaxBytes;
38
51
  /**
39
52
  * @param {Object} options
40
53
  * @param {import('@git-stunts/plumbing').default} options.plumbing - GitPlumbing instance.
41
54
  * @param {import('@git-stunts/alfred').Policy} [options.policy] - Resilience policy (defaults to 30 s timeout, no retry).
42
55
  * @param {number} [options.metadataCacheEntries=2048] - Maximum immutable metadata entries retained by this adapter.
56
+ * @param {number} [options.sessionIdleTimeoutMs=1000] - Idle delay before a reusable Git process closes automatically.
57
+ * @param {number} [options.treeCacheEntries=256] - Maximum immutable parsed tree objects retained by this adapter.
58
+ * @param {number} [options.treeCacheBytes=8388608] - Maximum estimated parsed tree bytes retained by this adapter.
43
59
  */
44
- constructor({ plumbing, policy, metadataCacheEntries = DEFAULT_METADATA_CACHE_ENTRIES }) {
60
+ constructor({
61
+ plumbing,
62
+ policy,
63
+ metadataCacheEntries = DEFAULT_METADATA_CACHE_ENTRIES,
64
+ sessionIdleTimeoutMs = DEFAULT_SESSION_IDLE_TIMEOUT_MS,
65
+ treeCacheEntries = DEFAULT_TREE_CACHE_ENTRIES,
66
+ treeCacheBytes = DEFAULT_TREE_CACHE_BYTES,
67
+ }) {
45
68
  super();
46
69
  GitPersistenceAdapter.#assertMetadataCacheEntries(metadataCacheEntries);
70
+ GitPersistenceAdapter.#assertSessionIdleTimeout(sessionIdleTimeoutMs);
71
+ GitPersistenceAdapter.#assertTreeCacheEntries(treeCacheEntries);
72
+ GitPersistenceAdapter.#assertTreeCacheBytes(treeCacheBytes);
47
73
  this.plumbing = plumbing;
48
74
  this.policy = policy ?? DEFAULT_POLICY;
49
75
  this.#metadataCache = new BoundedPromiseCache(metadataCacheEntries);
76
+ this.#sessions = new GitObjectSessionPool({ plumbing, idleTimeoutMs: sessionIdleTimeoutMs });
77
+ this.#treeCache = new BoundedPromiseCache(treeCacheEntries, {
78
+ maxWeight: treeCacheBytes,
79
+ weightOf: (tree) => tree.weight,
80
+ });
81
+ this.#treeReadMaxBytes = Math.max(MIN_READ_BLOB_LIMIT, treeCacheBytes);
50
82
  }
51
83
 
52
84
  /**
@@ -55,14 +87,69 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
55
87
  * @returns {Promise<string>} The Git OID of the stored blob.
56
88
  */
57
89
  async writeBlob(content) {
58
- return this.policy.execute(() => (
90
+ return await this.#runOperation(() => this.#writeBlob(content));
91
+ }
92
+
93
+ async #writeBlob(content) {
94
+ const oid = await this.policy.execute(() =>
59
95
  typeof globalThis.Bun !== 'undefined'
60
96
  ? this.#writeBlobFromTempFile(content)
61
97
  : this.plumbing.execute({
62
- args: ['hash-object', '-w', '--stdin'],
63
- input: content,
64
- })
65
- ));
98
+ args: ['hash-object', '-w', '--stdin'],
99
+ input: content,
100
+ })
101
+ );
102
+ return oid;
103
+ }
104
+
105
+ /**
106
+ * Writes a bounded group through one scoped fast-import session when the
107
+ * injected plumbing supports it. The session closes before OIDs are exposed,
108
+ * so later pruning cannot poison duplicate writes in a reused process.
109
+ * @override
110
+ * @param {Iterable<Uint8Array|string>} contents
111
+ * @returns {Promise<string[]>}
112
+ */
113
+ async writeBlobs(contents) {
114
+ return await this.#runOperation(async () => {
115
+ const replayableContents = [...contents];
116
+ if (!this.#sessions.supports('fastImport')) {
117
+ const oids = [];
118
+ for (const content of replayableContents) {
119
+ oids.push(await this.#writeBlob(content));
120
+ }
121
+ return oids;
122
+ }
123
+ let result;
124
+ let operationFailed = false;
125
+ let operationError;
126
+ try {
127
+ const oids = await this.#sessions.writeBlobs(replayableContents, (operation) =>
128
+ this.policy.execute(operation)
129
+ );
130
+ // mktree's quick lookup cannot discover packs created after its ODB snapshot.
131
+ await this.#sessions.retire('mktree');
132
+ result = [...oids];
133
+ } catch (error) {
134
+ operationFailed = true;
135
+ operationError = error;
136
+ }
137
+ try {
138
+ await this.#sessions.retire('fastImport');
139
+ } catch (retirementError) {
140
+ if (operationFailed) {
141
+ throw new AggregateError(
142
+ [operationError, retirementError],
143
+ 'Bulk Git object write and session retirement both failed'
144
+ );
145
+ }
146
+ throw retirementError;
147
+ }
148
+ if (operationFailed) {
149
+ throw operationError;
150
+ }
151
+ return result;
152
+ });
66
153
  }
67
154
 
68
155
  /**
@@ -71,12 +158,22 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
71
158
  * @returns {Promise<string>} The Git OID of the created tree.
72
159
  */
73
160
  async writeTree(entries) {
74
- return this.policy.execute(() =>
75
- this.plumbing.execute({
76
- args: ['mktree'],
77
- input: `${entries.join('\n')}\n`,
78
- }),
79
- );
161
+ return await this.#runOperation(async () => {
162
+ if (this.#sessions.supports('mktree')) {
163
+ const structured = GitTreeObjectCodec.parseMktreeLines(entries);
164
+ const oid = await this.#sessions.writeTree(structured, (operation) =>
165
+ this.policy.execute(operation)
166
+ );
167
+ return oid;
168
+ }
169
+ const oid = await this.policy.execute(() =>
170
+ this.plumbing.execute({
171
+ args: ['mktree'],
172
+ input: `${entries.join('\n')}\n`,
173
+ })
174
+ );
175
+ return oid;
176
+ });
80
177
  }
81
178
 
82
179
  /**
@@ -86,23 +183,43 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
86
183
  * @returns {Promise<Buffer>} The blob content.
87
184
  */
88
185
  async readBlob(oid, maxBytes) {
89
- const limit = maxBytes === undefined
90
- ? this.#maxBlobSize
91
- : GitPersistenceAdapter.#validatedReadBlobLimit(maxBytes);
92
- const chunks = [];
93
- let bytesRead = 0;
94
- for await (const chunk of await this.readBlobStream(oid)) {
95
- bytesRead += chunk.length;
96
- if (bytesRead > limit) {
97
- throw new CasError(
98
- `Blob ${oid} exceeds safety limit of ${limit} bytes`,
99
- ErrorCodes.RESTORE_TOO_LARGE,
100
- { oid, maxBytes: limit },
101
- );
186
+ return await this.#runOperation(async () => {
187
+ const limit =
188
+ maxBytes === undefined
189
+ ? this.#maxBlobSize
190
+ : GitPersistenceAdapter.#validatedReadBlobLimit(maxBytes);
191
+ if (this.#sessions.supports('catFile')) {
192
+ let object;
193
+ try {
194
+ object = await this.#sessions.read(oid, { maxBytes: limit }, (operation) =>
195
+ this.policy.execute(operation)
196
+ );
197
+ } catch (error) {
198
+ throw this.#normalizeObjectReadError(error, oid, limit);
199
+ }
200
+ if (object.type !== 'blob') {
201
+ throw createCasError(`Git object is not a blob: ${oid}`, ErrorCodes.GIT_ERROR, {
202
+ oid,
203
+ actualType: object.type,
204
+ });
205
+ }
206
+ return GitPersistenceAdapter.#toBuffer(object.content);
102
207
  }
103
- chunks.push(chunk);
104
- }
105
- return Buffer.concat(chunks);
208
+ const chunks = [];
209
+ let bytesRead = 0;
210
+ for await (const chunk of await this.#openBufferStream(['cat-file', 'blob', oid])) {
211
+ bytesRead += chunk.length;
212
+ if (bytesRead > limit) {
213
+ throw new CasError(
214
+ `Blob ${oid} exceeds safety limit of ${limit} bytes`,
215
+ ErrorCodes.RESTORE_TOO_LARGE,
216
+ { oid, maxBytes: limit }
217
+ );
218
+ }
219
+ chunks.push(chunk);
220
+ }
221
+ return Buffer.concat(chunks);
222
+ });
106
223
  }
107
224
 
108
225
  /**
@@ -113,6 +230,7 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
113
230
  * @returns {void}
114
231
  */
115
232
  setMaxBlobSize(maxBlobSize) {
233
+ this.#assertOpen();
116
234
  GitPersistenceAdapter.#assertMaxBlobSize(maxBlobSize);
117
235
  this.#maxBlobSize = maxBlobSize;
118
236
  }
@@ -123,13 +241,7 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
123
241
  * @returns {Promise<AsyncIterable<Buffer>>} The blob content stream.
124
242
  */
125
243
  async readBlobStream(oid) {
126
- const stream = await this.policy.execute(async () => (
127
- await this.plumbing.executeStream({
128
- args: ['cat-file', 'blob', oid],
129
- })
130
- ));
131
-
132
- return this.#bufferStream(stream);
244
+ return await this.#runOperation(() => this.#openBufferStream(['cat-file', 'blob', oid]));
133
245
  }
134
246
 
135
247
  /**
@@ -138,6 +250,22 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
138
250
  * @returns {Promise<Array<{ mode: string, type: string, oid: string, name: string }>>}
139
251
  */
140
252
  async readTree(treeOid) {
253
+ return await this.#runOperation(async () => {
254
+ if (this.#sessions.supports('catFile')) {
255
+ try {
256
+ const tree = await this.#readTreeObject(treeOid);
257
+ return tree.entries.map((entry) => ({ ...entry }));
258
+ } catch (error) {
259
+ if (!GitPersistenceAdapter.#isObjectBufferLimit(error)) {
260
+ throw this.#normalizeTreeReadError(error, treeOid);
261
+ }
262
+ }
263
+ }
264
+ return await this.#readTreeWithCommand(treeOid);
265
+ });
266
+ }
267
+
268
+ async #readTreeWithCommand(treeOid) {
141
269
  return this.policy.execute(async () => {
142
270
  const output = await this.plumbing.execute({
143
271
  args: ['ls-tree', '-z', treeOid],
@@ -154,15 +282,35 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
154
282
  * @returns {Promise<{ mode: string, type: string, oid: string, name: string }|null>}
155
283
  */
156
284
  async readTreeEntry(treeOid, treePath) {
157
- const key = `tree\0${treeOid}\0${treePath}`;
158
- const entry = await this.#metadataCache.getOrCreate(key, () => this.policy.execute(async () => {
285
+ return await this.#runOperation(async () => {
286
+ const key = `tree\0${treeOid}\0${treePath}`;
287
+ const entry = await this.#metadataCache.getOrCreate(key, async () => {
288
+ let found;
289
+ if (this.#sessions.supports('catFile')) {
290
+ try {
291
+ found = await this.#readExactTreePath(treeOid, treePath);
292
+ } catch (error) {
293
+ if (!GitPersistenceAdapter.#isObjectBufferLimit(error)) {
294
+ throw this.#normalizeTreeReadError(error, treeOid);
295
+ }
296
+ found = await this.#readTreeEntryWithCommand(treeOid, treePath);
297
+ }
298
+ } else {
299
+ found = await this.#readTreeEntryWithCommand(treeOid, treePath);
300
+ }
301
+ return found === null ? null : Object.freeze(found);
302
+ });
303
+ return entry === null ? null : { ...entry };
304
+ });
305
+ }
306
+
307
+ async #readTreeEntryWithCommand(treeOid, treePath) {
308
+ return this.policy.execute(async () => {
159
309
  const output = await this.plumbing.execute({
160
310
  args: ['ls-tree', '-z', treeOid, '--', treePath],
161
311
  });
162
- const found = GitPersistenceAdapter.#parseTreeOutput(output)[0] || null;
163
- return found === null ? null : Object.freeze(found);
164
- }));
165
- return entry === null ? null : { ...entry };
312
+ return GitPersistenceAdapter.#parseTreeOutput(output)[0] || null;
313
+ });
166
314
  }
167
315
 
168
316
  /**
@@ -171,11 +319,9 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
171
319
  * @returns {AsyncIterable<{ mode: string, type: string, oid: string, name: string }>}
172
320
  */
173
321
  async *iterateTree(treeOid) {
174
- const stream = await this.policy.execute(async () => (
175
- await this.plumbing.executeStream({
176
- args: ['ls-tree', '-z', treeOid],
177
- })
178
- ));
322
+ const stream = await this.#runOperation(() =>
323
+ this.#openBufferStream(['ls-tree', '-z', treeOid])
324
+ );
179
325
  let pending = '';
180
326
  for await (const chunk of stream) {
181
327
  pending += GitPersistenceAdapter.#toBuffer(chunk).toString();
@@ -200,7 +346,7 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
200
346
  * @returns {Promise<string>} Git object type.
201
347
  */
202
348
  async readObjectType(oid) {
203
- return (await this.#readObjectInfo(oid)).type;
349
+ return await this.#runOperation(async () => (await this.#readObjectInfo(oid)).type);
204
350
  }
205
351
 
206
352
  /**
@@ -209,7 +355,7 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
209
355
  * @returns {Promise<number>} Git object size in bytes.
210
356
  */
211
357
  async readObjectSize(oid) {
212
- return (await this.#readObjectInfo(oid)).size;
358
+ return await this.#runOperation(async () => (await this.#readObjectInfo(oid)).size);
213
359
  }
214
360
 
215
361
  /**
@@ -222,10 +368,22 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
222
368
  */
223
369
  async #readObjectInfo(oid) {
224
370
  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
- }));
371
+ if (this.#sessions.supports('catFile')) {
372
+ try {
373
+ const info = await this.#sessions.info(oid, (operation) =>
374
+ this.policy.execute(operation)
375
+ );
376
+ return Object.freeze({ oid: info.oid, type: info.type, size: info.size });
377
+ } catch (error) {
378
+ throw this.#normalizeObjectReadError(error, oid, this.#maxBlobSize);
379
+ }
380
+ }
381
+ const rawOutput = await this.policy.execute(() =>
382
+ this.plumbing.execute({
383
+ args: ['cat-file', OBJECT_INFO_ARGUMENT],
384
+ input: `${oid}\n`,
385
+ })
386
+ );
229
387
  const output = typeof rawOutput === 'string' ? rawOutput.trim() : '';
230
388
  if (output === `${oid} missing`) {
231
389
  throw new CasError(`Git object not found: ${oid}`, ErrorCodes.GIT_OBJECT_NOT_FOUND, {
@@ -251,6 +409,152 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
251
409
  });
252
410
  }
253
411
 
412
+ async #readTreeObject(treeOid) {
413
+ return this.#treeCache.getOrCreate(treeOid, async () => {
414
+ const object = await this.#sessions.read(
415
+ treeOid,
416
+ { maxBytes: this.#treeReadMaxBytes },
417
+ (operation) => this.policy.execute(operation)
418
+ );
419
+ if (object.type !== 'tree') {
420
+ throw createCasError(`Git object is not a tree: ${treeOid}`, ErrorCodes.TREE_PARSE_ERROR, {
421
+ treeOid,
422
+ actualType: object.type,
423
+ });
424
+ }
425
+ try {
426
+ return GitTreeObjectCodec.decode(object.content, treeOid);
427
+ } catch (error) {
428
+ throw createCasError(
429
+ `Git tree object is malformed: ${treeOid}`,
430
+ ErrorCodes.TREE_PARSE_ERROR,
431
+ { treeOid, originalError: error }
432
+ );
433
+ }
434
+ });
435
+ }
436
+
437
+ async #readExactTreePath(treeOid, treePath) {
438
+ if (typeof treePath !== 'string' || treePath.length === 0) {
439
+ throw createCasError('Git tree path must be a non-empty string', ErrorCodes.INVALID_OPTIONS, {
440
+ treeOid,
441
+ treePath,
442
+ });
443
+ }
444
+ const components = treePath.split('/');
445
+ if (components.some((component) => component.length === 0)) {
446
+ throw createCasError(
447
+ 'Git tree path contains an empty component',
448
+ ErrorCodes.INVALID_OPTIONS,
449
+ {
450
+ treeOid,
451
+ treePath,
452
+ }
453
+ );
454
+ }
455
+
456
+ let currentOid = treeOid;
457
+ for (let index = 0; index < components.length; index += 1) {
458
+ const tree = await this.#readTreeObject(currentOid);
459
+ const entry = tree.entries.find((candidate) => candidate.name === components[index]) ?? null;
460
+ if (entry === null) {
461
+ return null;
462
+ }
463
+ if (index === components.length - 1) {
464
+ return { ...entry, name: treePath };
465
+ }
466
+ if (entry.type !== 'tree') {
467
+ return null;
468
+ }
469
+ currentOid = entry.oid;
470
+ }
471
+ return null;
472
+ }
473
+
474
+ #normalizeObjectReadError(error, oid, maxBytes) {
475
+ if (error instanceof GitObjectMissingError) {
476
+ return new CasError(`Git object not found: ${oid}`, ErrorCodes.GIT_OBJECT_NOT_FOUND, { oid });
477
+ }
478
+ if (GitPersistenceAdapter.#isObjectBufferLimit(error)) {
479
+ return new CasError(
480
+ `Blob ${oid} exceeds safety limit of ${maxBytes} bytes`,
481
+ ErrorCodes.RESTORE_TOO_LARGE,
482
+ { oid, maxBytes }
483
+ );
484
+ }
485
+ return error;
486
+ }
487
+
488
+ #normalizeTreeReadError(error, treeOid) {
489
+ if (error instanceof GitObjectMissingError) {
490
+ return new CasError(`Git object not found: ${treeOid}`, ErrorCodes.GIT_OBJECT_NOT_FOUND, {
491
+ oid: treeOid,
492
+ });
493
+ }
494
+ return error;
495
+ }
496
+
497
+ async close() {
498
+ if (this.#closePromise !== null) {
499
+ return await this.#closePromise;
500
+ }
501
+ this.#closed = true;
502
+ this.#closePromise = (async () => {
503
+ const failures = [];
504
+ const active = [...this.#activeOperations];
505
+ await Promise.allSettled(active);
506
+
507
+ const streams = [...this.#activeStreams];
508
+ const streamResults = await Promise.allSettled(
509
+ streams.map((stream) => GitPersistenceAdapter.#closeStream(stream))
510
+ );
511
+ this.#activeStreams.clear();
512
+ failures.push(
513
+ ...streamResults
514
+ .filter((result) => result.status === 'rejected')
515
+ .map((result) => result.reason)
516
+ );
517
+
518
+ try {
519
+ await this.#sessions.close();
520
+ } catch (error) {
521
+ failures.push(error);
522
+ } finally {
523
+ this.#metadataCache = null;
524
+ this.#treeCache = null;
525
+ }
526
+ if (failures.length > 0) {
527
+ throw new AggregateError(failures, 'Git persistence adapter failed to close cleanly');
528
+ }
529
+ })();
530
+ return await this.#closePromise;
531
+ }
532
+
533
+ async [Symbol.asyncDispose]() {
534
+ await this.close();
535
+ }
536
+
537
+ #assertOpen() {
538
+ if (this.#closed) {
539
+ throw createCasError('Git persistence adapter is closed', ErrorCodes.RESOURCE_CLOSED);
540
+ }
541
+ }
542
+
543
+ #runOperation(operation) {
544
+ this.#assertOpen();
545
+ const promise = Promise.resolve().then(operation);
546
+ this.#activeOperations.add(promise);
547
+ void promise.then(
548
+ () => this.#activeOperations.delete(promise),
549
+ () => this.#activeOperations.delete(promise)
550
+ );
551
+ return promise;
552
+ }
553
+
554
+ static #isObjectBufferLimit(error) {
555
+ return error?.details?.code === 'OBJECT_BUFFER_LIMIT_EXCEEDED';
556
+ }
557
+
254
558
  /**
255
559
  * @param {number} metadataCacheEntries
256
560
  */
@@ -264,7 +568,40 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
264
568
  throw createCasError(
265
569
  'Git metadata cache entries must be a positive safe integer',
266
570
  ErrorCodes.INVALID_OPTIONS,
267
- { option: 'metadataCacheEntries', metadataCacheEntries },
571
+ { option: 'metadataCacheEntries', metadataCacheEntries }
572
+ );
573
+ }
574
+
575
+ static #assertTreeCacheEntries(treeCacheEntries) {
576
+ if (Number.isSafeInteger(treeCacheEntries) && treeCacheEntries >= 1) {
577
+ return;
578
+ }
579
+ throw createCasError(
580
+ 'Git tree cache entries must be a positive safe integer',
581
+ ErrorCodes.INVALID_OPTIONS,
582
+ { option: 'treeCacheEntries', treeCacheEntries }
583
+ );
584
+ }
585
+
586
+ static #assertSessionIdleTimeout(sessionIdleTimeoutMs) {
587
+ if (Number.isSafeInteger(sessionIdleTimeoutMs) && sessionIdleTimeoutMs >= 1) {
588
+ return;
589
+ }
590
+ throw createCasError(
591
+ 'Git session idle timeout must be a positive safe integer',
592
+ ErrorCodes.INVALID_OPTIONS,
593
+ { option: 'sessionIdleTimeoutMs', sessionIdleTimeoutMs }
594
+ );
595
+ }
596
+
597
+ static #assertTreeCacheBytes(treeCacheBytes) {
598
+ if (Number.isSafeInteger(treeCacheBytes) && treeCacheBytes >= 0) {
599
+ return;
600
+ }
601
+ throw createCasError(
602
+ 'Git tree cache bytes must be a non-negative safe integer',
603
+ ErrorCodes.INVALID_OPTIONS,
604
+ { option: 'treeCacheBytes', treeCacheBytes }
268
605
  );
269
606
  }
270
607
 
@@ -297,8 +634,44 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
297
634
  * @returns {AsyncIterable<Buffer>}
298
635
  */
299
636
  async *#bufferStream(stream) {
300
- for await (const chunk of stream) {
301
- yield GitPersistenceAdapter.#toBuffer(chunk);
637
+ try {
638
+ for await (const chunk of stream) {
639
+ yield GitPersistenceAdapter.#toBuffer(chunk);
640
+ }
641
+ } finally {
642
+ try {
643
+ await GitPersistenceAdapter.#closeStream(stream);
644
+ } finally {
645
+ this.#activeStreams.delete(stream);
646
+ }
647
+ }
648
+ }
649
+
650
+ async #openBufferStream(args) {
651
+ const stream = await this.policy.execute(
652
+ async () => await this.plumbing.executeStream({ args })
653
+ );
654
+ this.#activeStreams.add(stream);
655
+ return this.#bufferStream(stream);
656
+ }
657
+
658
+ static async #closeStream(stream) {
659
+ const operations = [];
660
+ if (typeof stream.destroy === 'function') {
661
+ operations.push(Promise.resolve().then(() => stream.destroy()));
662
+ }
663
+ if (stream.finished !== undefined) {
664
+ operations.push(Promise.resolve(stream.finished));
665
+ }
666
+ const results = await Promise.allSettled(operations);
667
+ const failures = results
668
+ .filter((result) => result.status === 'rejected')
669
+ .map((result) => result.reason);
670
+ if (failures.length === 1) {
671
+ throw failures[0];
672
+ }
673
+ if (failures.length > 1) {
674
+ throw new AggregateError(failures, 'Git output stream failed to terminate cleanly');
302
675
  }
303
676
  }
304
677
 
@@ -321,7 +694,11 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
321
694
  * @returns {number}
322
695
  */
323
696
  static #validatedReadBlobLimit(maxBytes) {
324
- if (!Number.isSafeInteger(maxBytes) || maxBytes < MIN_READ_BLOB_LIMIT || maxBytes > MAX_BLOB_SIZE_LIMIT) {
697
+ if (
698
+ !Number.isSafeInteger(maxBytes) ||
699
+ maxBytes < MIN_READ_BLOB_LIMIT ||
700
+ maxBytes > MAX_BLOB_SIZE_LIMIT
701
+ ) {
325
702
  throw createCasError(
326
703
  `maxBytes must be an integer in [${MIN_READ_BLOB_LIMIT}, ${MAX_BLOB_SIZE_LIMIT}]`,
327
704
  ErrorCodes.INVALID_OPTIONS,
@@ -330,7 +707,7 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
330
707
  value: maxBytes,
331
708
  min: MIN_READ_BLOB_LIMIT,
332
709
  max: MAX_BLOB_SIZE_LIMIT,
333
- },
710
+ }
334
711
  );
335
712
  }
336
713
  return maxBytes;
@@ -341,7 +718,11 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
341
718
  * @returns {void}
342
719
  */
343
720
  static #assertMaxBlobSize(maxBlobSize) {
344
- if (!Number.isInteger(maxBlobSize) || maxBlobSize < MIN_MAX_BLOB_SIZE || maxBlobSize > MAX_BLOB_SIZE_LIMIT) {
721
+ if (
722
+ !Number.isInteger(maxBlobSize) ||
723
+ maxBlobSize < MIN_MAX_BLOB_SIZE ||
724
+ maxBlobSize > MAX_BLOB_SIZE_LIMIT
725
+ ) {
345
726
  throw createCasError(
346
727
  `maxBlobSize must be an integer in [${MIN_MAX_BLOB_SIZE}, ${MAX_BLOB_SIZE_LIMIT}]`,
347
728
  ErrorCodes.INVALID_OPTIONS,
@@ -350,7 +731,7 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
350
731
  value: maxBlobSize,
351
732
  min: MIN_MAX_BLOB_SIZE,
352
733
  max: MAX_BLOB_SIZE_LIMIT,
353
- },
734
+ }
354
735
  );
355
736
  }
356
737
  }
@@ -376,19 +757,15 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
376
757
  static #parseTreeEntry(entry) {
377
758
  const tabIndex = entry.indexOf('\t');
378
759
  if (tabIndex === -1) {
379
- throw new CasError(
380
- `Malformed ls-tree entry: ${entry}`,
381
- ErrorCodes.TREE_PARSE_ERROR,
382
- { rawEntry: entry },
383
- );
760
+ throw new CasError(`Malformed ls-tree entry: ${entry}`, ErrorCodes.TREE_PARSE_ERROR, {
761
+ rawEntry: entry,
762
+ });
384
763
  }
385
764
  const meta = entry.slice(0, tabIndex).split(' ');
386
765
  if (meta.length !== 3) {
387
- throw new CasError(
388
- `Malformed ls-tree entry: ${entry}`,
389
- ErrorCodes.TREE_PARSE_ERROR,
390
- { rawEntry: entry },
391
- );
766
+ throw new CasError(`Malformed ls-tree entry: ${entry}`, ErrorCodes.TREE_PARSE_ERROR, {
767
+ rawEntry: entry,
768
+ });
392
769
  }
393
770
  return {
394
771
  mode: meta[0],