adaptive-pipeline 2.0.0

High-performance optimized, adaptive file processing pipeline with configurable stages, binary format support, and cross-platform compatibility
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
<!--
Adaptive Pipeline
Copyright (c) 2025 Michael Gardner, A Bit of Help, Inc.
SPDX-License-Identifier: BSD-3-Clause
See LICENSE file in the project root.
-->

# adaptive-pipeline

[![License](https://img.shields.io/badge/License-BSD_3--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause)
[![crates.io](https://img.shields.io/crates/v/adaptive-pipeline.svg)](https://crates.io/crates/adaptive-pipeline)
[![Documentation](https://docs.rs/adaptive-pipeline/badge.svg)](https://docs.rs/adaptive-pipeline)

**High-performance adaptive file processing pipeline** with configurable stages, binary format support, and cross-platform compatibility.

## 🎯 Overview

This crate provides the **application and infrastructure layers** for the Adaptive Pipeline system - including use cases, services, adapters, repositories, and a production-ready CLI.

### Key Features

- **⚑ Channel-Based Concurrency** - Reader β†’ CPU Workers β†’ Direct Writer pattern
- **🎯 Adaptive Performance** - Dynamic chunk sizing and worker scaling
- **πŸ” Enterprise Security** - AES-256-GCM, ChaCha20-Poly1305, Argon2 KDF
- **πŸ“Š Observable** - Prometheus metrics, structured tracing
- **πŸ›‘οΈ Zero-Panic** - No unwrap/expect/panic in production
- **🌐 Cross-Platform** - macOS, Linux, Windows support

## πŸ“¦ Installation

### As a Library

```toml
[dependencies]
adaptive-pipeline = "1.0"
```

### As a CLI Tool

```bash
cargo install adaptive-pipeline
```

## πŸ—οΈ Architecture

This crate implements the Application and Infrastructure layers:

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚         APPLICATION LAYER                 β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚  β”‚  Use Cases                          β”‚ β”‚
β”‚  β”‚  - ProcessFile                      β”‚ β”‚
β”‚  β”‚  - RestoreFile                      β”‚ β”‚
β”‚  β”‚  - CreatePipeline                   β”‚ β”‚
β”‚  β”‚  - ValidateFile                     β”‚ β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚  β”‚  Application Services               β”‚ β”‚
β”‚  β”‚  - ConcurrentPipeline (orchestrator)β”‚ β”‚
β”‚  β”‚  - StreamingFileProcessor           β”‚ β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   β”‚
                   β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚        INFRASTRUCTURE LAYER               β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚  β”‚  Adapters                           β”‚ β”‚
β”‚  β”‚  - TokioFileIO                      β”‚ β”‚
β”‚  β”‚  - AsyncCompression                 β”‚ β”‚
β”‚  β”‚  - AsyncEncryption                  β”‚ β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚  β”‚  Repositories                       β”‚ β”‚
β”‚  β”‚  - SqlitePipelineRepository         β”‚ β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚  β”‚  Runtime Management                 β”‚ β”‚
β”‚  β”‚  - ResourceManager (global tokens)  β”‚ β”‚
β”‚  β”‚  - StageExecutor                    β”‚ β”‚
β”‚  β”‚  - Supervisor (task management)     β”‚ β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

## πŸ“š Library Usage

### Processing Files

```rust
use adaptive_pipeline::application::use_cases::ProcessFileUseCase;
use adaptive_pipeline::application::services::ConcurrentPipeline;
use adaptive_pipeline_domain::value_objects::PipelineId;
use std::path::Path;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create pipeline service
    let pipeline_service = ConcurrentPipeline::new(
        file_io_service,
        pipeline_repository,
        stage_registry,
    );

    // Process file through pipeline
    let config = ProcessFileConfig {
        input: Path::new("input.dat").to_path_buf(),
        output: Path::new("output.adapipe").to_path_buf(),
        pipeline: "compress-encrypt".to_string(),
        chunk_size_mb: Some(8),
        workers: None,  // Auto-detect
        channel_depth: Some(4),
    };

    let result = ProcessFileUseCase::execute(config, pipeline_service).await?;

    println!("Processed {} bytes in {:.2}s",
        result.bytes_processed,
        result.duration.as_secs_f64()
    );

    Ok(())
}
```

### Creating Custom Pipelines

```rust
use adaptive_pipeline::application::use_cases::CreatePipelineUseCase;
use adaptive_pipeline_domain::entities::{Pipeline, PipelineStage, StageType};

// Define pipeline stages
let stages = vec![
    PipelineStage::new("compress".to_string(), StageType::Compression, 1),
    PipelineStage::new("encrypt".to_string(), StageType::Encryption, 2),
    PipelineStage::new("checksum".to_string(), StageType::Checksum, 3),
];

// Create and save pipeline
let pipeline = CreatePipelineUseCase::execute(
    "secure-backup".to_string(),
    stages,
    pipeline_repository,
).await?;

println!("Created pipeline: {}", pipeline.id());
```

### Restoring Files

```rust
use adaptive_pipeline::application::use_cases::RestoreFileUseCase;
use std::path::Path;

// Restore from .adapipe format
let result = RestoreFileUseCase::execute(
    Path::new("backup.adapipe"),
    Some(Path::new("/restore/directory")),
    false,  // mkdir
    false,  // overwrite
    pipeline_service,
).await?;

println!("Restored to: {}", result.output_path.display());
```

## πŸ–₯️ CLI Usage

### Process Files

```bash
# Basic processing
adaptive-pipeline process \
  --input data.bin \
  --output data.adapipe \
  --pipeline compress-encrypt

# With custom settings
adaptive-pipeline process \
  -i large.dat \
  -o large.adapipe \
  -p secure \
  --chunk-size-mb 16 \
  --workers 8 \
  --channel-depth 8
```

### Create Pipelines

```bash
# Compression only
adaptive-pipeline create \
  --name fast-compress \
  --stages compression:lz4

# Full security pipeline
adaptive-pipeline create \
  --name secure-backup \
  --stages compression:zstd,encryption:aes256gcm,integrity
```

### Restore Files

```bash
# Restore to original location
adaptive-pipeline restore --input backup.adapipe

# Restore to specific directory
adaptive-pipeline restore \
  --input data.adapipe \
  --output-dir /tmp/restored \
  --mkdir \
  --overwrite
```

### Validate Files

```bash
# Quick format validation
adaptive-pipeline validate-file --file output.adapipe

# Full integrity check
adaptive-pipeline validate-file --file output.adapipe --full
```

### System Benchmarking

```bash
# Quick benchmark
adaptive-pipeline benchmark

# Comprehensive test
adaptive-pipeline benchmark \
  --size-mb 1000 \
  --iterations 5
```

For complete CLI documentation, see the [root README](../README.md#-command-line-reference).

## ⚑ Performance

### Concurrency Model

**Channel-Based Execution:**

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   Channel    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   Direct     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Reader    │─────────────→│ CPU Workers  │─────────────→│   Writer   β”‚
β”‚   Task      β”‚ Backpressure β”‚  (Parallel)  β”‚ Random Accessβ”‚ (.adapipe) β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
     ↓                            ↓ ↓ ↓                         ↓
File I/O                    Rayon Threads               Concurrent Seeks
(Streaming)                 (CPU-bound)                 (No Mutex!)
```

**Key Optimizations:**
- Reader streams with backpressure
- Rayon work-stealing for CPU ops
- Direct concurrent writes (no bottleneck)
- Global resource semaphores

### Benchmarks (Mac Pro 2019, Intel Xeon W-3235 @ 3.3GHz, 12-core/24-thread, 48GB RAM, NVMe SSD)

Measured with `adaptive_pipeline benchmark` command (2025-10-07):

| File Size | Best Throughput | Optimal Config | Adaptive Config |
|-----------|----------------|----------------|-----------------|
| 100 MB    | **811 MB/s**   | 16MB chunks, 7 workers | 502 MB/s (16MB, 8 workers) |
| 1 GB      | **822 MB/s**   | 64MB chunks, 5 workers | 660 MB/s (64MB, 10 workers) |

**Performance Insights:**
- Consistent **800+ MB/s** throughput shows excellent scalability
- Lower worker counts (5-7) often outperform higher counts due to reduced context switching
- Larger chunks (16-64MB) maximize sequential I/O performance
- Adaptive configuration provides good baseline; fine-tuning can improve by 20-60%

Run your own benchmarks: `adaptive_pipeline benchmark --file <path>`

## πŸ”§ Configuration

### Environment Variables

```bash
# Database
export ADAPIPE_SQLITE_PATH="./pipeline.db"

# Logging
export RUST_LOG="adaptive_pipeline=debug,tower_http=warn"

# Performance
export RAYON_NUM_THREADS=8
export TOKIO_WORKER_THREADS=4
```

### Configuration File

```toml
# pipeline.toml
[pipeline]
chunk_size_mb = 8
parallel_workers = 0  # Auto-detect

[compression]
algorithm = "zstd"
level = "balanced"

[encryption]
algorithm = "aes256gcm"
key_derivation = "argon2id"
```

## πŸ“Š Observability

### Prometheus Metrics

```bash
# Start with metrics endpoint
adaptive-pipeline process \
  --input data.bin \
  --output data.adapipe \
  --pipeline test

# Query metrics (default port: 9090)
curl http://localhost:9090/metrics
```

**Key Metrics:**
- `pipeline_throughput_bytes_per_second`
- `pipeline_cpu_queue_depth`
- `pipeline_worker_utilization`
- `pipeline_chunk_processing_duration_ms`

### Structured Logging

```bash
# Enable debug logging
RUST_LOG=adaptive_pipeline=debug adaptive-pipeline process ...

# Log to file
adaptive-pipeline process ... 2>&1 | tee pipeline.log
```

## 🎯 Advanced Features

### Custom Stages

Implement the `StageService` trait:

```rust
use adaptive_pipeline_domain::services::StageService;
use adaptive_pipeline_domain::entities::{FileChunk, ProcessingContext};

pub struct MyCustomStage {
    // Stage configuration
}

impl StageService for MyCustomStage {
    fn process_chunk(
        &self,
        chunk: FileChunk,
        context: &mut ProcessingContext,
    ) -> Result<FileChunk, PipelineError> {
        // Custom processing logic
        Ok(chunk)
    }

    fn reverse_chunk(
        &self,
        chunk: FileChunk,
        context: &mut ProcessingContext,
    ) -> Result<FileChunk, PipelineError> {
        // Reverse transformation
        Ok(chunk)
    }
}
```

### Resource Management

```rust
use adaptive_pipeline::infrastructure::runtime::ResourceManager;

// Global resource manager
let rm = ResourceManager::global();

// Acquire CPU token (respects core count)
let cpu_token = rm.acquire_cpu_token().await?;

// Acquire I/O token (respects device type)
let io_token = rm.acquire_io_token().await?;

// Tokens auto-release on drop
```

### Binary Format

The `.adapipe` binary format includes:
- **Header** - Metadata, algorithms, original file info
- **Chunks** - Processed data with checksums
- **Footer** - Final statistics and verification data

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Header (1024 bytes)               β”‚
β”‚  - Magic bytes: ADAPIPE\0          β”‚
β”‚  - Version: 1                      β”‚
β”‚  - Original filename & checksum    β”‚
β”‚  - Pipeline ID and stages          β”‚
β”‚  - Compression/encryption config   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Chunk 0 (variable size)           β”‚
β”‚  - Sequence number                 β”‚
β”‚  - Compressed size                 β”‚
β”‚  - Data                            β”‚
β”‚  - Checksum                        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚  ... more chunks ...               β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Footer (1024 bytes)               β”‚
β”‚  - Total chunks                    β”‚
β”‚  - Output checksum                 β”‚
β”‚  - Processing timestamp            β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

## πŸ§ͺ Testing

```bash
# Run all tests
cargo test --workspace

# Unit tests only
cargo test --lib

# Integration tests
cargo test --test '*'

# With logging
RUST_LOG=debug cargo test -- --nocapture
```

## πŸ“Š Dependencies

### Application Layer
- **adaptive-pipeline-domain** - Business logic
- **adaptive-pipeline-bootstrap** - Platform abstraction
- **tokio** - Async runtime
- **rayon** - CPU parallelism

### Infrastructure Layer
- **sqlx** - Database (SQLite)
- **prometheus** - Metrics
- **tracing** - Structured logging
- **brotli / zstd / lz4 / flate2** - Compression
- **aes-gcm / chacha20poly1305** - Encryption
- **argon2 / scrypt** - Key derivation

## πŸ”— Related Crates

- **[adaptive-pipeline-domain]../adaptive-pipeline-domain** - Pure business logic
- **[adaptive-pipeline-bootstrap]../adaptive-pipeline-bootstrap** - Platform abstraction

## πŸ“„ License

BSD 3-Clause License - see [LICENSE](../LICENSE) file for details.

## 🀝 Contributing

Contributions welcome! Focus areas:
- βœ… New pipeline stages
- βœ… Performance optimizations
- βœ… Additional compression/encryption algorithms
- βœ… Enhanced observability
- βœ… Bug fixes and tests

---

**High Performance | Production Ready | Enterprise Security**