footing 0.1.3

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
//! Explicit application lifecycle orchestration.
//!
//! Hooks own the dependencies they need. The lifecycle only validates hook
//! identity and executes startup hooks in registration order. Shutdown hooks
//! run in reverse order so dependent resources stop before their dependencies.
//! The lifecycle is deliberately not a service locator for clocks, metrics,
//! workers, or shutdown handles.
//!
//! ```rust
//! use footing::runtime::Lifecycle;
//!
//! let lifecycle = Lifecycle::builder().build().unwrap();
//! assert!(lifecycle.hooks().is_empty());
//! ```

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;

/// Immutable ordered application lifecycle.
#[derive(Clone, Default)]
pub struct Lifecycle {
    hooks: Arc<[Arc<dyn LifecycleHook>]>,
}

impl Lifecycle {
    /// Creates a lifecycle builder.
    #[must_use]
    pub fn builder() -> LifecycleBuilder {
        LifecycleBuilder::new()
    }

    /// Returns hooks in execution order.
    #[must_use]
    pub fn hooks(&self) -> &[Arc<dyn LifecycleHook>] {
        &self.hooks
    }

    /// Executes every hook for one lifecycle stage.
    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()
    }
}

/// Builds a validated immutable [`Lifecycle`].
#[derive(Clone, Default)]
pub struct LifecycleBuilder {
    hooks: Vec<Arc<dyn LifecycleHook>>,
}

impl LifecycleBuilder {
    /// Creates an empty builder.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers a hook after the previously registered hooks.
    #[must_use]
    pub fn hook(mut self, hook: Arc<dyn LifecycleHook>) -> Self {
        self.hooks.push(hook);
        self
    }

    /// Validates hook identities and builds the lifecycle.
    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()
    }
}

/// A lifecycle action with explicitly captured dependencies.
#[async_trait]
pub trait LifecycleHook: Send + Sync + 'static {
    /// Returns a stable identifier used for validation and diagnostics.
    fn name(&self) -> &'static str;

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

/// Stage in the application lifecycle.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LifecycleStage {
    /// Immediately before application services start.
    BeforeStart,
    /// Immediately after application services start.
    AfterStart,
    /// Immediately before graceful shutdown begins.
    BeforeShutdown,
    /// After graceful shutdown completes.
    AfterShutdown,
}

impl LifecycleStage {
    /// Returns the stable diagnostic representation.
    #[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())
    }
}

/// Result of executing one lifecycle stage.
#[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,
        }
    }

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

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

    /// Returns the number of hooks completed before success or failure.
    #[must_use]
    pub const fn completed(self) -> usize {
        self.completed
    }
}

/// Lifecycle construction failure.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum LifecycleBuildError {
    /// A hook name is empty or contains unsupported characters.
    #[error("lifecycle hook name at index {index} is invalid: {name:?}")]
    InvalidHookName {
        /// Zero-based registration index.
        index: usize,
        /// Invalid hook name.
        name: &'static str,
    },
    /// Two hooks share the same stable name.
    #[error(
        "lifecycle hook name {name:?} is duplicated at indexes {first_index} and {second_index}"
    )]
    DuplicateHookName {
        /// Index of the first hook.
        first_index: usize,
        /// Index of the duplicate hook.
        second_index: usize,
        /// Duplicated hook name.
        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",
        })
    }
}

/// Failure returned by a lifecycle hook.
#[derive(Error)]
#[non_exhaustive]
pub enum LifecycleError {
    /// A hook failed while executing a stage.
    #[error("lifecycle hook {hook} failed during {stage}")]
    HookFailed {
        /// Stage being executed.
        stage: LifecycleStage,
        /// Stable hook name.
        hook: &'static str,
        /// Hook error.
        #[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())
        }
    }
}