@git-stunts/git-cas 6.5.7 → 6.5.8

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 (32) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/GUIDE.md +29 -0
  3. package/README.md +11 -7
  4. package/UPGRADING.md +29 -0
  5. package/build-info.json +2 -2
  6. package/docs/API.md +66 -12
  7. package/docs/releases/v6.5.8.md +89 -0
  8. package/index.d.ts +50 -0
  9. package/index.js +15 -1
  10. package/package.json +3 -2
  11. package/src/domain/services/AssetService.js +201 -10
  12. package/src/domain/services/BoundedWriteWavePersistence.js +235 -0
  13. package/src/domain/services/BundleBatchPlanner.js +349 -0
  14. package/src/domain/services/BundleService.js +225 -2
  15. package/src/domain/services/CasService.d.ts +16 -0
  16. package/src/domain/services/CasService.js +9 -18
  17. package/src/domain/services/ManifestRepository.js +129 -50
  18. package/src/domain/services/ManifestTreeService.js +47 -0
  19. package/src/domain/services/PageService.js +26 -9
  20. package/src/domain/services/RootSet.js +32 -0
  21. package/src/domain/services/RootSetPersistence.js +58 -1
  22. package/src/domain/services/StagedTarget.js +19 -0
  23. package/src/domain/services/StagingWorkspace.js +21 -7
  24. package/src/domain/services/forkCasPersistence.js +20 -0
  25. package/src/infrastructure/adapters/GitObjectSessionPool.js +47 -5
  26. package/src/infrastructure/adapters/GitPersistenceAdapter.js +169 -0
  27. package/src/infrastructure/adapters/GitPersistenceWriteScope.js +154 -0
  28. package/src/infrastructure/adapters/GitRefAdapter.js +38 -3
  29. package/src/infrastructure/adapters/GitUpdateRefSessionPool.js +115 -0
  30. package/src/package-version.js +1 -1
  31. package/src/ports/GitPersistencePort.js +43 -0
  32. package/src/ports/GitRefPort.js +8 -0
@@ -44,6 +44,23 @@ export default class GitObjectSessionPool {
44
44
  );
45
45
  }
46
46
 
47
+ async infoMany(objectNames, execute = EXECUTE_DIRECTLY) {
48
+ return await this.#run(
49
+ 'catFile',
50
+ (session) => execute(async () => {
51
+ if (typeof session.infoMany === 'function') {
52
+ return await session.infoMany(objectNames);
53
+ }
54
+ const infos = [];
55
+ for (const objectName of objectNames) {
56
+ infos.push(await session.info(objectName));
57
+ }
58
+ return Object.freeze(infos);
59
+ }),
60
+ isRecoverableCatError
61
+ );
62
+ }
63
+
47
64
  async read(objectName, options, execute = EXECUTE_DIRECTLY) {
48
65
  return await this.#run(
49
66
  'catFile',
@@ -55,10 +72,9 @@ export default class GitObjectSessionPool {
55
72
  async writeBlobs(contents, execute = EXECUTE_DIRECTLY) {
56
73
  return await this.#run('fastImport', (session) =>
57
74
  execute(async () => {
58
- const oids = [];
59
- for (const content of contents) {
60
- oids.push(await session.writeBlob(content));
61
- }
75
+ const oids = typeof session.writeBlobs === 'function'
76
+ ? await session.writeBlobs(contents)
77
+ : await GitObjectSessionPool.#writeBlobsIndividually(session, contents);
62
78
  await session.checkpoint();
63
79
  return Object.freeze(oids);
64
80
  })
@@ -69,6 +85,19 @@ export default class GitObjectSessionPool {
69
85
  return await this.#run('mktree', (session) => execute(() => session.write(entries)));
70
86
  }
71
87
 
88
+ async writeTrees(trees, execute = EXECUTE_DIRECTLY) {
89
+ return await this.#run('mktree', (session) => execute(async () => {
90
+ if (typeof session.writeMany === 'function') {
91
+ return await session.writeMany(trees);
92
+ }
93
+ const oids = [];
94
+ for (const entries of trees) {
95
+ oids.push(await session.write(entries));
96
+ }
97
+ return Object.freeze(oids);
98
+ }));
99
+ }
100
+
72
101
  async invalidate(protocol, expectedSession) {
73
102
  this.#cancelIdle(protocol);
74
103
  const opening = this.#sessions.get(protocol);
@@ -266,8 +295,21 @@ export default class GitObjectSessionPool {
266
295
  }
267
296
  }
268
297
 
298
+ static async #writeBlobsIndividually(session, contents) {
299
+ const oids = [];
300
+ for (const content of contents) {
301
+ oids.push(await session.writeBlob(content));
302
+ }
303
+ return oids;
304
+ }
305
+
269
306
  #scheduleIdle(protocol) {
270
- if (this.#closed || this.#active.has(protocol) || !this.#sessions.has(protocol)) {
307
+ if (
308
+ this.#idleTimeoutMs === null ||
309
+ this.#closed ||
310
+ this.#active.has(protocol) ||
311
+ !this.#sessions.has(protocol)
312
+ ) {
271
313
  return;
272
314
  }
273
315
  const opening = this.#sessions.get(protocol);
@@ -8,6 +8,7 @@ import { CasError, createCasError, ErrorCodes } from '../../domain/errors/index.
8
8
  import BoundedPromiseCache from '../../helpers/boundedPromiseCache.js';
9
9
  import GitTreeObjectCodec from '../codecs/GitTreeObjectCodec.js';
10
10
  import GitObjectSessionPool from './GitObjectSessionPool.js';
11
+ import GitPersistenceWriteScope from './GitPersistenceWriteScope.js';
11
12
 
12
13
  /**
13
14
  * Default resilience policy: 30 s timeout (no retry).
@@ -114,6 +115,9 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
114
115
  async writeBlobs(contents) {
115
116
  return await this.#runOperation(async () => {
116
117
  const replayableContents = [...contents];
118
+ if (replayableContents.length === 0) {
119
+ return [];
120
+ }
117
121
  if (!this.#sessions.supports('fastImport')) {
118
122
  const oids = [];
119
123
  for (const content of replayableContents) {
@@ -153,6 +157,25 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
153
157
  });
154
158
  }
155
159
 
160
+ /** Runs one bounded operation with an operation-owned fast-import process. */
161
+ async withWriteScope(operation) {
162
+ if (typeof operation !== 'function') {
163
+ throw createCasError(
164
+ 'Git persistence write scope requires an operation callback',
165
+ ErrorCodes.INVALID_OPTIONS,
166
+ );
167
+ }
168
+ return await this.#runOperation(async () => {
169
+ const scope = new GitPersistenceWriteScope({
170
+ adapter: this,
171
+ plumbing: this.plumbing,
172
+ execute: (attempt) => this.policy.execute(attempt),
173
+ retireMktree: () => this.#sessions.retire('mktree'),
174
+ });
175
+ return await scope.run(operation);
176
+ });
177
+ }
178
+
156
179
  /**
157
180
  * @override
158
181
  * @param {string[]} entries - Lines in `git mktree` format.
@@ -177,6 +200,40 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
177
200
  });
178
201
  }
179
202
 
203
+ /**
204
+ * Writes a bounded group of independent trees through one mktree session.
205
+ * @override
206
+ * @param {Iterable<string[]>} trees - Groups of lines in `git mktree` format.
207
+ * @returns {Promise<string[]>} Git OIDs in input order.
208
+ */
209
+ async writeTrees(trees) {
210
+ return await this.#runOperation(async () => {
211
+ const replayableTrees = [...trees];
212
+ if (replayableTrees.length === 0) {
213
+ return [];
214
+ }
215
+ if (this.#sessions.supports('mktree')) {
216
+ const structured = replayableTrees.map((entries) =>
217
+ GitTreeObjectCodec.parseMktreeLines(entries)
218
+ );
219
+ const oids = await this.#sessions.writeTrees(structured, (operation) =>
220
+ this.policy.execute(operation)
221
+ );
222
+ return [...oids];
223
+ }
224
+ const oids = [];
225
+ for (const entries of replayableTrees) {
226
+ oids.push(await this.policy.execute(() =>
227
+ this.plumbing.execute({
228
+ args: ['mktree'],
229
+ input: `${entries.join('\n')}\n`,
230
+ })
231
+ ));
232
+ }
233
+ return oids;
234
+ });
235
+ }
236
+
180
237
  /**
181
238
  * @override
182
239
  * @param {string} oid - Git object ID.
@@ -386,6 +443,88 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
386
443
  return await this.#runOperation(async () => (await this.#readObjectInfo(oid)).size);
387
444
  }
388
445
 
446
+ /**
447
+ * @override
448
+ * @param {Iterable<string>} oids - Git object IDs.
449
+ * @returns {Promise<Array<{oid: string, type: string, size: number}>>}
450
+ */
451
+ async readObjectInfos(oids) {
452
+ return await this.#runOperation(async () => {
453
+ const objectNames = [...oids];
454
+ if (objectNames.length === 0) {
455
+ return [];
456
+ }
457
+ const pending = new Array(objectNames.length);
458
+ const missing = [];
459
+ const missingSet = new Set();
460
+ for (let index = 0; index < objectNames.length; index += 1) {
461
+ const oid = objectNames[index];
462
+ const cached = this.#metadataCache.get(`object\0${oid}`);
463
+ if (cached !== undefined) {
464
+ pending[index] = cached;
465
+ } else if (!missingSet.has(oid)) {
466
+ missingSet.add(oid);
467
+ missing.push(oid);
468
+ }
469
+ }
470
+ const byOid = this.#cacheObjectInfoBatch(missing);
471
+ for (let index = 0; index < objectNames.length; index += 1) {
472
+ pending[index] ??= byOid.get(objectNames[index]);
473
+ }
474
+ return await Promise.all(pending);
475
+ });
476
+ }
477
+
478
+ #cacheObjectInfoBatch(objectNames) {
479
+ const byOid = new Map();
480
+ if (objectNames.length === 0) {
481
+ return byOid;
482
+ }
483
+ const batch = this.#readObjectInfosUncached(objectNames);
484
+ for (let index = 0; index < objectNames.length; index += 1) {
485
+ const oid = objectNames[index];
486
+ byOid.set(
487
+ oid,
488
+ this.#metadataCache.getOrCreate(`object\0${oid}`, async () => (await batch)[index])
489
+ );
490
+ }
491
+ return byOid;
492
+ }
493
+
494
+ async #readObjectInfosUncached(objectNames) {
495
+ let infos;
496
+ try {
497
+ infos = this.#sessions.supports('catFile')
498
+ ? await this.#sessions.infoMany(objectNames, (operation) => this.policy.execute(operation))
499
+ : await this.#readObjectInfosWithCommand(objectNames);
500
+ } catch (error) {
501
+ const oid = error?.details?.objectName ?? objectNames[0];
502
+ throw this.#normalizeObjectReadError(error, oid, this.#maxBlobSize);
503
+ }
504
+ if (infos.length !== objectNames.length) {
505
+ throw new CasError('Git metadata batch returned an invalid result count', ErrorCodes.GIT_ERROR, {
506
+ expectedCount: objectNames.length,
507
+ actualCount: infos.length,
508
+ });
509
+ }
510
+ return Object.freeze(infos.map((info, index) =>
511
+ GitPersistenceAdapter.#validatedObjectInfo(info, objectNames[index])
512
+ ));
513
+ }
514
+
515
+ async #readObjectInfosWithCommand(objectNames) {
516
+ const rawOutput = await this.policy.execute(() =>
517
+ this.plumbing.execute({
518
+ args: ['cat-file', OBJECT_INFO_ARGUMENT],
519
+ input: `${objectNames.join('\n')}\n`,
520
+ })
521
+ );
522
+ const lines = typeof rawOutput === 'string' ? rawOutput.trimEnd().split(/\r?\n/u) : [];
523
+ return lines.map((line, index) =>
524
+ GitPersistenceAdapter.#parseObjectInfo(line, objectNames[index])
525
+ );
526
+ }
527
+
389
528
  /**
390
529
  * Reads object metadata through Git's structured batch protocol. Missing
391
530
  * objects are reported on stdout with exit zero, avoiding runtime-specific
@@ -437,6 +576,36 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
437
576
  });
438
577
  }
439
578
 
579
+ static #parseObjectInfo(output, oid) {
580
+ if (output === `${oid} missing`) {
581
+ throw new CasError(`Git object not found: ${oid}`, ErrorCodes.GIT_OBJECT_NOT_FOUND, { oid });
582
+ }
583
+ const fields = output.split(' ');
584
+ return GitPersistenceAdapter.#validatedObjectInfo(
585
+ { oid: fields[0], type: fields[1], size: Number(fields[2]) },
586
+ oid,
587
+ output
588
+ );
589
+ }
590
+
591
+ static #validatedObjectInfo(info, requestedOid, output = info) {
592
+ if (
593
+ typeof info !== 'object' ||
594
+ info === null ||
595
+ info.oid !== requestedOid ||
596
+ !GIT_OBJECT_TYPES.has(info.type) ||
597
+ !Number.isSafeInteger(info.size) ||
598
+ info.size < 0
599
+ ) {
600
+ throw new CasError(
601
+ `Git object has invalid metadata: ${requestedOid}`,
602
+ ErrorCodes.GIT_ERROR,
603
+ { oid: requestedOid, output }
604
+ );
605
+ }
606
+ return Object.freeze({ oid: info.oid, type: info.type, size: info.size });
607
+ }
608
+
440
609
  async #readTreeObject(treeOid) {
441
610
  return this.#treeCache.getOrCreate(treeOid, async () => {
442
611
  const object = await this.#sessions.read(
@@ -0,0 +1,154 @@
1
+ import GitPersistencePort from '../../ports/GitPersistencePort.js';
2
+ import GitObjectSessionPool from './GitObjectSessionPool.js';
3
+
4
+ const EXECUTE_DIRECTLY = (operation) => operation();
5
+ const MAX_FAST_IMPORT_BLOB_BYTES = 64 * 1024 * 1024;
6
+ const UTF8_ENCODER = new globalThis.TextEncoder();
7
+
8
+ /** Operation-owned persistence view with one scoped fast-import process. */
9
+ export default class GitPersistenceWriteScope extends GitPersistencePort {
10
+ #adapter;
11
+ #execute;
12
+ #retireMktree;
13
+ #sessions;
14
+
15
+ constructor({ adapter, plumbing, execute = EXECUTE_DIRECTLY, retireMktree }) {
16
+ super();
17
+ this.#adapter = adapter;
18
+ this.#execute = execute;
19
+ this.#retireMktree = retireMktree;
20
+ this.#sessions = new GitObjectSessionPool({ plumbing, idleTimeoutMs: null });
21
+ }
22
+
23
+ async run(operation) {
24
+ let result;
25
+ let operationError;
26
+ let operationFailed = false;
27
+ try {
28
+ result = await operation(this);
29
+ } catch (error) {
30
+ operationFailed = true;
31
+ operationError = error;
32
+ }
33
+ let closeError;
34
+ let closeFailed = false;
35
+ try {
36
+ await this.#sessions.close();
37
+ } catch (error) {
38
+ closeFailed = true;
39
+ closeError = error;
40
+ }
41
+ if (operationFailed && closeFailed) {
42
+ throw new AggregateError(
43
+ [operationError, closeError],
44
+ 'Scoped Git write and session close both failed',
45
+ );
46
+ }
47
+ if (operationFailed) {
48
+ throw operationError;
49
+ }
50
+ if (closeFailed) {
51
+ throw closeError;
52
+ }
53
+ return result;
54
+ }
55
+
56
+ async writeBlob(content) {
57
+ if (
58
+ !this.#sessions.supports('fastImport') ||
59
+ contentBytes(content) > MAX_FAST_IMPORT_BLOB_BYTES
60
+ ) {
61
+ return await this.#adapter.writeBlob(content);
62
+ }
63
+ return (await this.writeBlobs([content]))[0];
64
+ }
65
+
66
+ async writeBlobs(contents) {
67
+ const replayable = [...contents];
68
+ if (replayable.length === 0) {
69
+ return [];
70
+ }
71
+ if (!this.#sessions.supports('fastImport')) {
72
+ return await this.#adapter.writeBlobs(replayable);
73
+ }
74
+ const { eligible, oversized } = partitionFastImportBlobs(replayable);
75
+ const results = new Array(replayable.length);
76
+ if (eligible.length > 0) {
77
+ const oids = await this.#sessions.writeBlobs(
78
+ eligible.map(({ content }) => content),
79
+ this.#execute,
80
+ );
81
+ eligible.forEach(({ index }, offset) => { results[index] = oids[offset]; });
82
+ await this.#retireMktree();
83
+ }
84
+ for (const { content, index } of oversized) {
85
+ results[index] = await this.#adapter.writeBlob(content);
86
+ }
87
+ return results;
88
+ }
89
+
90
+ async writeTree(entries) {
91
+ return await this.#adapter.writeTree(entries);
92
+ }
93
+
94
+ async writeTrees(trees) {
95
+ return await this.#adapter.writeTrees(trees);
96
+ }
97
+
98
+ async readBlob(oid, maxBytes) {
99
+ return await this.#adapter.readBlob(oid, maxBytes);
100
+ }
101
+
102
+ async readBlobStream(oid) {
103
+ return await this.#adapter.readBlobStream(oid);
104
+ }
105
+
106
+ async readTree(oid) {
107
+ return await this.#adapter.readTree(oid);
108
+ }
109
+
110
+ async readTreeEntry(oid, treePath) {
111
+ return await this.#adapter.readTreeEntry(oid, treePath);
112
+ }
113
+
114
+ async *iterateTree(oid) {
115
+ yield* this.#adapter.iterateTree(oid);
116
+ }
117
+
118
+ async readObjectType(oid) {
119
+ return await this.#adapter.readObjectType(oid);
120
+ }
121
+
122
+ async readObjectSize(oid) {
123
+ return await this.#adapter.readObjectSize(oid);
124
+ }
125
+
126
+ async readObjectInfos(oids) {
127
+ return await this.#adapter.readObjectInfos(oids);
128
+ }
129
+
130
+ setMaxBlobSize(maxBlobSize) {
131
+ this.#adapter.setMaxBlobSize(maxBlobSize);
132
+ }
133
+ }
134
+
135
+ function contentBytes(content) {
136
+ if (content instanceof Uint8Array) {
137
+ return content.byteLength;
138
+ }
139
+ return typeof content === 'string'
140
+ ? UTF8_ENCODER.encode(content).byteLength
141
+ : Number.MAX_SAFE_INTEGER;
142
+ }
143
+
144
+ function partitionFastImportBlobs(contents) {
145
+ const eligible = [];
146
+ const oversized = [];
147
+ contents.forEach((content, index) => {
148
+ const target = contentBytes(content) > MAX_FAST_IMPORT_BLOB_BYTES
149
+ ? oversized
150
+ : eligible;
151
+ target.push({ content, index });
152
+ });
153
+ return { eligible, oversized };
154
+ }
@@ -3,6 +3,7 @@ import GitRefPort from '../../ports/GitRefPort.js';
3
3
  import { CasError, ErrorCodes } from '../../domain/errors/index.js';
4
4
  import { isGitMissingRefError } from '../../domain/helpers/gitRefErrors.js';
5
5
  import Oid from '../../domain/value-objects/Oid.js';
6
+ import GitUpdateRefSessionPool from './GitUpdateRefSessionPool.js';
6
7
 
7
8
  /**
8
9
  * Default resilience policy: 30 s timeout (no retry).
@@ -30,6 +31,9 @@ const REF_NAME_ENCODER = new globalThis.TextEncoder();
30
31
  * (30 s timeout by default).
31
32
  */
32
33
  export default class GitRefAdapter extends GitRefPort {
34
+ #closed = false;
35
+ #updateRefs;
36
+
33
37
  /**
34
38
  * @param {Object} options
35
39
  * @param {import('@git-stunts/plumbing').default} options.plumbing - GitPlumbing instance.
@@ -39,6 +43,7 @@ export default class GitRefAdapter extends GitRefPort {
39
43
  super();
40
44
  this.plumbing = plumbing;
41
45
  this.policy = policy ?? DEFAULT_POLICY;
46
+ this.#updateRefs = new GitUpdateRefSessionPool({ plumbing });
42
47
  }
43
48
 
44
49
  /**
@@ -47,6 +52,7 @@ export default class GitRefAdapter extends GitRefPort {
47
52
  * @returns {Promise<string>} The commit OID.
48
53
  */
49
54
  async resolveRef(ref) {
55
+ this.#assertOpen();
50
56
  try {
51
57
  return await this.policy.execute(() =>
52
58
  this.plumbing.execute({ args: ['rev-parse', ref] }),
@@ -68,6 +74,7 @@ export default class GitRefAdapter extends GitRefPort {
68
74
  * @returns {Promise<string>} The tree OID.
69
75
  */
70
76
  async resolveTree(commitOid) {
77
+ this.#assertOpen();
71
78
  return this.policy.execute(() =>
72
79
  this.plumbing.execute({ args: ['rev-parse', `${commitOid}^{tree}`] }),
73
80
  );
@@ -79,6 +86,7 @@ export default class GitRefAdapter extends GitRefPort {
79
86
  * @returns {Promise<string[]>} Direct parent OIDs.
80
87
  */
81
88
  async resolveParents(commitOid) {
89
+ this.#assertOpen();
82
90
  const line = await this.policy.execute(() =>
83
91
  this.plumbing.execute({ args: ['rev-list', '--parents', '-n', '1', commitOid] }),
84
92
  );
@@ -103,6 +111,7 @@ export default class GitRefAdapter extends GitRefPort {
103
111
  * @returns {Promise<string>} The new commit OID.
104
112
  */
105
113
  async createCommit({ treeOid, parentOid, parentOids, message }) {
114
+ this.#assertOpen();
106
115
  const args = ['commit-tree', treeOid, '-m', message];
107
116
  const parents = parentOids ?? (parentOid ? [parentOid] : []);
108
117
  for (const parent of parents) {
@@ -122,6 +131,7 @@ export default class GitRefAdapter extends GitRefPort {
122
131
  * @returns {Promise<void>}
123
132
  */
124
133
  async updateRef({ ref, newOid, expectedOldOid }) {
134
+ this.#assertOpen();
125
135
  assertRefName(ref);
126
136
  const symbolicTarget = await this.#resolveSymbolicRef(ref);
127
137
  if (symbolicTarget !== null) {
@@ -137,9 +147,14 @@ export default class GitRefAdapter extends GitRefPort {
137
147
  args.push(expectedOldOid ?? '0'.repeat(newOid.length));
138
148
  }
139
149
  try {
140
- await this.policy.execute(() =>
141
- this.plumbing.execute({ args }),
142
- );
150
+ if (this.#updateRefs.supports()) {
151
+ await this.#updateRefs.update(
152
+ { ref, newOid, expectedOldOid, noDeref: true },
153
+ (operation) => this.policy.execute(operation),
154
+ );
155
+ } else {
156
+ await this.policy.execute(() => this.plumbing.execute({ args }));
157
+ }
143
158
  } catch (error) {
144
159
  const actual = await this.#inspectRefPosture(ref);
145
160
  if (postureDisprovesExpectedOid(actual, expectedOldOid)) {
@@ -156,6 +171,7 @@ export default class GitRefAdapter extends GitRefPort {
156
171
 
157
172
  /** @override */
158
173
  async anchorRef({ sourceRef, expectedSourceOid, targetRef }) {
174
+ this.#assertOpen();
159
175
  assertRefName(sourceRef);
160
176
  assertRefName(targetRef);
161
177
  const generation = Oid.from(expectedSourceOid).toString();
@@ -195,6 +211,7 @@ export default class GitRefAdapter extends GitRefPort {
195
211
 
196
212
  /** @override */
197
213
  async deleteRef({ ref, expectedOldOid }) {
214
+ this.#assertOpen();
198
215
  assertRefName(ref);
199
216
  const expectedGeneration = Oid.from(expectedOldOid).toString();
200
217
  // A post-probe type race may delete this managed symref name, never its
@@ -231,6 +248,7 @@ export default class GitRefAdapter extends GitRefPort {
231
248
 
232
249
  /** @override */
233
250
  async *iterateRefs({ prefix = 'refs/', after = null, limit } = {}) {
251
+ this.#assertOpen();
234
252
  assertRefPrefix(prefix);
235
253
  assertRefCursor(prefix, after);
236
254
  assertRefIterationLimit(limit);
@@ -246,6 +264,23 @@ export default class GitRefAdapter extends GitRefPort {
246
264
  yield* paginatedRefRecords({ stream, prefix, after, limit });
247
265
  }
248
266
 
267
+ /** @override */
268
+ async close() {
269
+ this.#closed = true;
270
+ await this.#updateRefs.close();
271
+ }
272
+
273
+ /** @override */
274
+ async [Symbol.asyncDispose]() {
275
+ await this.close();
276
+ }
277
+
278
+ #assertOpen() {
279
+ if (this.#closed) {
280
+ throw new CasError('Git ref adapter is closed', ErrorCodes.RESOURCE_CLOSED);
281
+ }
282
+ }
283
+
249
284
  async #inspectDirectRef(ref) {
250
285
  const output = await this.policy.execute(() =>
251
286
  this.plumbing.execute({
@@ -0,0 +1,115 @@
1
+ import createCasError from '../../domain/errors/createCasError.js';
2
+ import { ErrorCodes } from '../../domain/errors/index.js';
3
+
4
+ const EXECUTE_DIRECTLY = (operation) => operation();
5
+
6
+ /**
7
+ * Lazily owns one reusable typed update-ref process.
8
+ *
9
+ * A failed ref transaction is never replayed. Plumbing's typed session poisons
10
+ * and terminates itself on protocol or Git failure; this owner only discards
11
+ * the failed instance so a later, separately authorized mutation can open a
12
+ * fresh process.
13
+ */
14
+ export default class GitUpdateRefSessionPool {
15
+ #active = new Set();
16
+ #closed = false;
17
+ #closePromise = null;
18
+ #opening = null;
19
+ #plumbing;
20
+
21
+ constructor({ plumbing }) {
22
+ this.#plumbing = plumbing;
23
+ }
24
+
25
+ supports() {
26
+ return typeof this.#plumbing?.openUpdateRefSession === 'function';
27
+ }
28
+
29
+ async update(options, execute = EXECUTE_DIRECTLY) {
30
+ this.#assertOpen();
31
+ const operation = (async () => {
32
+ let session;
33
+ try {
34
+ session = await this.#session();
35
+ return await execute(() => session.update(options));
36
+ } catch (error) {
37
+ if (session !== undefined) {
38
+ await this.#discard(session);
39
+ }
40
+ throw error;
41
+ }
42
+ })();
43
+ this.#active.add(operation);
44
+ try {
45
+ return await operation;
46
+ } finally {
47
+ this.#active.delete(operation);
48
+ }
49
+ }
50
+
51
+ async close() {
52
+ if (this.#closePromise !== null) {
53
+ return await this.#closePromise;
54
+ }
55
+ this.#closed = true;
56
+ this.#closePromise = (async () => {
57
+ await Promise.allSettled([...this.#active]);
58
+ const opening = this.#opening;
59
+ this.#opening = null;
60
+ if (opening !== null) {
61
+ const session = await opening.catch(() => null);
62
+ if (session !== null) {
63
+ await session.close();
64
+ }
65
+ }
66
+ })();
67
+ return await this.#closePromise;
68
+ }
69
+
70
+ async #discard(expectedSession) {
71
+ const opening = this.#opening;
72
+ if (opening === null) {
73
+ return;
74
+ }
75
+ const session = await opening.catch(() => undefined);
76
+ if (session === expectedSession && this.#opening === opening) {
77
+ this.#opening = null;
78
+ await releaseDiscardedSession(session);
79
+ }
80
+ }
81
+
82
+ async #session() {
83
+ this.#assertOpen();
84
+ if (this.#opening === null) {
85
+ const opening = Promise.resolve().then(() => this.#plumbing.openUpdateRefSession());
86
+ this.#opening = opening;
87
+ opening.catch(() => {
88
+ if (this.#opening === opening) {
89
+ this.#opening = null;
90
+ }
91
+ });
92
+ }
93
+ return await this.#opening;
94
+ }
95
+
96
+ #assertOpen() {
97
+ if (this.#closed) {
98
+ throw createCasError('Git ref session pool is closed', ErrorCodes.RESOURCE_CLOSED);
99
+ }
100
+ }
101
+ }
102
+
103
+ async function releaseDiscardedSession(session) {
104
+ try {
105
+ if (typeof session.terminate === 'function') {
106
+ await session.terminate();
107
+ } else if (typeof session.abort === 'function') {
108
+ await session.abort();
109
+ } else if (typeof session.close === 'function') {
110
+ await session.close();
111
+ }
112
+ } catch {
113
+ // Preserve the mutation failure that caused this best-effort teardown.
114
+ }
115
+ }
@@ -1 +1 @@
1
- export const PACKAGE_VERSION = '6.5.7';
1
+ export const PACKAGE_VERSION = '6.5.8';