fluxion-stream
Part of Fluxion - A reactive stream processing library for Rust
Stream combinators for async Rust with strong temporal-ordering guarantees. This crate provides composable operators and lightweight sequencing utilities designed for correctness and performance in event-driven systems.
Table of Contents
- Overview
- Key Features
- Core Concepts
- Stream Operators
- Operator Selection Guide
- Quick Start
- Examples
- Testing
- License
Overview
fluxion-stream is a collection of reactive stream operators that maintain temporal ordering across asynchronous operations. Unlike standard stream combinators, all operators in this crate respect the intrinsic ordering of items (via timestamps, sequence numbers, or other ordering mechanisms), ensuring correct temporal sequencing even when events arrive out of order.
Use this crate when:
- You need to combine multiple async streams while preserving temporal order
- Events may arrive out of order and need to be resequenced
- You're building reactive systems (dashboards, monitoring, event processing)
- You need composable stream operations with correctness guarantees
Key Features
- Temporal Ordering: All operators maintain temporal correctness via the
Timestampedtrait - Composable Operators: 10+ stream combinators designed to work together seamlessly
- Error Propagation: Structured error handling through
StreamItem<T>enum - Zero-Copy: Minimal allocations and efficient buffering strategies
- Tokio Integration: Built on tokio streams for async runtime compatibility
- Type Safety: Compile-time guarantees for ordering and type compatibility
Core Concepts
Timestamp Traits
Fluxion uses two traits for temporal ordering:
HasTimestamp - Minimal Read-Only Interface
Provides read-only access to timestamp values:
Timestamped - Construction Methods
Extends HasTimestamp with an Inner type and construction/deconstruction capabilities:
When to use each:
- Implement
HasTimestampfor types that only need to expose a timestamp (read-only) - Implement
Timestampedfor wrapper types that construct timestamped values - Most operators require only
HasTimestampfor ordering
Implementations:
Sequenced<T>- Test utility fromfluxion-test-utilsusing monotonically growing sequence numbers- Custom domain types - Implement
HasTimestampfor your types (e.g., events with built-in timestamps)
Temporal Ordering
Temporal ordering means items are processed based on their intrinsic timestamp, not arrival time:
// Stream 1 sends: [timestamp=2, value=B]
// Stream 2 sends: [timestamp=1, value=A]
// Merged output: [timestamp=1, value=A], [timestamp=2, value=B] ✓ Correct temporal order
How it works:
- Each item has a
timestamp()value (chrono::DateTime, u64 counter, etc.) - Operators buffer items and emit them in order of their
timestamp()value - Late-arriving items are placed correctly in the sequence
- Gaps in timestamps may cause buffering until the sequence is complete
When to use:
- Event sourcing and event-driven architectures
- Time-series data processing
- Distributed system event correlation
- Any scenario where arrival order ≠ logical order
Error Propagation
All operators use StreamItem<T> for structured error handling:
Error handling patterns:
// Pattern 1: Unwrap (panic on error)
let value = stream.next.await.unwrap.unwrap;
// Pattern 2: Filter errors
let values = stream
.filter_map
.collect.await;
// Pattern 3: Handle explicitly
match stream.next.await
See Error Handling Guide for comprehensive patterns.
Stream Operators
Combination Operators
combine_latest
Combines multiple streams, emitting when any stream emits (after all have emitted once).
Use case: Dashboard combining data from multiple sources
use CombineLatestExt;
let combined = stream1.combine_latest;
Behavior:
- Waits for initial values from all streams
- Emits combined state when any stream produces a value
- Maintains latest value from each stream
- Preserves temporal ordering based on triggering stream
Full documentation | Tests | Benchmarks
with_latest_from
Samples secondary streams only when primary stream emits.
Use case: User actions enriched with latest configuration/state
use WithLatestFromExt;
let enriched = user_clicks.with_latest_from;
Behavior:
- Only emits when primary stream emits
- Samples latest values from secondary streams
- Primary stream drives the emission timing
- Secondary streams provide context
Full documentation | Tests | Benchmarks
ordered_merge
Merges multiple streams preserving temporal order.
Use case: Event log from multiple services
use OrderedStreamExt;
let merged = stream1.ordered_merge;
Behavior:
- Emits all items from all streams
- Items emitted in order of their
timestamp()value - Buffers items to ensure correct ordering
- Completes when all input streams complete
Full documentation | Tests | Benchmarks
merge_with
Stateful merging of multiple streams with shared state.
Use case: Repository pattern, event sourcing, aggregating events into domain state
use MergedStream;
use Sequenced;
let merged =
.merge_with
.merge_with
.into_fluxion_stream;
Behavior:
- Maintains shared mutable state across all merged streams
- Processes events in temporal order (uses
ordered_mergeinternally) - Each
merge_withcall adds a new stream to the merge - State is locked per-item for thread safety
- Can chain with other operators via
into_fluxion_stream()
Key Features:
- Stateful: Shared state accessible to all processing functions
- Composable: Chain multiple
merge_withcalls - Type-safe: Output type specified once in
seed() - Ordered: Temporal ordering guaranteed across all streams
Full documentation | Tests | Benchmarks
Filtering Operators
emit_when
Gates source emissions based on filter stream conditions.
Use case: Only emit sensor data when system is active
use EmitWhenExt;
let gated = source.emit_when;
Behavior:
- Buffers source items when gate is closed
- Emits buffered items when gate opens
- Maintains temporal ordering
- Completes when source completes
Full documentation | Tests | Benchmarks
take_latest_when
Samples source when filter condition is met.
Use case: Capture latest sensor reading on user request
use TakeLatestWhenExt;
let sampled = source.take_latest_when;
Behavior:
- Maintains latest value from source
- Emits latest value when filter condition is true
- Discards intermediate values (only latest matters)
- Useful for sampling / snapshot patterns
Full documentation | Tests | Benchmarks
sample_ratio
Probabilistic downsampling with configurable ratio.
Use case: Load reduction, logging sampling, monitoring downsampling
use SampleRatioExt;
// Sample approximately 10% of items
let sampled = stream.sample_ratio;
// For testing with deterministic seed
let sampled = stream.sample_ratio;
Behavior:
- Ratio range:
0.0(emit nothing) to1.0(emit all) - Panics if ratio outside valid range
- Deterministic with same seed for reproducible tests
- Errors always pass through (never sampled)
- Timestamp-preserving
Full documentation | Tests | Benchmarks
take_while_with
Emits while condition holds, terminates when false.
Use case: Process events until shutdown signal
use TakeWhileExt;
let bounded = source.take_while_with;
Behavior:
- Emits source items while condition is true
- Terminates stream when condition becomes false
- First false terminates immediately
- Preserves temporal ordering until termination
Full documentation | Tests | Benchmarks
Transformation Operators
scan_ordered
Accumulates state across stream items, emitting intermediate results.
Use case: Running totals, moving averages, state machines, building collections over time
use ScanOrderedExt;
use Sequenced;
let sums = stream.;
Behavior:
- Maintains accumulator state that persists across all items
- Emits transformed value for each input
- Errors propagate without affecting state
- Can transform types (e.g., i32 → String)
- Preserves timestamps from source items
Common Patterns:
- Running sum/count: Accumulate numeric values
- Building collections: Gather items into Vec/HashMap
- State machines: Track state transitions with context
- Moving calculations: Windowed statistics
Full documentation | Tests | Benchmarks
combine_with_previous
Pairs each value with the previous value.
Use case: Detect value changes or calculate deltas
use CombineWithPreviousExt;
let pairs = stream.combine_with_previous;
// Output: WithPrevious { previous: Some(1), current: 2 }
Behavior:
- First item has
previous = None - Subsequent items have
previous = Some(prev) - Useful for change detection and delta calculations
- Preserves temporal ordering
Full documentation | Tests | Benchmarks
window_by_count
Batches stream items into fixed-size windows.
Use case: Batch processing, aggregating metrics, reducing API calls
use WindowByCountExt;
let windowed = stream.window_by_count;
// Emits: vec![item1, item2, item3], vec![item4, item5, item6], ...
Behavior:
- Collects items into windows of specified size
- Emits complete window when size is reached
- Emits partial window on stream completion
- Errors pass through immediately (not batched)
- Useful for batch processing and reducing downstream operations
Full documentation | Tests | Benchmarks
Utility Operators
map_ordered
Maps values while preserving ordering wrapper.
let mapped = stream.map_ordered;
Full documentation | Tests | Benchmarks
filter_ordered
Filters values while preserving ordering wrapper.
let filtered = stream.filter_ordered;
Full documentation | Tests | Benchmarks
distinct_until_changed
Suppresses consecutive duplicate values.
Full documentation | Tests | Benchmarks
distinct_until_changed_by
Custom duplicate suppression with comparison function.
Use case: Field comparison, case-insensitive matching, threshold filtering, custom equality
Behavior:
- Custom comparison function for flexible duplicate detection
- No
PartialEqrequirement on inner type - Comparison returns
trueif values considered equal (filtered) - Follows Rust patterns:
sort_by,dedup_by,max_by
Full documentation | Tests | Benchmarks
tap
Perform side-effects without transforming items.
Use case: Debugging, logging, metrics collection, tracing
use ;
let pipeline = rx.into_fluxion_stream
.tap
.map_ordered
.tap;
Behavior:
- Pass-through operator: items flow unchanged
- Callback invoked with reference to each value
- Errors pass through unchanged (callback not invoked for errors)
- Timestamp-preserving
Full documentation | Tests | Benchmarks
Error Handling Operators
on_error
Selectively consume or propagate errors using the Chain of Responsibility pattern.
Use case: Logging errors, metrics collection, conditional error recovery
use OnErrorExt;
let handled = stream
.on_error
.on_error;
Behavior:
- Handler returns
trueto consume error (removesStreamItem::Error) - Handler returns
falseto propagate error downstream - Multiple
on_errorcalls can be chained - Value items pass through unchanged
- Enables side effects (logging, metrics) while filtering errors
Full documentation | Tests | Specification
Splitting Operators
partition
Splits a stream into two based on a predicate.
Use case: Error routing, priority queues, type routing, threshold filtering
use ;
use Sequenced;
use StreamExt;
let = unbounded_channel;
// Partition numbers into even and odd
let = rx.into_fluxion_stream
.partition;
tx.send.unwrap;
tx.send.unwrap;
tx.send.unwrap;
tx.send.unwrap;
drop;
// evens: 2, 4
// odds: 1, 3
Behavior:
- Chain-breaking operator (returns two streams)
- Spawns background routing task
- Timestamp-preserving (original timestamps maintained)
- Error propagation to both output streams
- Unbounded internal buffers
- Each item goes to exactly one output stream
Full documentation | Tests | Benchmarks
Multicasting Operators
share
Convert a cold stream into a hot, multi-subscriber broadcast source.
Use case: Share expensive computations across multiple consumers
use ;
use Sequenced;
let = ;
// Source operators run ONCE
let source = rx.into_fluxion_stream
.map_ordered;
// Share among multiple subscribers
let shared = source.share;
// Each subscriber chains independently
let evens = shared.subscribe.unwrap
.filter_ordered;
let strings = shared.subscribe.unwrap
.map_ordered;
Behavior:
- Hot stream: Late subscribers do not receive past items
- Shared execution: Source operators run once; results are broadcast to all
- Subscription factory: Call
subscribe()to create independent subscriber streams - Error propagation: Errors broadcast to all subscribers, then source closes
Full documentation | Tests | Benchmarks
Operator Selection Guide
When You Need Combined State
| Operator | Triggers On | Output | Best For |
|---|---|---|---|
combine_latest |
Any stream emits | Latest from all streams | Dashboards, state aggregation |
with_latest_from |
Primary emits | Primary + context | Enriching events with state |
merge_with |
Any stream emits | Transformed via state | Repository pattern, event sourcing |
When You Need All Items
| Operator | Output | Ordering | Best For |
|---|---|---|---|
ordered_merge |
Every item | Temporal | Event logs, audit trails |
combine_with_previous |
Pairs (prev, curr) | Temporal | Change detection, deltas |
scan_ordered |
Accumulated state | Temporal | Running totals, state machines |
When You Need Conditional Emission
| Operator | Buffering | Termination | Best For |
|---|---|---|---|
emit_when |
Yes (buffers when gated) | Source completes | Conditional processing |
take_latest_when |
No (only latest) | Source completes | Sampling, snapshots |
take_while_with |
No | First false | Bounded processing |
sample_ratio |
No | Source completes | Load reduction, logging sampling |
When You Need Deduplication
| Operator | Comparison | Requirement | Best For |
|---|---|---|---|
distinct_until_changed |
PartialEq |
Inner type must implement PartialEq |
Simple duplicate suppression |
distinct_until_changed_by |
Custom function | No trait requirements | Field comparison, case-insensitive, threshold-based |
When You Need Error Handling
| Operator | Consumes Errors | Enables Side Effects | Propagation Control | Best For |
|---|---|---|---|---|
on_error |
Selective | Yes (logging, metrics) | Handler-controlled | Layered error handling, monitoring |
When You Need Debugging / Observability
| Operator | Transforms Data | Side Effects | Best For |
|---|---|---|---|
tap |
No (pass-through) | Yes (logging, metrics) | Debugging pipelines, tracing, metrics |
When You Need Multicasting
| Operator | Late Subscribers | Source Execution | Best For |
|---|---|---|---|
share |
Miss past items | Once (broadcast) | Sharing expensive computations, fan-out |
When You Need Stream Splitting
| Operator | Outputs | Routing | Best For |
|---|---|---|---|
partition |
Two streams | By predicate | Error routing, priority queues, threshold filtering |
Quick Start
Add to your Cargo.toml:
[]
= "0.5"
= "0.5"
= { = "1", = ["full"] }
= "0.3"
Basic usage:
use ;
use Sequenced;
use StreamExt;
async
Examples
Combine Latest for Dashboard
use ;
use Sequenced;
use StreamExt;
async
Filter with emit_when
use ;
use Sequenced;
use StreamExt;
async
Running Total with scan_ordered
use ;
use Sequenced;
use StreamExt;
async
Change Detection with combine_with_previous
use ;
use Sequenced;
use StreamExt;
async
Testing
Run all tests:
Run specific operator tests:
Run with error tests:
The crate includes comprehensive test coverage for:
- Operator functionality (basic behavior)
- Error propagation scenarios
- Edge cases (empty streams, single items, etc.)
- Temporal ordering correctness
- Concurrent stream handling
License
Licensed under the Apache License, Version 2.0. See LICENSE for details.