@git-stunts/git-cas 6.5.0 → 6.5.2

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.
@@ -55,6 +55,7 @@ const ErrorCodes = Object.freeze({
55
55
  MANIFEST_NOT_FOUND: 'MANIFEST_NOT_FOUND',
56
56
  MISSING_KEY: 'MISSING_KEY',
57
57
  NO_MATCHING_RECIPIENT: 'NO_MATCHING_RECIPIENT',
58
+ PAGE_BATCH_LIMIT: 'PAGE_BATCH_LIMIT',
58
59
  PAGE_TOO_LARGE: 'PAGE_TOO_LARGE',
59
60
  PERSISTENCE_CAPABILITY_REQUIRED: 'PERSISTENCE_CAPABILITY_REQUIRED',
60
61
  PORT_NOT_IMPLEMENTED: 'PORT_NOT_IMPLEMENTED',
@@ -65,6 +66,7 @@ const ErrorCodes = Object.freeze({
65
66
  RECIPIENT_ALREADY_EXISTS: 'RECIPIENT_ALREADY_EXISTS',
66
67
  RECIPIENT_NOT_FOUND: 'RECIPIENT_NOT_FOUND',
67
68
  REPOSITORY_INSPECTION_INVALID: 'REPOSITORY_INSPECTION_INVALID',
69
+ RESOURCE_CLOSED: 'RESOURCE_CLOSED',
68
70
  RESTORE_TOO_LARGE: 'RESTORE_TOO_LARGE',
69
71
  RETENTION_WITNESS_INVALID: 'RETENTION_WITNESS_INVALID',
70
72
  ROOT_SET_CONFLICT: 'ROOT_SET_CONFLICT',
@@ -4,8 +4,13 @@ import { ErrorCodes } from '../errors/index.js';
4
4
  import { assertHandleObjectType, mapHandleTargetError } from '../helpers/handleTarget.js';
5
5
  import PageHandle from '../value-objects/PageHandle.js';
6
6
  import StagedPage from '../value-objects/StagedPage.js';
7
+ import BoundedPromiseCache from '../../helpers/boundedPromiseCache.js';
7
8
 
8
9
  export const DEFAULT_MAX_PAGE_SIZE = 16 * 1024 * 1024;
10
+ const DEFAULT_PAGE_CACHE_ENTRIES = 128;
11
+ const DEFAULT_PAGE_CACHE_BYTES = 8 * 1024 * 1024;
12
+ const DEFAULT_PAGE_WRITE_BATCH_BYTES = 32 * 1024 * 1024;
13
+ const DEFAULT_PAGE_WRITE_BATCH_PAGES = 256;
9
14
  const DEFAULT_CLOCK = Object.freeze({ now: () => new Date() });
10
15
 
11
16
  /**
@@ -14,19 +19,34 @@ const DEFAULT_CLOCK = Object.freeze({ now: () => new Date() });
14
19
  export default class PageService {
15
20
  #clock;
16
21
  #maxPageSize;
22
+ #payloads;
17
23
  #persistence;
18
24
 
19
25
  /**
20
26
  * @param {object} options
21
27
  * @param {import('../../ports/GitPersistencePort.js').default} options.persistence
22
28
  * @param {number} [options.maxPageSize]
29
+ * @param {number} [options.pageCacheEntries]
30
+ * @param {number} [options.pageCacheBytes]
23
31
  * @param {{ now(): Date }} [options.clock]
24
32
  */
25
- constructor({ persistence, maxPageSize = DEFAULT_MAX_PAGE_SIZE, clock = DEFAULT_CLOCK }) {
33
+ constructor({
34
+ persistence,
35
+ maxPageSize = DEFAULT_MAX_PAGE_SIZE,
36
+ pageCacheEntries = DEFAULT_PAGE_CACHE_ENTRIES,
37
+ pageCacheBytes = DEFAULT_PAGE_CACHE_BYTES,
38
+ clock = DEFAULT_CLOCK,
39
+ }) {
26
40
  PageService.#assertDependencies(persistence, clock);
27
41
  PageService.#assertLimit(maxPageSize, 'Configured max page size');
42
+ PageService.#assertPositiveLimit(pageCacheEntries, 'Page cache entries');
43
+ PageService.#assertLimit(pageCacheBytes, 'Page cache bytes');
28
44
  this.#persistence = persistence;
29
45
  this.#maxPageSize = maxPageSize;
46
+ this.#payloads = new BoundedPromiseCache(pageCacheEntries, {
47
+ maxWeight: pageCacheBytes,
48
+ weightOf: (value) => value.byteLength,
49
+ });
30
50
  this.#clock = clock;
31
51
  }
32
52
 
@@ -46,6 +66,62 @@ export default class PageService {
46
66
  });
47
67
  }
48
68
 
69
+ /**
70
+ * Stores one explicitly bounded page batch. All inputs are validated and
71
+ * collected before the persistence batch begins.
72
+ * @param {object} options
73
+ * @param {Array<{source: Uint8Array|Iterable<Uint8Array>|AsyncIterable<Uint8Array>, maxBytes?: number}>} options.pages
74
+ * @param {number} [options.maxBatchBytes]
75
+ * @param {number} [options.maxBatchPages]
76
+ * @returns {Promise<ReadonlyArray<StagedPage>>}
77
+ */
78
+ async putBatch({
79
+ pages,
80
+ maxBatchBytes = DEFAULT_PAGE_WRITE_BATCH_BYTES,
81
+ maxBatchPages = DEFAULT_PAGE_WRITE_BATCH_PAGES,
82
+ }) {
83
+ PageService.#assertBatch(pages, maxBatchBytes, maxBatchPages);
84
+ const prepared = [];
85
+ let totalBytes = 0;
86
+ for (const page of pages) {
87
+ if (page === null || typeof page !== 'object' || !Object.hasOwn(page, 'source')) {
88
+ throw createCasError('Page batch entry must provide source', ErrorCodes.INVALID_OPTIONS);
89
+ }
90
+ const pageLimit = this.#effectiveLimit(page.maxBytes);
91
+ const remainingBatchBytes = maxBatchBytes - totalBytes;
92
+ const overflow = remainingBatchBytes <= pageLimit
93
+ ? (observedBytes) => PageService.#batchTooLarge(
94
+ totalBytes + observedBytes,
95
+ maxBatchBytes,
96
+ )
97
+ : PageService.#tooLarge;
98
+ const bytes = await PageService.#collectWithOverflow(
99
+ page.source,
100
+ Math.min(pageLimit, remainingBatchBytes),
101
+ overflow,
102
+ );
103
+ totalBytes += bytes.length;
104
+ prepared.push({ bytes, observedAt: this.#observedAt() });
105
+ }
106
+
107
+ if (prepared.length === 0) {
108
+ return Object.freeze([]);
109
+ }
110
+ const oids = await this.#writeBlobs(prepared.map((page) => page.bytes));
111
+ if (oids.length !== prepared.length) {
112
+ throw createCasError(
113
+ 'Persistence returned the wrong number of page object identifiers',
114
+ ErrorCodes.GIT_ERROR,
115
+ { expected: prepared.length, actual: oids.length },
116
+ );
117
+ }
118
+ return Object.freeze(oids.map((oid, index) => new StagedPage({
119
+ handle: new PageHandle({ oid }),
120
+ size: prepared[index].bytes.length,
121
+ observedAt: prepared[index].observedAt,
122
+ })));
123
+ }
124
+
49
125
  /**
50
126
  * @param {{ handle: PageHandle|string|object }} options
51
127
  * @returns {AsyncIterable<Uint8Array>}
@@ -64,7 +140,24 @@ export default class PageService {
64
140
  * @returns {Promise<Uint8Array>}
65
141
  */
66
142
  async get({ handle, maxBytes }) {
67
- return await PageService.#collect(this.open({ handle }), this.#effectiveLimit(maxBytes));
143
+ const limit = this.#effectiveLimit(maxBytes);
144
+ const pageHandle = PageHandle.from(handle);
145
+ let payload = this.#payloads.get(pageHandle.oid);
146
+ if (payload === undefined) {
147
+ const root = await this.resolveRoot(pageHandle);
148
+ if (root.size > limit) {
149
+ throw PageService.#tooLarge(root.size, limit);
150
+ }
151
+ payload = this.#payloads.getOrCreate(
152
+ root.oid,
153
+ async () => await this.#readRoot(root),
154
+ );
155
+ }
156
+ const bytes = await payload;
157
+ if (bytes.byteLength > limit) {
158
+ throw PageService.#tooLarge(bytes.byteLength, limit);
159
+ }
160
+ return new Uint8Array(bytes);
68
161
  }
69
162
 
70
163
  /**
@@ -106,6 +199,17 @@ export default class PageService {
106
199
  return value;
107
200
  }
108
201
 
202
+ async #readRoot(root) {
203
+ try {
204
+ return await PageService.#collect(
205
+ await this.#persistence.readBlobStream(root.oid),
206
+ this.#maxPageSize,
207
+ );
208
+ } catch (error) {
209
+ throw mapHandleTargetError(error, root.handle);
210
+ }
211
+ }
212
+
109
213
  #observedAt() {
110
214
  const now = this.#clock.now();
111
215
  if (!(now instanceof Date) || Number.isNaN(now.getTime())) {
@@ -114,10 +218,25 @@ export default class PageService {
114
218
  return now.toISOString();
115
219
  }
116
220
 
221
+ async #writeBlobs(contents) {
222
+ if (typeof this.#persistence.writeBlobs === 'function') {
223
+ return await this.#persistence.writeBlobs(contents);
224
+ }
225
+ const oids = [];
226
+ for (const content of contents) {
227
+ oids.push(await this.#persistence.writeBlob(content));
228
+ }
229
+ return oids;
230
+ }
231
+
117
232
  static async #collect(source, maxBytes) {
233
+ return await PageService.#collectWithOverflow(source, maxBytes, PageService.#tooLarge);
234
+ }
235
+
236
+ static async #collectWithOverflow(source, maxBytes, overflow) {
118
237
  if (isBytes(source)) {
119
238
  if (source.length > maxBytes) {
120
- throw PageService.#tooLarge(source.length, maxBytes);
239
+ throw overflow(source.length, maxBytes);
121
240
  }
122
241
  return new Uint8Array(source);
123
242
  }
@@ -141,7 +260,7 @@ export default class PageService {
141
260
  }
142
261
  total += bytes.length;
143
262
  if (total > maxBytes) {
144
- throw PageService.#tooLarge(total, maxBytes);
263
+ throw overflow(total, maxBytes);
145
264
  }
146
265
  chunks.push(bytes);
147
266
  }
@@ -155,6 +274,14 @@ export default class PageService {
155
274
  });
156
275
  }
157
276
 
277
+ static #batchTooLarge(observedBytes, maxBatchBytes) {
278
+ return createCasError(
279
+ 'Page batch exceeds its configured byte limit',
280
+ ErrorCodes.PAGE_BATCH_LIMIT,
281
+ { observedBytes, maxBatchBytes },
282
+ );
283
+ }
284
+
158
285
  static #assertLimit(value, label) {
159
286
  if (!Number.isSafeInteger(value) || value < 0) {
160
287
  throw createCasError(`${label} must be a non-negative safe integer`, ErrorCodes.INVALID_OPTIONS, {
@@ -163,6 +290,29 @@ export default class PageService {
163
290
  }
164
291
  }
165
292
 
293
+ static #assertPositiveLimit(value, label) {
294
+ if (!Number.isSafeInteger(value) || value < 1) {
295
+ throw createCasError(`${label} must be a positive safe integer`, ErrorCodes.INVALID_OPTIONS, {
296
+ value,
297
+ });
298
+ }
299
+ }
300
+
301
+ static #assertBatch(pages, maxBatchBytes, maxBatchPages) {
302
+ PageService.#assertPositiveLimit(maxBatchBytes, 'Page batch bytes');
303
+ PageService.#assertPositiveLimit(maxBatchPages, 'Page batch pages');
304
+ if (!Array.isArray(pages)) {
305
+ throw createCasError('Page batch must be an array', ErrorCodes.INVALID_OPTIONS);
306
+ }
307
+ if (pages.length > maxBatchPages) {
308
+ throw createCasError(
309
+ 'Page batch exceeds its configured page limit',
310
+ ErrorCodes.PAGE_BATCH_LIMIT,
311
+ { observedPages: pages.length, maxBatchPages },
312
+ );
313
+ }
314
+ }
315
+
166
316
  static #assertDependencies(persistence, clock) {
167
317
  const methods = ['writeBlob', 'readBlobStream', 'readObjectType', 'readObjectSize'];
168
318
  if (!persistence || methods.some((method) => typeof persistence[method] !== 'function')) {
@@ -4,7 +4,9 @@
4
4
  */
5
5
  export default class BoundedPromiseCache {
6
6
  /** @type {Map<string, { promise: Promise<unknown>, weight: number }>} */
7
- #entries = new Map();
7
+ #completed = new Map();
8
+ /** @type {Map<string, Promise<unknown>>} */
9
+ #inFlight = new Map();
8
10
  #maxEntries;
9
11
  #maxWeight;
10
12
  #totalWeight = 0;
@@ -34,6 +36,21 @@ export default class BoundedPromiseCache {
34
36
  this.#weightOf = weightOf;
35
37
  }
36
38
 
39
+ /**
40
+ * @template T
41
+ * @param {string} key
42
+ * @returns {Promise<T>|undefined}
43
+ */
44
+ get(key) {
45
+ const cached = this.#completed.get(key);
46
+ if (cached !== undefined) {
47
+ this.#completed.delete(key);
48
+ this.#completed.set(key, cached);
49
+ return cached.promise;
50
+ }
51
+ return this.#inFlight.get(key);
52
+ }
53
+
37
54
  /**
38
55
  * @template T
39
56
  * @param {string} key
@@ -41,45 +58,30 @@ export default class BoundedPromiseCache {
41
58
  * @returns {Promise<T>}
42
59
  */
43
60
  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;
61
+ const present = this.get(key);
62
+ if (present !== undefined) {
63
+ return present;
49
64
  }
50
65
 
51
66
  const source = Promise.resolve().then(factory);
52
- const entry = { promise: source, weight: 0 };
53
67
  const tracked = source.then(
54
68
  (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();
69
+ this.#removeInFlight(key, tracked);
70
+ const weight = this.#resolvedWeight(value);
71
+ if (weight <= this.#maxWeight) {
72
+ const entry = { promise: Promise.resolve(value), weight };
73
+ this.#completed.set(key, entry);
74
+ this.#totalWeight += weight;
75
+ this.#evictCompleted();
70
76
  }
71
77
  return value;
72
78
  },
73
79
  (error) => {
74
- if (this.#entries.get(key) === entry) {
75
- this.#remove(key, entry);
76
- }
80
+ this.#removeInFlight(key, tracked);
77
81
  throw error;
78
82
  },
79
83
  );
80
- entry.promise = tracked;
81
- this.#entries.set(key, entry);
82
- this.#evict();
84
+ this.#inFlight.set(key, tracked);
83
85
  return tracked;
84
86
  }
85
87
 
@@ -91,18 +93,24 @@ export default class BoundedPromiseCache {
91
93
  return weight;
92
94
  }
93
95
 
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);
96
+ #evictCompleted() {
97
+ while (this.#completed.size > this.#maxEntries || this.#totalWeight > this.#maxWeight) {
98
+ const oldestKey = this.#completed.keys().next().value;
99
+ const oldest = this.#completed.get(oldestKey);
100
+ this.#removeCompleted(oldestKey, oldest);
99
101
  }
100
102
  }
101
103
 
102
- #remove(key, entry) {
103
- if (entry === undefined || !this.#entries.delete(key)) {
104
+ #removeCompleted(key, entry) {
105
+ if (entry === undefined || !this.#completed.delete(key)) {
104
106
  return;
105
107
  }
106
108
  this.#totalWeight -= entry.weight;
107
109
  }
110
+
111
+ #removeInFlight(key, promise) {
112
+ if (this.#inFlight.get(key) === promise) {
113
+ this.#inFlight.delete(key);
114
+ }
115
+ }
108
116
  }
@@ -0,0 +1,333 @@
1
+ import {
2
+ GitObjectMissingError,
3
+ GitProtocolError,
4
+ InvalidArgumentError,
5
+ } from '@git-stunts/plumbing';
6
+
7
+ const PROTOCOLS = Object.freeze({
8
+ catFile: Object.freeze({ opener: 'openCatFileSession', abort: 'terminate' }),
9
+ fastImport: Object.freeze({ opener: 'openFastImportSession', abort: 'abort' }),
10
+ mktree: Object.freeze({ opener: 'openMktreeSession', abort: 'terminate' }),
11
+ });
12
+ const EXECUTE_DIRECTLY = (operation) => operation();
13
+
14
+ /**
15
+ * Lazily owns one typed plumbing session per Git object protocol.
16
+ */
17
+ export default class GitObjectSessionPool {
18
+ #active = new Map();
19
+ #closePromise = null;
20
+ #closed = false;
21
+ #idleFailures = new Map();
22
+ #idleTimeoutMs;
23
+ #idleTimers = new Map();
24
+ #plumbing;
25
+ #poisoned = new Map();
26
+ #retirements = new Map();
27
+ #sessions = new Map();
28
+
29
+ constructor({ plumbing, idleTimeoutMs }) {
30
+ this.#plumbing = plumbing;
31
+ this.#idleTimeoutMs = idleTimeoutMs;
32
+ }
33
+
34
+ supports(protocol) {
35
+ const descriptor = PROTOCOLS[protocol];
36
+ return descriptor !== undefined && typeof this.#plumbing[descriptor.opener] === 'function';
37
+ }
38
+
39
+ async info(objectName, execute = EXECUTE_DIRECTLY) {
40
+ return await this.#run(
41
+ 'catFile',
42
+ (session) => execute(() => session.info(objectName)),
43
+ isRecoverableCatError
44
+ );
45
+ }
46
+
47
+ async read(objectName, options, execute = EXECUTE_DIRECTLY) {
48
+ return await this.#run(
49
+ 'catFile',
50
+ (session) => execute(() => session.read(objectName, options)),
51
+ isRecoverableCatError
52
+ );
53
+ }
54
+
55
+ async writeBlobs(contents, execute = EXECUTE_DIRECTLY) {
56
+ return await this.#run('fastImport', (session) =>
57
+ execute(async () => {
58
+ const oids = [];
59
+ for (const content of contents) {
60
+ oids.push(await session.writeBlob(content));
61
+ }
62
+ await session.checkpoint();
63
+ return Object.freeze(oids);
64
+ })
65
+ );
66
+ }
67
+
68
+ async writeTree(entries, execute = EXECUTE_DIRECTLY) {
69
+ return await this.#run('mktree', (session) => execute(() => session.write(entries)));
70
+ }
71
+
72
+ async invalidate(protocol, expectedSession) {
73
+ this.#cancelIdle(protocol);
74
+ const opening = this.#sessions.get(protocol);
75
+ if (expectedSession !== undefined) {
76
+ if (opening !== undefined) {
77
+ const current = await opening.catch(() => undefined);
78
+ if (current === expectedSession && this.#sessions.get(protocol) === opening) {
79
+ this.#sessions.delete(protocol);
80
+ }
81
+ }
82
+ await this.#trackRetirement(protocol, () => this.#abort(protocol, expectedSession));
83
+ return;
84
+ }
85
+ this.#sessions.delete(protocol);
86
+ if (opening === undefined) {
87
+ const retirement = this.#retirements.get(protocol);
88
+ if (retirement !== undefined) {
89
+ await retirement.completion;
90
+ }
91
+ return;
92
+ }
93
+ await this.#trackRetirement(protocol, async () => {
94
+ const session = await opening.catch(() => undefined);
95
+ if (session !== undefined) {
96
+ await this.#abort(protocol, session);
97
+ }
98
+ });
99
+ }
100
+
101
+ async retire(protocol) {
102
+ this.#cancelIdle(protocol);
103
+ const opening = this.#sessions.get(protocol);
104
+ this.#sessions.delete(protocol);
105
+ if (opening === undefined) {
106
+ const retirement = this.#retirements.get(protocol);
107
+ if (retirement !== undefined) {
108
+ await retirement.completion;
109
+ }
110
+ return;
111
+ }
112
+ await this.#trackRetirement(protocol, async () => {
113
+ const session = await opening.catch(() => undefined);
114
+ if (session !== undefined) {
115
+ await this.#closeSession(protocol, session, `Git ${protocol} session failed to retire`);
116
+ }
117
+ });
118
+ }
119
+
120
+ async close() {
121
+ if (this.#closePromise !== null) {
122
+ return await this.#closePromise;
123
+ }
124
+ this.#closed = true;
125
+ for (const protocol of this.#idleTimers.keys()) {
126
+ this.#cancelIdle(protocol);
127
+ }
128
+ const sessions = [...this.#sessions.entries()];
129
+ const poisoned = new Map(this.#poisoned);
130
+ const retirements = [...this.#retirements.values()].map((retirement) => retirement.barrier);
131
+ this.#sessions.clear();
132
+ this.#closePromise = (async () => {
133
+ const results = await Promise.allSettled(
134
+ sessions.map(async ([protocol, opening]) => {
135
+ const session = await opening;
136
+ await this.#closeSession(
137
+ protocol,
138
+ session,
139
+ `Git ${protocol} session failed to close or terminate`
140
+ );
141
+ })
142
+ );
143
+ await Promise.allSettled(retirements);
144
+ const failures = results
145
+ .filter((result) => result.status === 'rejected')
146
+ .map((result) => result.reason);
147
+ failures.push(...this.#idleFailures.values());
148
+ for (const [protocol, error] of poisoned) {
149
+ if (!this.#idleFailures.has(protocol)) {
150
+ failures.push(error);
151
+ }
152
+ }
153
+ if (failures.length > 0) {
154
+ throw new AggregateError(failures, 'One or more Git object sessions failed to close');
155
+ }
156
+ })();
157
+ return await this.#closePromise;
158
+ }
159
+
160
+ async #run(protocol, operation, recoverable = () => false) {
161
+ this.#cancelIdle(protocol);
162
+ this.#active.set(protocol, (this.#active.get(protocol) ?? 0) + 1);
163
+ try {
164
+ return await this.#attempt({ protocol, operation, recoverable, mayRetry: true });
165
+ } finally {
166
+ this.#release(protocol);
167
+ }
168
+ }
169
+
170
+ async #attempt({ protocol, operation, recoverable, mayRetry }) {
171
+ let session;
172
+ try {
173
+ session = await this.#session(protocol);
174
+ return await operation(session);
175
+ } catch (error) {
176
+ if (recoverable(error) || error instanceof InvalidArgumentError) {
177
+ throw error;
178
+ }
179
+ try {
180
+ await this.invalidate(protocol, session);
181
+ } catch (invalidationError) {
182
+ throw new AggregateError(
183
+ [error, invalidationError],
184
+ `Git ${protocol} operation and session invalidation both failed`
185
+ );
186
+ }
187
+ if (mayRetry && error instanceof GitProtocolError) {
188
+ return await this.#attempt({ protocol, operation, recoverable, mayRetry: false });
189
+ }
190
+ throw error;
191
+ }
192
+ }
193
+
194
+ #release(protocol) {
195
+ const remaining = (this.#active.get(protocol) ?? 1) - 1;
196
+ if (remaining === 0) {
197
+ this.#active.delete(protocol);
198
+ this.#scheduleIdle(protocol);
199
+ return;
200
+ }
201
+ this.#active.set(protocol, remaining);
202
+ }
203
+
204
+ async #session(protocol) {
205
+ if (this.#closed) {
206
+ throw new Error('Git object session pool is closed');
207
+ }
208
+ const poison = this.#poisoned.get(protocol);
209
+ if (poison !== undefined) {
210
+ throw poison;
211
+ }
212
+ const descriptor = PROTOCOLS[protocol];
213
+ if (descriptor === undefined || typeof this.#plumbing[descriptor.opener] !== 'function') {
214
+ throw new Error(`Git object protocol is unavailable: ${protocol}`);
215
+ }
216
+ let opening = this.#sessions.get(protocol);
217
+ if (opening === undefined) {
218
+ let retirement = this.#retirements.get(protocol);
219
+ while (retirement !== undefined) {
220
+ await retirement.barrier;
221
+ const latest = this.#retirements.get(protocol);
222
+ if (latest === retirement) {
223
+ break;
224
+ }
225
+ retirement = latest;
226
+ }
227
+ if (this.#closed) {
228
+ throw new Error('Git object session pool is closed');
229
+ }
230
+ opening = this.#sessions.get(protocol);
231
+ }
232
+ if (opening === undefined) {
233
+ opening = Promise.resolve().then(() => this.#plumbing[descriptor.opener]());
234
+ this.#sessions.set(protocol, opening);
235
+ opening.catch(() => {
236
+ if (this.#sessions.get(protocol) === opening) {
237
+ this.#sessions.delete(protocol);
238
+ }
239
+ });
240
+ }
241
+ return await opening;
242
+ }
243
+
244
+ async #abort(protocol, session) {
245
+ const method = PROTOCOLS[protocol]?.abort;
246
+ if (method !== undefined && typeof session[method] === 'function') {
247
+ try {
248
+ await session[method]();
249
+ } catch (error) {
250
+ this.#poisoned.set(protocol, error);
251
+ throw error;
252
+ }
253
+ }
254
+ }
255
+
256
+ async #closeSession(protocol, session, message) {
257
+ try {
258
+ await session.close();
259
+ } catch (closeError) {
260
+ try {
261
+ await this.#abort(protocol, session);
262
+ } catch (abortError) {
263
+ throw new AggregateError([closeError, abortError], message);
264
+ }
265
+ throw closeError;
266
+ }
267
+ }
268
+
269
+ #scheduleIdle(protocol) {
270
+ if (this.#closed || this.#active.has(protocol) || !this.#sessions.has(protocol)) {
271
+ return;
272
+ }
273
+ const opening = this.#sessions.get(protocol);
274
+ const timer = setTimeout(() => {
275
+ this.#idleTimers.delete(protocol);
276
+ if (this.#active.has(protocol) || this.#sessions.get(protocol) !== opening) {
277
+ return;
278
+ }
279
+ this.#sessions.delete(protocol);
280
+ this.#trackIdleRetirement(protocol, opening);
281
+ }, this.#idleTimeoutMs);
282
+ timer.unref?.();
283
+ this.#idleTimers.set(protocol, timer);
284
+ }
285
+
286
+ #trackIdleRetirement(protocol, opening) {
287
+ this.#trackRetirement(
288
+ protocol,
289
+ async () => {
290
+ const session = await opening;
291
+ await this.#closeSession(
292
+ protocol,
293
+ session,
294
+ `Idle Git ${protocol} session failed to close or terminate`
295
+ );
296
+ },
297
+ true
298
+ );
299
+ }
300
+
301
+ #trackRetirement(protocol, operation, recordFailure = false) {
302
+ const previous = this.#retirements.get(protocol)?.barrier ?? Promise.resolve();
303
+ const completion = previous.then(operation);
304
+ const barrier = completion.catch((error) => {
305
+ if (recordFailure) {
306
+ this.#idleFailures.set(protocol, error);
307
+ }
308
+ });
309
+ const retirement = { barrier, completion };
310
+ this.#retirements.set(protocol, retirement);
311
+ void barrier.finally(() => {
312
+ if (this.#retirements.get(protocol) === retirement) {
313
+ this.#retirements.delete(protocol);
314
+ }
315
+ });
316
+ return completion;
317
+ }
318
+
319
+ #cancelIdle(protocol) {
320
+ const timer = this.#idleTimers.get(protocol);
321
+ if (timer !== undefined) {
322
+ clearTimeout(timer);
323
+ this.#idleTimers.delete(protocol);
324
+ }
325
+ }
326
+ }
327
+
328
+ function isRecoverableCatError(error) {
329
+ return (
330
+ error instanceof GitObjectMissingError ||
331
+ error?.details?.code === 'OBJECT_BUFFER_LIMIT_EXCEEDED'
332
+ );
333
+ }