@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.
@@ -9,6 +9,8 @@ import BoundedPromiseCache from '../../helpers/boundedPromiseCache.js';
9
9
  export const DEFAULT_MAX_PAGE_SIZE = 16 * 1024 * 1024;
10
10
  const DEFAULT_PAGE_CACHE_ENTRIES = 128;
11
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;
12
14
  const DEFAULT_CLOCK = Object.freeze({ now: () => new Date() });
13
15
 
14
16
  /**
@@ -64,6 +66,62 @@ export default class PageService {
64
66
  });
65
67
  }
66
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
+
67
125
  /**
68
126
  * @param {{ handle: PageHandle|string|object }} options
69
127
  * @returns {AsyncIterable<Uint8Array>}
@@ -160,10 +218,25 @@ export default class PageService {
160
218
  return now.toISOString();
161
219
  }
162
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
+
163
232
  static async #collect(source, maxBytes) {
233
+ return await PageService.#collectWithOverflow(source, maxBytes, PageService.#tooLarge);
234
+ }
235
+
236
+ static async #collectWithOverflow(source, maxBytes, overflow) {
164
237
  if (isBytes(source)) {
165
238
  if (source.length > maxBytes) {
166
- throw PageService.#tooLarge(source.length, maxBytes);
239
+ throw overflow(source.length, maxBytes);
167
240
  }
168
241
  return new Uint8Array(source);
169
242
  }
@@ -187,7 +260,7 @@ export default class PageService {
187
260
  }
188
261
  total += bytes.length;
189
262
  if (total > maxBytes) {
190
- throw PageService.#tooLarge(total, maxBytes);
263
+ throw overflow(total, maxBytes);
191
264
  }
192
265
  chunks.push(bytes);
193
266
  }
@@ -201,6 +274,14 @@ export default class PageService {
201
274
  });
202
275
  }
203
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
+
204
285
  static #assertLimit(value, label) {
205
286
  if (!Number.isSafeInteger(value) || value < 0) {
206
287
  throw createCasError(`${label} must be a non-negative safe integer`, ErrorCodes.INVALID_OPTIONS, {
@@ -217,6 +298,21 @@ export default class PageService {
217
298
  }
218
299
  }
219
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
+
220
316
  static #assertDependencies(persistence, clock) {
221
317
  const methods = ['writeBlob', 'readBlobStream', 'readObjectType', 'readObjectSize'];
222
318
  if (!persistence || methods.some((method) => typeof persistence[method] !== 'function')) {
@@ -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
+ }