@git-stunts/git-cas 3.0.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.
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Animated progress bar for store/restore operations.
3
+ * Wires CasService EventEmitter events to a bijou progress bar on stderr.
4
+ */
5
+
6
+ import { statSync } from 'node:fs';
7
+ import { createAnimatedProgressBar } from '@flyingrobots/bijou';
8
+ import { getCliContext } from './context.js';
9
+
10
+ /**
11
+ * Format bytes as human-readable string.
12
+ */
13
+ function formatBytes(bytes) {
14
+ if (bytes < 1024) {
15
+ return `${bytes} B`;
16
+ }
17
+ if (bytes < 1024 * 1024) {
18
+ return `${(bytes / 1024).toFixed(1)} KiB`;
19
+ }
20
+ if (bytes < 1024 * 1024 * 1024) {
21
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
22
+ }
23
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GiB`;
24
+ }
25
+
26
+ /**
27
+ * Create a progress tracker for store operations.
28
+ *
29
+ * @param {Object} options
30
+ * @param {string} options.filePath - Path to the file being stored.
31
+ * @param {number} options.chunkSize - Chunk size in bytes.
32
+ * @param {boolean} [options.quiet] - Suppress all progress output.
33
+ * @returns {{ attach(observer: { on(event: string, fn: Function): void, removeListener(event: string, fn: Function): void }): void, detach(): void }}
34
+ */
35
+ export function createStoreProgress({ filePath, chunkSize, quiet, fileSize: providedSize }) {
36
+ if (quiet) {
37
+ return { attach() {}, detach() {} };
38
+ }
39
+
40
+ const ctx = getCliContext();
41
+ if (ctx.mode === 'pipe') {
42
+ return { attach() {}, detach() {} };
43
+ }
44
+
45
+ const fileSize = providedSize ?? statSync(filePath).size;
46
+ const totalChunks = fileSize === 0 ? 0 : Math.ceil(fileSize / chunkSize);
47
+
48
+ if (totalChunks === 0) {
49
+ return { attach() {}, detach() {} };
50
+ }
51
+
52
+ return createProgressTracker({ ctx, totalChunks, event: 'chunk:stored', label: 'Storing' });
53
+ }
54
+
55
+ /**
56
+ * Create a progress tracker for restore operations.
57
+ *
58
+ * @param {Object} options
59
+ * @param {number} options.totalChunks - Number of chunks to restore.
60
+ * @param {boolean} [options.quiet] - Suppress all progress output.
61
+ * @returns {{ attach(observer: { on(event: string, fn: Function): void, removeListener(event: string, fn: Function): void }): void, detach(): void }}
62
+ */
63
+ export function createRestoreProgress({ totalChunks, quiet }) {
64
+ if (quiet || totalChunks === 0) {
65
+ return { attach() {}, detach() {} };
66
+ }
67
+
68
+ const ctx = getCliContext();
69
+ if (ctx.mode === 'pipe') {
70
+ return { attach() {}, detach() {} };
71
+ }
72
+
73
+ return createProgressTracker({ ctx, totalChunks, event: 'chunk:restored', label: 'Restoring' });
74
+ }
75
+
76
+ /**
77
+ * Internal: builds the progress tracker object.
78
+ */
79
+ function createProgressTracker({ ctx, totalChunks, event, label }) {
80
+ const width = Math.min(40, (ctx.runtime.columns || 80) - 30);
81
+ const bar = createAnimatedProgressBar({ width, showPercent: false, ctx });
82
+
83
+ let chunksProcessed = 0;
84
+ let bytesProcessed = 0;
85
+ let startTime = null;
86
+ let service = null;
87
+ let handler = null;
88
+
89
+ function onChunk({ size }) {
90
+ if (!startTime) {
91
+ startTime = Date.now();
92
+ }
93
+ chunksProcessed++;
94
+ bytesProcessed += size;
95
+
96
+ const pct = (chunksProcessed / totalChunks) * 100;
97
+ const elapsed = (Date.now() - startTime) / 1000;
98
+ const throughput = elapsed > 0 ? bytesProcessed / elapsed : 0;
99
+
100
+ if (ctx.mode === 'interactive') {
101
+ const status = ` ${label} ${chunksProcessed}/${totalChunks} ${formatBytes(throughput)}/s `;
102
+ process.stderr.write(`\r\x1b[K${status}`);
103
+ bar.update(pct);
104
+ } else if (chunksProcessed === 1 || chunksProcessed === totalChunks || chunksProcessed % 10 === 0) {
105
+ ctx.io.write(`${label} ${chunksProcessed}/${totalChunks} ${Math.round(pct)}%\n`);
106
+ }
107
+ }
108
+
109
+ return {
110
+ attach(svc) {
111
+ service = svc;
112
+ handler = onChunk;
113
+ bar.start();
114
+ service.on(event, handler);
115
+ },
116
+ detach() {
117
+ if (service && handler) {
118
+ service.removeListener(event, handler);
119
+ }
120
+ const elapsed = startTime ? (Date.now() - startTime) / 1000 : 0;
121
+ const throughput = elapsed > 0 ? bytesProcessed / elapsed : 0;
122
+ const msg = ` ${label} ${chunksProcessed}/${totalChunks} done ${formatBytes(throughput)}/s`;
123
+ bar.stop(msg);
124
+ },
125
+ };
126
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Vault list filtering and table formatting utilities.
3
+ */
4
+
5
+ /**
6
+ * Convert a simple glob pattern to a RegExp.
7
+ *
8
+ * @param {string} pattern - Glob pattern (supports *, **, ?).
9
+ * @param {string} str - String to test.
10
+ * @returns {boolean}
11
+ */
12
+ export function matchGlob(pattern, str) {
13
+ if (pattern.length > 200) {
14
+ throw new Error(`Glob pattern too long (${pattern.length} chars, max 200)`);
15
+ }
16
+ const escaped = pattern
17
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
18
+ .replace(/\*\*/g, '\0')
19
+ .replace(/\*/g, '[^/]*')
20
+ .replace(/\0/g, '.*')
21
+ .replace(/\?/g, '[^/]');
22
+ return new RegExp(`^${escaped}$`).test(str);
23
+ }
24
+
25
+ /**
26
+ * Filter vault entries by an optional glob pattern.
27
+ *
28
+ * @param {Array<{slug: string, treeOid: string}>} entries
29
+ * @param {string} [pattern]
30
+ * @returns {Array<{slug: string, treeOid: string}>}
31
+ */
32
+ export function filterEntries(entries, pattern) {
33
+ if (!pattern) {
34
+ return entries;
35
+ }
36
+ return entries.filter(e => matchGlob(pattern, e.slug));
37
+ }
38
+
39
+ /**
40
+ * Format entries as an aligned table with header (for TTY output).
41
+ *
42
+ * @param {Array<{slug: string, treeOid: string}>} entries
43
+ * @returns {string}
44
+ */
45
+ export function formatTable(entries) {
46
+ if (entries.length === 0) {
47
+ return '';
48
+ }
49
+ const maxSlug = Math.max('SLUG'.length, ...entries.map(e => e.slug.length));
50
+ const header = `${'SLUG'.padEnd(maxSlug)} TREE OID`;
51
+ const rows = entries.map(e => `${e.slug.padEnd(maxSlug)} ${e.treeOid}`);
52
+ return `${header}\n${rows.join('\n')}\n`;
53
+ }
54
+
55
+ /**
56
+ * Format entries as tab-separated rows (for piped output).
57
+ *
58
+ * @param {Array<{slug: string, treeOid: string}>} entries
59
+ * @returns {string}
60
+ */
61
+ export function formatTabSeparated(entries) {
62
+ return entries.map(e => `${e.slug}\t${e.treeOid}\n`).join('');
63
+ }
package/index.d.ts CHANGED
@@ -11,13 +11,14 @@ import type {
11
11
  CryptoPort,
12
12
  CodecPort,
13
13
  GitPersistencePort,
14
+ ObservabilityPort,
14
15
  CasServiceOptions,
15
16
  DeriveKeyOptions,
16
17
  DeriveKeyResult,
17
18
  } from "./src/domain/services/CasService.js";
18
19
 
19
20
  export { CasService, Manifest, Chunk };
20
- export type { EncryptionMeta, ManifestData, CompressionMeta, KdfParams, SubManifestRef, CryptoPort, CodecPort, GitPersistencePort, CasServiceOptions, DeriveKeyOptions, DeriveKeyResult };
21
+ export type { EncryptionMeta, ManifestData, CompressionMeta, KdfParams, SubManifestRef, CryptoPort, CodecPort, GitPersistencePort, ObservabilityPort, CasServiceOptions, DeriveKeyOptions, DeriveKeyResult };
21
22
 
22
23
  /** Abstract port for cryptographic operations. */
23
24
  export declare class CryptoPortBase {
@@ -93,14 +94,47 @@ export declare class CborCodec extends CodecPortBase {
93
94
  constructor();
94
95
  }
95
96
 
97
+ /** No-op observability adapter. */
98
+ export declare class SilentObserver {
99
+ metric(channel: string, data: Record<string, unknown>): void;
100
+ log(level: string, msg: string, meta?: Record<string, unknown>): void;
101
+ span(name: string): { end(meta?: Record<string, unknown>): void };
102
+ }
103
+
104
+ /** EventEmitter-based observability adapter for backward compatibility. */
105
+ export declare class EventEmitterObserver {
106
+ metric(channel: string, data: Record<string, unknown>): void;
107
+ log(level: string, msg: string, meta?: Record<string, unknown>): void;
108
+ span(name: string): { end(meta?: Record<string, unknown>): void };
109
+ on(event: string, listener: (...args: unknown[]) => void): this;
110
+ removeListener(event: string, listener: (...args: unknown[]) => void): this;
111
+ listenerCount(event: string): number;
112
+ }
113
+
114
+ /** Stats-collecting observability adapter. */
115
+ export declare class StatsCollector {
116
+ metric(channel: string, data: Record<string, unknown>): void;
117
+ log(level: string, msg: string, meta?: Record<string, unknown>): void;
118
+ span(name: string): { end(meta?: Record<string, unknown>): void };
119
+ summary(): {
120
+ chunksProcessed: number;
121
+ bytesTotal: number;
122
+ elapsed: number;
123
+ throughput: number;
124
+ errors: number;
125
+ };
126
+ }
127
+
96
128
  /** Constructor options for {@link ContentAddressableStore}. */
97
129
  export interface ContentAddressableStoreOptions {
98
130
  plumbing: unknown;
99
131
  chunkSize?: number;
100
132
  codec?: CodecPort;
101
133
  crypto?: CryptoPort;
134
+ observability?: ObservabilityPort;
102
135
  policy?: unknown;
103
136
  merkleThreshold?: number;
137
+ concurrency?: number;
104
138
  }
105
139
 
106
140
  /** A single vault entry. */
@@ -257,6 +291,12 @@ export default class ContentAddressableStore {
257
291
  passphrase?: string;
258
292
  }): Promise<{ buffer: Buffer; bytesWritten: number }>;
259
293
 
294
+ restoreStream(options: {
295
+ manifest: Manifest;
296
+ encryptionKey?: Buffer;
297
+ passphrase?: string;
298
+ }): AsyncIterable<Buffer>;
299
+
260
300
  createTree(options: { manifest: Manifest }): Promise<string>;
261
301
 
262
302
  verifyIntegrity(manifest: Manifest): Promise<boolean>;
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.0.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",
@@ -66,12 +66,21 @@
66
66
  "format": "prettier --write ."
67
67
  },
68
68
  "dependencies": {
69
+ "@flyingrobots/bijou": "^0.2.0",
70
+ "@flyingrobots/bijou-node": "^0.2.0",
71
+ "@flyingrobots/bijou-tui": "^0.2.0",
69
72
  "@git-stunts/alfred": "^0.10.0",
70
73
  "@git-stunts/plumbing": "^2.8.0",
71
74
  "cbor-x": "^1.6.0",
72
75
  "commander": "^14.0.3",
73
76
  "zod": "^3.24.1"
74
77
  },
78
+ "pnpm": {
79
+ "onlyBuiltDependencies": [
80
+ "cbor-extract",
81
+ "esbuild"
82
+ ]
83
+ },
75
84
  "devDependencies": {
76
85
  "@eslint/js": "^9.17.0",
77
86
  "eslint": "^9.17.0",
@@ -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: {