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
// Copyright 2025 Umberto Gotti <umberto.gotti@umbertogotti.dev>
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
//! Async execution utilities for stream processing.
//!
//! This crate provides subscription-based execution patterns for consuming streams
//! with async handlers. It focuses on the **execution** of stream processing, while
//! `fluxion-stream` focuses on **composition** of streams.
//!
//! # Overview
//!
//! The execution utilities solve a common problem: how to process stream items with
//! async functions while controlling concurrency and cancellation behavior.
//!
//! ## Key Concepts
//!
//! - **Subscription**: Attach an async handler to a stream and run it to completion
//! - **Sequential execution**: Process items one at a time (no concurrent handlers)
//! - **Cancellation**: Automatically cancel outdated work when new items arrive
//! - **Error handling**: Propagate errors from handlers while continuing stream processing
//!
//! # Execution Patterns
//!
//! This crate provides two execution patterns:
//!
//! ## [`subscribe`] - Sequential Processing
//!
//! Process each item sequentially with an async handler. Every item is processed
//! to completion before the next item is handled.
//!
//! **Use when:**
//! - Every item must be processed
//! - Processing order matters
//! - Side effects must occur for each item
//! - Work cannot be skipped
//!
//! **Examples:**
//! - Writing each event to a database
//! - Sending each notification
//! - Processing every transaction
//! - Logging all events
//!
//! ## [`subscribe_latest`] - Latest-Value Processing
//!
//! Process only the latest item, automatically canceling work for outdated items.
//! When a new item arrives while processing, the current work is canceled and the
//! new item is processed instead.
//!
//! **Use when:**
//! - Only the latest value matters
//! - Old values become irrelevant
//! - Expensive operations should skip intermediate values
//! - UI updates or state synchronization
//!
//! **Examples:**
//! - Rendering UI based on latest state
//! - Auto-saving the current document
//! - Updating a preview
//! - Recalculating derived values
//!
//! # Architecture
//!
//! ## Extension Trait Pattern
//!
//! Both utilities are provided as extension traits on `Stream`:
//!
//! ```text
//! use fluxion_exec::SubscribeExt;
//! use futures::StreamExt;
//!
//! # async fn example() {
//! let (tx, rx) = futures::channel::mpsc::unbounded::<i32>();
//! let stream = tokio_stream::wrappers::UnboundedReceiverStream::new(rx);
//!
//! // Any Stream can use subscribe
//! stream.subscribe(|value| async move {
//! println!("Processing: {}", value);
//! Ok::<_, Box<dyn std::error::Error>>(())
//! }).await;
//! # }
//! ```
//!
//! ## Task Spawning
//!
//! Both patterns spawn tokio tasks internally:
//!
//! - **[`subscribe`]**: Spawns one task per stream item (sequential)
//! - **[`subscribe_latest`]**: Spawns tasks and cancels obsolete ones
//!
//! This means:
//! - Handlers must be `Send + 'static`
//! - Processing happens on the tokio runtime
//! - Multiple streams can be processed concurrently
//!
//! # Performance Characteristics
//!
//! ## Sequential Processing (`subscribe`)
//!
//! - **Latency**: Items wait for previous items to complete
//! - **Throughput**: Limited by handler execution time
//! - **Memory**: $O(1)$ - processes one item at a time
//! - **Ordering**: Maintains strict order
//!
//! **Best for**: Correctness over throughput
//!
//! ## Latest-Value Processing (`subscribe_latest`)
//!
//! - **Latency**: Immediate start on new items (cancels old work)
//! - **Throughput**: Skips intermediate values for efficiency
//! - **Memory**: $O(1)$ - one active task at a time
//! - **Ordering**: Processes latest available
//!
//! **Best for**: Responsiveness over completeness
//!
//! # Comparison with Other Patterns
//!
//! ## vs `for_each` (futures)
//!
//! ```text
//! // futures::StreamExt::for_each - blocks until stream ends
//! stream.for_each(|item| async {
//! process(item).await;
//! }).await;
//!
//! // subscribe - returns immediately, spawns background task
//! stream.subscribe(process).await;
//! ```
//!
//! ## vs `buffer_unordered` (futures)
//!
//! ```text
//! // futures - processes N items concurrently
//! stream.map(process).buffer_unordered(10).collect().await;
//!
//! // subscribe - strictly sequential
//! stream.subscribe(process).await;
//! ```
//!
//! ## vs Manual Task Spawning
//!
//! ```text
//! // Manual - no cancellation on new items
//! while let Some(item) = stream.next().await {
//! tokio::spawn(async move { process(item).await });
//! }
//!
//! // subscribe_latest - automatic cancellation
//! stream.subscribe_latest(process).await;
//! ```
//!
//! # Common Patterns
//!
//! ## Pattern: Database Writes
//!
//! Every item must be persisted:
//!
//! ```text
//! use fluxion_exec::SubscribeExt;
//! use futures::StreamExt;
//!
//! # async fn example() {
//! # let (tx, rx) = futures::channel::mpsc::unbounded::<i32>();
//! # let stream = tokio_stream::wrappers::UnboundedReceiverStream::new(rx);
//! stream.subscribe(|event| async move {
//! // Save to database
//! // database.insert(event).await?;
//! Ok::<_, Box<dyn std::error::Error>>(())
//! }).await;
//! # }
//! ```
//!
//! ## Pattern: UI Updates
//!
//! Only latest state matters:
//!
//! ```text
//! use fluxion_exec::SubscribeLatestExt;
//! use futures::StreamExt;
//!
//! # async fn example() {
//! # let (tx, rx) = futures::channel::mpsc::unbounded::<i32>();
//! # let stream = tokio_stream::wrappers::UnboundedReceiverStream::new(rx);
//! stream.subscribe_latest(|state| async move {
//! // Render UI with latest state
//! // update_ui(state).await?;
//! Ok::<_, Box<dyn std::error::Error>>(())
//! }).await;
//! # }
//! ```
//!
//! ## Pattern: Batch Processing
//!
//! Combine with `chunks` for batch operations:
//!
//! ```text
//! use fluxion_exec::SubscribeExt;
//! use futures::StreamExt;
//!
//! # async fn example() {
//! # let (tx, rx) = futures::channel::mpsc::unbounded::<i32>();
//! # let stream = tokio_stream::wrappers::UnboundedReceiverStream::new(rx);
//! stream
//! .chunks(100) // Batch 100 items
//! .subscribe(|batch| async move {
//! // Process batch
//! // database.insert_batch(batch).await?;
//! Ok::<_, Box<dyn std::error::Error>>(())
//! })
//! .await;
//! # }
//! ```
//!
//! ## Pattern: Error Recovery
//!
//! Handle errors without stopping the stream:
//!
//! ```text
//! use fluxion_exec::SubscribeExt;
//! use futures::StreamExt;
//!
//! # async fn example() {
//! # let (tx, rx) = futures::channel::mpsc::unbounded::<i32>();
//! # let stream = tokio_stream::wrappers::UnboundedReceiverStream::new(rx);
//! stream.subscribe(|item| async move {
//! match process_item(item).await {
//! Ok(result) => Ok(()),
//! Err(e) => {
//! eprintln!("Error processing item: {}", e);
//! Ok(()) // Continue processing despite error
//! }
//! }
//! }).await;
//!
//! # async fn process_item(_item: i32) -> Result<(), Box<dyn std::error::Error>> { Ok(()) }
//! # }
//! ```
//!
//! # Anti-Patterns
//!
//! ## ❌ Don't: Use `subscribe_latest` for Critical Work
//!
//! ```text
//! // BAD: Payment processing might be skipped!
//! payment_stream.subscribe_latest(|payment| async move {
//! process_payment(payment).await // Could be canceled!
//! }).await;
//! ```
//!
//! Use `subscribe` for work that must complete:
//!
//! ```text
//! // GOOD: Every payment is processed
//! payment_stream.subscribe(|payment| async move {
//! process_payment(payment).await
//! }).await;
//! ```
//!
//! ## ❌ Don't: Block in Handlers
//!
//! ```text
//! // BAD: Blocking operations stall the executor
//! stream.subscribe(|item| async move {
//! std::thread::sleep(Duration::from_secs(1)); // Blocks!
//! Ok(())
//! }).await;
//! ```
//!
//! Use async operations or `spawn_blocking`:
//!
//! ```text
//! // GOOD: Async sleep doesn't block
//! stream.subscribe(|item| async move {
//! tokio::time::sleep(Duration::from_secs(1)).await;
//! Ok(())
//! }).await;
//! ```
//!
//! ## ❌ Don't: Use for CPU-Intensive Work
//!
//! ```text
//! // BAD: CPU-intensive work on async runtime
//! stream.subscribe(|data| async move {
//! expensive_computation(data); // Blocks executor!
//! Ok(())
//! }).await;
//! ```
//!
//! Offload to blocking threadpool:
//!
//! ```text
//! // GOOD: CPU work on dedicated threads
//! stream.subscribe(|data| async move {
//! tokio::task::spawn_blocking(move || {
//! expensive_computation(data)
//! }).await?;
//! Ok(())
//! }).await;
//! ```
//!
//! # Error Handling
//!
//! Both subscription methods return `Result`:
//!
//! - **`Ok(())`**: Stream completed successfully
//! - **`Err(e)`**: Handler returned an error
//!
//! Errors from handlers are propagated but don't stop stream processing automatically.
//! Design your handlers to return `Ok(())` to continue processing despite errors, or
//! return `Err(e)` to stop on first error.
//!
//! # Getting Started
//!
//! Add to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! fluxion-exec = { path = "../fluxion-exec" }
//! tokio = { version = "1.48", features = ["rt", "sync"] }
//! futures = "0.3"
//! ```
//!
//! See individual trait documentation for detailed examples:
//! - [`SubscribeExt`] for sequential processing
//! - [`SubscribeLatestExt`] for latest-value processing
//!
//! [`subscribe`]: SubscribeExt::subscribe
//! [`subscribe_latest`]: SubscribeLatestExt::subscribe_latest
extern crate alloc;
// Re-export commonly used types
pub use SubscribeExt;
pub use SubscribeLatestExt;