Compare commits
1 Commits
main
...
0c5b5051e3
| Author | SHA1 | Date | |
|---|---|---|---|
| 0c5b5051e3 |
18
CHANGELOG.md
18
CHANGELOG.md
@@ -6,24 +6,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.10.0] - 2025-11-15
|
||||
|
||||
### Added
|
||||
- implement take errors
|
||||
|
||||
## [0.9.0] - 2025-11-15
|
||||
|
||||
### Added
|
||||
- mad not properly surfaces panics
|
||||
- add publish
|
||||
- add readme
|
||||
|
||||
### Fixed
|
||||
- *(deps)* update all dependencies (#38)
|
||||
|
||||
### Other
|
||||
- *(deps)* update rust crate tracing-subscriber to v0.3.20 (#37)
|
||||
|
||||
## [0.8.1] - 2025-08-09
|
||||
|
||||
### Other
|
||||
|
||||
122
Cargo.lock
generated
122
Cargo.lock
generated
@@ -13,9 +13,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.101"
|
||||
version = "1.0.100"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5f0e0fee31ef5ed1ba1316088939cea399010ed7731dba877ed44aeb407a75ea"
|
||||
checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"
|
||||
|
||||
[[package]]
|
||||
name = "async-trait"
|
||||
version = "0.1.89"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
@@ -184,11 +195,11 @@ checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
|
||||
|
||||
[[package]]
|
||||
name = "matchers"
|
||||
version = "0.2.0"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
|
||||
checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558"
|
||||
dependencies = [
|
||||
"regex-automata",
|
||||
"regex-automata 0.1.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -211,9 +222,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "notmad"
|
||||
version = "0.11.0"
|
||||
version = "0.8.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"futures",
|
||||
"futures-util",
|
||||
"rand",
|
||||
@@ -227,11 +239,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "nu-ansi-term"
|
||||
version = "0.50.3"
|
||||
version = "0.46.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||
checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"overload",
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -240,6 +253,12 @@ version = "1.20.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775"
|
||||
|
||||
[[package]]
|
||||
name = "overload"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot"
|
||||
version = "0.12.3"
|
||||
@@ -341,6 +360,27 @@ dependencies = [
|
||||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-automata 0.4.9",
|
||||
"regex-syntax 0.8.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.1.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132"
|
||||
dependencies = [
|
||||
"regex-syntax 0.6.29",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.9"
|
||||
@@ -349,9 +389,15 @@ checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-syntax",
|
||||
"regex-syntax 0.8.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.6.29"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1"
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.5"
|
||||
@@ -420,18 +466,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.18"
|
||||
version = "2.0.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
|
||||
checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.18"
|
||||
version = "2.0.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
|
||||
checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -450,9 +496,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.49.0"
|
||||
version = "1.48.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86"
|
||||
checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"libc",
|
||||
@@ -478,9 +524,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tokio-util"
|
||||
version = "0.7.18"
|
||||
version = "0.7.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"
|
||||
checksum = "2efa149fe76073d6e8fd97ef4f4eca7b67f599660115591483572e406e165594"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
@@ -491,9 +537,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tracing"
|
||||
version = "0.1.44"
|
||||
version = "0.1.41"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
|
||||
checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"pin-project-lite",
|
||||
@@ -503,9 +549,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tracing-attributes"
|
||||
version = "0.1.31"
|
||||
version = "0.1.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
|
||||
checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -514,9 +560,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tracing-core"
|
||||
version = "0.1.36"
|
||||
version = "0.1.33"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
|
||||
checksum = "e672c95779cf947c5311f83787af4fa8fffd12fb27e4993211a84bdfd9610f9c"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"valuable",
|
||||
@@ -535,14 +581,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tracing-subscriber"
|
||||
version = "0.3.22"
|
||||
version = "0.3.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f30143827ddab0d256fd843b7a66d164e9f271cfa0dde49142c5ca0ca291f1e"
|
||||
checksum = "e8189decb5ac0fa7bc8b96b7cb9b2701d60d48805aca84a238004d665fcc4008"
|
||||
dependencies = [
|
||||
"matchers",
|
||||
"nu-ansi-term",
|
||||
"once_cell",
|
||||
"regex-automata",
|
||||
"regex",
|
||||
"sharded-slab",
|
||||
"smallvec",
|
||||
"thread_local",
|
||||
@@ -599,6 +645,28 @@ dependencies = [
|
||||
"wit-bindgen-rt",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi"
|
||||
version = "0.3.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
|
||||
dependencies = [
|
||||
"winapi-i686-pc-windows-gnu",
|
||||
"winapi-x86_64-pc-windows-gnu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi-i686-pc-windows-gnu"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
|
||||
|
||||
[[package]]
|
||||
name = "winapi-x86_64-pc-windows-gnu"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
|
||||
@@ -3,9 +3,10 @@ members = ["crates/*"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
version = "0.11.0"
|
||||
version = "0.8.1"
|
||||
|
||||
[workspace.dependencies]
|
||||
mad = { path = "crates/mad" }
|
||||
|
||||
anyhow = { version = "1.0.71" }
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
|
||||
214
README.md
214
README.md
@@ -4,163 +4,165 @@
|
||||
[](https://docs.rs/notmad)
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
|
||||
A simple lifecycle manager for long-running Rust applications. Run multiple services concurrently with graceful shutdown handling.
|
||||
## Overview
|
||||
|
||||
MAD is a robust lifecycle manager designed for long-running Rust operations. It provides a simple, composable way to manage multiple concurrent services within your application, handling graceful startup and shutdown automatically.
|
||||
|
||||
### Perfect for:
|
||||
- 🌐 Web servers
|
||||
- 📨 Queue consumers and message processors
|
||||
- 🔌 gRPC servers
|
||||
- ⏰ Cron job runners
|
||||
- 🔄 Background workers
|
||||
- 📡 Any long-running async operations
|
||||
|
||||
## Features
|
||||
|
||||
- **Component-based architecture** - Build your application from composable, reusable components
|
||||
- **Graceful shutdown** - Automatic handling of shutdown signals with proper cleanup
|
||||
- **Concurrent execution** - Run multiple components in parallel with tokio
|
||||
- **Error handling** - Built-in error propagation and logging
|
||||
- **Cancellation tokens** - Coordinate shutdown across all components
|
||||
- **Minimal boilerplate** - Focus on your business logic, not lifecycle management
|
||||
|
||||
## Installation
|
||||
|
||||
Add MAD to your `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
notmad = "0.10.0"
|
||||
notmad = "0.7.5"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
async-trait = "0.1"
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
Here's a simple example of a component that simulates a long-running server:
|
||||
|
||||
```rust
|
||||
use notmad::{Component, Mad};
|
||||
use mad::{Component, Mad};
|
||||
use async_trait::async_trait;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
struct MyService;
|
||||
// Define your component
|
||||
struct WebServer {
|
||||
port: u16,
|
||||
}
|
||||
|
||||
impl Component for MyService {
|
||||
async fn run(&self, cancellation: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
println!("Service running...");
|
||||
cancellation.cancelled().await;
|
||||
println!("Service stopped");
|
||||
#[async_trait]
|
||||
impl Component for WebServer {
|
||||
fn name(&self) -> Option<String> {
|
||||
Some(format!("WebServer on port {}", self.port))
|
||||
}
|
||||
|
||||
async fn run(&self, cancellation: CancellationToken) -> Result<(), mad::MadError> {
|
||||
println!("Starting web server on port {}", self.port);
|
||||
|
||||
// Your server logic here
|
||||
// The cancellation token will be triggered on shutdown
|
||||
tokio::select! {
|
||||
_ = cancellation.cancelled() => {
|
||||
println!("Shutting down web server");
|
||||
}
|
||||
_ = self.serve() => {
|
||||
println!("Server stopped");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl WebServer {
|
||||
async fn serve(&self) {
|
||||
// Simulate a running server
|
||||
tokio::time::sleep(std::time::Duration::from_secs(3600)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
// Build and run your application
|
||||
Mad::builder()
|
||||
.add(MyService)
|
||||
.add(WebServer { port: 8080 })
|
||||
.add(WebServer { port: 8081 }) // You can add multiple instances
|
||||
.run()
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
## Basic Usage
|
||||
## Advanced Usage
|
||||
|
||||
### Axum Web Server with Graceful Shutdown
|
||||
### Custom Components
|
||||
|
||||
Here's how to run an Axum server with MAD's graceful shutdown:
|
||||
Components can be anything that implements the `Component` trait:
|
||||
|
||||
```rust
|
||||
use axum::{Router, routing::get};
|
||||
use notmad::{Component, ComponentInfo};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use mad::{Component, Mad};
|
||||
use async_trait::async_trait;
|
||||
|
||||
struct WebServer {
|
||||
port: u16,
|
||||
struct QueueProcessor {
|
||||
queue_name: String,
|
||||
}
|
||||
|
||||
impl Component for WebServer {
|
||||
fn info(&self) -> ComponentInfo {
|
||||
format!("WebServer:{}", self.port).into()
|
||||
#[async_trait]
|
||||
impl Component for QueueProcessor {
|
||||
fn name(&self) -> Option<String> {
|
||||
Some(format!("QueueProcessor-{}", self.queue_name))
|
||||
}
|
||||
|
||||
async fn run(&self, cancel: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
let app = Router::new().route("/", get(|| async { "Hello, World!" }));
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", self.port))
|
||||
.await?;
|
||||
|
||||
println!("Listening on http://0.0.0.0:{}", self.port);
|
||||
|
||||
// Run server with graceful shutdown
|
||||
axum::serve(listener, app)
|
||||
.with_graceful_shutdown(async move {
|
||||
cancel.cancelled().await;
|
||||
println!("Shutting down server...");
|
||||
})
|
||||
.await?;
|
||||
|
||||
async fn run(&self, cancellation: CancellationToken) -> Result<(), mad::MadError> {
|
||||
while !cancellation.is_cancelled() {
|
||||
// Process messages from queue
|
||||
self.process_next_message().await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Run Multiple Services
|
||||
### Error Handling
|
||||
|
||||
MAD provides comprehensive error handling through the `MadError` type with automatic conversion from `anyhow::Error`:
|
||||
|
||||
```rust
|
||||
Mad::builder()
|
||||
.add(WebServer { port: 8080 })
|
||||
.add(WebServer { port: 8081 })
|
||||
.run()
|
||||
.await?;
|
||||
```
|
||||
|
||||
### Use Functions as Components
|
||||
|
||||
```rust
|
||||
Mad::builder()
|
||||
.add_fn(|cancel| async move {
|
||||
println!("Running...");
|
||||
cancel.cancelled().await;
|
||||
Ok(())
|
||||
})
|
||||
.run()
|
||||
.await?;
|
||||
```
|
||||
|
||||
## Lifecycle Hooks
|
||||
|
||||
Components support optional setup and cleanup phases:
|
||||
|
||||
```rust
|
||||
impl Component for DatabaseService {
|
||||
async fn setup(&self) -> Result<(), notmad::MadError> {
|
||||
println!("Connecting to database...");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run(&self, cancel: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
cancel.cancelled().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn close(&self) -> Result<(), notmad::MadError> {
|
||||
println!("Closing database connection...");
|
||||
Ok(())
|
||||
async fn run(&self, cancellation: CancellationToken) -> Result<(), mad::MadError> {
|
||||
// Errors automatically convert from anyhow::Error to MadError
|
||||
database_operation().await?;
|
||||
|
||||
// Or return explicit errors
|
||||
if some_condition {
|
||||
return Err(anyhow::anyhow!("Something went wrong").into());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
## Migration from v0.10
|
||||
|
||||
### Breaking Changes
|
||||
|
||||
1. **`name()` → `info()`**: Returns `ComponentInfo` instead of `Option<String>`
|
||||
```rust
|
||||
// Before
|
||||
fn name(&self) -> Option<String> { Some("my-service".into()) }
|
||||
|
||||
// After
|
||||
fn info(&self) -> ComponentInfo { "my-service".into() }
|
||||
```
|
||||
|
||||
2. **No more `async-trait`**: Remove the dependency and `#[async_trait]` attribute
|
||||
```rust
|
||||
// Before
|
||||
#[async_trait]
|
||||
impl Component for MyService { }
|
||||
|
||||
// After
|
||||
impl Component for MyService { }
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
See [examples directory](crates/mad/examples) for complete working examples.
|
||||
Check out the [examples directory](crates/mad/examples) for more detailed examples:
|
||||
|
||||
- **basic** - Simple component lifecycle
|
||||
- **fn** - Using functions as components
|
||||
- **signals** - Handling system signals
|
||||
- **error_log** - Error handling and logging
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
|
||||
|
||||
## License
|
||||
|
||||
MIT - see [LICENSE](LICENSE)
|
||||
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
||||
|
||||
## Links
|
||||
## Author
|
||||
|
||||
- [Documentation](https://docs.rs/notmad)
|
||||
- [Repository](https://github.com/kjuulh/mad)
|
||||
- [Crates.io](https://crates.io/crates/notmad)
|
||||
Created and maintained by [kjuulh](https://github.com/kjuulh)
|
||||
|
||||
## Repository
|
||||
|
||||
Find the source code at [https://github.com/kjuulh/mad](https://github.com/kjuulh/mad)
|
||||
|
||||
@@ -10,6 +10,7 @@ readme = "../../README.md"
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
async-trait = "0.1.81"
|
||||
futures = "0.3.30"
|
||||
futures-util = "0.3.30"
|
||||
rand = "0.9.0"
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
use notmad::ComponentInfo;
|
||||
use async_trait::async_trait;
|
||||
use rand::Rng;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::Level;
|
||||
|
||||
struct WaitServer {}
|
||||
#[async_trait]
|
||||
impl notmad::Component for WaitServer {
|
||||
fn info(&self) -> ComponentInfo {
|
||||
"WaitServer".into()
|
||||
fn name(&self) -> Option<String> {
|
||||
Some("WaitServer".into())
|
||||
}
|
||||
|
||||
async fn run(&self, _cancellation: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
async fn run(&self, cancellation: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
let millis_wait = rand::thread_rng().gen_range(500..3000);
|
||||
|
||||
tracing::debug!("waiting: {}ms", millis_wait);
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
//! - Graceful shutdown with cancellation tokens
|
||||
//! - Concurrent component execution
|
||||
|
||||
use notmad::{Component, ComponentInfo, Mad, MadError};
|
||||
use async_trait::async_trait;
|
||||
use notmad::{Component, Mad, MadError};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use tokio::time::{Duration, interval};
|
||||
@@ -20,9 +21,10 @@ struct WebServer {
|
||||
request_count: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for WebServer {
|
||||
fn info(&self) -> ComponentInfo {
|
||||
format!("web-server-{}", self.port).into()
|
||||
fn name(&self) -> Option<String> {
|
||||
Some(format!("web-server-{}", self.port))
|
||||
}
|
||||
|
||||
async fn setup(&self) -> Result<(), MadError> {
|
||||
@@ -79,9 +81,10 @@ struct JobProcessor {
|
||||
processing_interval: Duration,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for JobProcessor {
|
||||
fn info(&self) -> ComponentInfo {
|
||||
format!("job-processor-{}", self.queue_name).into()
|
||||
fn name(&self) -> Option<String> {
|
||||
Some(format!("job-processor-{}", self.queue_name))
|
||||
}
|
||||
|
||||
async fn setup(&self) -> Result<(), MadError> {
|
||||
@@ -136,9 +139,10 @@ struct HealthChecker {
|
||||
check_interval: Duration,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for HealthChecker {
|
||||
fn info(&self) -> ComponentInfo {
|
||||
"health-checker".into()
|
||||
fn name(&self) -> Option<String> {
|
||||
Some("health-checker".to_string())
|
||||
}
|
||||
|
||||
async fn run(&self, cancellation: CancellationToken) -> Result<(), MadError> {
|
||||
@@ -177,9 +181,10 @@ struct FailingComponent {
|
||||
fail_after: Duration,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for FailingComponent {
|
||||
fn info(&self) -> ComponentInfo {
|
||||
"failing-component".into()
|
||||
fn name(&self) -> Option<String> {
|
||||
Some("failing-component".to_string())
|
||||
}
|
||||
|
||||
async fn run(&self, cancellation: CancellationToken) -> Result<(), MadError> {
|
||||
@@ -204,9 +209,10 @@ impl Component for FailingComponent {
|
||||
/// Debug component that logs system status periodically.
|
||||
struct DebugComponent;
|
||||
|
||||
#[async_trait]
|
||||
impl Component for DebugComponent {
|
||||
fn info(&self) -> ComponentInfo {
|
||||
"debug-component".into()
|
||||
fn name(&self) -> Option<String> {
|
||||
Some("debug-component".to_string())
|
||||
}
|
||||
|
||||
async fn run(&self, cancel: CancellationToken) -> Result<(), MadError> {
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
use notmad::ComponentInfo;
|
||||
use async_trait::async_trait;
|
||||
use rand::Rng;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::Level;
|
||||
|
||||
struct ErrorServer {}
|
||||
#[async_trait]
|
||||
impl notmad::Component for ErrorServer {
|
||||
fn info(&self) -> ComponentInfo {
|
||||
"ErrorServer".into()
|
||||
fn name(&self) -> Option<String> {
|
||||
Some("ErrorServer".into())
|
||||
}
|
||||
|
||||
async fn run(&self, _cancellation: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
async fn run(&self, cancellation: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
let millis_wait = rand::thread_rng().gen_range(500..3000);
|
||||
|
||||
tracing::debug!("waiting: {}ms", millis_wait);
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
use notmad::ComponentInfo;
|
||||
use async_trait::async_trait;
|
||||
use rand::Rng;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::Level;
|
||||
|
||||
struct WaitServer {}
|
||||
#[async_trait]
|
||||
impl notmad::Component for WaitServer {
|
||||
fn info(&self) -> ComponentInfo {
|
||||
"WaitServer".into()
|
||||
fn name(&self) -> Option<String> {
|
||||
Some("WaitServer".into())
|
||||
}
|
||||
|
||||
async fn run(&self, _cancellation: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
//! This example shows how to run a web server, queue processor, and
|
||||
//! scheduled task together, with graceful shutdown on Ctrl+C.
|
||||
|
||||
use notmad::{Component, ComponentInfo, Mad, MadError};
|
||||
use async_trait::async_trait;
|
||||
use notmad::{Component, Mad, MadError};
|
||||
use tokio::time::{Duration, interval};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
@@ -15,21 +16,22 @@ struct WebServer {
|
||||
port: u16,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for WebServer {
|
||||
fn info(&self) -> ComponentInfo {
|
||||
format!("WebServer:{}", self.port).into()
|
||||
fn name(&self) -> Option<String> {
|
||||
Some(format!("WebServer:{}", self.port))
|
||||
}
|
||||
|
||||
async fn setup(&self) -> Result<(), MadError> {
|
||||
println!("[{}] Binding to port...", self.info());
|
||||
println!("[{}] Binding to port...", self.name().unwrap());
|
||||
// Simulate server setup time
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
println!("[{}] Ready to accept connections", self.info());
|
||||
println!("[{}] Ready to accept connections", self.name().unwrap());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run(&self, cancellation: CancellationToken) -> Result<(), MadError> {
|
||||
println!("[{}] Server started", self.info());
|
||||
println!("[{}] Server started", self.name().unwrap());
|
||||
|
||||
// Simulate handling requests until shutdown
|
||||
let mut request_id = 0;
|
||||
@@ -38,12 +40,12 @@ impl Component for WebServer {
|
||||
while !cancellation.is_cancelled() {
|
||||
tokio::select! {
|
||||
_ = cancellation.cancelled() => {
|
||||
println!("[{}] Shutdown signal received", self.info());
|
||||
println!("[{}] Shutdown signal received", self.name().unwrap());
|
||||
break;
|
||||
}
|
||||
_ = interval.tick() => {
|
||||
request_id += 1;
|
||||
println!("[{}] Handling request #{}", self.info(), request_id);
|
||||
println!("[{}] Handling request #{}", self.name().unwrap(), request_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,10 +54,10 @@ impl Component for WebServer {
|
||||
}
|
||||
|
||||
async fn close(&self) -> Result<(), MadError> {
|
||||
println!("[{}] Closing connections...", self.info());
|
||||
println!("[{}] Closing connections...", self.name().unwrap());
|
||||
// Simulate graceful connection drain
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
println!("[{}] Server stopped", self.info());
|
||||
println!("[{}] Server stopped", self.name().unwrap());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -68,13 +70,14 @@ struct QueueProcessor {
|
||||
queue_name: String,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for QueueProcessor {
|
||||
fn info(&self) -> ComponentInfo {
|
||||
format!("QueueProcessor:{}", self.queue_name).into()
|
||||
fn name(&self) -> Option<String> {
|
||||
Some(format!("QueueProcessor:{}", self.queue_name))
|
||||
}
|
||||
|
||||
async fn run(&self, cancellation: CancellationToken) -> Result<(), MadError> {
|
||||
println!("[{}] Started processing", self.info());
|
||||
println!("[{}] Started processing", self.name().unwrap());
|
||||
|
||||
let mut message_count = 0;
|
||||
|
||||
@@ -83,19 +86,19 @@ impl Component for QueueProcessor {
|
||||
// Simulate waiting for and processing a message
|
||||
tokio::select! {
|
||||
_ = cancellation.cancelled() => {
|
||||
println!("[{}] Stopping message processing", self.info());
|
||||
println!("[{}] Stopping message processing", self.name().unwrap());
|
||||
break;
|
||||
}
|
||||
_ = tokio::time::sleep(Duration::from_secs(1)) => {
|
||||
message_count += 1;
|
||||
println!("[{}] Processed message #{}", self.info(), message_count);
|
||||
println!("[{}] Processed message #{}", self.name().unwrap(), message_count);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!(
|
||||
"[{}] Processed {} messages total",
|
||||
self.info(),
|
||||
self.name().unwrap(),
|
||||
message_count
|
||||
);
|
||||
Ok(())
|
||||
@@ -113,15 +116,16 @@ struct ScheduledTask {
|
||||
interval_secs: u64,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for ScheduledTask {
|
||||
fn info(&self) -> ComponentInfo {
|
||||
format!("ScheduledTask:{}", self.task_name).into()
|
||||
fn name(&self) -> Option<String> {
|
||||
Some(format!("ScheduledTask:{}", self.task_name))
|
||||
}
|
||||
|
||||
async fn run(&self, cancellation: CancellationToken) -> Result<(), MadError> {
|
||||
println!(
|
||||
"[{}] Scheduled to run every {} seconds",
|
||||
self.info(),
|
||||
self.name().unwrap(),
|
||||
self.interval_secs
|
||||
);
|
||||
|
||||
@@ -131,17 +135,17 @@ impl Component for ScheduledTask {
|
||||
while !cancellation.is_cancelled() {
|
||||
tokio::select! {
|
||||
_ = cancellation.cancelled() => {
|
||||
println!("[{}] Scheduler stopping", self.info());
|
||||
println!("[{}] Scheduler stopping", self.name().unwrap());
|
||||
break;
|
||||
}
|
||||
_ = interval.tick() => {
|
||||
run_count += 1;
|
||||
println!("[{}] Executing run #{}", self.info(), run_count);
|
||||
println!("[{}] Executing run #{}", self.name().unwrap(), run_count);
|
||||
|
||||
// Simulate task execution
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
|
||||
println!("[{}] Run #{} completed", self.info(), run_count);
|
||||
println!("[{}] Run #{} completed", self.name().unwrap(), run_count);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
use notmad::ComponentInfo;
|
||||
use async_trait::async_trait;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
struct NestedErrorComponent {
|
||||
name: String,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl notmad::Component for NestedErrorComponent {
|
||||
fn info(&self) -> ComponentInfo {
|
||||
self.name.clone().into()
|
||||
fn name(&self) -> Option<String> {
|
||||
Some(self.name.clone())
|
||||
}
|
||||
|
||||
async fn run(&self, _cancellation: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
@@ -27,9 +28,10 @@ impl notmad::Component for NestedErrorComponent {
|
||||
|
||||
struct AnotherFailingComponent;
|
||||
|
||||
#[async_trait]
|
||||
impl notmad::Component for AnotherFailingComponent {
|
||||
fn info(&self) -> ComponentInfo {
|
||||
"another-component".into()
|
||||
fn name(&self) -> Option<String> {
|
||||
Some("another-component".into())
|
||||
}
|
||||
|
||||
async fn run(&self, _cancellation: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
use notmad::ComponentInfo;
|
||||
use async_trait::async_trait;
|
||||
use rand::Rng;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::Level;
|
||||
|
||||
struct WaitServer {}
|
||||
#[async_trait]
|
||||
impl notmad::Component for WaitServer {
|
||||
fn info(&self) -> ComponentInfo {
|
||||
"WaitServer".into()
|
||||
fn name(&self) -> Option<String> {
|
||||
Some("WaitServer".into())
|
||||
}
|
||||
|
||||
async fn run(&self, _cancellation: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
async fn run(&self, cancellation: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
let millis_wait = rand::thread_rng().gen_range(500..3000);
|
||||
|
||||
tracing::debug!("waiting: {}ms", millis_wait);
|
||||
@@ -22,9 +23,10 @@ impl notmad::Component for WaitServer {
|
||||
}
|
||||
|
||||
struct RespectCancel {}
|
||||
#[async_trait]
|
||||
impl notmad::Component for RespectCancel {
|
||||
fn info(&self) -> ComponentInfo {
|
||||
"RespectCancel".into()
|
||||
fn name(&self) -> Option<String> {
|
||||
Some("RespectCancel".into())
|
||||
}
|
||||
|
||||
async fn run(&self, cancellation: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
@@ -36,12 +38,13 @@ impl notmad::Component for RespectCancel {
|
||||
}
|
||||
|
||||
struct NeverStopServer {}
|
||||
#[async_trait]
|
||||
impl notmad::Component for NeverStopServer {
|
||||
fn info(&self) -> ComponentInfo {
|
||||
"NeverStopServer".into()
|
||||
fn name(&self) -> Option<String> {
|
||||
Some("NeverStopServer".into())
|
||||
}
|
||||
|
||||
async fn run(&self, _cancellation: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
async fn run(&self, cancellation: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
// Simulates a server running for some time. Is normally supposed to be futures blocking indefinitely
|
||||
tokio::time::sleep(std::time::Duration::from_millis(999999999)).await;
|
||||
|
||||
|
||||
@@ -1,21 +1,42 @@
|
||||
//! # MAD - Lifecycle Manager for Rust Applications
|
||||
//!
|
||||
//! A simple lifecycle manager for long-running Rust applications. Run multiple services
|
||||
//! concurrently with graceful shutdown handling.
|
||||
//! MAD is a robust lifecycle manager designed for long-running Rust operations. It provides
|
||||
//! a simple, composable way to manage multiple concurrent services within your application,
|
||||
//! handling graceful startup and shutdown automatically.
|
||||
//!
|
||||
//! ## Overview
|
||||
//!
|
||||
//! MAD helps you build applications composed of multiple long-running components that need
|
||||
//! to be orchestrated together. It handles:
|
||||
//!
|
||||
//! - **Concurrent execution** of multiple components
|
||||
//! - **Graceful shutdown** with cancellation tokens
|
||||
//! - **Error aggregation** from multiple components
|
||||
//! - **Lifecycle management** with setup, run, and close phases
|
||||
//!
|
||||
//! ## Quick Start
|
||||
//!
|
||||
//! ```rust,no_run
|
||||
//! use notmad::{Component, Mad};
|
||||
//! use async_trait::async_trait;
|
||||
//! use tokio_util::sync::CancellationToken;
|
||||
//!
|
||||
//! struct MyService;
|
||||
//! struct MyService {
|
||||
//! name: String,
|
||||
//! }
|
||||
//!
|
||||
//! #[async_trait]
|
||||
//! impl Component for MyService {
|
||||
//! async fn run(&self, cancel: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
//! println!("Running...");
|
||||
//! cancel.cancelled().await;
|
||||
//! println!("Stopped");
|
||||
//! fn name(&self) -> Option<String> {
|
||||
//! Some(self.name.clone())
|
||||
//! }
|
||||
//!
|
||||
//! async fn run(&self, cancellation: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
//! // Your service logic here
|
||||
//! while !cancellation.is_cancelled() {
|
||||
//! // Do work...
|
||||
//! tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
||||
//! }
|
||||
//! Ok(())
|
||||
//! }
|
||||
//! }
|
||||
@@ -23,24 +44,40 @@
|
||||
//! #[tokio::main]
|
||||
//! async fn main() -> anyhow::Result<()> {
|
||||
//! Mad::builder()
|
||||
//! .add(MyService)
|
||||
//! .add(MyService { name: "service-1".into() })
|
||||
//! .add(MyService { name: "service-2".into() })
|
||||
//! .run()
|
||||
//! .await?;
|
||||
//! Ok(())
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! ## Features
|
||||
//! ## Component Lifecycle
|
||||
//!
|
||||
//! - Run multiple components concurrently
|
||||
//! - Graceful shutdown with cancellation tokens
|
||||
//! - Optional lifecycle hooks: `setup()`, `run()`, `close()`
|
||||
//! - Automatic error aggregation
|
||||
//! - SIGTERM and Ctrl+C signal handling
|
||||
//! Components go through three phases:
|
||||
//!
|
||||
//! 1. **Setup**: Optional initialization phase before components start running
|
||||
//! 2. **Run**: Main execution phase where components perform their work
|
||||
//! 3. **Close**: Optional cleanup phase after components stop
|
||||
//!
|
||||
//! ## Error Handling
|
||||
//!
|
||||
//! MAD provides comprehensive error handling through [`MadError`], which can:
|
||||
//! - Wrap errors from individual components
|
||||
//! - Aggregate multiple errors when several components fail
|
||||
//! - Automatically convert from `anyhow::Error`
|
||||
//!
|
||||
//! ## Shutdown Behavior
|
||||
//!
|
||||
//! MAD handles shutdown gracefully:
|
||||
//! - Responds to SIGTERM and Ctrl+C signals
|
||||
//! - Propagates cancellation tokens to all components
|
||||
//! - Waits for components to finish cleanup
|
||||
//! - Configurable cancellation timeout
|
||||
|
||||
use futures::stream::FuturesUnordered;
|
||||
use futures_util::StreamExt;
|
||||
use std::{error::Error, fmt::Display, pin::Pin, sync::Arc};
|
||||
use std::{fmt::Display, sync::Arc, error::Error};
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
|
||||
use tokio_util::sync::CancellationToken;
|
||||
@@ -64,13 +101,15 @@ pub enum MadError {
|
||||
|
||||
/// Error that occurred during the run phase of a component.
|
||||
#[error(transparent)]
|
||||
RunError { run: anyhow::Error },
|
||||
RunError {
|
||||
run: anyhow::Error
|
||||
},
|
||||
|
||||
/// Error that occurred during the close phase of a component.
|
||||
#[error("component(s) failed during close")]
|
||||
CloseError {
|
||||
CloseError {
|
||||
#[source]
|
||||
close: anyhow::Error,
|
||||
close: anyhow::Error
|
||||
},
|
||||
|
||||
/// Multiple errors from different components.
|
||||
@@ -126,10 +165,6 @@ impl AggregateError {
|
||||
pub fn get_errors(&self) -> &[MadError] {
|
||||
&self.errors
|
||||
}
|
||||
|
||||
pub fn take_errors(self) -> Vec<MadError> {
|
||||
self.errors
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for AggregateError {
|
||||
@@ -145,7 +180,7 @@ impl Display for AggregateError {
|
||||
writeln!(f, "{} component errors occurred:", self.errors.len())?;
|
||||
for (i, error) in self.errors.iter().enumerate() {
|
||||
write!(f, "\n[Component {}] {}", i + 1, error)?;
|
||||
|
||||
|
||||
// Print the error chain for each component error
|
||||
let mut source = error.source();
|
||||
let mut level = 1;
|
||||
@@ -168,10 +203,12 @@ impl Display for AggregateError {
|
||||
///
|
||||
/// ```rust
|
||||
/// use notmad::{Component, Mad};
|
||||
/// use async_trait::async_trait;
|
||||
/// use tokio_util::sync::CancellationToken;
|
||||
///
|
||||
/// struct MyComponent;
|
||||
///
|
||||
/// #[async_trait]
|
||||
/// impl Component for MyComponent {
|
||||
/// async fn run(&self, _cancel: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
/// Ok(())
|
||||
@@ -187,7 +224,7 @@ impl Display for AggregateError {
|
||||
/// # }
|
||||
/// ```
|
||||
pub struct Mad {
|
||||
components: Vec<SharedComponent>,
|
||||
components: Vec<Arc<dyn Component + Send + Sync + 'static>>,
|
||||
|
||||
should_cancel: Option<std::time::Duration>,
|
||||
}
|
||||
@@ -231,8 +268,10 @@ impl Mad {
|
||||
///
|
||||
/// ```rust
|
||||
/// use notmad::{Component, Mad};
|
||||
/// # use async_trait::async_trait;
|
||||
/// # use tokio_util::sync::CancellationToken;
|
||||
/// # struct MyService;
|
||||
/// # #[async_trait]
|
||||
/// # impl Component for MyService {
|
||||
/// # async fn run(&self, _: CancellationToken) -> Result<(), notmad::MadError> { Ok(()) }
|
||||
/// # }
|
||||
@@ -262,8 +301,10 @@ impl Mad {
|
||||
/// ```rust
|
||||
/// use notmad::Mad;
|
||||
/// # use notmad::Component;
|
||||
/// # use async_trait::async_trait;
|
||||
/// # use tokio_util::sync::CancellationToken;
|
||||
/// # struct DebugService;
|
||||
/// # #[async_trait]
|
||||
/// # impl Component for DebugService {
|
||||
/// # async fn run(&self, _: CancellationToken) -> Result<(), notmad::MadError> { Ok(()) }
|
||||
/// # }
|
||||
@@ -351,7 +392,7 @@ impl Mad {
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `should_cancel` - Duration to wait after cancellation before forcing shutdown.
|
||||
/// Pass `None` to wait indefinitely.
|
||||
/// Pass `None` to wait indefinitely.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
@@ -426,7 +467,7 @@ impl Mad {
|
||||
tracing::debug!("setting up components");
|
||||
|
||||
for comp in &self.components {
|
||||
tracing::trace!(component = %comp.info(), "mad setting up");
|
||||
tracing::trace!(component = &comp.name(), "mad setting up");
|
||||
|
||||
match comp.setup().await {
|
||||
Ok(_) | Err(MadError::SetupNotDefined) => {}
|
||||
@@ -456,37 +497,16 @@ impl Mad {
|
||||
channels.push(error_rx);
|
||||
|
||||
tokio::spawn(async move {
|
||||
let info = comp.info().clone();
|
||||
let name = comp.name().clone();
|
||||
|
||||
tracing::debug!(component = %info, "mad running");
|
||||
|
||||
let handle = tokio::spawn(async move { comp.run(job_cancellation).await });
|
||||
tracing::debug!(component = name, "mad running");
|
||||
|
||||
tokio::select! {
|
||||
_ = cancellation_token.cancelled() => {
|
||||
error_tx.send(CompletionResult { res: Ok(()) , name: info.name }).await
|
||||
error_tx.send(CompletionResult { res: Ok(()) , name }).await
|
||||
}
|
||||
res = handle => {
|
||||
let res = match res {
|
||||
Ok(res) => res,
|
||||
Err(join) => {
|
||||
match join.source() {
|
||||
Some(error) => {
|
||||
Err(MadError::RunError{run: anyhow::anyhow!("component aborted: {:?}", error)})
|
||||
},
|
||||
None => {
|
||||
if join.is_panic(){
|
||||
Err(MadError::RunError { run: anyhow::anyhow!("component panicked: {}", join) })
|
||||
} else {
|
||||
Err(MadError::RunError { run: anyhow::anyhow!("component faced unknown error: {}", join) })
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
error_tx.send(CompletionResult { res , name: info.name }).await
|
||||
res = comp.run(job_cancellation) => {
|
||||
error_tx.send(CompletionResult { res , name }).await
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -563,7 +583,7 @@ impl Mad {
|
||||
tracing::debug!("closing components");
|
||||
|
||||
for comp in &self.components {
|
||||
tracing::trace!(component = %comp.info(), "mad closing");
|
||||
tracing::trace!(component = &comp.name(), "mad closing");
|
||||
match comp.close().await {
|
||||
Ok(_) | Err(MadError::CloseNotDefined) => {}
|
||||
Err(e) => return Err(e),
|
||||
@@ -581,46 +601,6 @@ async fn signal_unix_terminate() {
|
||||
sigterm.recv().await;
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
pub struct ComponentInfo {
|
||||
name: Option<String>,
|
||||
}
|
||||
|
||||
impl Display for ComponentInfo {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(
|
||||
self.name
|
||||
.as_ref()
|
||||
.map(|n| n.as_str())
|
||||
.unwrap_or_else(|| "unknown"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl ComponentInfo {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn with_name(&mut self, name: impl Into<String>) -> &mut Self {
|
||||
self.name = Some(name.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for ComponentInfo {
|
||||
fn from(value: String) -> Self {
|
||||
Self { name: Some(value) }
|
||||
}
|
||||
}
|
||||
impl From<&str> for ComponentInfo {
|
||||
fn from(value: &str) -> Self {
|
||||
Self {
|
||||
name: Some(value.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait for implementing MAD components.
|
||||
///
|
||||
/// Components represent individual services or tasks that run as part
|
||||
@@ -630,16 +610,18 @@ impl From<&str> for ComponentInfo {
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use notmad::{Component, ComponentInfo, MadError};
|
||||
/// use notmad::{Component, MadError};
|
||||
/// use async_trait::async_trait;
|
||||
/// use tokio_util::sync::CancellationToken;
|
||||
///
|
||||
/// struct DatabaseConnection {
|
||||
/// url: String,
|
||||
/// }
|
||||
///
|
||||
/// #[async_trait]
|
||||
/// impl Component for DatabaseConnection {
|
||||
/// fn info(&self) -> ComponentInfo {
|
||||
/// "database".into()
|
||||
/// fn name(&self) -> Option<String> {
|
||||
/// Some("database".to_string())
|
||||
/// }
|
||||
///
|
||||
/// async fn setup(&self) -> Result<(), MadError> {
|
||||
@@ -661,7 +643,8 @@ impl From<&str> for ComponentInfo {
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub trait Component: Send + Sync + 'static {
|
||||
#[async_trait::async_trait]
|
||||
pub trait Component {
|
||||
/// Returns an optional name for the component.
|
||||
///
|
||||
/// This name is used in logging and error messages to identify
|
||||
@@ -670,8 +653,8 @@ pub trait Component: Send + Sync + 'static {
|
||||
/// # Default
|
||||
///
|
||||
/// Returns `None` if not overridden.
|
||||
fn info(&self) -> ComponentInfo {
|
||||
ComponentInfo::default()
|
||||
fn name(&self) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Optional setup phase called before the component starts running.
|
||||
@@ -689,8 +672,8 @@ pub trait Component: Send + Sync + 'static {
|
||||
///
|
||||
/// If setup fails with an error other than `SetupNotDefined`,
|
||||
/// the entire application will stop before any components start running.
|
||||
fn setup(&self) -> impl Future<Output = Result<(), MadError>> + Send + '_ {
|
||||
async { Err(MadError::SetupNotDefined) }
|
||||
async fn setup(&self) -> Result<(), MadError> {
|
||||
Err(MadError::SetupNotDefined)
|
||||
}
|
||||
|
||||
/// Main execution phase of the component.
|
||||
@@ -712,10 +695,7 @@ pub trait Component: Send + Sync + 'static {
|
||||
/// # Errors
|
||||
///
|
||||
/// Any error returned will trigger shutdown of all other components.
|
||||
fn run(
|
||||
&self,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> impl Future<Output = Result<(), MadError>> + Send + '_;
|
||||
async fn run(&self, cancellation_token: CancellationToken) -> Result<(), MadError>;
|
||||
|
||||
/// Optional cleanup phase called after the component stops.
|
||||
///
|
||||
@@ -732,73 +712,8 @@ pub trait Component: Send + Sync + 'static {
|
||||
///
|
||||
/// Errors during close are logged but don't prevent other components
|
||||
/// from closing.
|
||||
fn close(&self) -> impl Future<Output = Result<(), MadError>> + Send + '_ {
|
||||
async { Err(MadError::CloseNotDefined) }
|
||||
}
|
||||
}
|
||||
|
||||
trait AsyncComponent: Send + Sync + 'static {
|
||||
fn info_async(&self) -> ComponentInfo;
|
||||
|
||||
fn setup_async(&self) -> Pin<Box<dyn Future<Output = Result<(), MadError>> + Send + '_>>;
|
||||
|
||||
fn run_async(
|
||||
&self,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> Pin<Box<dyn Future<Output = Result<(), MadError>> + Send + '_>>;
|
||||
|
||||
fn close_async(&self) -> Pin<Box<dyn Future<Output = Result<(), MadError>> + Send + '_>>;
|
||||
}
|
||||
|
||||
impl<E: Component> AsyncComponent for E {
|
||||
#[inline(always)]
|
||||
fn info_async(&self) -> ComponentInfo {
|
||||
self.info()
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn setup_async(&self) -> Pin<Box<dyn Future<Output = Result<(), MadError>> + Send + '_>> {
|
||||
Box::pin(self.setup())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn run_async(
|
||||
&self,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> Pin<Box<dyn Future<Output = Result<(), MadError>> + Send + '_>> {
|
||||
Box::pin(self.run(cancellation_token))
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn close_async(&self) -> Pin<Box<dyn Future<Output = Result<(), MadError>> + Send + '_>> {
|
||||
Box::pin(self.close())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SharedComponent {
|
||||
component: Arc<dyn AsyncComponent + Send + Sync + 'static>,
|
||||
}
|
||||
|
||||
impl SharedComponent {
|
||||
#[inline(always)]
|
||||
pub fn info(&self) -> ComponentInfo {
|
||||
self.component.info_async()
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
async fn setup(&self) -> Result<(), MadError> {
|
||||
self.component.setup_async().await
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
async fn run(&self, cancellation_token: CancellationToken) -> Result<(), MadError> {
|
||||
self.component.run_async(cancellation_token).await
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
async fn close(&self) -> Result<(), MadError> {
|
||||
self.component.close_async().await
|
||||
Err(MadError::CloseNotDefined)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -812,10 +727,12 @@ impl SharedComponent {
|
||||
///
|
||||
/// ```rust
|
||||
/// use notmad::{Component, IntoComponent, Mad};
|
||||
/// # use async_trait::async_trait;
|
||||
/// # use tokio_util::sync::CancellationToken;
|
||||
///
|
||||
/// struct MyService;
|
||||
///
|
||||
/// # #[async_trait]
|
||||
/// # impl Component for MyService {
|
||||
/// # async fn run(&self, _: CancellationToken) -> Result<(), notmad::MadError> { Ok(()) }
|
||||
/// # }
|
||||
@@ -826,14 +743,12 @@ impl SharedComponent {
|
||||
/// ```
|
||||
pub trait IntoComponent {
|
||||
/// Converts self into an Arc-wrapped component.
|
||||
fn into_component(self) -> SharedComponent;
|
||||
fn into_component(self) -> Arc<dyn Component + Send + Sync + 'static>;
|
||||
}
|
||||
|
||||
impl<T: Component> IntoComponent for T {
|
||||
fn into_component(self) -> SharedComponent {
|
||||
SharedComponent {
|
||||
component: Arc::new(self),
|
||||
}
|
||||
impl<T: Component + Send + Sync + 'static> IntoComponent for T {
|
||||
fn into_component(self) -> Arc<dyn Component + Send + Sync + 'static> {
|
||||
Arc::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -857,6 +772,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<F, Fut> Component for ClosureComponent<F, Fut>
|
||||
where
|
||||
F: Fn(CancellationToken) -> Fut + Send + Sync + 'static,
|
||||
@@ -870,6 +786,7 @@ where
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use anyhow::Context;
|
||||
|
||||
#[test]
|
||||
fn test_error_chaining_display() {
|
||||
@@ -879,13 +796,13 @@ mod tests {
|
||||
.context("failed to read configuration")
|
||||
.context("unable to initialize database")
|
||||
.context("service startup failed");
|
||||
|
||||
|
||||
let mad_error = MadError::Inner(error);
|
||||
let display = format!("{}", mad_error);
|
||||
|
||||
|
||||
// Should display the top-level error message
|
||||
assert!(display.contains("service startup failed"));
|
||||
|
||||
|
||||
// Test error chain iteration
|
||||
if let MadError::Inner(ref e) = mad_error {
|
||||
let chain: Vec<String> = e.chain().map(|c| c.to_string()).collect();
|
||||
@@ -901,26 +818,26 @@ mod tests {
|
||||
fn test_aggregate_error_display() {
|
||||
let error1 = MadError::Inner(
|
||||
anyhow::anyhow!("database connection failed")
|
||||
.context("failed to connect to PostgreSQL"),
|
||||
.context("failed to connect to PostgreSQL")
|
||||
);
|
||||
|
||||
|
||||
let error2 = MadError::Inner(
|
||||
anyhow::anyhow!("port already in use")
|
||||
.context("failed to bind to port 8080")
|
||||
.context("web server initialization failed"),
|
||||
.context("web server initialization failed")
|
||||
);
|
||||
|
||||
|
||||
let aggregate = MadError::AggregateError(AggregateError {
|
||||
errors: vec![error1, error2],
|
||||
});
|
||||
|
||||
|
||||
let display = format!("{}", aggregate);
|
||||
|
||||
|
||||
// Check that it shows multiple errors
|
||||
assert!(display.contains("2 component errors occurred"));
|
||||
assert!(display.contains("[Component 1]"));
|
||||
assert!(display.contains("[Component 2]"));
|
||||
|
||||
|
||||
// Check that context chains are displayed
|
||||
assert!(display.contains("failed to connect to PostgreSQL"));
|
||||
assert!(display.contains("database connection failed"));
|
||||
@@ -935,7 +852,7 @@ mod tests {
|
||||
let aggregate = AggregateError {
|
||||
errors: vec![error],
|
||||
};
|
||||
|
||||
|
||||
let display = format!("{}", aggregate);
|
||||
// Single error should be displayed directly
|
||||
assert!(display.contains("single error"));
|
||||
@@ -947,9 +864,9 @@ mod tests {
|
||||
let error = MadError::Inner(
|
||||
anyhow::anyhow!("root cause")
|
||||
.context("middle layer")
|
||||
.context("top layer"),
|
||||
.context("top layer")
|
||||
);
|
||||
|
||||
|
||||
// Test that we can access the error chain
|
||||
if let MadError::Inner(ref e) = error {
|
||||
let chain: Vec<String> = e.chain().map(|c| c.to_string()).collect();
|
||||
@@ -965,12 +882,13 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn test_component_error_propagation() {
|
||||
struct FailingComponent;
|
||||
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Component for FailingComponent {
|
||||
fn info(&self) -> ComponentInfo {
|
||||
"test-component".into()
|
||||
fn name(&self) -> Option<String> {
|
||||
Some("test-component".to_string())
|
||||
}
|
||||
|
||||
|
||||
async fn run(&self, _cancel: CancellationToken) -> Result<(), MadError> {
|
||||
Err(anyhow::anyhow!("IO error")
|
||||
.context("failed to open file")
|
||||
@@ -978,16 +896,16 @@ mod tests {
|
||||
.into())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
let result = Mad::builder()
|
||||
.add(FailingComponent)
|
||||
.cancellation(Some(std::time::Duration::from_millis(100)))
|
||||
.run()
|
||||
.await;
|
||||
|
||||
|
||||
assert!(result.is_err());
|
||||
let error = result.unwrap_err();
|
||||
|
||||
|
||||
// Check error display
|
||||
let display = format!("{}", error);
|
||||
assert!(display.contains("component initialization failed"));
|
||||
|
||||
@@ -4,15 +4,19 @@
|
||||
//! without performing any work. Useful for keeping the application alive
|
||||
//! or as placeholders in conditional component loading.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::{Component, ComponentInfo, IntoComponent, MadError, SharedComponent};
|
||||
use crate::{Component, MadError};
|
||||
|
||||
/// A default waiter component that panics if run.
|
||||
///
|
||||
/// This is used internally as a placeholder that should never
|
||||
/// actually be executed.
|
||||
pub struct DefaultWaiter;
|
||||
pub struct DefaultWaiter {}
|
||||
#[async_trait]
|
||||
impl Component for DefaultWaiter {
|
||||
async fn run(&self, _cancellation_token: CancellationToken) -> Result<(), MadError> {
|
||||
panic!("should never be called");
|
||||
@@ -34,13 +38,13 @@ impl Component for DefaultWaiter {
|
||||
/// let waiter = Waiter::new(service.into_component());
|
||||
/// ```
|
||||
pub struct Waiter {
|
||||
comp: SharedComponent,
|
||||
comp: Arc<dyn Component + Send + Sync + 'static>,
|
||||
}
|
||||
|
||||
impl Default for Waiter {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
comp: DefaultWaiter {}.into_component(),
|
||||
comp: Arc::new(DefaultWaiter {}),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,20 +54,21 @@ impl Waiter {
|
||||
///
|
||||
/// The wrapped component's name will be used (prefixed with "waiter/"),
|
||||
/// but its run method will not be called.
|
||||
pub fn new(c: SharedComponent) -> Self {
|
||||
pub fn new(c: Arc<dyn Component + Send + Sync + 'static>) -> Self {
|
||||
Self { comp: c }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for Waiter {
|
||||
/// Returns the name of the waiter, prefixed with "waiter/".
|
||||
///
|
||||
/// If the wrapped component has a name, it will be "waiter/{name}".
|
||||
/// Otherwise, returns "waiter".
|
||||
fn info(&self) -> ComponentInfo {
|
||||
match &self.comp.info().name {
|
||||
Some(name) => format!("waiter/{name}").into(),
|
||||
None => "waiter".into(),
|
||||
fn name(&self) -> Option<String> {
|
||||
match self.comp.name() {
|
||||
Some(name) => Some(format!("waiter/{name}")),
|
||||
None => Some("waiter".into()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use notmad::{Component, ComponentInfo, Mad, MadError};
|
||||
use async_trait::async_trait;
|
||||
use notmad::{Component, Mad, MadError};
|
||||
use rand::Rng;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
@@ -8,12 +9,13 @@ use tracing_test::traced_test;
|
||||
|
||||
struct NeverEndingRun {}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for NeverEndingRun {
|
||||
fn info(&self) -> ComponentInfo {
|
||||
"NeverEndingRun".into()
|
||||
fn name(&self) -> Option<String> {
|
||||
Some("NeverEndingRun".into())
|
||||
}
|
||||
|
||||
async fn run(&self, _cancellation: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
async fn run(&self, cancellation: CancellationToken) -> Result<(), notmad::MadError> {
|
||||
let millis_wait = rand::thread_rng().gen_range(50..1000);
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_millis(millis_wait)).await;
|
||||
@@ -136,30 +138,6 @@ async fn test_can_shutdown_gracefully() -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_component_panics_shutdowns_cleanly() -> anyhow::Result<()> {
|
||||
let res = Mad::builder()
|
||||
.add_fn({
|
||||
move |_cancel| async move {
|
||||
panic!("my inner panic");
|
||||
}
|
||||
})
|
||||
.add_fn(|cancel| async move {
|
||||
cancel.cancelled().await;
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.run()
|
||||
.await;
|
||||
|
||||
let err_content = res.unwrap_err().to_string();
|
||||
assert!(err_content.contains("component panicked"));
|
||||
assert!(err_content.contains("my inner panic"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_can_easily_transform_error() -> anyhow::Result<()> {
|
||||
fn fallible() -> anyhow::Result<()> {
|
||||
|
||||
Reference in New Issue
Block a user