gearbox_rs_core/cog.rs
1use crate::error::Error;
2use crate::hub::Hub;
3use async_trait::async_trait;
4use std::sync::Arc;
5
6/// A managed service component in the Gearbox framework.
7///
8/// Cogs are the building blocks of a Gearbox application. Each Cog is constructed
9/// once at startup, stored in the [`Hub`] registry, and made available to route
10/// handlers via the [`Inject<T>`](crate::Inject) extractor.
11///
12/// You rarely implement this trait by hand — the `#[cog]` proc macro generates
13/// the implementation, the [`CogFactory`](crate::CogFactory), and the inventory
14/// registration automatically.
15///
16/// # Example
17///
18/// ```ignore
19/// #[cog]
20/// pub struct UserService {
21/// #[inject]
22/// db: Arc<Database>,
23/// #[config]
24/// settings: UserConfig,
25/// }
26/// ```
27#[async_trait]
28pub trait Cog: Send + Sync + 'static {
29 /// Construct this Cog, resolving dependencies and configuration from the [`Hub`].
30 async fn new(hub: Arc<Hub>) -> Result<Self, Error>
31 where
32 Self: Sized;
33
34 /// Called after all cogs have been initialized.
35 /// Override to perform post-initialization work (start background tasks, warm caches, etc.).
36 async fn on_start(&self) -> Result<(), Error> {
37 Ok(())
38 }
39
40 /// Called during graceful shutdown.
41 /// Override to perform cleanup (flush buffers, close connections, etc.).
42 async fn on_shutdown(&self) -> Result<(), Error> {
43 Ok(())
44 }
45}