modrun 1.1.0

Modular application composer for Tokio: domain modules, typed wiring, lifecycle
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
//! Public error type for modrun.

use std::any::type_name;
use std::error;
use std::fmt;
use std::io;
use std::result;
use std::time::Duration;

/// Owned user error retained as [`std::error::Error::source`].
pub type BoxError = Box<dyn error::Error + Send + Sync>;

/// Result alias used throughout the crate and by hooks / fallible constructors.
pub type Result<T> = result::Result<T, Error>;

/// Errors produced while wiring, starting, or stopping an application.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// A required group has no members.
    #[error("required group is empty: {type_name}")]
    EmptyGroup {
        /// Group type name shown in diagnostics (`Group<T>`).
        type_name: &'static str,
    },

    /// A group member provider's result type does not match the declared element type.
    #[error("provide_group_dyn type mismatch: expected {expected}, got {actual}")]
    GroupMemberTypeMismatch {
        /// Element type the caller declared.
        expected: &'static str,
        /// Result type reported by the erased provider.
        actual: &'static str,
    },

    /// A public type was registered more than once.
    #[error("type already provided: {0}")]
    AlreadyProvided(&'static str),

    /// A private type was registered more than once in the same module.
    #[error("type already provided privately in module '{module}': {type_name}")]
    AlreadyProvidedPrivate {
        /// Module name shown in diagnostics.
        module: &'static str,
        /// Type name that collided.
        type_name: &'static str,
    },

    /// The dependency graph contains a cycle.
    #[error("dependency cycle detected involving: {0}")]
    Cycle(String),

    /// A value was requested before it had been constructed.
    #[error("dependency not constructed yet: {0}")]
    NotConstructed(&'static str),

    /// No provider exists for a requested type.
    #[error("missing provider for type: {type_name} (from module '{module}')")]
    MissingProvider {
        /// Missing type.
        type_name: &'static str,
        /// Scope that requested it.
        module: &'static str,
    },

    /// A provider depends on something nothing registers.
    #[error(
        "provider for {provider} in module '{module}' needs a dependency nothing provides: {dependency}{}",
        group_registration_hint(.dependency)
    )]
    ProviderMissingDep {
        /// Provider result type.
        provider: &'static str,
        /// Module that owns the provider.
        module: &'static str,
        /// Missing dependency type.
        dependency: &'static str,
    },

    /// An invoker depends on something nothing registers.
    #[error(
        "invoker in module '{module}' needs a dependency nothing provides: {dependency}{}",
        group_registration_hint(.dependency)
    )]
    InvokerMissingDep {
        /// Module that owns the invoker.
        module: &'static str,
        /// Missing dependency type.
        dependency: &'static str,
    },

    /// Internal downcast of a cached value failed.
    #[error("failed to downcast value to {0}")]
    Downcast(&'static str),

    /// A fallible constructor returned an error.
    #[error("constructor for {type_name} failed: {source}")]
    ConstructorFailed {
        /// Type being constructed.
        type_name: &'static str,
        /// The user error from the constructor.
        #[source]
        source: BoxError,
    },

    /// A fallible invoker returned an error.
    #[error("invoker {name} failed: {source}")]
    InvokerFailed {
        /// Rust type name of the invoker function.
        name: &'static str,
        /// The user error from the invoker.
        #[source]
        source: BoxError,
    },

    /// Hook registration after start completed.
    #[error("cannot append lifecycle hook after start has finished")]
    AppendAfterStart,

    /// Hook registration while stopping.
    #[error("cannot append lifecycle hook while stopping")]
    AppendWhileStopping,

    /// Graph construction exceeded its budget.
    #[error("application build timed out after {0:?}")]
    BuildTimeout(Duration),

    /// Start phase exceeded its budget.
    #[error("application start timed out after {0:?}")]
    StartTimeout(Duration),

    /// Stop phase exceeded its budget.
    #[error("application stop timed out after {0:?}")]
    StopTimeout(Duration),

    /// Unwind after a failed/cancelled start exceeded its budget.
    #[error("application stop timed out after {0:?} while unwinding")]
    UnwindTimeout(Duration),

    /// A background [`crate::task`] failed while start was still running, and
    /// unwind did not surface a more specific join error.
    #[error("background task failed during start")]
    TaskFailedDuringStart,

    /// Failed to install a SIGINT listener.
    #[error("failed to listen for SIGINT: {0}")]
    SigintListen(#[source] io::Error),

    /// Failed to install a SIGTERM listener.
    #[error("failed to listen for SIGTERM: {0}")]
    SigtermListen(#[source] io::Error),

    /// Failed to install a process-signal listener (non-Unix platforms).
    #[error("failed to listen for process signal: {0}")]
    SignalListen(#[source] io::Error),

    /// Several OnStop hooks failed; see [`MultipleStopError::errors`].
    #[error(transparent)]
    MultipleStop(MultipleStopError),

    /// Cleanup failed after an earlier phase error; both are retained.
    #[error("cleanup failed after an earlier phase error: {cleanup}; earlier: {earlier}")]
    CleanupAfterFailure {
        /// Error from stop/unwind.
        #[source]
        cleanup: Box<Error>,
        /// Error from the earlier phase.
        earlier: Box<Error>,
    },

    /// An application hook returned this failure.
    ///
    /// Prefer [`Error::hook`] rather than constructing this variant directly.
    /// [`crate::Lifecycle`] overwrites [`Self::Hook::name`] with the registering
    /// hook's [`Hook::name`](crate::Hook::name) when start/stop returns this
    /// variant. [`Error::Io`] and other variants are left unchanged.
    #[error("{}", hook_failed_message(.name, .source))]
    Hook {
        /// [`crate::Hook::name`]; defaults to `"unnamed"` from [`Error::hook`]
        /// until [`crate::Lifecycle`] attaches the registering hook's name.
        name: &'static str,
        /// The user error from the hook.
        #[source]
        source: BoxError,
    },

    /// I/O failure with a short context label (e.g. bind / serve).
    ///
    /// Prefer [`Error::io`] rather than constructing this variant directly.
    #[error("{context}: {source}")]
    Io {
        /// What was being done when I/O failed.
        context: String,
        /// Underlying I/O error.
        #[source]
        source: io::Error,
    },
}

/// Several OnStop hook failures aggregated into one error.
#[derive(Debug)]
#[non_exhaustive]
pub struct MultipleStopError {
    count: usize,
    summary: String,
    errors: Vec<Error>,
}

impl MultipleStopError {
    /// Number of failed hooks.
    #[must_use]
    pub fn count(&self) -> usize {
        self.count
    }

    /// Semicolon-joined displays for easy logging.
    #[must_use]
    pub fn summary(&self) -> &str {
        &self.summary
    }

    /// Individual failures in stop order.
    #[must_use]
    pub fn errors(&self) -> &[Error] {
        &self.errors
    }
}

impl fmt::Display for MultipleStopError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} OnStop hooks failed: {}", self.count, self.summary)
    }
}

impl error::Error for MultipleStopError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        self.errors
            .first()
            .map(|e| e as &(dyn error::Error + 'static))
    }
}

impl Error {
    /// Wrap a hook failure, keeping the original error as [`std::error::Error::source`].
    ///
    /// Accepts anything convertible to [`BoxError`], including `&str`, `String`,
    /// [`std::io::Error`], and types that implement [`std::error::Error`].
    /// [`crate::Lifecycle`] overwrites [`Self::Hook::name`] with the registering
    /// hook's [`Hook::name`](crate::Hook::name) when start/stop returns this variant.
    pub fn hook(err: impl Into<BoxError>) -> Self {
        Self::Hook {
            name: "unnamed",
            source: err.into(),
        }
    }

    /// Attach a hook name when the failure is already [`Error::Hook`].
    /// Other variants (for example [`Error::Io`]) are left unchanged so
    /// callers can still match on them.
    pub(crate) fn with_hook_name(self, hook_name: &'static str) -> Self {
        match self {
            Self::Hook { source, .. } => Self::Hook {
                name: hook_name,
                source,
            },
            other => other,
        }
    }

    /// Wrap an I/O failure with a short context label (e.g. `"bind 127.0.0.1:3000"`).
    ///
    /// There is no `From<std::io::Error>` impl, so `listener.bind().await?` does
    /// not compile in a `modrun::Result` function — map with this helper instead.
    pub fn io(context: impl Into<String>, source: io::Error) -> Self {
        Self::Io {
            context: context.into(),
            source,
        }
    }

    pub(crate) fn constructor_failed<T: ?Sized>(err: impl Into<BoxError>) -> Self {
        Self::ConstructorFailed {
            type_name: type_name::<T>(),
            source: err.into(),
        }
    }

    pub(crate) fn invoker_failed(name: &'static str, err: impl Into<BoxError>) -> Self {
        Self::InvokerFailed {
            name,
            source: err.into(),
        }
    }

    pub(crate) fn multiple_stop(errors: Vec<Error>) -> Self {
        let count = errors.len();
        let summary = errors
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("; ");
        Self::MultipleStop(MultipleStopError {
            count,
            summary,
            errors,
        })
    }
}

/// Wrap a user-facing fallible value with constructor/invoker context.
pub(crate) fn user_ctor_err<T: ?Sized>(err: impl Into<BoxError>) -> Error {
    Error::constructor_failed::<T>(err)
}

pub(crate) fn user_invoke_err(name: &'static str, err: impl Into<BoxError>) -> Error {
    Error::invoker_failed(name, err)
}

fn hook_failed_message(name: &'static str, source: &BoxError) -> String {
    format!("hook '{name}' failed: {source}")
}

fn group_registration_hint(dependency: &str) -> &'static str {
    if dependency.contains("Group<") {
        "; register the group with init_group, provide_group, or require_group"
    } else {
        ""
    }
}

/// Aggregate multiple hook failures into a single error.
pub(crate) fn aggregate_errors(errors: Vec<Error>) -> Result<()> {
    match errors.len() {
        0 => Ok(()),
        1 => Err(errors.into_iter().next().expect("len checked")),
        _ => Err(Error::multiple_stop(errors)),
    }
}

/// Prefer a cleanup failure as the primary error, while retaining the earlier
/// phase error when both fail.
pub(crate) fn combine_results(earlier: Result<()>, later: Result<()>) -> Result<()> {
    match earlier {
        Ok(()) => later,
        Err(e) => Err(with_cleanup(e, later)),
    }
}

/// Keep a phase error; if cleanup also failed, wrap both.
pub(crate) fn with_cleanup(earlier: Error, cleanup: Result<()>) -> Error {
    match cleanup {
        Ok(()) => earlier,
        Err(cleanup) => Error::CleanupAfterFailure {
            cleanup: Box::new(cleanup),
            earlier: Box::new(earlier),
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::error::Error as StdError;
    use std::io;

    #[test]
    fn hook_preserves_io_source() {
        let err = Error::hook(io::Error::other("disk full"));
        let src = StdError::source(&err).expect("source");
        assert!(src.to_string().contains("disk full"), "source was {src}");
    }

    #[test]
    fn constructor_failed_preserves_source() {
        let err = Error::constructor_failed::<u32>("nope");
        let src = StdError::source(&err).expect("source");
        assert!(src.to_string().contains("nope"), "source was {src}");
        assert!(
            err.to_string().contains("constructor for"),
            "display was {err}"
        );
    }

    #[test]
    fn io_helper_sets_context_and_source() {
        let err = Error::io("bind", io::Error::other("addr in use"));
        match &err {
            Error::Io { context, source } => {
                assert_eq!(context, "bind");
                assert!(source.to_string().contains("addr in use"));
            }
            other => panic!("expected Io, got {other}"),
        }
        assert!(StdError::source(&err).is_some());
    }

    #[test]
    fn cleanup_after_failure_source_is_cleanup() {
        let err = Error::CleanupAfterFailure {
            cleanup: Box::new(Error::hook("cleanup")),
            earlier: Box::new(Error::hook("earlier")),
        };
        let src = StdError::source(&err).expect("source");
        assert!(src.to_string().contains("cleanup"), "source was {src}");
    }

    #[test]
    fn with_cleanup_ok_is_the_phase_error() {
        let err = with_cleanup(Error::hook("earlier"), Ok(()));
        assert!(err.to_string().contains("earlier"), "display was {err}");
        assert!(!err.to_string().contains("cleanup failed"));
    }

    #[test]
    fn with_cleanup_err_wraps_both() {
        let err = with_cleanup(Error::hook("earlier"), Err(Error::hook("cleanup")));
        match err {
            Error::CleanupAfterFailure { cleanup, earlier } => {
                assert!(cleanup.to_string().contains("cleanup"));
                assert!(earlier.to_string().contains("earlier"));
            }
            other => panic!("expected CleanupAfterFailure, got {other}"),
        }
    }

    #[test]
    fn multiple_stop_source_is_first_error() {
        let err = Error::multiple_stop(vec![Error::hook("stop-a"), Error::hook("stop-b")]);
        let src = StdError::source(&err).expect("source");
        assert!(src.to_string().contains("stop-a"), "source was {src}");
        match &err {
            Error::MultipleStop(inner) => {
                assert_eq!(inner.count(), 2);
                assert!(inner.summary().contains("stop-a"));
                assert!(inner.errors()[1].to_string().contains("stop-b"));
            }
            other => panic!("expected MultipleStop, got {other}"),
        }
    }

    #[test]
    fn hook_display_includes_context() {
        let err = Error::hook("boom");
        let msg = err.to_string();
        assert!(msg.contains("boom"), "unexpected: {msg}");
        assert!(msg.contains("hook 'unnamed' failed"), "unexpected: {msg}");
    }

    #[test]
    fn with_hook_name_labels_unnamed_hook() {
        let err = Error::hook("boom").with_hook_name("http");
        match &err {
            Error::Hook { name, .. } => assert_eq!(*name, "http"),
            other => panic!("expected Hook, got {other}"),
        }
        let msg = err.to_string();
        assert!(msg.contains("http"), "unexpected: {msg}");
        assert!(msg.contains("boom"), "unexpected: {msg}");
    }

    #[test]
    fn with_hook_name_leaves_io_unchanged() {
        let err = Error::io("bind", io::Error::other("addr in use")).with_hook_name("http.serve");
        match err {
            Error::Io { context, .. } => assert_eq!(context, "bind"),
            other => panic!("expected Io, got {other}"),
        }
    }

    #[test]
    fn invoker_failed_includes_function_name() {
        let err = Error::invoker_failed("boot", "nope");
        let msg = err.to_string();
        assert!(msg.contains("boot"), "unexpected: {msg}");
        assert!(msg.contains("nope"), "unexpected: {msg}");
        let src = StdError::source(&err).expect("source");
        assert!(src.to_string().contains("nope"), "source was {src}");
    }
}