@git-stunts/git-cas 6.5.7 → 6.5.9

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 (37) hide show
  1. package/ARCHITECTURE.md +9 -0
  2. package/CHANGELOG.md +39 -0
  3. package/GUIDE.md +54 -0
  4. package/README.md +17 -9
  5. package/UPGRADING.md +68 -0
  6. package/build-info.json +2 -2
  7. package/docs/API.md +115 -12
  8. package/docs/releases/v6.5.8.md +89 -0
  9. package/docs/releases/v6.5.9.md +119 -0
  10. package/index.d.ts +75 -0
  11. package/index.js +19 -1
  12. package/package.json +4 -2
  13. package/src/domain/services/AssetService.js +201 -10
  14. package/src/domain/services/BoundedWriteWavePersistence.js +235 -0
  15. package/src/domain/services/BundleBatchPlanner.js +349 -0
  16. package/src/domain/services/BundleService.js +225 -2
  17. package/src/domain/services/CasService.d.ts +16 -0
  18. package/src/domain/services/CasService.js +9 -18
  19. package/src/domain/services/ManifestRepository.js +129 -50
  20. package/src/domain/services/ManifestTreeService.js +47 -0
  21. package/src/domain/services/PageService.js +36 -10
  22. package/src/domain/services/RootSet.js +32 -0
  23. package/src/domain/services/RootSetPersistence.js +58 -1
  24. package/src/domain/services/StagedTarget.js +19 -0
  25. package/src/domain/services/StagingWorkspace.js +95 -20
  26. package/src/domain/services/StagingWorkspaceRegistry.js +9 -4
  27. package/src/domain/services/WorkspaceCompoundAdmission.js +61 -0
  28. package/src/domain/services/WorkspaceCompoundScope.js +193 -0
  29. package/src/domain/services/forkCasPersistence.js +20 -0
  30. package/src/infrastructure/adapters/GitObjectSessionPool.js +47 -5
  31. package/src/infrastructure/adapters/GitPersistenceAdapter.js +169 -0
  32. package/src/infrastructure/adapters/GitPersistenceWriteScope.js +154 -0
  33. package/src/infrastructure/adapters/GitRefAdapter.js +38 -3
  34. package/src/infrastructure/adapters/GitUpdateRefSessionPool.js +115 -0
  35. package/src/package-version.js +1 -1
  36. package/src/ports/GitPersistencePort.js +43 -0
  37. package/src/ports/GitRefPort.js +8 -0
@@ -0,0 +1,193 @@
1
+ import createCasError from '../errors/createCasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+
4
+ export const DEFAULT_WORKSPACE_COMPOUND_OPERATIONS = 64;
5
+ export const MAX_WORKSPACE_COMPOUND_OPERATIONS = 1_024;
6
+
7
+ /** Bounded provisional page and bundle writes owned by one compound admission. */
8
+ export default class WorkspaceCompoundScope {
9
+ #active = true;
10
+ #abortFailure;
11
+ #aborted = false;
12
+ #bundles;
13
+ #failed = false;
14
+ #failure;
15
+ #maxOperations;
16
+ #operationCount = 0;
17
+ #overflowFailure = null;
18
+ #pages;
19
+ #persistence;
20
+ #staged = [];
21
+ #tail = Promise.resolve();
22
+
23
+ constructor({ pages, bundles, persistence, maxOperations }) {
24
+ WorkspaceCompoundScope.#assertDependencies({ pages, bundles, persistence });
25
+ this.#pages = pages;
26
+ this.#bundles = bundles;
27
+ this.#persistence = persistence;
28
+ this.#maxOperations = WorkspaceCompoundScope.#operationLimit(maxOperations);
29
+ this.api = Object.freeze({
30
+ pages: Object.freeze({
31
+ putBatch: (options) =>
32
+ this.#enqueue('pages.putBatch', async () => await this.#putPages(options)),
33
+ }),
34
+ bundles: Object.freeze({
35
+ putOrderedBatch: (options) =>
36
+ this.#enqueue('bundles.putOrderedBatch', async () => await this.#putBundles(options)),
37
+ }),
38
+ });
39
+ Object.freeze(this);
40
+ }
41
+
42
+ async execute(operation) {
43
+ if (typeof operation !== 'function') {
44
+ throw createCasError(
45
+ 'Workspace compound admission requires an operation callback',
46
+ ErrorCodes.INVALID_OPTIONS
47
+ );
48
+ }
49
+ let value;
50
+ let callbackError;
51
+ let callbackFailed = false;
52
+ try {
53
+ value = await operation(this.api);
54
+ } catch (error) {
55
+ callbackFailed = true;
56
+ callbackError = error;
57
+ this.#aborted = true;
58
+ this.#abortFailure = error;
59
+ }
60
+ this.#active = false;
61
+ await this.#tail;
62
+ if (callbackFailed && this.#failed && callbackError !== this.#failure) {
63
+ throw new AggregateError(
64
+ [callbackError, this.#failure],
65
+ 'Workspace compound callback and staged operation both failed'
66
+ );
67
+ }
68
+ if (callbackFailed) {
69
+ throw callbackError;
70
+ }
71
+ if (this.#failed) {
72
+ throw this.#failure;
73
+ }
74
+ if (this.#staged.length === 0) {
75
+ throw createCasError(
76
+ 'Workspace compound admission staged no handles',
77
+ ErrorCodes.INVALID_OPTIONS
78
+ );
79
+ }
80
+ return Object.freeze({
81
+ value,
82
+ staged: Object.freeze([...this.#staged]),
83
+ operationCount: this.#operationCount,
84
+ });
85
+ }
86
+
87
+ #enqueue(method, operation) {
88
+ if (!this.#active) {
89
+ return Promise.reject(
90
+ createCasError('Workspace compound scope is closed', ErrorCodes.WORKSPACE_STATE_INVALID, {
91
+ method,
92
+ })
93
+ );
94
+ }
95
+ if (this.#overflowFailure !== null) {
96
+ return Promise.reject(this.#overflowFailure);
97
+ }
98
+ this.#operationCount += 1;
99
+ if (this.#operationCount > this.#maxOperations) {
100
+ this.#overflowFailure = createCasError(
101
+ 'Workspace compound operation count exceeds the configured maximum',
102
+ ErrorCodes.INVALID_OPTIONS,
103
+ {
104
+ operationCount: this.#operationCount,
105
+ maxOperations: this.#maxOperations,
106
+ method,
107
+ }
108
+ );
109
+ this.#recordFailure(this.#overflowFailure);
110
+ return Promise.reject(this.#overflowFailure);
111
+ }
112
+ const result = this.#tail.then(async () => {
113
+ if (this.#failed) {
114
+ throw this.#failure;
115
+ }
116
+ if (this.#aborted) {
117
+ throw this.#abortFailure;
118
+ }
119
+ try {
120
+ return await operation();
121
+ } catch (error) {
122
+ this.#recordFailure(error);
123
+ throw error;
124
+ }
125
+ });
126
+ this.#tail = result.then(
127
+ () => undefined,
128
+ () => undefined,
129
+ );
130
+ return result;
131
+ }
132
+
133
+ #recordFailure(error) {
134
+ if (!this.#failed) {
135
+ this.#failed = true;
136
+ this.#failure = error;
137
+ }
138
+ }
139
+
140
+ async #putPages(options) {
141
+ const staged = await this.#pages.putBatchWithPersistence(options, this.#persistence);
142
+ return this.#record(staged, 'page');
143
+ }
144
+
145
+ async #putBundles(options) {
146
+ const staged = await this.#bundles.putOrderedBatchWithPersistence(options, this.#persistence);
147
+ return this.#record(staged, 'bundle');
148
+ }
149
+
150
+ #record(staged, kind) {
151
+ if (!Array.isArray(staged) || staged.some((artifact) => !artifact?.handle)) {
152
+ throw createCasError(
153
+ `Workspace compound ${kind} batch did not return staged handles`,
154
+ ErrorCodes.WORKSPACE_STATE_INVALID,
155
+ { kind }
156
+ );
157
+ }
158
+ this.#staged.push(...staged);
159
+ return Object.freeze(staged.map((artifact) => artifact.handle));
160
+ }
161
+
162
+ static #operationLimit(value) {
163
+ const limit = value ?? DEFAULT_WORKSPACE_COMPOUND_OPERATIONS;
164
+ if (!Number.isSafeInteger(limit) || limit <= 0 || limit > MAX_WORKSPACE_COMPOUND_OPERATIONS) {
165
+ throw createCasError(
166
+ 'Workspace compound operation limit is outside the supported range',
167
+ ErrorCodes.INVALID_OPTIONS,
168
+ { maxOperations: value, hardMaximum: MAX_WORKSPACE_COMPOUND_OPERATIONS }
169
+ );
170
+ }
171
+ return limit;
172
+ }
173
+
174
+ static #assertDependencies({ pages, bundles, persistence }) {
175
+ const missing = [
176
+ ['pages.putBatchWithPersistence', typeof pages?.putBatchWithPersistence !== 'function'],
177
+ [
178
+ 'bundles.putOrderedBatchWithPersistence',
179
+ typeof bundles?.putOrderedBatchWithPersistence !== 'function',
180
+ ],
181
+ ['persistence', persistence === null || typeof persistence !== 'object'],
182
+ ]
183
+ .filter(([, absent]) => absent)
184
+ .map(([name]) => name);
185
+ if (missing.length > 0) {
186
+ throw createCasError(
187
+ 'Workspace compound scope requires complete dependencies',
188
+ ErrorCodes.INVALID_OPTIONS,
189
+ { missing }
190
+ );
191
+ }
192
+ }
193
+ }
@@ -0,0 +1,20 @@
1
+ import CasService from './CasService.js';
2
+
3
+ /** Creates an operation-local CAS facade over another persistence port. */
4
+ export default function forkCasPersistence(cas, persistence) {
5
+ return new CasService({
6
+ persistence,
7
+ codec: cas.codec,
8
+ crypto: cas.crypto,
9
+ observability: cas.observability,
10
+ chunkSize: cas.chunkSize,
11
+ merkleThreshold: cas.merkleThreshold,
12
+ concurrency: cas.concurrency,
13
+ chunker: cas.chunker,
14
+ maxRestoreBufferSize: cas.maxRestoreBufferSize,
15
+ maxBlobSize: cas.maxBlobSize,
16
+ compressionAdapter: cas.compressionAdapter,
17
+ formatVersion: cas.formatVersion,
18
+ legacyMode: cas.legacyMode,
19
+ });
20
+ }
@@ -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
+ }