use std::{borrow::Cow, collections::BTreeMap, fmt, sync::Arc};
use async_trait::async_trait;
use thiserror::Error;
use crate::{
clock::{SharedClock, system_clock},
observability::{MetricRecorder, MetricRegistry, TracingConfig},
result::{BoxError, ClassifyError, ErrorKind},
worker::{
LocalWorkerLeaseStore, ShutdownToken, ShutdownTrigger, WorkerLeaseStore, WorkerRunOptions,
shutdown_channel,
},
};
const MAX_LIFECYCLE_HOOK_NAME_LENGTH: usize = 96;
#[cfg(feature = "time")]
use crate::clock::{SharedUtcClock, system_utc_clock};
#[derive(Clone)]
#[non_exhaustive]
pub struct RuntimeParts {
service_name: String,
lifecycle: ApplicationLifecycle,
clock: SharedClock,
#[cfg(feature = "time")]
utc_clock: SharedUtcClock,
metrics: Option<Arc<MetricRegistry>>,
worker_lease_store: Arc<dyn WorkerLeaseStore>,
shutdown_trigger: ShutdownTrigger,
shutdown_token: ShutdownToken,
}
impl RuntimeParts {
#[must_use]
pub fn builder(service_name: impl Into<String>) -> RuntimePartsBuilder {
RuntimePartsBuilder::new(service_name)
}
#[must_use]
pub fn service_name(&self) -> &str {
&self.service_name
}
#[must_use]
pub fn clock(&self) -> &SharedClock {
&self.clock
}
#[must_use]
pub const fn lifecycle(&self) -> &ApplicationLifecycle {
&self.lifecycle
}
pub async fn run_lifecycle_stage(
&self,
stage: LifecycleStage,
) -> Result<LifecycleRunSummary, LifecycleError> {
self.lifecycle.run_stage(stage, self).await
}
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
#[must_use]
pub fn utc_clock(&self) -> &SharedUtcClock {
&self.utc_clock
}
#[must_use]
pub fn metrics_registry(&self) -> Option<&Arc<MetricRegistry>> {
self.metrics.as_ref()
}
#[must_use]
pub fn metrics_recorder(&self) -> Option<Arc<dyn MetricRecorder>> {
self.metrics
.as_ref()
.map(|registry| Arc::clone(registry) as Arc<dyn MetricRecorder>)
}
#[must_use]
pub fn worker_lease_store(&self) -> Arc<dyn WorkerLeaseStore> {
Arc::clone(&self.worker_lease_store)
}
#[must_use]
pub fn worker_run_options(&self) -> WorkerRunOptions {
let mut options = WorkerRunOptions::new()
.with_clock(Arc::clone(&self.clock))
.with_metrics(self.metrics_recorder());
options = options.with_lease_store(
self.service_name.clone(),
Arc::clone(&self.worker_lease_store),
);
options
}
#[must_use]
pub fn shutdown_trigger(&self) -> ShutdownTrigger {
self.shutdown_trigger.clone()
}
#[must_use]
pub fn shutdown_token(&self) -> ShutdownToken {
self.shutdown_token.clone()
}
}
impl fmt::Debug for RuntimeParts {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("RuntimeParts")
.field("service_name", &self.service_name)
.field("lifecycle_hooks", &self.lifecycle.hooks().len())
.field("metrics_enabled", &self.metrics.is_some())
.finish_non_exhaustive()
}
}
#[derive(Clone, Default)]
pub struct ApplicationLifecycle {
hooks: Arc<[Arc<dyn LifecycleHook>]>,
}
impl ApplicationLifecycle {
#[must_use]
pub fn new() -> Self {
Self {
hooks: Arc::from([]),
}
}
#[must_use]
pub fn with_hook(mut self, hook: Arc<dyn LifecycleHook>) -> Self {
let mut hooks = self.hooks.iter().cloned().collect::<Vec<_>>();
hooks.push(hook);
self.hooks = Arc::from(hooks);
self
}
#[must_use]
pub fn hooks(&self) -> &[Arc<dyn LifecycleHook>] {
&self.hooks
}
pub async fn run_stage(
&self,
stage: LifecycleStage,
runtime: &RuntimeParts,
) -> Result<LifecycleRunSummary, LifecycleError> {
validate_lifecycle_hooks(&self.hooks)
.map_err(|source| LifecycleError::InvalidHooks { stage, source })?;
let mut summary = LifecycleRunSummary::new(stage, self.hooks.len());
for hook in self.hooks.iter() {
tracing::debug!(
service = runtime.service_name(),
lifecycle_stage = stage.as_str(),
lifecycle_hook = hook.name(),
"running lifecycle hook"
);
hook.on_stage(stage, runtime)
.await
.map_err(|source| LifecycleError::HookFailed {
stage,
hook: hook.name().to_owned(),
source,
})?;
summary.completed += 1;
}
Ok(summary)
}
}
impl fmt::Debug for ApplicationLifecycle {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ApplicationLifecycle")
.field("hooks", &self.hooks.len())
.finish()
}
}
#[async_trait]
pub trait LifecycleHook: Send + Sync + 'static {
fn name(&self) -> &str;
async fn on_stage(&self, stage: LifecycleStage, runtime: &RuntimeParts)
-> 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",
}
}
}
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 {
#[must_use]
pub 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(Error)]
#[non_exhaustive]
pub enum LifecycleError {
#[error("lifecycle hooks are invalid during {stage}")]
InvalidHooks {
stage: LifecycleStage,
#[source]
source: RuntimePartsError,
},
#[error("lifecycle hook {hook} failed during {stage}")]
HookFailed {
stage: LifecycleStage,
hook: String,
#[source]
source: BoxError,
},
}
impl fmt::Debug for LifecycleError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidHooks { stage, .. } => formatter
.debug_struct("LifecycleError")
.field("code", &"lifecycle_hooks_invalid")
.field("stage", stage)
.finish_non_exhaustive(),
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 {
match self {
Self::InvalidHooks { source, .. } => source.error_kind(),
Self::HookFailed { .. } => ErrorKind::Internal,
}
}
fn error_code(&self) -> Cow<'static, str> {
Cow::Borrowed(match self {
Self::InvalidHooks { .. } => "lifecycle_hooks_invalid",
Self::HookFailed { .. } => "lifecycle_hook_failed",
})
}
}
#[derive(Clone)]
#[non_exhaustive]
pub struct RuntimePartsBuilder {
service_name: String,
lifecycle_hooks: Vec<Arc<dyn LifecycleHook>>,
clock: SharedClock,
#[cfg(feature = "time")]
utc_clock: SharedUtcClock,
metrics: Option<Arc<MetricRegistry>>,
metrics_enabled: bool,
worker_lease_store: Option<Arc<dyn WorkerLeaseStore>>,
}
impl RuntimePartsBuilder {
#[must_use]
pub fn new(service_name: impl Into<String>) -> Self {
Self {
service_name: service_name.into().trim().to_owned(),
lifecycle_hooks: Vec::new(),
clock: system_clock(),
#[cfg(feature = "time")]
utc_clock: system_utc_clock(),
metrics: None,
metrics_enabled: false,
worker_lease_store: None,
}
}
#[must_use]
pub fn with_clock(mut self, clock: SharedClock) -> Self {
self.clock = clock;
self
}
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
#[must_use]
pub fn with_utc_clock(mut self, clock: SharedUtcClock) -> Self {
self.utc_clock = clock;
self
}
#[must_use]
pub const fn with_metrics_enabled(mut self, enabled: bool) -> Self {
self.metrics_enabled = enabled;
self
}
#[must_use]
pub fn with_metric_registry(mut self, registry: Arc<MetricRegistry>) -> Self {
self.metrics = Some(registry);
self.metrics_enabled = true;
self
}
#[must_use]
pub fn with_lifecycle_hook(mut self, hook: Arc<dyn LifecycleHook>) -> Self {
self.lifecycle_hooks.push(hook);
self
}
#[must_use]
pub fn with_worker_lease_store(mut self, store: Arc<dyn WorkerLeaseStore>) -> Self {
self.worker_lease_store = Some(store);
self
}
pub fn build(self) -> Result<RuntimeParts, RuntimePartsError> {
TracingConfig::try_new(&self.service_name)
.map_err(|_| RuntimePartsError::InvalidServiceName)?;
validate_lifecycle_hooks(&self.lifecycle_hooks)?;
let (shutdown_trigger, shutdown_token) = shutdown_channel();
let metrics = match (self.metrics, self.metrics_enabled) {
(Some(registry), _) => Some(registry),
(None, true) => Some(Arc::new(MetricRegistry::new())),
(None, false) => None,
};
Ok(RuntimeParts {
service_name: self.service_name,
lifecycle: ApplicationLifecycle {
hooks: Arc::from(self.lifecycle_hooks),
},
clock: self.clock,
#[cfg(feature = "time")]
utc_clock: self.utc_clock,
metrics,
worker_lease_store: self
.worker_lease_store
.unwrap_or_else(|| Arc::new(LocalWorkerLeaseStore::new())),
shutdown_trigger,
shutdown_token,
})
}
}
impl fmt::Debug for RuntimePartsBuilder {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("RuntimePartsBuilder")
.field("service_name", &self.service_name)
.field("lifecycle_hooks", &self.lifecycle_hooks.len())
.field("metrics_enabled", &self.metrics_enabled)
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum RuntimePartsError {
#[error("runtime service name is invalid")]
InvalidServiceName,
#[error("runtime lifecycle hook name at index {index} is invalid: {name:?}")]
InvalidLifecycleHookName {
#[doc = "The zero-based item index."]
index: usize,
#[doc = "The name value."]
name: String,
},
#[error(
"runtime lifecycle hook name {name:?} is duplicated at indexes {first_index} and {second_index}"
)]
DuplicateLifecycleHookName {
first_index: usize,
second_index: usize,
name: String,
},
}
impl ClassifyError for RuntimePartsError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> Cow<'static, str> {
Cow::Borrowed(match self {
Self::InvalidServiceName => "runtime_invalid_service_name",
Self::InvalidLifecycleHookName { .. } => "runtime_invalid_lifecycle_hook_name",
Self::DuplicateLifecycleHookName { .. } => "runtime_duplicate_lifecycle_hook_name",
})
}
}
fn validate_lifecycle_hooks(hooks: &[Arc<dyn LifecycleHook>]) -> Result<(), RuntimePartsError> {
let mut names = BTreeMap::<&str, usize>::new();
for (index, hook) in hooks.iter().enumerate() {
let name = hook.name();
if !valid_lifecycle_hook_name(name) {
return Err(RuntimePartsError::InvalidLifecycleHookName {
index,
name: name.to_owned(),
});
}
if let Some(first_index) = names.get(name).copied() {
return Err(RuntimePartsError::DuplicateLifecycleHookName {
first_index,
second_index: index,
name: name.to_owned(),
});
}
names.insert(name, index);
}
Ok(())
}
fn valid_lifecycle_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 async_trait::async_trait;
use super::*;
#[test]
fn runtime_parts_create_metrics_when_enabled() {
let runtime = RuntimeParts::builder("example_service")
.with_metrics_enabled(true)
.build()
.expect("runtime should build");
assert_eq!(runtime.service_name(), "example_service");
assert!(runtime.metrics_registry().is_some());
assert!(runtime.metrics_recorder().is_some());
assert!(!runtime.shutdown_token().is_shutdown_requested());
}
#[tokio::test]
async fn runtime_lifecycle_runs_registered_hooks_in_order() {
let seen = Arc::new(Mutex::new(Vec::new()));
let runtime = RuntimeParts::builder("example_service")
.with_lifecycle_hook(Arc::new(RecordingLifecycleHook::new(
"first",
Arc::clone(&seen),
)))
.with_lifecycle_hook(Arc::new(RecordingLifecycleHook::new(
"second",
Arc::clone(&seen),
)))
.build()
.expect("runtime should build");
let summary = runtime
.run_lifecycle_stage(LifecycleStage::BeforeStart)
.await
.expect("lifecycle should run");
assert_eq!(summary.stage(), LifecycleStage::BeforeStart);
assert_eq!(summary.hooks(), 2);
assert_eq!(summary.completed(), 2);
assert_eq!(
&*seen.lock().expect("seen lock should not poison"),
&["first:before_start", "second:before_start"]
);
}
#[tokio::test]
async fn runtime_lifecycle_reports_hook_failure() {
let runtime = RuntimeParts::builder("example_service")
.with_lifecycle_hook(Arc::new(FailingLifecycleHook))
.build()
.expect("runtime should build");
let error = runtime
.run_lifecycle_stage(LifecycleStage::BeforeStart)
.await
.expect_err("lifecycle should fail");
assert!(matches!(&error, LifecycleError::HookFailed { .. }));
assert!(!format!("{error:?}").contains("lifecycle failed"));
}
#[test]
fn runtime_parts_reject_invalid_lifecycle_hook_name() {
let error = RuntimeParts::builder("example_service")
.with_lifecycle_hook(Arc::new(RecordingLifecycleHook::new(
"startup diagnostics",
Arc::new(Mutex::new(Vec::new())),
)))
.build()
.expect_err("runtime should reject unstable hook names");
assert!(matches!(
error,
RuntimePartsError::InvalidLifecycleHookName { index: 0, .. }
));
}
#[test]
fn runtime_parts_reject_duplicate_lifecycle_hook_names() {
let seen = Arc::new(Mutex::new(Vec::new()));
let error = RuntimeParts::builder("example_service")
.with_lifecycle_hook(Arc::new(RecordingLifecycleHook::new(
"startup_diagnostics",
Arc::clone(&seen),
)))
.with_lifecycle_hook(Arc::new(RecordingLifecycleHook::new(
"startup_diagnostics",
Arc::clone(&seen),
)))
.build()
.expect_err("runtime should reject duplicate hook names");
assert!(matches!(
error,
RuntimePartsError::DuplicateLifecycleHookName {
first_index: 0,
second_index: 1,
..
}
));
}
#[test]
fn runtime_worker_options_use_injected_clock() {
use crate::clock::ManualClock;
let clock = ManualClock::new();
let runtime = RuntimeParts::builder("example_service")
.with_clock(clock.shared())
.build()
.expect("runtime should build");
let before = runtime.worker_run_options().clock().now();
clock.advance(std::time::Duration::from_secs(5));
let after = runtime.worker_run_options().clock().now();
assert_eq!(
after.duration_since(before),
std::time::Duration::from_secs(5)
);
}
struct RecordingLifecycleHook {
name: &'static str,
seen: Arc<Mutex<Vec<String>>>,
}
impl RecordingLifecycleHook {
fn new(name: &'static str, seen: Arc<Mutex<Vec<String>>>) -> Self {
Self { name, seen }
}
}
#[async_trait]
impl LifecycleHook for RecordingLifecycleHook {
fn name(&self) -> &str {
self.name
}
async fn on_stage(
&self,
stage: LifecycleStage,
_runtime: &RuntimeParts,
) -> Result<(), BoxError> {
self.seen
.lock()
.expect("seen lock should not poison")
.push(format!("{}:{}", self.name, stage.as_str()));
Ok(())
}
}
struct FailingLifecycleHook;
#[async_trait]
impl LifecycleHook for FailingLifecycleHook {
fn name(&self) -> &str {
"failing"
}
async fn on_stage(
&self,
_stage: LifecycleStage,
_runtime: &RuntimeParts,
) -> Result<(), BoxError> {
Err(std::io::Error::other("lifecycle failed").into())
}
}
#[cfg(feature = "time")]
#[test]
fn runtime_parts_accept_injected_utc_clock() {
use crate::clock::ManualUtcClock;
let clock = ManualUtcClock::at(time::OffsetDateTime::UNIX_EPOCH);
let runtime = RuntimeParts::builder("example_service")
.with_utc_clock(clock.shared())
.build()
.expect("runtime should build");
assert_eq!(
runtime.utc_clock().now_utc(),
time::OffsetDateTime::UNIX_EPOCH
);
}
#[test]
fn runtime_parts_reject_invalid_service_name() {
let error = RuntimeParts::builder("not valid").build().unwrap_err();
assert_eq!(error, RuntimePartsError::InvalidServiceName);
}
}