@git-stunts/git-cas 4.0.1 → 5.0.0

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/CHANGELOG.md CHANGED
@@ -5,6 +5,28 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [5.0.0] — Hydra (2026-02-28)
9
+
10
+ ### Breaking Changes
11
+ - **`CasService` constructor accepts `chunker` port** — a new optional `ChunkingPort` parameter controls chunking strategy. Existing code that does not pass `chunker` is unaffected (defaults to `FixedChunker`).
12
+ - **Major version bump** — new hexagonal port (`ChunkingPort`) and manifest schema extension warrant a semver-major release for downstream tooling awareness.
13
+
14
+ ### Added
15
+ - **Content-defined chunking (CDC)** — Buzhash rolling-hash engine with configurable `minChunkSize` (64 KiB), `maxChunkSize` (1 MiB), and `targetChunkSize` (256 KiB). CDC limits the dedup blast radius to 1–2 chunks on incremental edits vs. total invalidation with fixed-size chunking. Benchmarked at 265 MB/s and 98.4% chunk reuse on small edits.
16
+ - **`ChunkingPort`** — new hexagonal port (`src/ports/ChunkingPort.js`) with `async *chunk(source)`, `strategy`, and `params`. Abstracts chunking behind a pluggable interface.
17
+ - **`FixedChunker`** — adapter wrapping existing fixed-size buffer slicing behind `ChunkingPort`.
18
+ - **`CdcChunker`** — adapter wrapping the buzhash CDC engine behind `ChunkingPort`.
19
+ - **`chunking` manifest field** — optional `{ strategy: 'fixed' | 'cdc', params: {...} }` metadata in manifests. Fixed-strategy manifests omit the field for full backward compatibility.
20
+ - **`ChunkingSchema`** — Zod discriminated union (`FixedChunkingSchema` + `CdcChunkingSchema`) for manifest validation.
21
+ - **`INVALID_CHUNKING_STRATEGY` error code** — thrown when an unrecognized chunking strategy is encountered in a manifest.
22
+ - **Facade `chunking` config** — `ContentAddressableStore` constructor accepts `chunking: { strategy, ... }` declarative config or a raw `chunker` port instance.
23
+ - **CDC benchmarks** (`test/benchmark/chunking.bench.js`) — throughput and dedup efficiency comparison.
24
+ - 90 new unit tests (709 total).
25
+
26
+ ### Changed
27
+ - `CasService._chunkAndStore()` refactored to delegate to `ChunkingPort` instead of inline buffer slicing.
28
+ - `ChunkingPort`, `FixedChunker`, `CdcChunker` exported from the main entry point.
29
+
8
30
  ## [4.0.1] — M8 Spit Shine + M9 Cockpit (2026-02-28)
9
31
 
10
32
  ### Added
package/README.md CHANGED
@@ -44,6 +44,21 @@ We use the object database.
44
44
 
45
45
  See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
46
46
 
47
+ ## What's new in v5.0.0
48
+
49
+ **Content-defined chunking (CDC)** — Fixed-size chunking invalidates every chunk after an edit. CDC uses a buzhash rolling hash to find natural boundaries, limiting the blast radius to 1–2 chunks. Benchmarked at 98.4% chunk reuse on small edits vs 32% for fixed.
50
+
51
+ ```js
52
+ const cas = new ContentAddressableStore({
53
+ plumbing,
54
+ chunking: { strategy: 'cdc', targetChunkSize: 262144, minChunkSize: 65536, maxChunkSize: 1048576 },
55
+ });
56
+ ```
57
+
58
+ **`ChunkingPort`** — new hexagonal port abstracts chunking strategy. `FixedChunker` and `CdcChunker` adapters ship out of the box. Bring your own chunker by extending `ChunkingPort`.
59
+
60
+ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
61
+
47
62
  ## What's new in v4.0.1
48
63
 
49
64
  **`git cas verify`** — verify stored asset integrity from the CLI without restoring (`git cas verify --slug my-asset`).
@@ -32,12 +32,12 @@ function formatBytes(bytes) {
32
32
  * @param {boolean} [options.quiet] - Suppress all progress output.
33
33
  * @returns {{ attach(observer: { on(event: string, fn: Function): void, removeListener(event: string, fn: Function): void }): void, detach(): void }}
34
34
  */
35
- export function createStoreProgress({ filePath, chunkSize, quiet, fileSize: providedSize }) {
35
+ export function createStoreProgress({ filePath, chunkSize, quiet, fileSize: providedSize, ctx: providedCtx }) {
36
36
  if (quiet) {
37
37
  return { attach() {}, detach() {} };
38
38
  }
39
39
 
40
- const ctx = getCliContext();
40
+ const ctx = providedCtx || getCliContext();
41
41
  if (ctx.mode === 'pipe') {
42
42
  return { attach() {}, detach() {} };
43
43
  }
@@ -60,12 +60,12 @@ export function createStoreProgress({ filePath, chunkSize, quiet, fileSize: prov
60
60
  * @param {boolean} [options.quiet] - Suppress all progress output.
61
61
  * @returns {{ attach(observer: { on(event: string, fn: Function): void, removeListener(event: string, fn: Function): void }): void, detach(): void }}
62
62
  */
63
- export function createRestoreProgress({ totalChunks, quiet }) {
63
+ export function createRestoreProgress({ totalChunks, quiet, ctx: providedCtx }) {
64
64
  if (quiet || totalChunks === 0) {
65
65
  return { attach() {}, detach() {} };
66
66
  }
67
67
 
68
- const ctx = getCliContext();
68
+ const ctx = providedCtx || getCliContext();
69
69
  if (ctx.mode === 'pipe') {
70
70
  return { attach() {}, detach() {} };
71
71
  }
package/index.d.ts CHANGED
@@ -20,6 +20,31 @@ import type {
20
20
  export { CasService, Manifest, Chunk };
21
21
  export type { EncryptionMeta, ManifestData, CompressionMeta, KdfParams, SubManifestRef, CryptoPort, CodecPort, GitPersistencePort, ObservabilityPort, CasServiceOptions, DeriveKeyOptions, DeriveKeyResult };
22
22
 
23
+ /** Abstract port for splitting a byte stream into chunks. */
24
+ export declare class ChunkingPort {
25
+ get strategy(): string;
26
+ get params(): Record<string, unknown>;
27
+ chunk(source: AsyncIterable<Buffer>): AsyncIterable<Buffer>;
28
+ }
29
+
30
+ /** Fixed-size chunking adapter. */
31
+ export declare class FixedChunker extends ChunkingPort {
32
+ constructor(options?: { chunkSize?: number });
33
+ get strategy(): "fixed";
34
+ get params(): { chunkSize: number };
35
+ }
36
+
37
+ /** Content-defined chunking adapter using buzhash rolling hash. */
38
+ export declare class CdcChunker extends ChunkingPort {
39
+ constructor(options?: {
40
+ minChunkSize?: number;
41
+ maxChunkSize?: number;
42
+ targetChunkSize?: number;
43
+ });
44
+ get strategy(): "cdc";
45
+ get params(): { target: number; min: number; max: number };
46
+ }
47
+
23
48
  /** Abstract port for cryptographic operations. */
24
49
  export declare class CryptoPortBase {
25
50
  sha256(buf: Buffer): string | Promise<string>;
@@ -125,6 +150,15 @@ export declare class StatsCollector {
125
150
  };
126
151
  }
127
152
 
153
+ /** Declarative chunking strategy configuration. */
154
+ export interface ChunkingConfig {
155
+ strategy: "fixed" | "cdc";
156
+ chunkSize?: number;
157
+ targetChunkSize?: number;
158
+ minChunkSize?: number;
159
+ maxChunkSize?: number;
160
+ }
161
+
128
162
  /** Constructor options for {@link ContentAddressableStore}. */
129
163
  export interface ContentAddressableStoreOptions {
130
164
  plumbing: unknown;
@@ -135,6 +169,8 @@ export interface ContentAddressableStoreOptions {
135
169
  policy?: unknown;
136
170
  merkleThreshold?: number;
137
171
  concurrency?: number;
172
+ chunking?: ChunkingConfig;
173
+ chunker?: ChunkingPort;
138
174
  }
139
175
 
140
176
  /** A single vault entry. */
package/index.js CHANGED
@@ -15,12 +15,15 @@ import NodeCryptoAdapter from './src/infrastructure/adapters/NodeCryptoAdapter.j
15
15
  import Manifest from './src/domain/value-objects/Manifest.js';
16
16
  import Chunk from './src/domain/value-objects/Chunk.js';
17
17
  import CryptoPort from './src/ports/CryptoPort.js';
18
+ import ChunkingPort from './src/ports/ChunkingPort.js';
18
19
  import ObservabilityPort from './src/ports/ObservabilityPort.js';
19
20
  import JsonCodec from './src/infrastructure/codecs/JsonCodec.js';
20
21
  import CborCodec from './src/infrastructure/codecs/CborCodec.js';
21
22
  import SilentObserver from './src/infrastructure/adapters/SilentObserver.js';
22
23
  import EventEmitterObserver from './src/infrastructure/adapters/EventEmitterObserver.js';
23
24
  import StatsCollector from './src/infrastructure/adapters/StatsCollector.js';
25
+ import FixedChunker from './src/infrastructure/chunkers/FixedChunker.js';
26
+ import CdcChunker from './src/infrastructure/chunkers/CdcChunker.js';
24
27
 
25
28
  export {
26
29
  CasService,
@@ -29,6 +32,7 @@ export {
29
32
  GitRefAdapter,
30
33
  NodeCryptoAdapter,
31
34
  CryptoPort,
35
+ ChunkingPort,
32
36
  ObservabilityPort,
33
37
  Manifest,
34
38
  Chunk,
@@ -37,6 +41,8 @@ export {
37
41
  SilentObserver,
38
42
  EventEmitterObserver,
39
43
  StatsCollector,
44
+ FixedChunker,
45
+ CdcChunker,
40
46
  };
41
47
 
42
48
  /**
@@ -72,8 +78,10 @@ export default class ContentAddressableStore {
72
78
  * @param {import('@git-stunts/alfred').Policy} [options.policy] - Resilience policy for Git I/O.
73
79
  * @param {number} [options.merkleThreshold=1000] - Chunk count threshold for Merkle manifests.
74
80
  * @param {number} [options.concurrency=1] - Maximum parallel chunk I/O operations.
81
+ * @param {{ strategy: string, chunkSize?: number, targetChunkSize?: number, minChunkSize?: number, maxChunkSize?: number }} [options.chunking] - Chunking strategy config.
82
+ * @param {import('./src/ports/ChunkingPort.js').default} [options.chunker] - Pre-built ChunkingPort instance (advanced).
75
83
  */
76
- constructor({ plumbing, chunkSize, codec, policy, crypto, observability, merkleThreshold, concurrency }) {
84
+ constructor({ plumbing, chunkSize, codec, policy, crypto, observability, merkleThreshold, concurrency, chunking, chunker }) {
77
85
  this.plumbing = plumbing;
78
86
  this.chunkSizeConfig = chunkSize;
79
87
  this.codecConfig = codec;
@@ -82,6 +90,8 @@ export default class ContentAddressableStore {
82
90
  this.observabilityConfig = observability;
83
91
  this.merkleThresholdConfig = merkleThreshold;
84
92
  this.concurrencyConfig = concurrency;
93
+ this.chunkingConfig = chunking;
94
+ this.chunkerConfig = chunker;
85
95
  this.service = null;
86
96
  this.#servicePromise = null;
87
97
  }
@@ -102,6 +112,34 @@ export default class ContentAddressableStore {
102
112
  return await this.#servicePromise;
103
113
  }
104
114
 
115
+ /**
116
+ * Resolves the chunker from config options.
117
+ * @private
118
+ * @returns {import('./src/ports/ChunkingPort.js').default|undefined}
119
+ */
120
+ #resolveChunker() {
121
+ // Direct ChunkingPort instance takes precedence
122
+ if (this.chunkerConfig) {
123
+ return this.chunkerConfig;
124
+ }
125
+ // Build from declarative chunking config
126
+ if (this.chunkingConfig) {
127
+ if (this.chunkingConfig.strategy === 'cdc') {
128
+ return new CdcChunker({
129
+ targetChunkSize: this.chunkingConfig.targetChunkSize,
130
+ minChunkSize: this.chunkingConfig.minChunkSize,
131
+ maxChunkSize: this.chunkingConfig.maxChunkSize,
132
+ });
133
+ }
134
+ // 'fixed' or unrecognized — fall through to default (FixedChunker via CasService)
135
+ if (this.chunkingConfig.strategy === 'fixed' && this.chunkingConfig.chunkSize) {
136
+ return new FixedChunker({ chunkSize: this.chunkingConfig.chunkSize });
137
+ }
138
+ }
139
+ // undefined → CasService will default to FixedChunker
140
+ return undefined;
141
+ }
142
+
105
143
  /**
106
144
  * Constructs adapters, resolves crypto, and creates CasService + VaultService.
107
145
  * @private
@@ -113,6 +151,7 @@ export default class ContentAddressableStore {
113
151
  policy: this.policyConfig
114
152
  });
115
153
  const crypto = this.cryptoConfig || await getDefaultCryptoAdapter();
154
+ const chunker = this.#resolveChunker();
116
155
  this.service = new CasService({
117
156
  persistence,
118
157
  chunkSize: this.chunkSizeConfig,
@@ -121,6 +160,7 @@ export default class ContentAddressableStore {
121
160
  observability: this.observabilityConfig || new SilentObserver(),
122
161
  merkleThreshold: this.merkleThresholdConfig,
123
162
  concurrency: this.concurrencyConfig,
163
+ chunker,
124
164
  });
125
165
 
126
166
  const ref = new GitRefAdapter({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@git-stunts/git-cas",
3
- "version": "4.0.1",
3
+ "version": "5.0.0",
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",
@@ -38,6 +38,30 @@ export declare const CompressionSchema: z.ZodObject<{
38
38
  algorithm: z.ZodEnum<["gzip"]>;
39
39
  }>;
40
40
 
41
+ /** Validates fixed-size chunking parameters. */
42
+ export declare const FixedChunkingSchema: z.ZodObject<{
43
+ strategy: z.ZodLiteral<"fixed">;
44
+ params: z.ZodObject<{
45
+ chunkSize: z.ZodNumber;
46
+ }>;
47
+ }>;
48
+
49
+ /** Validates content-defined chunking (CDC) parameters. */
50
+ export declare const CdcChunkingSchema: z.ZodObject<{
51
+ strategy: z.ZodLiteral<"cdc">;
52
+ params: z.ZodObject<{
53
+ target: z.ZodNumber;
54
+ min: z.ZodNumber;
55
+ max: z.ZodNumber;
56
+ }>;
57
+ }>;
58
+
59
+ /** Validates chunking metadata (fixed or CDC). */
60
+ export declare const ChunkingSchema: z.ZodDiscriminatedUnion<
61
+ "strategy",
62
+ [typeof FixedChunkingSchema, typeof CdcChunkingSchema]
63
+ >;
64
+
41
65
  /** Validates a sub-manifest reference in a v2 Merkle manifest. */
42
66
  export declare const SubManifestRefSchema: z.ZodObject<{
43
67
  oid: z.ZodString;
@@ -54,5 +78,6 @@ export declare const ManifestSchema: z.ZodObject<{
54
78
  chunks: z.ZodArray<typeof ChunkSchema>;
55
79
  encryption: z.ZodOptional<typeof EncryptionSchema>;
56
80
  compression: z.ZodOptional<typeof CompressionSchema>;
81
+ chunking: z.ZodOptional<typeof ChunkingSchema>;
57
82
  subManifests: z.ZodOptional<z.ZodArray<typeof SubManifestRefSchema>>;
58
83
  }>;
@@ -38,6 +38,30 @@ export const CompressionSchema = z.object({
38
38
  algorithm: z.enum(['gzip']),
39
39
  });
40
40
 
41
+ /** Validates fixed-size chunking parameters. */
42
+ export const FixedChunkingSchema = z.object({
43
+ strategy: z.literal('fixed'),
44
+ params: z.object({
45
+ chunkSize: z.number().int().positive(),
46
+ }),
47
+ });
48
+
49
+ /** Validates content-defined chunking (CDC) parameters. */
50
+ export const CdcChunkingSchema = z.object({
51
+ strategy: z.literal('cdc'),
52
+ params: z.object({
53
+ target: z.number().int().positive(),
54
+ min: z.number().int().positive(),
55
+ max: z.number().int().positive(),
56
+ }),
57
+ });
58
+
59
+ /** Validates chunking metadata (fixed or CDC). */
60
+ export const ChunkingSchema = z.discriminatedUnion('strategy', [
61
+ FixedChunkingSchema,
62
+ CdcChunkingSchema,
63
+ ]);
64
+
41
65
  /** Validates a sub-manifest reference in a v2 Merkle manifest. */
42
66
  export const SubManifestRefSchema = z.object({
43
67
  oid: z.string().min(1),
@@ -54,5 +78,6 @@ export const ManifestSchema = z.object({
54
78
  chunks: z.array(ChunkSchema),
55
79
  encryption: EncryptionSchema.optional(),
56
80
  compression: CompressionSchema.optional(),
81
+ chunking: ChunkingSchema.optional(),
57
82
  subManifests: z.array(SubManifestRefSchema).optional(),
58
83
  });
@@ -9,6 +9,7 @@ import { promisify } from 'node:util';
9
9
  import Manifest from '../value-objects/Manifest.js';
10
10
  import CasError from '../errors/CasError.js';
11
11
  import Semaphore from './Semaphore.js';
12
+ import FixedChunker from '../../infrastructure/chunkers/FixedChunker.js';
12
13
 
13
14
  const gunzipAsync = promisify(gunzip);
14
15
 
@@ -28,8 +29,9 @@ export default class CasService {
28
29
  * @param {number} [options.chunkSize=262144] - 256 KiB
29
30
  * @param {number} [options.merkleThreshold=1000] - Chunk count threshold for Merkle manifests.
30
31
  * @param {number} [options.concurrency=1] - Maximum parallel chunk I/O operations.
32
+ * @param {import('../../ports/ChunkingPort.js').default} [options.chunker] - Chunking strategy (default FixedChunker).
31
33
  */
32
- constructor({ persistence, codec, crypto, observability, chunkSize = 256 * 1024, merkleThreshold = 1000, concurrency = 1 }) {
34
+ constructor({ persistence, codec, crypto, observability, chunkSize = 256 * 1024, merkleThreshold = 1000, concurrency = 1, chunker }) {
33
35
  CasService._validateObservability(observability);
34
36
  if (chunkSize < 1024) {
35
37
  throw new Error('Chunk size must be at least 1024 bytes');
@@ -39,6 +41,8 @@ export default class CasService {
39
41
  this.crypto = crypto;
40
42
  this.observability = observability;
41
43
  this.chunkSize = chunkSize;
44
+ /** @type {import('../../ports/ChunkingPort.js').default} */
45
+ this.chunker = chunker || new FixedChunker({ chunkSize });
42
46
  if (!Number.isInteger(merkleThreshold) || merkleThreshold < 1) {
43
47
  throw new Error('Merkle threshold must be a positive integer');
44
48
  }
@@ -90,14 +94,14 @@ export default class CasService {
90
94
  }
91
95
 
92
96
  /**
93
- * Reads an async iterable source, splits it into fixed-size chunks, and stores each in Git.
97
+ * Reads an async iterable source, splits it into chunks via the configured
98
+ * chunker, and stores each chunk in Git.
94
99
  * @private
95
100
  * @param {AsyncIterable<Buffer>} source - The data source to chunk.
96
101
  * @param {Object} manifestData - Mutable manifest accumulator.
97
102
  * @throws {CasError} STREAM_ERROR if the source stream fails.
98
103
  */
99
104
  async _chunkAndStore(source, manifestData) {
100
- let buffer = Buffer.alloc(0);
101
105
  const sem = new Semaphore(this.concurrency);
102
106
  const pending = [];
103
107
  let nextIndex = 0;
@@ -114,12 +118,8 @@ export default class CasService {
114
118
  };
115
119
 
116
120
  try {
117
- for await (const chunk of source) {
118
- buffer = Buffer.concat([buffer, chunk]);
119
- while (buffer.length >= this.chunkSize) {
120
- launchWrite(buffer.slice(0, this.chunkSize), nextIndex++);
121
- buffer = buffer.slice(this.chunkSize);
122
- }
121
+ for await (const chunk of this.chunker.chunk(source)) {
122
+ launchWrite(chunk, nextIndex++);
123
123
  }
124
124
  } catch (err) {
125
125
  await Promise.allSettled(pending);
@@ -134,10 +134,6 @@ export default class CasService {
134
134
  throw casErr;
135
135
  }
136
136
 
137
- if (buffer.length > 0) {
138
- launchWrite(buffer, nextIndex++);
139
- }
140
-
141
137
  const results = await Promise.all(pending);
142
138
  results.sort((a, b) => a.index - b.index);
143
139
  for (const entry of results) {
@@ -220,6 +216,24 @@ export default class CasService {
220
216
  }
221
217
  }
222
218
 
219
+ /**
220
+ * Validates that a chunking strategy is recognized.
221
+ * @param {Object} [chunking] - Chunking options from a manifest.
222
+ * @throws {CasError} INVALID_CHUNKING_STRATEGY if the strategy is unrecognized.
223
+ * @private
224
+ */
225
+ _validateChunking(chunking) {
226
+ if (!chunking) { return; }
227
+ const validStrategies = ['fixed', 'cdc'];
228
+ if (!validStrategies.includes(chunking.strategy)) {
229
+ throw new CasError(
230
+ `Unsupported chunking strategy: ${chunking.strategy}`,
231
+ 'INVALID_CHUNKING_STRATEGY',
232
+ { strategy: chunking.strategy },
233
+ );
234
+ }
235
+ }
236
+
223
237
  /**
224
238
  * Chunks an async iterable source and stores it in Git.
225
239
  *
@@ -253,6 +267,14 @@ export default class CasService {
253
267
 
254
268
  const manifestData = { slug, filename, size: 0, chunks: [] };
255
269
 
270
+ // Record chunking metadata for non-default strategies
271
+ if (this.chunker.strategy !== 'fixed') {
272
+ manifestData.chunking = {
273
+ strategy: this.chunker.strategy,
274
+ params: this.chunker.params,
275
+ };
276
+ }
277
+
256
278
  let processedSource = source;
257
279
  if (compression) {
258
280
  processedSource = this._compressStream(processedSource);
@@ -29,6 +29,9 @@ export default class Manifest {
29
29
  this.chunks = data.chunks.map((c) => new Chunk(c));
30
30
  this.encryption = data.encryption ? { ...data.encryption } : undefined;
31
31
  this.compression = data.compression ? { ...data.compression } : undefined;
32
+ this.chunking = data.chunking
33
+ ? { strategy: data.chunking.strategy, params: { ...data.chunking.params } }
34
+ : undefined;
32
35
  this.subManifests = data.subManifests ? data.subManifests.map((s) => ({ ...s })) : undefined;
33
36
  Object.freeze(this);
34
37
  } catch (error) {
@@ -52,6 +55,7 @@ export default class Manifest {
52
55
  chunks: this.chunks,
53
56
  encryption: this.encryption,
54
57
  compression: this.compression,
58
+ chunking: this.chunking,
55
59
  subManifests: this.subManifests,
56
60
  };
57
61
  }
@@ -0,0 +1,339 @@
1
+ /**
2
+ * Content-Defined Chunking engine using Buzhash rolling hash.
3
+ *
4
+ * Splits an async stream of buffers into content-defined chunks whose
5
+ * boundaries are determined by the rolling hash value. This provides
6
+ * shift-resistant deduplication — small edits only affect nearby chunks.
7
+ *
8
+ * @example
9
+ * ```js
10
+ * import CdcChunker from './CdcChunker.js';
11
+ * const chunker = new CdcChunker({ targetChunkSize: 262144 });
12
+ * for await (const chunk of chunker.chunk(source)) {
13
+ * console.log(chunk.length);
14
+ * }
15
+ * ```
16
+ */
17
+
18
+ import ChunkingPort from '../../ports/ChunkingPort.js';
19
+
20
+ // ---------------------------------------------------------------------------
21
+ // Buzhash byte-table (256 entries, deterministic)
22
+ // ---------------------------------------------------------------------------
23
+ // Generated from a seeded xorshift64 PRNG so every runtime produces the
24
+ // same table without needing `crypto.getRandomValues`.
25
+ // ---------------------------------------------------------------------------
26
+
27
+ /**
28
+ * Generates the deterministic 256-entry Buzhash byte table using a
29
+ * seeded xorshift64 PRNG.
30
+ * @returns {Uint32Array}
31
+ */
32
+ function generateBuzTable() {
33
+ const table = new Uint32Array(256);
34
+ // Seed chosen arbitrarily — must never change.
35
+ let s = BigInt('0x6a09e667f3bcc908');
36
+ for (let i = 0; i < 256; i++) {
37
+ // xorshift64
38
+ s ^= s << 13n;
39
+ s &= 0xffffffffffffffffn;
40
+ s ^= s >> 7n;
41
+ s &= 0xffffffffffffffffn;
42
+ s ^= s << 17n;
43
+ s &= 0xffffffffffffffffn;
44
+ table[i] = Number(s & 0xffffffffn);
45
+ }
46
+ return table;
47
+ }
48
+
49
+ /** @type {Uint32Array} */
50
+ const BUZ_TABLE = generateBuzTable();
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // Constants
54
+ // ---------------------------------------------------------------------------
55
+
56
+ /** Window size for the Buzhash sliding window. */
57
+ const WINDOW_SIZE = 64;
58
+ const WINDOW_MASK = WINDOW_SIZE - 1; // 63, for fast modulo
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // Rolling-hash state object
62
+ // ---------------------------------------------------------------------------
63
+
64
+ /**
65
+ * Mutable rolling-hash + chunk-accumulation state.
66
+ *
67
+ * Passed by reference into the per-phase helper functions so that the
68
+ * `chunk()` async generator stays short and simple. Also carries the
69
+ * chunker configuration to keep helper parameter counts low.
70
+ *
71
+ * @typedef {Object} ChunkState
72
+ * @property {number} hash - Current Buzhash value.
73
+ * @property {Uint8Array} win - Sliding window ring buffer.
74
+ * @property {number} winPos - Current write position in `win`.
75
+ * @property {number} hashFed - Bytes fed since last reset.
76
+ * @property {Buffer} chunkBuf - Pre-allocated chunk output buffer.
77
+ * @property {number} chunkLen - Bytes written to chunkBuf so far.
78
+ * @property {number} minSize - Minimum chunk size.
79
+ * @property {number} maxSize - Maximum chunk size.
80
+ * @property {number} mask - Boundary detection mask.
81
+ */
82
+
83
+ /**
84
+ * Reset rolling-hash and chunk accumulation state for a new chunk.
85
+ * @param {ChunkState} st
86
+ */
87
+ function resetState(st) {
88
+ st.hash = 0;
89
+ st.winPos = 0;
90
+ st.hashFed = 0;
91
+ st.chunkLen = 0;
92
+ st.win.fill(0);
93
+ }
94
+
95
+ // ---------------------------------------------------------------------------
96
+ // Per-phase helpers (keep the async generator under the line/complexity cap)
97
+ // ---------------------------------------------------------------------------
98
+
99
+ /**
100
+ * Phase 1 — fill the sliding window (first 64 bytes of each chunk).
101
+ * Uses a simplified hash update (no outgoing-byte removal).
102
+ *
103
+ * @param {ChunkState} st
104
+ * @param {Buffer} buf - Source buffer being processed.
105
+ * @param {number} srcPos - Current read offset in `buf`.
106
+ * @returns {number} Updated srcPos.
107
+ */
108
+ function fillWindow(st, buf, srcPos) {
109
+ const need = WINDOW_SIZE - st.hashFed;
110
+ const avail = buf.length - srcPos;
111
+ const n = need < avail ? need : avail;
112
+ const end = srcPos + n;
113
+ const table = BUZ_TABLE;
114
+
115
+ while (srcPos < end) {
116
+ const byte = buf[srcPos];
117
+ st.hash = (((st.hash << 1) | (st.hash >>> 31)) ^ table[byte]) >>> 0;
118
+ st.win[st.winPos] = byte;
119
+ st.winPos = (st.winPos + 1) & WINDOW_MASK;
120
+ st.chunkBuf[st.chunkLen++] = byte;
121
+ srcPos++;
122
+ }
123
+ st.hashFed += n;
124
+ return srcPos;
125
+ }
126
+
127
+ /**
128
+ * Phase 2 — pre-min region (window full, no boundary checks).
129
+ * Bulk-copies bytes into the chunk buffer while updating the hash.
130
+ *
131
+ * @param {ChunkState} st
132
+ * @param {Buffer} buf
133
+ * @param {number} srcPos
134
+ * @returns {number} Updated srcPos.
135
+ */
136
+ function feedPreMin(st, buf, srcPos) {
137
+ const needed = st.minSize - st.chunkLen;
138
+ const avail = buf.length - srcPos;
139
+ const n = needed < avail ? needed : avail;
140
+ const end = srcPos + n;
141
+ const table = BUZ_TABLE;
142
+
143
+ // Bulk-copy into chunk buffer
144
+ buf.copy(st.chunkBuf, st.chunkLen, srcPos, end);
145
+
146
+ // Feed bytes into rolling hash (window is full)
147
+ while (srcPos < end) {
148
+ const byte = buf[srcPos];
149
+ st.hash = (((st.hash << 1) | (st.hash >>> 31)) ^ table[st.win[st.winPos]] ^ table[byte]) >>> 0;
150
+ st.win[st.winPos] = byte;
151
+ st.winPos = (st.winPos + 1) & WINDOW_MASK;
152
+ srcPos++;
153
+ }
154
+ st.chunkLen += n;
155
+ return srcPos;
156
+ }
157
+
158
+ /**
159
+ * Phase 3 — scan for a content-defined boundary in [minSize, maxSize).
160
+ *
161
+ * @param {ChunkState} st
162
+ * @param {Buffer} buf
163
+ * @param {number} srcPos
164
+ * @returns {{ srcPos: number, found: boolean }}
165
+ */
166
+ function scanBoundary(st, buf, srcPos) {
167
+ const { mask, maxSize } = st;
168
+ const table = BUZ_TABLE;
169
+ const limit = buf.length < (srcPos + maxSize - st.chunkLen)
170
+ ? buf.length
171
+ : (srcPos + maxSize - st.chunkLen);
172
+
173
+ let h = st.hash;
174
+ let wp = st.winPos;
175
+ const { win, chunkBuf } = st;
176
+ let cl = st.chunkLen;
177
+
178
+ while (srcPos < limit) {
179
+ const byte = buf[srcPos];
180
+ h = (((h << 1) | (h >>> 31)) ^ table[win[wp]] ^ table[byte]) >>> 0;
181
+ win[wp] = byte;
182
+ wp = (wp + 1) & WINDOW_MASK;
183
+ chunkBuf[cl++] = byte;
184
+ srcPos++;
185
+
186
+ if ((h & mask) === 0) {
187
+ st.hash = h;
188
+ st.winPos = wp;
189
+ st.chunkLen = cl;
190
+ return { srcPos, found: true };
191
+ }
192
+ }
193
+
194
+ st.hash = h;
195
+ st.winPos = wp;
196
+ st.chunkLen = cl;
197
+ return { srcPos, found: false };
198
+ }
199
+
200
+ /**
201
+ * Process a single source buffer through all three CDC phases.
202
+ *
203
+ * Returns an array of completed chunks (may be empty if no boundary
204
+ * was found within this buffer).
205
+ *
206
+ * @param {ChunkState} st
207
+ * @param {Buffer} buf
208
+ * @returns {Buffer[]} Completed chunks ready to yield.
209
+ */
210
+ function processBuf(st, buf) {
211
+ /** @type {Buffer[]} */
212
+ const completed = [];
213
+ let srcPos = 0;
214
+
215
+ while (srcPos < buf.length) {
216
+ // Phase 1: fill window if needed
217
+ if (st.hashFed < WINDOW_SIZE) {
218
+ srcPos = fillWindow(st, buf, srcPos);
219
+ if (st.hashFed < WINDOW_SIZE) { break; }
220
+ }
221
+
222
+ // Phase 2: bulk-feed bytes until minSize
223
+ if (st.chunkLen < st.minSize) {
224
+ srcPos = feedPreMin(st, buf, srcPos);
225
+ }
226
+
227
+ // Phase 3: scan for boundary
228
+ const result = scanBoundary(st, buf, srcPos);
229
+ srcPos = result.srcPos;
230
+
231
+ if (result.found || st.chunkLen >= st.maxSize) {
232
+ completed.push(Buffer.from(st.chunkBuf.subarray(0, st.chunkLen)));
233
+ resetState(st);
234
+ }
235
+ }
236
+
237
+ return completed;
238
+ }
239
+
240
+ // ---------------------------------------------------------------------------
241
+ // CdcChunker
242
+ // ---------------------------------------------------------------------------
243
+
244
+ /**
245
+ * @typedef {Object} CdcChunkerOptions
246
+ * @property {number} [minChunkSize=65536] - Minimum chunk size in bytes (64 KiB).
247
+ * @property {number} [maxChunkSize=1048576] - Maximum chunk size in bytes (1 MiB).
248
+ * @property {number} [targetChunkSize=262144] - Target (average) chunk size in bytes (256 KiB).
249
+ */
250
+
251
+ /**
252
+ * CDC chunker that uses a Buzhash rolling hash to find content-defined
253
+ * chunk boundaries within an async byte stream.
254
+ */
255
+ export default class CdcChunker extends ChunkingPort {
256
+ /** @type {number} */ #minChunkSize;
257
+ /** @type {number} */ #maxChunkSize;
258
+ /** @type {number} */ #targetChunkSize;
259
+ /** @type {number} */ #mask;
260
+
261
+ /**
262
+ * @param {CdcChunkerOptions} [options]
263
+ */
264
+ constructor({
265
+ minChunkSize = 65_536,
266
+ maxChunkSize = 1_048_576,
267
+ targetChunkSize = 262_144,
268
+ } = {}) {
269
+ super();
270
+ if (minChunkSize > maxChunkSize) {
271
+ throw new RangeError(
272
+ `minChunkSize (${minChunkSize}) must not exceed maxChunkSize (${maxChunkSize})`,
273
+ );
274
+ }
275
+ if (targetChunkSize < minChunkSize || targetChunkSize > maxChunkSize) {
276
+ throw new RangeError(
277
+ `targetChunkSize (${targetChunkSize}) must be in [${minChunkSize}, ${maxChunkSize}]`,
278
+ );
279
+ }
280
+
281
+ this.#minChunkSize = minChunkSize;
282
+ this.#maxChunkSize = maxChunkSize;
283
+ this.#targetChunkSize = targetChunkSize;
284
+
285
+ // Mask: nearest power-of-2 minus 1 that is <= targetChunkSize.
286
+ // E.g. target 262144 (2^18) -> mask 0x3FFFF (2^18 - 1).
287
+ const bits = Math.floor(Math.log2(targetChunkSize));
288
+ this.#mask = ((1 << bits) - 1) >>> 0;
289
+ }
290
+
291
+ /** @override */
292
+ get strategy() {
293
+ return 'cdc';
294
+ }
295
+
296
+ /** @override */
297
+ get params() {
298
+ return {
299
+ target: this.#targetChunkSize,
300
+ min: this.#minChunkSize,
301
+ max: this.#maxChunkSize,
302
+ };
303
+ }
304
+
305
+ /**
306
+ * Splits an async byte stream into content-defined chunks.
307
+ *
308
+ * Yields `Buffer` instances. The caller may concatenate them or write
309
+ * each one directly to storage.
310
+ *
311
+ * @override
312
+ * @param {AsyncIterable<Buffer>} source - Incoming byte stream.
313
+ * @yields {Buffer} Content-defined chunks.
314
+ */
315
+ async *chunk(source) {
316
+ /** @type {ChunkState} */
317
+ const st = {
318
+ hash: 0,
319
+ win: new Uint8Array(WINDOW_SIZE),
320
+ winPos: 0,
321
+ hashFed: 0,
322
+ chunkBuf: Buffer.allocUnsafe(this.#maxChunkSize),
323
+ chunkLen: 0,
324
+ minSize: this.#minChunkSize,
325
+ maxSize: this.#maxChunkSize,
326
+ mask: this.#mask,
327
+ };
328
+
329
+ for await (const buf of source) {
330
+ const chunks = processBuf(st, buf);
331
+ for (const c of chunks) { yield c; }
332
+ }
333
+
334
+ // Flush final partial chunk (may be < minSize — allowed for EOF).
335
+ if (st.chunkLen > 0) {
336
+ yield Buffer.from(st.chunkBuf.subarray(0, st.chunkLen));
337
+ }
338
+ }
339
+ }
@@ -0,0 +1,49 @@
1
+ import ChunkingPort from '../../ports/ChunkingPort.js';
2
+
3
+ /**
4
+ * {@link ChunkingPort} implementation that splits data into fixed-size chunks.
5
+ *
6
+ * Buffers incoming data and yields exactly {@link chunkSize} byte chunks.
7
+ * The final chunk may be smaller than {@link chunkSize} if the source does
8
+ * not divide evenly. An empty source produces no chunks.
9
+ */
10
+ export default class FixedChunker extends ChunkingPort {
11
+ /** @type {number} */
12
+ #chunkSize;
13
+
14
+ /**
15
+ * @param {Object} [options]
16
+ * @param {number} [options.chunkSize=262144] - Chunk size in bytes (default 256 KiB).
17
+ */
18
+ constructor({ chunkSize = 262144 } = {}) {
19
+ super();
20
+ this.#chunkSize = chunkSize;
21
+ }
22
+
23
+ /** @override */
24
+ get strategy() {
25
+ return 'fixed';
26
+ }
27
+
28
+ /** @override */
29
+ get params() {
30
+ return { chunkSize: this.#chunkSize };
31
+ }
32
+
33
+ /** @override */
34
+ async *chunk(source) {
35
+ let buffer = Buffer.alloc(0);
36
+
37
+ for await (const data of source) {
38
+ buffer = Buffer.concat([buffer, data]);
39
+ while (buffer.length >= this.#chunkSize) {
40
+ yield buffer.slice(0, this.#chunkSize);
41
+ buffer = buffer.slice(this.#chunkSize);
42
+ }
43
+ }
44
+
45
+ if (buffer.length > 0) {
46
+ yield buffer;
47
+ }
48
+ }
49
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Abstract port for splitting a byte stream into chunks.
3
+ *
4
+ * Implementations define a chunking strategy (e.g. fixed-size, content-defined)
5
+ * and expose the configuration parameters that govern it.
6
+ *
7
+ * @abstract
8
+ */
9
+ export default class ChunkingPort {
10
+ constructor() {
11
+ if (new.target === ChunkingPort) {
12
+ throw new Error('ChunkingPort is abstract and cannot be instantiated directly');
13
+ }
14
+ }
15
+
16
+ /**
17
+ * Returns the strategy identifier for this chunker (e.g. `'fixed'`, `'cdc'`).
18
+ * @abstract
19
+ * @returns {string}
20
+ */
21
+ get strategy() {
22
+ throw new Error('Not implemented');
23
+ }
24
+
25
+ /**
26
+ * Returns the configuration parameters for this chunker.
27
+ * @abstract
28
+ * @returns {Object}
29
+ */
30
+ get params() {
31
+ throw new Error('Not implemented');
32
+ }
33
+
34
+ /**
35
+ * Splits an async byte stream into chunks.
36
+ *
37
+ * @abstract
38
+ * @param {AsyncIterable<Buffer>} _source - The input byte stream.
39
+ * @yields {Buffer} Chunks of data whose size depends on the strategy.
40
+ * @returns {AsyncGenerator<Buffer>}
41
+ */
42
+ async *chunk(_source) { // eslint-disable-line require-yield
43
+ throw new Error('Not implemented');
44
+ }
45
+ }