Skip to main content

mads_core/
lifecycle.rs

1//! Application lifecycle hooks, state transitions, and failure rollback.
2
3use std::future::Future;
4use std::pin::Pin;
5
6use crate::{ApplicationContext, Diagnostic, Error, MADS010, MADS011, Result};
7
8enum HookGroup {
9    Infrastructure(&'static str),
10    Application,
11}
12
13struct RegisteredHook {
14    group: HookGroup,
15    sequence: usize,
16    hook: Box<dyn LifecycleHook>,
17}
18
19/// The lifecycle state of an application.
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub enum LifecycleState {
22    /// The application has been built but has not started.
23    Created,
24    /// The application is starting lifecycle hooks.
25    Starting,
26    /// The application has started successfully.
27    Running,
28    /// The application is stopping lifecycle hooks.
29    Stopping,
30    /// The application has stopped and cannot be restarted.
31    Stopped,
32}
33
34/// The asynchronous result returned by a lifecycle hook.
35pub type LifecycleFuture<'a> = Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
36
37/// Starts and stops an application resource.
38pub trait LifecycleHook: Send + Sync {
39    /// Returns a stable name used in lifecycle diagnostics.
40    fn name(&self) -> &str;
41
42    /// Starts this resource using the completed application context.
43    fn start<'a>(&'a self, context: &'a ApplicationContext) -> LifecycleFuture<'a>;
44
45    /// Stops this resource using the completed application context.
46    fn stop<'a>(&'a self, context: &'a ApplicationContext) -> LifecycleFuture<'a>;
47}
48
49pub(crate) enum LifecycleRegistration {
50    Infrastructure {
51        owner: &'static str,
52        hook: Box<dyn LifecycleHook>,
53    },
54    Application {
55        hook: Box<dyn LifecycleHook>,
56    },
57}
58
59/// A native provider value accompanied by lifecycle hooks registered for it.
60pub struct LifecycleResource<T> {
61    value: T,
62    registrations: Vec<LifecycleRegistration>,
63}
64
65impl<T> LifecycleResource<T> {
66    /// Creates a lifecycle resource without any hooks.
67    pub fn new(value: T) -> Self {
68        Self {
69            value,
70            registrations: Vec::new(),
71        }
72    }
73
74    /// Adds an infrastructure hook owned by the named framework component.
75    #[must_use]
76    pub fn with_infrastructure_hook<H>(mut self, owner: &'static str, hook: H) -> Self
77    where
78        H: LifecycleHook + 'static,
79    {
80        self.registrations
81            .push(LifecycleRegistration::Infrastructure {
82                owner,
83                hook: Box::new(hook),
84            });
85        self
86    }
87
88    /// Adds an application hook after previously authored registrations.
89    #[must_use]
90    pub fn with_application_hook<H>(mut self, hook: H) -> Self
91    where
92        H: LifecycleHook + 'static,
93    {
94        self.registrations.push(LifecycleRegistration::Application {
95            hook: Box::new(hook),
96        });
97        self
98    }
99
100    pub(crate) fn into_parts(self) -> (T, Vec<LifecycleRegistration>) {
101        (self.value, self.registrations)
102    }
103}
104
105/// Coordinates ordered lifecycle hooks for one application.
106pub struct LifecycleManager {
107    state: LifecycleState,
108    hooks: Vec<RegisteredHook>,
109    next_sequence: usize,
110}
111
112impl LifecycleManager {
113    /// Creates a manager in the created state with no lifecycle hooks.
114    pub fn new() -> Self {
115        Self {
116            state: LifecycleState::Created,
117            hooks: Vec::new(),
118            next_sequence: 0,
119        }
120    }
121
122    /// Adds a lifecycle hook that starts after previously registered hooks.
123    pub fn add_hook<H>(&mut self, hook: H) -> &mut Self
124    where
125        H: LifecycleHook + 'static,
126    {
127        self.add_registration(LifecycleRegistration::Application {
128            hook: Box::new(hook),
129        });
130        self
131    }
132
133    /// Adds an infrastructure hook owned by the named framework component.
134    #[doc(hidden)]
135    pub fn add_infrastructure_hook<H>(&mut self, owner: &'static str, hook: H) -> &mut Self
136    where
137        H: LifecycleHook + 'static,
138    {
139        self.add_registration(LifecycleRegistration::Infrastructure {
140            owner,
141            hook: Box::new(hook),
142        });
143        self
144    }
145
146    pub(crate) fn add_boxed_infrastructure_hook(
147        &mut self,
148        owner: &'static str,
149        hook: Box<dyn LifecycleHook>,
150    ) {
151        self.add_registration(LifecycleRegistration::Infrastructure { owner, hook });
152    }
153
154    pub(crate) fn add_registration(&mut self, registration: LifecycleRegistration) {
155        let (group, hook) = match registration {
156            LifecycleRegistration::Infrastructure { owner, hook } => {
157                (HookGroup::Infrastructure(owner), hook)
158            }
159            LifecycleRegistration::Application { hook } => (HookGroup::Application, hook),
160        };
161        self.hooks.push(RegisteredHook {
162            group,
163            sequence: self.next_sequence,
164            hook,
165        });
166        self.next_sequence += 1;
167    }
168
169    /// Returns the manager's current lifecycle state.
170    pub const fn state(&self) -> LifecycleState {
171        self.state
172    }
173
174    /// Starts infrastructure hooks by owner before application hooks in registration order.
175    #[allow(clippy::result_large_err)]
176    pub async fn start(&mut self, context: &ApplicationContext) -> Result<()> {
177        if self.state != LifecycleState::Created {
178            return Err(invalid_transition(self.state, "start"));
179        }
180
181        self.state = LifecycleState::Starting;
182        self.hooks
183            .sort_by(|left, right| match (&left.group, &right.group) {
184                (HookGroup::Infrastructure(left_owner), HookGroup::Infrastructure(right_owner)) => {
185                    left_owner
186                        .cmp(right_owner)
187                        .then(left.sequence.cmp(&right.sequence))
188                }
189                (HookGroup::Infrastructure(_), HookGroup::Application) => std::cmp::Ordering::Less,
190                (HookGroup::Application, HookGroup::Infrastructure(_)) => {
191                    std::cmp::Ordering::Greater
192                }
193                (HookGroup::Application, HookGroup::Application) => {
194                    left.sequence.cmp(&right.sequence)
195                }
196            });
197        let mut started: Vec<usize> = Vec::new();
198
199        for index in 0..self.hooks.len() {
200            let hook = self.hooks[index].hook.as_ref();
201            if let Err(error) = hook.start(context).await {
202                let mut diagnostic = hook_failure_diagnostic(hook.name(), "startup");
203                for started_index in started.into_iter().rev() {
204                    let rollback_hook = self.hooks[started_index].hook.as_ref();
205                    if let Err(rollback_error) = rollback_hook.stop(context).await {
206                        diagnostic = diagnostic.with_suggestion(format!(
207                            "rollback hook {} failed: {rollback_error}",
208                            rollback_hook.name()
209                        ));
210                    }
211                }
212                self.state = LifecycleState::Stopped;
213                return Err(Error::with_source(diagnostic, error));
214            }
215            started.push(index);
216        }
217
218        self.state = LifecycleState::Running;
219        Ok(())
220    }
221
222    /// Stops all hooks in reverse successful startup order.
223    #[allow(clippy::result_large_err)]
224    pub async fn shutdown(&mut self, context: &ApplicationContext) -> Result<()> {
225        if self.state != LifecycleState::Running {
226            return Err(invalid_transition(self.state, "shutdown"));
227        }
228
229        self.state = LifecycleState::Stopping;
230        let mut failure = None;
231
232        for registration in self.hooks.iter().rev() {
233            let hook = registration.hook.as_ref();
234            if let Err(error) = hook.stop(context).await
235                && failure.is_none()
236            {
237                failure = Some(hook_failure(hook.name(), "shutdown", error));
238            }
239        }
240
241        self.state = LifecycleState::Stopped;
242        failure.map_or(Ok(()), Err)
243    }
244}
245
246impl Default for LifecycleManager {
247    fn default() -> Self {
248        Self::new()
249    }
250}
251
252fn invalid_transition(state: LifecycleState, operation: &str) -> Error {
253    Error::new(
254        Diagnostic::new(
255            MADS010,
256            "invalid lifecycle transition",
257            format!("cannot {operation} an application while it is {state:?}"),
258        )
259        .with_subject(operation),
260    )
261}
262
263fn hook_failure(name: &str, operation: &str, error: Error) -> Error {
264    Error::with_source(hook_failure_diagnostic(name, operation), error)
265}
266
267fn hook_failure_diagnostic(name: &str, operation: &str) -> Diagnostic {
268    Diagnostic::new(
269        MADS011,
270        "lifecycle hook failed",
271        format!("lifecycle hook failed during {operation}"),
272    )
273    .with_subject(name)
274}
275
276#[cfg(test)]
277mod tests {
278    use std::any::TypeId;
279
280    use super::*;
281    use crate::ProviderContribution;
282
283    struct Value;
284
285    struct NamedHook(&'static str);
286
287    impl LifecycleHook for NamedHook {
288        fn name(&self) -> &str {
289            self.0
290        }
291
292        fn start<'a>(&'a self, _: &'a ApplicationContext) -> LifecycleFuture<'a> {
293            Box::pin(async { Ok(()) })
294        }
295
296        fn stop<'a>(&'a self, _: &'a ApplicationContext) -> LifecycleFuture<'a> {
297            Box::pin(async { Ok(()) })
298        }
299    }
300
301    #[test]
302    fn resource_preserves_hook_order_and_erases_the_native_value() {
303        let resource = LifecycleResource::new(Value)
304            .with_infrastructure_hook("zeta", NamedHook("first"))
305            .with_application_hook(NamedHook("second"))
306            .with_infrastructure_hook("alpha", NamedHook("third"));
307
308        let (provider, registrations) = ProviderContribution::from_resource(resource).into_parts();
309
310        assert_eq!(provider.as_ref().type_id(), TypeId::of::<Value>());
311        assert_eq!(registrations.len(), 3);
312        assert!(matches!(
313            &registrations[0],
314            LifecycleRegistration::Infrastructure { owner: "zeta", hook }
315                if hook.name() == "first"
316        ));
317        assert!(matches!(
318            &registrations[1],
319            LifecycleRegistration::Application { hook } if hook.name() == "second"
320        ));
321        assert!(matches!(
322            &registrations[2],
323            LifecycleRegistration::Infrastructure { owner: "alpha", hook }
324                if hook.name() == "third"
325        ));
326    }
327}