footing 0.1.0

Feature-gated foundations for Rust backend services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
//! Service runtime parts shared by application bootstraps.
//!
//! The type keeps cross-cutting runtime handles in one place: service identity,
//! lifecycle hooks, clock, metrics, and graceful worker shutdown. Applications
//! remain responsible for domain state and network listeners.
//!
//! ```rust
//! use footing::runtime::RuntimeParts;
//!
//! let runtime = RuntimeParts::builder("billing-api")
//!     .with_metrics_enabled(true)
//!     .build()
//!     .unwrap();
//!
//! assert_eq!(runtime.service_name(), "billing-api");
//! assert!(runtime.metrics_registry().is_some());
//! ```
//!
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};

/// Shared runtime handles for one service process.
#[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 {
    /// Creates a builder for runtime parts.
    #[must_use]
    pub fn builder(service_name: impl Into<String>) -> RuntimePartsBuilder {
        RuntimePartsBuilder::new(service_name)
    }

    /// Returns the service name used in logs and metrics.
    #[must_use]
    pub fn service_name(&self) -> &str {
        &self.service_name
    }

    /// Returns the process clock.
    #[must_use]
    pub fn clock(&self) -> &SharedClock {
        &self.clock
    }

    /// Returns application lifecycle hooks registered for this runtime.
    #[must_use]
    pub const fn lifecycle(&self) -> &ApplicationLifecycle {
        &self.lifecycle
    }

    /// Runs one lifecycle stage for every registered hook.
    pub async fn run_lifecycle_stage(
        &self,
        stage: LifecycleStage,
    ) -> Result<LifecycleRunSummary, LifecycleError> {
        self.lifecycle.run_stage(stage, self).await
    }

    /// Returns the UTC wall clock for business timestamps.
    #[cfg(feature = "time")]
    #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
    #[must_use]
    pub fn utc_clock(&self) -> &SharedUtcClock {
        &self.utc_clock
    }

    /// Returns the in-memory metric registry, when metrics are enabled.
    #[must_use]
    pub fn metrics_registry(&self) -> Option<&Arc<MetricRegistry>> {
        self.metrics.as_ref()
    }

    /// Returns the metric recorder as a trait object, when metrics are enabled.
    #[must_use]
    pub fn metrics_recorder(&self) -> Option<Arc<dyn MetricRecorder>> {
        self.metrics
            .as_ref()
            .map(|registry| Arc::clone(registry) as Arc<dyn MetricRecorder>)
    }

    /// Returns the worker lease store used by generic worker runners.
    #[must_use]
    pub fn worker_lease_store(&self) -> Arc<dyn WorkerLeaseStore> {
        Arc::clone(&self.worker_lease_store)
    }

    /// Builds standard worker run options for this process.
    #[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
    }

    /// Returns a trigger that can request worker shutdown.
    #[must_use]
    pub fn shutdown_trigger(&self) -> ShutdownTrigger {
        self.shutdown_trigger.clone()
    }

    /// Returns a token that workers can wait on.
    #[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)]
/// Represents application lifecycle.
pub struct ApplicationLifecycle {
    hooks: Arc<[Arc<dyn LifecycleHook>]>,
}

impl ApplicationLifecycle {
    #[must_use]
    /// Creates a new instance.
    pub fn new() -> Self {
        Self {
            hooks: Arc::from([]),
        }
    }

    #[must_use]
    /// Configures hook and returns the updated value.
    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]
    /// Returns the hooks.
    pub fn hooks(&self) -> &[Arc<dyn LifecycleHook>] {
        &self.hooks
    }

    /// Runs stage.
    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()
    }
}

/// Defines the contract for lifecycle hook.
#[async_trait]
pub trait LifecycleHook: Send + Sync + 'static {
    /// Returns the name.
    fn name(&self) -> &str;

    /// Runs the hook for one lifecycle stage.
    async fn on_stage(&self, stage: LifecycleStage, runtime: &RuntimeParts)
    -> Result<(), BoxError>;
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// Enumerates the supported lifecycle stage values.
pub enum LifecycleStage {
    /// Indicates before start.
    BeforeStart,
    /// Indicates after start.
    AfterStart,
    /// Indicates before shutdown.
    BeforeShutdown,
    /// Indicates after shutdown.
    AfterShutdown,
}

impl LifecycleStage {
    #[must_use]
    /// Returns this value as str.
    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]
/// Summary of lifecycle run.
pub struct LifecycleRunSummary {
    stage: LifecycleStage,
    hooks: usize,
    completed: usize,
}

impl LifecycleRunSummary {
    #[must_use]
    /// Creates a new instance.
    pub const fn new(stage: LifecycleStage, hooks: usize) -> Self {
        Self {
            stage,
            hooks,
            completed: 0,
        }
    }

    #[must_use]
    /// Returns the stage.
    pub const fn stage(self) -> LifecycleStage {
        self.stage
    }

    #[must_use]
    /// Returns the hooks.
    pub const fn hooks(self) -> usize {
        self.hooks
    }

    #[must_use]
    /// Returns the completed.
    pub const fn completed(self) -> usize {
        self.completed
    }
}

#[derive(Error)]
#[non_exhaustive]
/// Errors that can occur while handling lifecycle.
pub enum LifecycleError {
    #[error("lifecycle hooks are invalid during {stage}")]
    /// The hooks is invalid.
    InvalidHooks {
        /// The stage value.
        stage: LifecycleStage,
        #[source]
        /// The source value.
        source: RuntimePartsError,
    },
    #[error("lifecycle hook {hook} failed during {stage}")]
    /// Indicates hook failed.
    HookFailed {
        /// The stage value.
        stage: LifecycleStage,
        /// The hook value.
        hook: String,
        #[source]
        /// The source value.
        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",
        })
    }
}

/// Builder for [`RuntimeParts`].
#[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 {
    /// Creates a runtime builder.
    #[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,
        }
    }

    /// Overrides the runtime clock. Primarily useful for tests.
    #[must_use]
    pub fn with_clock(mut self, clock: SharedClock) -> Self {
        self.clock = clock;
        self
    }

    /// Overrides the UTC wall clock. Primarily useful for tests.
    #[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
    }

    /// Enables or disables the default in-memory metric registry.
    #[must_use]
    pub const fn with_metrics_enabled(mut self, enabled: bool) -> Self {
        self.metrics_enabled = enabled;
        self
    }

    /// Uses a caller-provided metric registry.
    #[must_use]
    pub fn with_metric_registry(mut self, registry: Arc<MetricRegistry>) -> Self {
        self.metrics = Some(registry);
        self.metrics_enabled = true;
        self
    }

    /// Registers an application lifecycle hook.
    #[must_use]
    pub fn with_lifecycle_hook(mut self, hook: Arc<dyn LifecycleHook>) -> Self {
        self.lifecycle_hooks.push(hook);
        self
    }

    /// Uses a caller-provided worker lease store.
    #[must_use]
    pub fn with_worker_lease_store(mut self, store: Arc<dyn WorkerLeaseStore>) -> Self {
        self.worker_lease_store = Some(store);
        self
    }

    /// Builds the runtime parts.
    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()
    }
}

/// Runtime construction errors.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum RuntimePartsError {
    /// The service name is empty or contains unsupported characters.
    #[error("runtime service name is invalid")]
    InvalidServiceName,
    /// A lifecycle hook name is empty, unstable, or contains unsupported characters.
    #[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,
    },
    /// Two lifecycle hooks share the same stable name.
    #[error(
        "runtime lifecycle hook name {name:?} is duplicated at indexes {first_index} and {second_index}"
    )]
    DuplicateLifecycleHookName {
        /// The first index value.
        first_index: usize,
        /// The second index value.
        second_index: usize,
        /// The name value.
        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);
    }
}