task_forge/
lib.rs

1//! # Task Forge
2//!
3//! **Task Forge** is a simple and flexible library for managing asynchronous task execution in Rust.  
4//! It provides an efficient `TaskForge` structure for spawning, tracking, and communicating with tasks concurrently.
5//!
6//! ## Features
7//! - Spawn and manage multiple asynchronous tasks.
8//! - Send messages to tasks and receive their outputs.
9//! - Track task states (`Running`, `Closed`).
10//! - Automatically notify when tasks complete or when the forge is cleaned.
11//! - Flexible task creation with support for generic task arguments.
12//! - Customizable error handling using different error handlers.
13//! - Wait for all tasks to finish with an optional timeout.
14//!
15//! ## Example Usage
16//! ```rust
17//! use task_forge::{task::TaskTrait, Sender, Receiver, channel, TaskForge, task::TaskInterface};
18//!
19//! struct EchoTask;
20//!
21//! impl TaskTrait<String, String, String> for EchoTask {
22//!     fn begin(
23//!         _: String,
24//!         mut message_receiver: Receiver<String>,
25//!         task_interface: TaskInterface<String>,
26//!     ) {
27//!         tokio::spawn(async move {
28//!             if let Some(input) = message_receiver.recv().await {
29//!                 task_interface
30//!                     .output(format!("Echo: {input}"))
31//!                     .await
32//!                     .unwrap();
33//!             }
34//!         });
35//!     }
36//! }
37//!
38//! #[tokio::main]
39//! async fn main() {
40//!     let (task_forge, _) = TaskForge::<String, String>::new();
41//!
42//!     let task_id = 1;
43//!     task_forge.new_task::<EchoTask, _>(task_id, "Hello".to_string()).await.unwrap();
44//!     task_forge.send(task_id, "Hello again!".to_string()).await.unwrap();
45//!
46//!     let mut result_receiver = task_forge.new_result_redirection().await;
47//!     let result = result_receiver.recv().await.unwrap();
48//!     assert_eq!(result.output.as_ref(), "Echo: Hello again!");
49//! }
50//! ```
51
52/// This module contains error handling types.
53pub mod errors;
54/// Contains the trait definitions for tasks.
55pub mod task;
56/// The implementation of the task forge.
57pub mod task_forge;
58
59pub use task::TaskTrait;
60pub use task_forge::{OpId, TaskForge};
61pub use tokio::sync::mpsc::{channel, Receiver, Sender};
62
63/// Type alias for a communication channel.
64pub type Channel<T> = (Sender<T>, Receiver<T>);
65
66/// Creates a new message channel with a fixed buffer size.
67pub fn new_channel<T: Send>() -> Channel<T> {
68    tokio::sync::mpsc::channel(task_forge::CHANNEL_SIZE) // Taille configurable
69}