Skip to main content

mortise_core/runtime/
modules.rs

1//! The runtime status of each module, from the health components of an environment.
2//!
3//! `nwidart/laravel-modules` 13.4 names the indicators of a module
4//! `module:{lower case module name}:{key}`, and adds a component `modules` that lists each
5//! module and gives an `error` for one that is enabled but missing on disk. Whether an
6//! environment has them is read from what it answers, not from `composer.lock`.
7
8use serde_json::Value;
9
10use crate::app::AppSnapshot;
11use crate::runtime::actuator::{Component, Status};
12
13/// The name of the component that lists the modules.
14const MODULES: &str = "modules";
15
16/// What the running app reports about one module.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct ModuleRuntime {
19    /// The name of the module, as the app's files give it.
20    pub module: String,
21    /// The worst status of its indicators. Down when `error` is there.
22    pub status: Status,
23    /// What the `modules` component says is wrong with the module, as the app wrote it.
24    pub error: Option<String>,
25    /// The module's own indicators, each named by its key: `storage` for
26    /// `module:blog:storage`. In the app's order.
27    pub indicators: Vec<Component>,
28}
29
30/// The components of an answer, split between the app and its modules.
31#[derive(Debug, Clone, Default, PartialEq, Eq)]
32pub struct RuntimeByModule {
33    /// The components of the app itself, in the app's order.
34    pub app: Vec<Component>,
35    /// The modules that have a status, in the order of the app's modules.
36    pub modules: Vec<ModuleRuntime>,
37    /// The errors the `modules` component gives for names that are no module of the
38    /// app: each name, in the app's case, with its sentence.
39    pub elsewhere: Vec<(String, String)>,
40}
41
42impl RuntimeByModule {
43    /// The runtime of a module, by its name. `None` when it has no status.
44    pub fn of(&self, module: &str) -> Option<&ModuleRuntime> {
45        self.modules.iter().find(|runtime| runtime.module == module)
46    }
47}
48
49/// How bad a status is: Down, Out of service, Up, Unknown, as Spring orders them.
50fn rank(status: Status) -> u8 {
51    match status {
52        Status::Down => 0,
53        Status::OutOfService => 1,
54        Status::Up => 2,
55        Status::Unknown => 3,
56    }
57}
58
59/// The module and the key of a module indicator: `("blog", "storage")` for
60/// `module:blog:storage`.
61fn indicator_name(name: &str) -> Option<(&str, &str)> {
62    let (module, key) = name.strip_prefix("module:")?.split_once(':')?;
63    // The package does not refuse an empty key: `module:billing:` is Billing's.
64    (!module.is_empty()).then_some((module, key))
65}
66
67/// The errors of the `modules` component: the name of each module it reports, in its
68/// own case, with the sentence. The detail is the JSON text of an object, or `[]` when
69/// the app has no module: PHP writes an empty array so.
70///
71/// `None` when the component is not the list of laravel-modules: its one detail is
72/// not `modules`, or an entry is not `{"enabled": bool}` with an optional `"error"`
73/// sentence. That is a check that failed, with the exception as its `error`, or a
74/// component of the app's own under that name.
75fn errors(component: &Component) -> Option<Vec<(String, String)>> {
76    let [(key, text)] = component.details.as_slice() else {
77        return None;
78    };
79    if key != MODULES {
80        return None;
81    }
82    let modules = match serde_json::from_str(text).ok()? {
83        Value::Object(modules) => modules,
84        Value::Array(empty) if empty.is_empty() => return Some(Vec::new()),
85        _ => return None,
86    };
87    let mut errors = Vec::new();
88    for (name, module) in modules {
89        let Value::Object(fields) = module else {
90            return None;
91        };
92        let shape = fields.iter().all(|(field, value)| match field.as_str() {
93            "enabled" => value.is_boolean(),
94            "error" => value.is_string(),
95            _ => false,
96        });
97        if !shape || !fields.contains_key("enabled") {
98            return None;
99        }
100        if let Some(Value::String(error)) = fields.get("error") {
101            errors.push((name, error.clone()));
102        }
103    }
104    Some(errors)
105}
106
107/// Splits the components of an answer between the app and its modules.
108///
109/// An indicator `module:{name}:{key}` belongs to the module whose name, in ASCII lower
110/// case, is `{name}`: PHP's `strtolower` changes ASCII only. The `modules` component
111/// of laravel-modules leaves the app's list; an error it gives for a name that is no
112/// module of the app goes to `elsewhere`. A component named `modules` of another shape
113/// stays the app's.
114pub fn by_module(app: &AppSnapshot, components: &[Component]) -> RuntimeByModule {
115    let lower: Vec<String> = app
116        .modules
117        .iter()
118        .map(|module| module.name.to_ascii_lowercase())
119        .collect();
120    let position = |name: &str| lower.iter().position(|lower| *lower == name);
121
122    let mut indicators: Vec<Vec<Component>> = vec![Vec::new(); app.modules.len()];
123    let mut errors_of: Vec<Option<String>> = vec![None; app.modules.len()];
124    let mut own = Vec::new();
125    let mut elsewhere = Vec::new();
126    for component in components {
127        if let Some(errors) = (component.name == MODULES)
128            .then(|| errors(component))
129            .flatten()
130        {
131            for (name, error) in errors {
132                match position(&name.to_ascii_lowercase()) {
133                    Some(at) => errors_of[at] = Some(error),
134                    None => elsewhere.push((name, error)),
135                }
136            }
137            continue;
138        }
139        match indicator_name(&component.name)
140            .and_then(|(module, key)| Some((position(module)?, key)))
141        {
142            Some((at, key)) => indicators[at].push(Component {
143                name: key.to_owned(),
144                ..component.clone()
145            }),
146            None => own.push(component.clone()),
147        }
148    }
149
150    let modules = app
151        .modules
152        .iter()
153        .zip(indicators)
154        .zip(errors_of)
155        .filter_map(|((module, indicators), error)| {
156            let worst = indicators
157                .iter()
158                .map(|indicator| indicator.status)
159                .min_by_key(|status| rank(*status));
160            let status = if error.is_some() {
161                Status::Down
162            } else {
163                worst?
164            };
165            Some(ModuleRuntime {
166                module: module.name.clone(),
167                status,
168                error,
169                indicators,
170            })
171        })
172        .collect();
173    RuntimeByModule {
174        app: own,
175        modules,
176        elsewhere,
177    }
178}