streamweave 0.4.0

Composable, async, stream-first computation in pure Rust
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
481
482
483
# streamweave

[![Crates.io](https://img.shields.io/crates/v/streamweave.svg)](https://crates.io/crates/streamweave)
[![Documentation](https://docs.rs/streamweave/badge.svg)](https://docs.rs/streamweave)
[![License: CC BY-SA 4.0](https://img.shields.io/badge/License-CC%20BY--SA%204.0-lightgrey.svg)](https://creativecommons.org/licenses/by-sa/4.0/)

**Core traits and types for StreamWeave**  
*The foundational abstractions that power all StreamWeave data processing.*

The `streamweave` package provides the core traits and types that form the foundation of the StreamWeave framework. All other StreamWeave packages depend on these core abstractions to build producers, transformers, and consumers.

## ✨ Key Features

- **Producer Trait**: Define components that generate data streams
- **Transformer Trait**: Define components that transform data streams
- **Consumer Trait**: Define components that consume data streams
- **Input/Output Traits**: Type-safe stream interfaces
- **Port System**: Type-safe multi-port connections for graph-based processing
- **Configuration System**: Unified configuration for error handling and component naming
- **Error Handling Integration**: Seamless integration with `streamweave-error`

## πŸ“¦ Installation

Add this to your `Cargo.toml`:

```toml
[dependencies]
streamweave = "0.3.0"
```

## πŸš€ Quick Start

### Basic Pipeline Example

```rust
use streamweave::{
    Producer, Transformer, Consumer,
    Input, Output,
};

// This example shows the core traits in action
// See specific package implementations for concrete examples
```

For a complete working example, see the [pipeline package](../pipeline/README.md) or check out the [examples directory](https://github.com/Industrial/streamweave/tree/main/examples).

## πŸ“– API Overview

### Producer Trait

The `Producer` trait defines components that generate data streams. Producers are the starting point of any StreamWeave pipeline.

```rust
use streamweave::Producer;

#[async_trait::async_trait]
trait Producer: Output {
    type OutputPorts: PortList;
    
    fn produce(&mut self) -> Self::OutputStream;
    
    // Configuration methods
    fn with_config(&self, config: ProducerConfig<Self::Output>) -> Self;
    fn with_name(self, name: String) -> Self;
    
    // Error handling
    fn handle_error(&self, error: &StreamError<Self::Output>) -> ErrorAction;
}
```

**Key Methods:**
- `produce()` - Generates the output stream
- `with_config()` - Applies configuration (error strategy, name)
- `handle_error()` - Handles errors according to configured strategy

**Example Producer Implementation:**

```rust
use streamweave::{Producer, Output, ProducerConfig};
use streamweave_error::ErrorStrategy;
use futures::Stream;
use std::pin::Pin;

struct NumberProducer {
    numbers: Vec<i32>,
    config: ProducerConfig<i32>,
}

impl Output for NumberProducer {
    type Output = i32;
    type OutputStream = Pin<Box<dyn Stream<Item = i32> + Send>>;
}

#[async_trait::async_trait]
impl Producer for NumberProducer {
    type OutputPorts = (i32,);
    
    fn produce(&mut self) -> Self::OutputStream {
        Box::pin(futures::stream::iter(self.numbers.clone()))
    }
    
    fn set_config_impl(&mut self, config: ProducerConfig<Self::Output>) {
        self.config = config;
    }
    
    fn get_config_impl(&self) -> &ProducerConfig<Self::Output> {
        &self.config
    }
    
    fn get_config_mut_impl(&mut self) -> &mut ProducerConfig<Self::Output> {
        &mut self.config
    }
}
```

### Transformer Trait

The `Transformer` trait defines components that transform data streams. Transformers process items as they flow through the pipeline.

```rust
use streamweave::Transformer;

#[async_trait::async_trait]
trait Transformer: Input + Output {
    type InputPorts: PortList;
    type OutputPorts: PortList;
    
    fn transform(&mut self, input: Self::InputStream) -> Self::OutputStream;
    
    // Configuration methods
    fn with_config(&self, config: TransformerConfig<Self::Input>) -> Self;
    fn with_name(self, name: String) -> Self;
    
    // Error handling
    fn handle_error(&self, error: &StreamError<Self::Input>) -> ErrorAction;
}
```

**Key Methods:**
- `transform()` - Transforms the input stream into an output stream
- `with_config()` - Applies configuration (error strategy, name)
- `handle_error()` - Handles errors according to configured strategy

**Example Transformer Implementation:**

```rust
use streamweave::{Transformer, Input, Output, TransformerConfig};
use streamweave_error::ErrorStrategy;
use futures::StreamExt;
use std::pin::Pin;

struct DoubleTransformer {
    config: TransformerConfig<i32>,
}

impl Input for DoubleTransformer {
    type Input = i32;
    type InputStream = Pin<Box<dyn Stream<Item = i32> + Send>>;
}

impl Output for DoubleTransformer {
    type Output = i32;
    type OutputStream = Pin<Box<dyn Stream<Item = i32> + Send>>;
}

#[async_trait::async_trait]
impl Transformer for DoubleTransformer {
    type InputPorts = (i32,);
    type OutputPorts = (i32,);
    
    fn transform(&mut self, input: Self::InputStream) -> Self::OutputStream {
        Box::pin(input.map(|x| x * 2))
    }
    
    fn set_config_impl(&mut self, config: TransformerConfig<Self::Input>) {
        self.config = config;
    }
    
    fn get_config_impl(&self) -> &TransformerConfig<Self::Input> {
        &self.config
    }
    
    fn get_config_mut_impl(&mut self) -> &mut TransformerConfig<Self::Input> {
        &mut self.config
    }
}
```

### Consumer Trait

The `Consumer` trait defines components that consume data streams. Consumers are the end point of a pipeline.

```rust
use streamweave::Consumer;

#[async_trait::async_trait]
trait Consumer: Input {
    type InputPorts: PortList;
    
    async fn consume(&mut self, stream: Self::InputStream);
    
    // Configuration methods
    fn with_config(&self, config: ConsumerConfig<Self::Input>) -> Self;
    fn with_name(self, name: String) -> Self;
    
    // Error handling
    fn handle_error(&self, error: &StreamError<Self::Input>) -> ErrorAction;
}
```

**Key Methods:**
- `consume()` - Consumes the input stream (async)
- `with_config()` - Applies configuration (error strategy, name)
- `handle_error()` - Handles errors according to configured strategy

**Example Consumer Implementation:**

```rust
use streamweave::{Consumer, Input, ConsumerConfig};
use streamweave_error::ErrorStrategy;
use futures::StreamExt;
use std::pin::Pin;
use std::sync::Arc;
use tokio::sync::Mutex;

struct VecConsumer<T> {
    items: Arc<Mutex<Vec<T>>>,
    config: ConsumerConfig<T>,
}

impl<T: Send + Sync + 'static> Input for VecConsumer<T> {
    type Input = T;
    type InputStream = Pin<Box<dyn Stream<Item = T> + Send>>;
}

#[async_trait::async_trait]
impl<T: Send + Sync + 'static> Consumer for VecConsumer<T> {
    type InputPorts = (T,);
    
    async fn consume(&mut self, mut stream: Self::InputStream) {
        while let Some(item) = stream.next().await {
            self.items.lock().await.push(item);
        }
    }
    
    fn set_config_impl(&mut self, config: ConsumerConfig<Self::Input>) {
        self.config = config;
    }
    
    fn get_config_impl(&self) -> &ConsumerConfig<Self::Input> {
        &self.config
    }
    
    fn get_config_mut_impl(&mut self) -> &mut ConsumerConfig<Self::Input> {
        &mut self.config
    }
}
```

### Input and Output Traits

The `Input` and `Output` traits define the stream interfaces for components.

**Input Trait:**
```rust
pub trait Input {
    type Input;
    type InputStream: Stream<Item = Self::Input> + Send;
}
```

**Output Trait:**
```rust
pub trait Output {
    type Output;
    type OutputStream: Stream<Item = Self::Output> + Send;
}
```

These traits ensure type safety and enable components to be composed together in pipelines and graphs.

### Port System

The port system enables type-safe multi-port connections in the Graph API. Ports are represented as tuples, allowing components to have multiple inputs or outputs.

```rust
use streamweave::port::{PortList, GetPort};

// Single port
type SinglePort = (i32,);

// Multiple ports
type MultiPort = (i32, String, bool);

// Extract port types at compile time
type FirstPort = <MultiPort as GetPort<0>>::Type;  // i32
type SecondPort = <MultiPort as GetPort<1>>::Type; // String
type ThirdPort = <MultiPort as GetPort<2>>::Type;  // bool
```

The port system supports up to 12 ports per component, with compile-time type checking.

### Configuration System

All components support configuration through `ProducerConfig`, `TransformerConfig`, and `ConsumerConfig`:

```rust
use streamweave_error::ErrorStrategy;

// Configure error handling
let config = ProducerConfig::default()
    .with_error_strategy(ErrorStrategy::Skip)
    .with_name("my_producer".to_string());

let producer = producer.with_config(config);
```

**Configuration Options:**
- `error_strategy` - How to handle errors (Stop, Skip, Retry, Custom)
- `name` - Component name for logging and metrics

## πŸ“š Usage Examples

### Creating a Producer

```rust
use streamweave::{Producer, Output, ProducerConfig};
use streamweave_error::ErrorStrategy;

// Create a producer with error handling
let producer = MyProducer::new()
    .with_config(
        ProducerConfig::default()
            .with_error_strategy(ErrorStrategy::Retry(3))
            .with_name("data_source".to_string())
    );
```

### Creating a Transformer

```rust
use streamweave::{Transformer, TransformerConfig};
use streamweave_error::ErrorStrategy;

// Create a transformer with error handling
let transformer = MyTransformer::new()
    .with_config(
        TransformerConfig::default()
            .with_error_strategy(ErrorStrategy::Skip)
            .with_name("data_processor".to_string())
    );
```

### Creating a Consumer

```rust
use streamweave::{Consumer, ConsumerConfig};
use streamweave_error::ErrorStrategy;

// Create a consumer with error handling
let consumer = MyConsumer::new()
    .with_config(
        ConsumerConfig {
            error_strategy: ErrorStrategy::Stop,
            name: "data_sink".to_string(),
        }
    );
```

### Error Handling Strategies

All components support multiple error handling strategies:

```rust
use streamweave_error::ErrorStrategy;

// Stop on first error (default)
ErrorStrategy::Stop

// Skip errors and continue processing
ErrorStrategy::Skip

// Retry up to N times
ErrorStrategy::Retry(3)

// Custom error handler
ErrorStrategy::new_custom(|error| {
    // Custom logic
    ErrorAction::Skip
})
```

## πŸ—οΈ Architecture

The streamweave core package provides the foundational abstractions:

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Producer  │───produces───> Stream<T>
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚
       β”‚ Stream flows through
       β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Transformer │───transforms───> Stream<U>
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚
       β”‚ Stream flows through
       β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Consumer   │───consumes───> (writes, stores, etc.)
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

All components:
- Implement `Input` and/or `Output` traits for type safety
- Support configuration for error handling and naming
- Integrate with the error handling system
- Can be used in both Pipeline and Graph APIs

## πŸ”— Dependencies

`streamweave` depends on:

- `tokio` - Async runtime
- `futures` - Stream abstractions
- `async-trait` - Async trait support
- `chrono` - Timestamp support
- `streamweave-error` - Error handling system

## 🎯 Use Cases

The core traits are used to:

1. **Build Custom Components**: Create producers, transformers, and consumers for specific use cases
2. **Type-Safe Composition**: Ensure components can be safely connected in pipelines
3. **Error Handling**: Provide consistent error handling across all components
4. **Graph API**: Enable multi-port connections in complex topologies
5. **Configuration**: Standardize component configuration and naming

## πŸ” Error Handling

All components integrate with the `streamweave-error` package for consistent error handling:

- **Error Strategies**: Stop, Skip, Retry, or Custom handlers
- **Error Context**: Automatic error context creation with timestamps and component info
- **Component Info**: Automatic component identification for error reporting

## ⚑ Performance Considerations

- **Zero-Cost Abstractions**: Traits compile to efficient code with no runtime overhead
- **Stream-Based**: All processing is stream-based for memory efficiency
- **Async**: Full async/await support for concurrent processing
- **Type Safety**: Compile-time type checking prevents runtime errors

## πŸ“ Examples

For more examples, see:
- [Pipeline Examples]https://github.com/Industrial/streamweave/tree/main/examples/basic_pipeline
- [Graph Examples]https://github.com/Industrial/streamweave/tree/main/examples
- [Package Implementations]../ - See specific packages for concrete implementations

## πŸ“– Documentation

- [Full API Documentation]https://docs.rs/streamweave
- [Repository]https://github.com/Industrial/streamweave/tree/main/packages/streamweave
- [StreamWeave Main Documentation]https://docs.rs/streamweave

## πŸ”— See Also

- [streamweave-error]../error/README.md - Error handling system
- [streamweave-pipeline]../pipeline/README.md - Pipeline builder and execution
- [streamweave-graph]../graph/README.md - Graph API for complex topologies
- [streamweave-message]../message/README.md - Message envelope and metadata

## 🀝 Contributing

Contributions are welcome! Please see the [Contributing Guide](https://github.com/Industrial/streamweave/blob/main/CONTRIBUTING.md) for details.

## πŸ“„ License

This project is licensed under the [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/) license.