use std::{collections::BTreeMap, fmt, sync::Arc};
use async_trait::async_trait;
use thiserror::Error;
use crate::result::{BoxError, ClassifyError, ErrorKind};
const MAX_LIFECYCLE_HOOK_NAME_LENGTH: usize = 96;
#[derive(Clone, Default)]
pub struct Lifecycle {
hooks: Arc<[Arc<dyn LifecycleHook>]>,
}
impl Lifecycle {
#[must_use]
pub fn builder() -> LifecycleBuilder {
LifecycleBuilder::new()
}
#[must_use]
pub fn hooks(&self) -> &[Arc<dyn LifecycleHook>] {
&self.hooks
}
pub async fn run(&self, stage: LifecycleStage) -> Result<LifecycleRunSummary, LifecycleError> {
let mut summary = LifecycleRunSummary::new(stage, self.hooks.len());
for offset in 0..self.hooks.len() {
let index = if stage.is_shutdown() {
self.hooks.len() - offset - 1
} else {
offset
};
let hook = &self.hooks[index];
tracing::debug!(
lifecycle_stage = stage.as_str(),
lifecycle_hook = hook.name(),
"running lifecycle hook"
);
hook.run(stage)
.await
.map_err(|source| LifecycleError::HookFailed {
stage,
hook: hook.name(),
source,
})?;
summary.completed += 1;
}
Ok(summary)
}
}
impl fmt::Debug for Lifecycle {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Lifecycle")
.field("hooks", &self.hooks.len())
.finish()
}
}
#[derive(Clone, Default)]
pub struct LifecycleBuilder {
hooks: Vec<Arc<dyn LifecycleHook>>,
}
impl LifecycleBuilder {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn hook(mut self, hook: Arc<dyn LifecycleHook>) -> Self {
self.hooks.push(hook);
self
}
pub fn build(self) -> Result<Lifecycle, LifecycleBuildError> {
validate_hooks(&self.hooks)?;
Ok(Lifecycle {
hooks: Arc::from(self.hooks),
})
}
}
impl fmt::Debug for LifecycleBuilder {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("LifecycleBuilder")
.field("hooks", &self.hooks.len())
.finish()
}
}
#[async_trait]
pub trait LifecycleHook: Send + Sync + 'static {
fn name(&self) -> &'static str;
async fn run(&self, stage: LifecycleStage) -> Result<(), BoxError>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LifecycleStage {
BeforeStart,
AfterStart,
BeforeShutdown,
AfterShutdown,
}
impl LifecycleStage {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::BeforeStart => "before_start",
Self::AfterStart => "after_start",
Self::BeforeShutdown => "before_shutdown",
Self::AfterShutdown => "after_shutdown",
}
}
const fn is_shutdown(self) -> bool {
matches!(self, Self::BeforeShutdown | Self::AfterShutdown)
}
}
impl fmt::Display for LifecycleStage {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct LifecycleRunSummary {
stage: LifecycleStage,
hooks: usize,
completed: usize,
}
impl LifecycleRunSummary {
const fn new(stage: LifecycleStage, hooks: usize) -> Self {
Self {
stage,
hooks,
completed: 0,
}
}
#[must_use]
pub const fn stage(self) -> LifecycleStage {
self.stage
}
#[must_use]
pub const fn hooks(self) -> usize {
self.hooks
}
#[must_use]
pub const fn completed(self) -> usize {
self.completed
}
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum LifecycleBuildError {
#[error("lifecycle hook name at index {index} is invalid: {name:?}")]
InvalidHookName {
index: usize,
name: &'static str,
},
#[error(
"lifecycle hook name {name:?} is duplicated at indexes {first_index} and {second_index}"
)]
DuplicateHookName {
first_index: usize,
second_index: usize,
name: &'static str,
},
}
impl ClassifyError for LifecycleBuildError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> crate::result::ErrorCode {
crate::result::ErrorCode::internal(match self {
Self::InvalidHookName { .. } => "lifecycle_invalid_hook_name",
Self::DuplicateHookName { .. } => "lifecycle_duplicate_hook_name",
})
}
}
#[derive(Error)]
#[non_exhaustive]
pub enum LifecycleError {
#[error("lifecycle hook {hook} failed during {stage}")]
HookFailed {
stage: LifecycleStage,
hook: &'static str,
#[source]
source: BoxError,
},
}
impl fmt::Debug for LifecycleError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::HookFailed { stage, hook, .. } => formatter
.debug_struct("LifecycleError")
.field("code", &"lifecycle_hook_failed")
.field("stage", stage)
.field("hook", hook)
.finish_non_exhaustive(),
}
}
}
impl ClassifyError for LifecycleError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Internal
}
fn error_code(&self) -> crate::result::ErrorCode {
crate::result::ErrorCode::internal("lifecycle_hook_failed")
}
}
fn validate_hooks(hooks: &[Arc<dyn LifecycleHook>]) -> Result<(), LifecycleBuildError> {
let mut names = BTreeMap::<&'static str, usize>::new();
for (index, hook) in hooks.iter().enumerate() {
let name = hook.name();
if !valid_hook_name(name) {
return Err(LifecycleBuildError::InvalidHookName { index, name });
}
if let Some(first_index) = names.insert(name, index) {
return Err(LifecycleBuildError::DuplicateHookName {
first_index,
second_index: index,
name,
});
}
}
Ok(())
}
fn valid_hook_name(value: &str) -> bool {
!value.is_empty()
&& value.len() <= MAX_LIFECYCLE_HOOK_NAME_LENGTH
&& value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use super::*;
#[tokio::test]
async fn lifecycle_runs_startup_hooks_in_registration_order() {
let seen = Arc::new(Mutex::new(Vec::new()));
let lifecycle = Lifecycle::builder()
.hook(Arc::new(RecordingHook::new("first", Arc::clone(&seen))))
.hook(Arc::new(RecordingHook::new("second", Arc::clone(&seen))))
.build()
.expect("lifecycle should build");
let summary = lifecycle
.run(LifecycleStage::BeforeStart)
.await
.expect("lifecycle should run");
assert_eq!(summary.hooks(), 2);
assert_eq!(summary.completed(), 2);
assert_eq!(&*seen.lock().unwrap(), &["first", "second"]);
}
#[tokio::test]
async fn lifecycle_runs_shutdown_hooks_in_reverse_registration_order() {
let seen = Arc::new(Mutex::new(Vec::new()));
let lifecycle = Lifecycle::builder()
.hook(Arc::new(RecordingHook::new(
"dependency",
Arc::clone(&seen),
)))
.hook(Arc::new(RecordingHook::new("dependent", Arc::clone(&seen))))
.build()
.expect("lifecycle should build");
lifecycle
.run(LifecycleStage::BeforeShutdown)
.await
.expect("lifecycle should run");
assert_eq!(&*seen.lock().unwrap(), &["dependent", "dependency"]);
}
#[test]
fn lifecycle_rejects_duplicate_hook_names() {
let seen = Arc::new(Mutex::new(Vec::new()));
let error = Lifecycle::builder()
.hook(Arc::new(RecordingHook::new("same", Arc::clone(&seen))))
.hook(Arc::new(RecordingHook::new("same", Arc::clone(&seen))))
.build()
.expect_err("duplicate hooks must be rejected");
assert!(matches!(
error,
LifecycleBuildError::DuplicateHookName {
first_index: 0,
second_index: 1,
..
}
));
}
#[tokio::test]
async fn lifecycle_reports_hook_failure_without_exposing_source_details() {
let lifecycle = Lifecycle::builder()
.hook(Arc::new(FailingHook))
.build()
.expect("lifecycle should build");
let error = lifecycle
.run(LifecycleStage::BeforeStart)
.await
.expect_err("hook should fail");
assert!(!format!("{error:?}").contains("private failure"));
}
struct RecordingHook {
name: &'static str,
seen: Arc<Mutex<Vec<&'static str>>>,
}
impl RecordingHook {
fn new(name: &'static str, seen: Arc<Mutex<Vec<&'static str>>>) -> Self {
Self { name, seen }
}
}
#[async_trait]
impl LifecycleHook for RecordingHook {
fn name(&self) -> &'static str {
self.name
}
async fn run(&self, _stage: LifecycleStage) -> Result<(), BoxError> {
self.seen.lock().unwrap().push(self.name);
Ok(())
}
}
struct FailingHook;
#[async_trait]
impl LifecycleHook for FailingHook {
fn name(&self) -> &'static str {
"failing"
}
async fn run(&self, _stage: LifecycleStage) -> Result<(), BoxError> {
Err(std::io::Error::other("private failure").into())
}
}
}