Skip to main content

taktora_executor/
observer.rs

1//! `Observer` trait — lifecycle hooks invoked by the executor.
2
3use crate::error::ExecutorError;
4use crate::task_id::TaskId;
5
6/// Generic user event carried by [`Observer::on_send_event`].
7///
8/// # Construction
9///
10/// Use [`UserEvent::new`] to create a value; struct literal syntax is not
11/// available from outside this crate because `UserEvent` is `#[non_exhaustive]`.
12#[derive(Clone, Debug, Default)]
13#[non_exhaustive]
14pub struct UserEvent {
15    /// User-defined event kind.
16    pub kind: u32,
17    /// Numeric payload.
18    pub int_data: i64,
19    /// Optional string payload.
20    pub string_data: Option<String>,
21}
22
23impl UserEvent {
24    /// Create a new event with the given `kind` and `int_data`.
25    #[must_use]
26    pub const fn new(kind: u32, int_data: i64) -> Self {
27        Self {
28            kind,
29            int_data,
30            string_data: None,
31        }
32    }
33
34    /// Attach an optional string payload to this event.
35    #[must_use]
36    pub fn with_string(mut self, s: impl Into<String>) -> Self {
37        self.string_data = Some(s.into());
38        self
39    }
40}
41
42/// Lifecycle observer invoked by the executor at well-defined points.
43///
44/// All methods have no-op defaults. The executor never blocks on observer
45/// callbacks — heavy work should be queued internally.
46pub trait Observer: Send + Sync {
47    /// Called once just before the dispatch loop begins.
48    fn on_executor_up(&self) {}
49    /// Called once just after the dispatch loop finishes cleanly.
50    fn on_executor_down(&self) {}
51    /// Called when the dispatch loop returns an error.
52    fn on_executor_error(&self, _e: &ExecutorError) {}
53
54    /// Called before an item with `app_id().is_some()` runs (per invocation).
55    fn on_app_start(&self, _task: TaskId, _app: u32, _instance: Option<u32>) {}
56    /// Called after such an item runs.
57    fn on_app_stop(&self, _task: TaskId) {}
58    /// Called when an item returns `Err` or panics.
59    fn on_app_error(&self, _task: TaskId, _e: &(dyn std::error::Error + 'static)) {}
60
61    /// Called when an item invokes `Context::send_event`.
62    fn on_send_event(&self, _task: TaskId, _ev: UserEvent) {}
63}
64
65/// No-op observer used when the user does not configure one.
66pub struct NoopObserver;
67impl Observer for NoopObserver {}