@git-stunts/git-cas 6.5.1 → 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.
@@ -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
+ }