@git-stunts/git-cas 6.5.6 → 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 (33) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/GUIDE.md +29 -0
  3. package/README.md +16 -10
  4. package/UPGRADING.md +48 -0
  5. package/build-info.json +2 -2
  6. package/docs/API.md +66 -12
  7. package/docs/releases/v6.5.7.md +56 -0
  8. package/docs/releases/v6.5.8.md +89 -0
  9. package/index.d.ts +50 -0
  10. package/index.js +15 -1
  11. package/package.json +4 -2
  12. package/src/domain/services/AssetService.js +201 -10
  13. package/src/domain/services/BoundedWriteWavePersistence.js +235 -0
  14. package/src/domain/services/BundleBatchPlanner.js +349 -0
  15. package/src/domain/services/BundleService.js +225 -2
  16. package/src/domain/services/CasService.d.ts +16 -0
  17. package/src/domain/services/CasService.js +9 -18
  18. package/src/domain/services/ManifestRepository.js +129 -50
  19. package/src/domain/services/ManifestTreeService.js +47 -0
  20. package/src/domain/services/PageService.js +26 -9
  21. package/src/domain/services/RootSet.js +32 -0
  22. package/src/domain/services/RootSetPersistence.js +58 -1
  23. package/src/domain/services/StagedTarget.js +19 -0
  24. package/src/domain/services/StagingWorkspace.js +21 -7
  25. package/src/domain/services/forkCasPersistence.js +20 -0
  26. package/src/infrastructure/adapters/GitObjectSessionPool.js +47 -5
  27. package/src/infrastructure/adapters/GitPersistenceAdapter.js +217 -16
  28. package/src/infrastructure/adapters/GitPersistenceWriteScope.js +154 -0
  29. package/src/infrastructure/adapters/GitRefAdapter.js +38 -3
  30. package/src/infrastructure/adapters/GitUpdateRefSessionPool.js +115 -0
  31. package/src/package-version.js +1 -1
  32. package/src/ports/GitPersistencePort.js +43 -0
  33. 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).
@@ -19,6 +20,7 @@ import GitObjectSessionPool from './GitObjectSessionPool.js';
19
20
  */
20
21
  const DEFAULT_POLICY = Policy.timeout(30_000);
21
22
  export const DEFAULT_MAX_BLOB_SIZE = 10 * 1024 * 1024;
23
+ const MAX_SESSION_STREAM_BLOB_BYTES = DEFAULT_MAX_BLOB_SIZE;
22
24
  const DEFAULT_METADATA_CACHE_ENTRIES = 2_048;
23
25
  const DEFAULT_SESSION_IDLE_TIMEOUT_MS = 1_000;
24
26
  const DEFAULT_TREE_CACHE_BYTES = 8 * 1024 * 1024;
@@ -113,6 +115,9 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
113
115
  async writeBlobs(contents) {
114
116
  return await this.#runOperation(async () => {
115
117
  const replayableContents = [...contents];
118
+ if (replayableContents.length === 0) {
119
+ return [];
120
+ }
116
121
  if (!this.#sessions.supports('fastImport')) {
117
122
  const oids = [];
118
123
  for (const content of replayableContents) {
@@ -152,6 +157,25 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
152
157
  });
153
158
  }
154
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
+
155
179
  /**
156
180
  * @override
157
181
  * @param {string[]} entries - Lines in `git mktree` format.
@@ -176,6 +200,40 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
176
200
  });
177
201
  }
178
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
+
179
237
  /**
180
238
  * @override
181
239
  * @param {string} oid - Git object ID.
@@ -189,21 +247,7 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
189
247
  ? this.#maxBlobSize
190
248
  : GitPersistenceAdapter.#validatedReadBlobLimit(maxBytes);
191
249
  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);
250
+ return await this.#readBlobFromSession(oid, limit);
207
251
  }
208
252
  const chunks = [];
209
253
  let bytesRead = 0;
@@ -241,7 +285,48 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
241
285
  * @returns {Promise<AsyncIterable<Buffer>>} The blob content stream.
242
286
  */
243
287
  async readBlobStream(oid) {
244
- return await this.#runOperation(() => this.#openBufferStream(['cat-file', 'blob', oid]));
288
+ return await this.#runOperation(async () => {
289
+ if (!this.#sessions.supports('catFile')) {
290
+ return await this.#openBlobStream(oid);
291
+ }
292
+ let info;
293
+ try {
294
+ info = await this.#readObjectInfo(oid);
295
+ } catch {
296
+ return await this.#openBlobStream(oid);
297
+ }
298
+ if (info.type !== 'blob' || info.size > MAX_SESSION_STREAM_BLOB_BYTES) {
299
+ return await this.#openBlobStream(oid);
300
+ }
301
+ try {
302
+ const content = await this.#readBlobFromSession(oid, MAX_SESSION_STREAM_BLOB_BYTES);
303
+ return GitPersistenceAdapter.#singleBufferStream(content);
304
+ } catch {
305
+ return await this.#openBlobStream(oid);
306
+ }
307
+ });
308
+ }
309
+
310
+ async #readBlobFromSession(oid, maxBytes) {
311
+ let object;
312
+ try {
313
+ object = await this.#sessions.read(oid, { maxBytes }, (operation) =>
314
+ this.policy.execute(operation)
315
+ );
316
+ } catch (error) {
317
+ throw this.#normalizeObjectReadError(error, oid, maxBytes);
318
+ }
319
+ if (object.type !== 'blob') {
320
+ throw createCasError(`Git object is not a blob: ${oid}`, ErrorCodes.GIT_ERROR, {
321
+ oid,
322
+ actualType: object.type,
323
+ });
324
+ }
325
+ return GitPersistenceAdapter.#toBuffer(object.content);
326
+ }
327
+
328
+ async #openBlobStream(oid) {
329
+ return await this.#openBufferStream(['cat-file', 'blob', oid]);
245
330
  }
246
331
 
247
332
  /**
@@ -358,6 +443,88 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
358
443
  return await this.#runOperation(async () => (await this.#readObjectInfo(oid)).size);
359
444
  }
360
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
+
361
528
  /**
362
529
  * Reads object metadata through Git's structured batch protocol. Missing
363
530
  * objects are reported on stdout with exit zero, avoiding runtime-specific
@@ -409,6 +576,36 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
409
576
  });
410
577
  }
411
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
+
412
609
  async #readTreeObject(treeOid) {
413
610
  return this.#treeCache.getOrCreate(treeOid, async () => {
414
611
  const object = await this.#sessions.read(
@@ -675,6 +872,10 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
675
872
  }
676
873
  }
677
874
 
875
+ static async *#singleBufferStream(content) {
876
+ yield content;
877
+ }
878
+
678
879
  /**
679
880
  * @param {Buffer|Uint8Array|string} chunk
680
881
  * @returns {Buffer}
@@ -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({