@git-stunts/git-cas 3.1.0 → 4.0.1

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.
package/index.js CHANGED
@@ -3,8 +3,10 @@
3
3
  * @fileoverview Content Addressable Store - Managed blob storage in Git.
4
4
  */
5
5
 
6
- import { createReadStream, writeFileSync } from 'node:fs';
6
+ import { createReadStream, createWriteStream } from 'node:fs';
7
7
  import path from 'node:path';
8
+ import { Readable, Transform } from 'node:stream';
9
+ import { pipeline } from 'node:stream/promises';
8
10
  import CasService from './src/domain/services/CasService.js';
9
11
  import VaultService from './src/domain/services/VaultService.js';
10
12
  import GitPersistenceAdapter from './src/infrastructure/adapters/GitPersistenceAdapter.js';
@@ -13,8 +15,12 @@ import NodeCryptoAdapter from './src/infrastructure/adapters/NodeCryptoAdapter.j
13
15
  import Manifest from './src/domain/value-objects/Manifest.js';
14
16
  import Chunk from './src/domain/value-objects/Chunk.js';
15
17
  import CryptoPort from './src/ports/CryptoPort.js';
18
+ import ObservabilityPort from './src/ports/ObservabilityPort.js';
16
19
  import JsonCodec from './src/infrastructure/codecs/JsonCodec.js';
17
20
  import CborCodec from './src/infrastructure/codecs/CborCodec.js';
21
+ import SilentObserver from './src/infrastructure/adapters/SilentObserver.js';
22
+ import EventEmitterObserver from './src/infrastructure/adapters/EventEmitterObserver.js';
23
+ import StatsCollector from './src/infrastructure/adapters/StatsCollector.js';
18
24
 
19
25
  export {
20
26
  CasService,
@@ -23,10 +29,14 @@ export {
23
29
  GitRefAdapter,
24
30
  NodeCryptoAdapter,
25
31
  CryptoPort,
32
+ ObservabilityPort,
26
33
  Manifest,
27
34
  Chunk,
28
35
  JsonCodec,
29
- CborCodec
36
+ CborCodec,
37
+ SilentObserver,
38
+ EventEmitterObserver,
39
+ StatsCollector,
30
40
  };
31
41
 
32
42
  /**
@@ -58,16 +68,20 @@ export default class ContentAddressableStore {
58
68
  * @param {number} [options.chunkSize] - Chunk size in bytes (default 256 KiB).
59
69
  * @param {import('./src/ports/CodecPort.js').default} [options.codec] - Manifest codec (default JsonCodec).
60
70
  * @param {import('./src/ports/CryptoPort.js').default} [options.crypto] - Crypto adapter (auto-detected if omitted).
71
+ * @param {import('./src/ports/ObservabilityPort.js').default} [options.observability] - Observability adapter (SilentObserver if omitted).
61
72
  * @param {import('@git-stunts/alfred').Policy} [options.policy] - Resilience policy for Git I/O.
62
73
  * @param {number} [options.merkleThreshold=1000] - Chunk count threshold for Merkle manifests.
74
+ * @param {number} [options.concurrency=1] - Maximum parallel chunk I/O operations.
63
75
  */
64
- constructor({ plumbing, chunkSize, codec, policy, crypto, merkleThreshold }) {
76
+ constructor({ plumbing, chunkSize, codec, policy, crypto, observability, merkleThreshold, concurrency }) {
65
77
  this.plumbing = plumbing;
66
78
  this.chunkSizeConfig = chunkSize;
67
79
  this.codecConfig = codec;
68
80
  this.policyConfig = policy;
69
81
  this.cryptoConfig = crypto;
82
+ this.observabilityConfig = observability;
70
83
  this.merkleThresholdConfig = merkleThreshold;
84
+ this.concurrencyConfig = concurrency;
71
85
  this.service = null;
72
86
  this.#servicePromise = null;
73
87
  }
@@ -104,7 +118,9 @@ export default class ContentAddressableStore {
104
118
  chunkSize: this.chunkSizeConfig,
105
119
  codec: this.codecConfig || new JsonCodec(),
106
120
  crypto,
121
+ observability: this.observabilityConfig || new SilentObserver(),
107
122
  merkleThreshold: this.merkleThresholdConfig,
123
+ concurrency: this.concurrencyConfig,
108
124
  });
109
125
 
110
126
  const ref = new GitRefAdapter({
@@ -253,12 +269,17 @@ export default class ContentAddressableStore {
253
269
  */
254
270
  async restoreFile({ manifest, encryptionKey, passphrase, outputPath }) {
255
271
  const service = await this.#getService();
256
- const { buffer, bytesWritten } = await service.restore({
257
- manifest,
258
- encryptionKey,
259
- passphrase,
272
+ const iterable = service.restoreStream({ manifest, encryptionKey, passphrase });
273
+ const readable = Readable.from(iterable);
274
+ const writable = createWriteStream(outputPath);
275
+ let bytesWritten = 0;
276
+ const counter = new Transform({
277
+ transform(chunk, _encoding, cb) {
278
+ bytesWritten += chunk.length;
279
+ cb(null, chunk);
280
+ },
260
281
  });
261
- writeFileSync(outputPath, buffer);
282
+ await pipeline(readable, counter, writable);
262
283
  return { bytesWritten };
263
284
  }
264
285
 
@@ -275,6 +296,19 @@ export default class ContentAddressableStore {
275
296
  return await service.restore(options);
276
297
  }
277
298
 
299
+ /**
300
+ * Restores a file from its manifest as an async iterable of Buffer chunks.
301
+ * @param {Object} options
302
+ * @param {import('./src/domain/value-objects/Manifest.js').default} options.manifest - The file manifest.
303
+ * @param {Buffer} [options.encryptionKey] - 32-byte key, required if manifest is encrypted.
304
+ * @param {string} [options.passphrase] - Passphrase for KDF-based decryption.
305
+ * @returns {AsyncIterable<Buffer>}
306
+ */
307
+ async *restoreStream(options) {
308
+ const service = await this.#getService();
309
+ yield* service.restoreStream(options);
310
+ }
311
+
278
312
  /**
279
313
  * Creates a Git tree object from a manifest.
280
314
  * @param {Object} options
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@git-stunts/git-cas",
3
- "version": "3.1.0",
3
+ "version": "4.0.1",
4
4
  "description": "Content-addressed storage backed by Git's object database, with optional encryption and pluggable codecs",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -3,7 +3,6 @@
3
3
  * Domain service for Content Addressable Storage operations.
4
4
  */
5
5
 
6
- import { EventEmitter } from "node:events";
7
6
  import Manifest from "../value-objects/Manifest.js";
8
7
  import type { EncryptionMeta, CompressionMeta, KdfParams } from "../value-objects/Manifest.js";
9
8
 
@@ -40,13 +39,22 @@ export interface GitPersistencePort {
40
39
  ): Promise<Array<{ mode: string; type: string; oid: string; name: string }>>;
41
40
  }
42
41
 
42
+ /** Port interface for observability (metrics, logging, tracing). */
43
+ export interface ObservabilityPort {
44
+ metric(channel: string, data: Record<string, unknown>): void;
45
+ log(level: "debug" | "info" | "warn" | "error", msg: string, meta?: Record<string, unknown>): void;
46
+ span(name: string): { end(meta?: Record<string, unknown>): void };
47
+ }
48
+
43
49
  /** Constructor options for {@link CasService}. */
44
50
  export interface CasServiceOptions {
45
51
  persistence: GitPersistencePort;
46
52
  codec: CodecPort;
47
53
  crypto: CryptoPort;
54
+ observability: ObservabilityPort;
48
55
  chunkSize?: number;
49
56
  merkleThreshold?: number;
57
+ concurrency?: number;
50
58
  }
51
59
 
52
60
  /** Options for key derivation. */
@@ -74,12 +82,14 @@ export interface DeriveKeyResult {
74
82
  * Provides chunking, encryption, and integrity verification for storing
75
83
  * arbitrary data in Git's object database.
76
84
  */
77
- export default class CasService extends EventEmitter {
85
+ export default class CasService {
78
86
  readonly persistence: GitPersistencePort;
79
87
  readonly codec: CodecPort;
80
88
  readonly crypto: CryptoPort;
89
+ readonly observability: ObservabilityPort;
81
90
  readonly chunkSize: number;
82
91
  readonly merkleThreshold: number;
92
+ readonly concurrency: number;
83
93
 
84
94
  constructor(options: CasServiceOptions);
85
95
 
@@ -112,6 +122,12 @@ export default class CasService extends EventEmitter {
112
122
  passphrase?: string;
113
123
  }): Promise<{ buffer: Buffer; bytesWritten: number }>;
114
124
 
125
+ restoreStream(options: {
126
+ manifest: Manifest;
127
+ encryptionKey?: Buffer;
128
+ passphrase?: string;
129
+ }): AsyncIterable<Buffer>;
130
+
115
131
  readManifest(options: { treeOid: string }): Promise<Manifest>;
116
132
 
117
133
  deleteAsset(options: {
@@ -3,12 +3,12 @@
3
3
  * @fileoverview Domain service for Content Addressable Storage operations.
4
4
  * @module
5
5
  */
6
- import { EventEmitter } from 'node:events';
7
6
  import { gunzip, createGzip } from 'node:zlib';
8
7
  import { Readable } from 'node:stream';
9
8
  import { promisify } from 'node:util';
10
9
  import Manifest from '../value-objects/Manifest.js';
11
10
  import CasError from '../errors/CasError.js';
11
+ import Semaphore from './Semaphore.js';
12
12
 
13
13
  const gunzipAsync = promisify(gunzip);
14
14
 
@@ -16,39 +16,53 @@ const gunzipAsync = promisify(gunzip);
16
16
  * Domain service for Content Addressable Storage operations.
17
17
  *
18
18
  * Provides chunking, encryption, and integrity verification for storing
19
- * arbitrary data in Git's object database. Extends {@link EventEmitter} to
20
- * emit progress events during store/restore operations.
21
- *
22
- * @fires CasService#chunk:stored
23
- * @fires CasService#chunk:restored
24
- * @fires CasService#file:stored
25
- * @fires CasService#file:restored
26
- * @fires CasService#integrity:pass
27
- * @fires CasService#integrity:fail
28
- * @fires CasService#error
19
+ * arbitrary data in Git's object database.
29
20
  */
30
- export default class CasService extends EventEmitter {
21
+ export default class CasService {
31
22
  /**
32
23
  * @param {Object} options
33
24
  * @param {import('../../ports/GitPersistencePort.js').default} options.persistence
34
25
  * @param {import('../../ports/CodecPort.js').default} options.codec
35
26
  * @param {import('../../ports/CryptoPort.js').default} options.crypto
27
+ * @param {import('../../ports/ObservabilityPort.js').default} options.observability
36
28
  * @param {number} [options.chunkSize=262144] - 256 KiB
37
29
  * @param {number} [options.merkleThreshold=1000] - Chunk count threshold for Merkle manifests.
30
+ * @param {number} [options.concurrency=1] - Maximum parallel chunk I/O operations.
38
31
  */
39
- constructor({ persistence, codec, crypto, chunkSize = 256 * 1024, merkleThreshold = 1000 }) {
40
- super();
32
+ constructor({ persistence, codec, crypto, observability, chunkSize = 256 * 1024, merkleThreshold = 1000, concurrency = 1 }) {
33
+ CasService._validateObservability(observability);
41
34
  if (chunkSize < 1024) {
42
35
  throw new Error('Chunk size must be at least 1024 bytes');
43
36
  }
44
37
  this.persistence = persistence;
45
38
  this.codec = codec;
46
39
  this.crypto = crypto;
40
+ this.observability = observability;
47
41
  this.chunkSize = chunkSize;
48
42
  if (!Number.isInteger(merkleThreshold) || merkleThreshold < 1) {
49
43
  throw new Error('Merkle threshold must be a positive integer');
50
44
  }
51
45
  this.merkleThreshold = merkleThreshold;
46
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
47
+ throw new Error('Concurrency must be a positive integer');
48
+ }
49
+ this.concurrency = concurrency;
50
+ }
51
+
52
+ /**
53
+ * Validates that observability implements ObservabilityPort.
54
+ * @private
55
+ * @param {*} observability
56
+ */
57
+ static _validateObservability(observability) {
58
+ if (
59
+ !observability ||
60
+ typeof observability.metric !== 'function' ||
61
+ typeof observability.log !== 'function' ||
62
+ typeof observability.span !== 'function'
63
+ ) {
64
+ throw new Error('observability must implement ObservabilityPort');
65
+ }
52
66
  }
53
67
 
54
68
  /**
@@ -62,18 +76,17 @@ export default class CasService extends EventEmitter {
62
76
  }
63
77
 
64
78
  /**
65
- * Stores a single buffer chunk in Git and appends its metadata to the manifest.
79
+ * Stores a single buffer chunk in Git, returning its metadata.
66
80
  * @private
67
81
  * @param {Buffer} buf - The chunk data to store.
68
- * @param {Object} manifestData - Mutable manifest accumulator.
82
+ * @param {number} index - Chunk index.
83
+ * @returns {Promise<{ index: number, size: number, digest: string, blob: string }>}
69
84
  */
70
- async _storeChunk(buf, manifestData) {
85
+ async _storeChunk(buf, index) {
71
86
  const digest = await this._sha256(buf);
72
87
  const blob = await this.persistence.writeBlob(buf);
73
- const entry = { index: manifestData.chunks.length, size: buf.length, digest, blob };
74
- manifestData.chunks.push(entry);
75
- manifestData.size += buf.length;
76
- this.emit('chunk:stored', { index: entry.index, size: entry.size, digest, blob });
88
+ this.observability.metric('chunk', { action: 'stored', index, size: buf.length, digest, blob });
89
+ return { index, size: buf.length, digest, blob };
77
90
  }
78
91
 
79
92
  /**
@@ -85,53 +98,51 @@ export default class CasService extends EventEmitter {
85
98
  */
86
99
  async _chunkAndStore(source, manifestData) {
87
100
  let buffer = Buffer.alloc(0);
101
+ const sem = new Semaphore(this.concurrency);
102
+ const pending = [];
103
+ let nextIndex = 0;
104
+
105
+ const launchWrite = (buf, idx) => {
106
+ const p = sem.acquire().then(async () => {
107
+ try {
108
+ return await this._storeChunk(buf, idx);
109
+ } finally {
110
+ sem.release();
111
+ }
112
+ });
113
+ pending.push(p);
114
+ };
88
115
 
89
116
  try {
90
117
  for await (const chunk of source) {
91
118
  buffer = Buffer.concat([buffer, chunk]);
92
119
  while (buffer.length >= this.chunkSize) {
93
- await this._storeChunk(buffer.slice(0, this.chunkSize), manifestData);
120
+ launchWrite(buffer.slice(0, this.chunkSize), nextIndex++);
94
121
  buffer = buffer.slice(this.chunkSize);
95
122
  }
96
123
  }
97
124
  } catch (err) {
125
+ await Promise.allSettled(pending);
98
126
  if (err instanceof CasError) { throw err; }
99
127
  const casErr = new CasError(
100
128
  `Stream error during store: ${err.message}`,
101
129
  'STREAM_ERROR',
102
- { chunksWritten: manifestData.chunks.length, originalError: err },
130
+ { chunksDispatched: nextIndex, originalError: err },
103
131
  );
104
- if (this.listenerCount('error') > 0) {
105
- this.emit('error', { code: casErr.code, message: casErr.message });
106
- }
132
+ await Promise.allSettled(pending);
133
+ this.observability.metric('error', { code: casErr.code, message: casErr.message });
107
134
  throw casErr;
108
135
  }
109
136
 
110
137
  if (buffer.length > 0) {
111
- await this._storeChunk(buffer, manifestData);
138
+ launchWrite(buffer, nextIndex++);
112
139
  }
113
- }
114
140
 
115
- /**
116
- * Validates that an encryption key is a 32-byte Buffer or Uint8Array.
117
- * @private
118
- * @param {*} key
119
- * @throws {CasError} INVALID_KEY_TYPE if key is not a Buffer
120
- * @throws {CasError} INVALID_KEY_LENGTH if key is not 32 bytes
121
- */
122
- _validateKey(key) {
123
- if (!Buffer.isBuffer(key) && !(key instanceof Uint8Array)) {
124
- throw new CasError(
125
- 'Encryption key must be a Buffer or Uint8Array',
126
- 'INVALID_KEY_TYPE',
127
- );
128
- }
129
- if (key.length !== 32) {
130
- throw new CasError(
131
- `Encryption key must be 32 bytes, got ${key.length}`,
132
- 'INVALID_KEY_LENGTH',
133
- { expected: 32, actual: key.length },
134
- );
141
+ const results = await Promise.all(pending);
142
+ results.sort((a, b) => a.index - b.index);
143
+ for (const entry of results) {
144
+ manifestData.chunks.push(entry);
145
+ manifestData.size += entry.size;
135
146
  }
136
147
  }
137
148
 
@@ -144,7 +155,6 @@ export default class CasService extends EventEmitter {
144
155
  * @throws {CasError} INVALID_KEY_TYPE | INVALID_KEY_LENGTH if the key is invalid.
145
156
  */
146
157
  async encrypt({ buffer, key }) {
147
- this._validateKey(key);
148
158
  return await this.crypto.encryptBuffer(buffer, key);
149
159
  }
150
160
 
@@ -238,7 +248,7 @@ export default class CasService extends EventEmitter {
238
248
  }
239
249
 
240
250
  if (encryptionKey) {
241
- this._validateKey(encryptionKey);
251
+ this.crypto._validateKey(encryptionKey);
242
252
  }
243
253
 
244
254
  const manifestData = { slug, filename, size: 0, chunks: [] };
@@ -262,8 +272,8 @@ export default class CasService extends EventEmitter {
262
272
  }
263
273
 
264
274
  const manifest = new Manifest(manifestData);
265
- this.emit('file:stored', {
266
- slug, size: manifest.size, chunkCount: manifest.chunks.length, encrypted: !!encryptionKey,
275
+ this.observability.metric('file', {
276
+ action: 'stored', slug, size: manifest.size, chunkCount: manifest.chunks.length, encrypted: !!encryptionKey,
267
277
  });
268
278
  return manifest;
269
279
  }
@@ -366,13 +376,11 @@ export default class CasService extends EventEmitter {
366
376
  'INTEGRITY_ERROR',
367
377
  { chunkIndex: chunk.index, expected: chunk.digest, actual: digest },
368
378
  );
369
- if (this.listenerCount('error') > 0) {
370
- this.emit('error', { code: err.code, message: err.message });
371
- }
379
+ this.observability.metric('error', { code: err.code, message: err.message });
372
380
  throw err;
373
381
  }
374
382
  buffers.push(blob);
375
- this.emit('chunk:restored', { index: chunk.index, size: blob.length, digest: chunk.digest });
383
+ this.observability.metric('chunk', { action: 'restored', index: chunk.index, size: blob.length, digest: chunk.digest });
376
384
  }
377
385
  return buffers;
378
386
  }
@@ -414,7 +422,7 @@ export default class CasService extends EventEmitter {
414
422
  );
415
423
  }
416
424
  if (encryptionKey) {
417
- this._validateKey(encryptionKey);
425
+ this.crypto._validateKey(encryptionKey);
418
426
  } else if (manifest.encryption?.encrypted) {
419
427
  throw new CasError('Encryption key required to restore encrypted content', 'MISSING_KEY');
420
428
  }
@@ -436,12 +444,56 @@ export default class CasService extends EventEmitter {
436
444
  * @throws {CasError} INTEGRITY_ERROR if chunk verification or decryption fails.
437
445
  */
438
446
  async restore({ manifest, encryptionKey, passphrase }) {
447
+ const chunks = [];
448
+ for await (const chunk of this.restoreStream({ manifest, encryptionKey, passphrase })) {
449
+ chunks.push(chunk);
450
+ }
451
+ const buffer = Buffer.concat(chunks);
452
+ return { buffer, bytesWritten: buffer.length };
453
+ }
454
+
455
+ /**
456
+ * Restores a file from its manifest as an async iterable of Buffer chunks.
457
+ *
458
+ * For unencrypted, uncompressed files this is true per-chunk streaming
459
+ * with O(chunkSize) memory. For encrypted or compressed files, all chunks
460
+ * are buffered internally for decryption/decompression, then yielded.
461
+ *
462
+ * @param {Object} options
463
+ * @param {import('../value-objects/Manifest.js').default} options.manifest - The file manifest.
464
+ * @param {Buffer} [options.encryptionKey] - 32-byte key, required if manifest is encrypted.
465
+ * @param {string} [options.passphrase] - Passphrase for KDF-based decryption.
466
+ * Note: For unencrypted files, each yielded buffer corresponds to an original
467
+ * stored chunk. For encrypted/compressed files, yielded buffers are
468
+ * chunkSize-sliced pieces of the decrypted/decompressed result and may not
469
+ * correspond 1:1 to the original chunks.
470
+ *
471
+ * @yields {Buffer}
472
+ * @throws {CasError} MISSING_KEY if manifest is encrypted but no key is provided.
473
+ * @throws {CasError} INTEGRITY_ERROR if chunk verification or decryption fails.
474
+ */
475
+ async *restoreStream({ manifest, encryptionKey, passphrase }) {
439
476
  const key = await this._resolveEncryptionKey(manifest, encryptionKey, passphrase);
440
477
 
441
478
  if (manifest.chunks.length === 0) {
442
- return { buffer: Buffer.alloc(0), bytesWritten: 0 };
479
+ this.observability.metric('file', {
480
+ action: 'restored', slug: manifest.slug, size: 0, chunkCount: 0,
481
+ });
482
+ return;
483
+ }
484
+
485
+ if (manifest.encryption?.encrypted || manifest.compression) {
486
+ yield* this._restoreBuffered(manifest, key);
487
+ } else {
488
+ yield* this._restoreStreaming(manifest);
443
489
  }
490
+ }
444
491
 
492
+ /**
493
+ * Buffered restore path for encrypted/compressed manifests.
494
+ * @private
495
+ */
496
+ async *_restoreBuffered(manifest, key) {
445
497
  let buffer = Buffer.concat(await this._readAndVerifyChunks(manifest.chunks));
446
498
 
447
499
  if (manifest.encryption?.encrypted) {
@@ -449,18 +501,78 @@ export default class CasService extends EventEmitter {
449
501
  }
450
502
 
451
503
  if (manifest.compression) {
452
- try {
453
- buffer = await gunzipAsync(buffer);
454
- } catch (err) {
455
- if (err instanceof CasError) { throw err; }
456
- throw new CasError(`Decompression failed: ${err.message}`, 'INTEGRITY_ERROR', { originalError: err });
504
+ buffer = await this._decompress(buffer);
505
+ }
506
+
507
+ this.observability.metric('file', {
508
+ action: 'restored', slug: manifest.slug, size: buffer.length, chunkCount: manifest.chunks.length,
509
+ });
510
+
511
+ for (let offset = 0; offset < buffer.length; offset += this.chunkSize) {
512
+ yield buffer.subarray(offset, offset + this.chunkSize);
513
+ }
514
+ }
515
+
516
+ /**
517
+ * Per-chunk streaming restore with read-ahead.
518
+ * @private
519
+ */
520
+ async *_restoreStreaming(manifest) {
521
+ const chunks = manifest.chunks;
522
+ const readAhead = this.concurrency;
523
+ let totalSize = 0;
524
+
525
+ const readAndVerify = async (chunk) => {
526
+ const blob = await this.persistence.readBlob(chunk.blob);
527
+ const digest = await this._sha256(blob);
528
+ if (digest !== chunk.digest) {
529
+ const err = new CasError(
530
+ `Chunk ${chunk.index} integrity check failed`,
531
+ 'INTEGRITY_ERROR',
532
+ { chunkIndex: chunk.index, expected: chunk.digest, actual: digest },
533
+ );
534
+ this.observability.metric('error', { code: err.code, message: err.message });
535
+ throw err;
536
+ }
537
+ return blob;
538
+ };
539
+
540
+ const ahead = [];
541
+ for (let i = 0; i < Math.min(readAhead, chunks.length); i++) {
542
+ ahead.push(readAndVerify(chunks[i]));
543
+ }
544
+
545
+ try {
546
+ for (let i = 0; i < chunks.length; i++) {
547
+ const blob = await ahead[i % readAhead];
548
+ this.observability.metric('chunk', { action: 'restored', index: chunks[i].index, size: blob.length, digest: chunks[i].digest });
549
+ totalSize += blob.length;
550
+ const nextIdx = i + readAhead;
551
+ if (nextIdx < chunks.length) {
552
+ ahead[i % readAhead] = readAndVerify(chunks[nextIdx]);
553
+ }
554
+ yield blob;
457
555
  }
556
+ } finally {
557
+ await Promise.allSettled(ahead);
458
558
  }
459
559
 
460
- this.emit('file:restored', {
461
- slug: manifest.slug, size: buffer.length, chunkCount: manifest.chunks.length,
560
+ this.observability.metric('file', {
561
+ action: 'restored', slug: manifest.slug, size: totalSize, chunkCount: chunks.length,
462
562
  });
463
- return { buffer, bytesWritten: buffer.length };
563
+ }
564
+
565
+ /**
566
+ * Decompresses a gzip buffer.
567
+ * @private
568
+ */
569
+ async _decompress(buffer) {
570
+ try {
571
+ return await gunzipAsync(buffer);
572
+ } catch (err) {
573
+ if (err instanceof CasError) { throw err; }
574
+ throw new CasError(`Decompression failed: ${err.message}`, 'INTEGRITY_ERROR', { originalError: err });
575
+ }
464
576
  }
465
577
 
466
578
  /**
@@ -619,13 +731,13 @@ export default class CasService extends EventEmitter {
619
731
  const blob = await this.persistence.readBlob(chunk.blob);
620
732
  const digest = await this._sha256(blob);
621
733
  if (digest !== chunk.digest) {
622
- this.emit('integrity:fail', {
623
- slug: manifest.slug, chunkIndex: chunk.index, expected: chunk.digest, actual: digest,
734
+ this.observability.metric('integrity', {
735
+ action: 'fail', slug: manifest.slug, chunkIndex: chunk.index, expected: chunk.digest, actual: digest,
624
736
  });
625
737
  return false;
626
738
  }
627
739
  }
628
- this.emit('integrity:pass', { slug: manifest.slug });
740
+ this.observability.metric('integrity', { action: 'pass', slug: manifest.slug });
629
741
  return true;
630
742
  }
631
743
  }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Counting semaphore for limiting concurrency.
3
+ */
4
+ export default class Semaphore {
5
+ #max;
6
+ #active = 0;
7
+ #queue = [];
8
+
9
+ /**
10
+ * @param {number} concurrency - Maximum concurrent permits.
11
+ */
12
+ constructor(concurrency) {
13
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
14
+ throw new Error('Semaphore concurrency must be a positive integer');
15
+ }
16
+ this.#max = concurrency;
17
+ }
18
+
19
+ /**
20
+ * Acquire a permit, waiting if necessary.
21
+ * @returns {Promise<void>}
22
+ */
23
+ acquire() {
24
+ if (this.#active < this.#max) {
25
+ this.#active++;
26
+ return Promise.resolve();
27
+ }
28
+ return new Promise((resolve) => {
29
+ this.#queue.push(resolve);
30
+ });
31
+ }
32
+
33
+ /**
34
+ * Release a permit.
35
+ */
36
+ release() {
37
+ if (this.#queue.length > 0) {
38
+ const next = this.#queue.shift();
39
+ next();
40
+ } else {
41
+ if (this.#active === 0) {
42
+ throw new Error('Semaphore release called without an active permit');
43
+ }
44
+ this.#active--;
45
+ }
46
+ }
47
+ }