Skip to main content

rustvello_core/
middleware.rs

1//! Task middleware for pre/post execution hooks.
2//!
3//! Middleware runs runner-local (not distributed). For distributed status
4//! callbacks, use the trigger system instead.
5
6use async_trait::async_trait;
7
8use rustvello_proto::identifiers::{InvocationId, TaskId};
9
10use crate::error::{RustvelloError, RustvelloResult};
11
12/// Hook that runs before and after each task invocation on this runner.
13///
14/// Middlewares are called in registration order (FIFO for `before`,
15/// LIFO for `after`). If any `before` hook returns `Err`, the task
16/// is not executed and the error is propagated.
17///
18/// # Example
19///
20/// ```rust
21/// use async_trait::async_trait;
22/// use rustvello_core::middleware::TaskMiddleware;
23/// use rustvello_core::error::{RustvelloError, RustvelloResult};
24/// use rustvello_proto::identifiers::{InvocationId, TaskId};
25///
26/// struct LoggingMiddleware;
27///
28/// #[async_trait]
29/// impl TaskMiddleware for LoggingMiddleware {
30///     async fn before(&self, inv_id: &InvocationId, task_id: &TaskId) -> RustvelloResult<()> {
31///         println!("Starting {} for {}", task_id, inv_id);
32///         Ok(())
33///     }
34///
35///     async fn after(
36///         &self,
37///         inv_id: &InvocationId,
38///         task_id: &TaskId,
39///         result: &Result<String, RustvelloError>,
40///     ) -> RustvelloResult<()> {
41///         println!("Finished {} for {}: {}", task_id, inv_id, result.is_ok());
42///         Ok(())
43///     }
44/// }
45/// ```
46#[async_trait]
47pub trait TaskMiddleware: Send + Sync {
48    /// Called before the task function runs.
49    async fn before(&self, inv_id: &InvocationId, task_id: &TaskId) -> RustvelloResult<()>;
50
51    /// Called after the task function runs (regardless of success/failure).
52    async fn after(
53        &self,
54        inv_id: &InvocationId,
55        task_id: &TaskId,
56        result: &Result<String, RustvelloError>,
57    ) -> RustvelloResult<()>;
58}