Skip to main content

mortise_core/runtime/
live.rs

1//! An environment that is kept fresh: asked on a worker thread, again and again.
2//!
3//! `health` is asked every 15 s while the window is visible. Everything else is asked
4//! when the environment is opened, every 5 minutes, and when the user reads the app again.
5//! `prometheus` is asked every 15 s only while the Metrics tab is open and the window is visible,
6//! after `health` when both are due. None leaves after the tab closes. One request is on its way at
7//! a time.
8
9use std::sync::{Arc, Condvar, Mutex};
10use std::time::{Duration, Instant};
11
12use crate::app::AppSnapshot;
13use crate::modules::module::{Module, artisan_command};
14use crate::runtime::actuator::{
15    Answer, NoMetrics, Route, Secret, Task, ask, ask_metrics, ask_status,
16};
17use crate::runtime::environment::Environment;
18
19/// How often things are asked.
20#[derive(Debug, Clone, Copy)]
21pub struct Pace {
22    /// Between two requests for `health`.
23    pub status: Duration,
24    /// Between two requests for everything.
25    pub everything: Duration,
26    /// The window counts as visible this long after the interface last drew itself.
27    /// The Metrics tab counts as open as long after it last drew itself.
28    pub seen: Duration,
29    /// Between two requests for `prometheus`.
30    pub metrics: Duration,
31}
32
33impl Default for Pace {
34    fn default() -> Self {
35        Self {
36            status: Duration::from_secs(15),
37            everything: Duration::from_secs(5 * 60),
38            seen: Duration::from_secs(3),
39            metrics: Duration::from_secs(15),
40        }
41    }
42}
43
44/// What a [`LiveRuntime`] holds at this moment.
45#[derive(Debug, Clone, Default)]
46pub struct RuntimeState {
47    /// The last answer. `None` until the first one is there.
48    pub answer: Option<Arc<Answer>>,
49    /// When the last answer came.
50    pub checked: Option<Instant>,
51    /// True while a request is on its way.
52    pub asking: bool,
53}
54
55struct Shared {
56    state: RuntimeState,
57    /// Everything is asked for at the next turn.
58    refresh: bool,
59    /// When the interface last drew itself.
60    seen: Instant,
61    /// When the Metrics tab last drew itself. `None` until it does.
62    metrics_seen: Option<Instant>,
63    stop: bool,
64}
65
66/// An environment with a worker thread that asks it.
67pub struct LiveRuntime {
68    shared: Arc<(Mutex<Shared>, Condvar)>,
69}
70
71impl LiveRuntime {
72    /// Starts asking the environment. `on_change` is called from the worker thread
73    /// after every answer.
74    pub fn open(
75        environment: Environment,
76        secret: Secret,
77        on_change: impl Fn() + Send + 'static,
78    ) -> Self {
79        Self::open_with(environment, secret, Pace::default(), on_change)
80    }
81
82    /// As [`LiveRuntime::open`], at another pace. Tests use it.
83    pub fn open_with(
84        environment: Environment,
85        secret: Secret,
86        pace: Pace,
87        on_change: impl Fn() + Send + 'static,
88    ) -> Self {
89        Self::open_with_metrics(environment, secret, pace, on_change, |_| {})
90    }
91
92    /// As [`LiveRuntime::open_with`], and hands every answer of `prometheus` to `on_metrics`,
93    /// on the worker thread, before `on_change` is called.
94    pub fn open_with_metrics(
95        environment: Environment,
96        secret: Secret,
97        pace: Pace,
98        on_change: impl Fn() + Send + 'static,
99        mut on_metrics: impl FnMut(Result<String, NoMetrics>) + Send + 'static,
100    ) -> Self {
101        let shared = Arc::new((
102            Mutex::new(Shared {
103                state: RuntimeState {
104                    asking: true,
105                    ..RuntimeState::default()
106                },
107                refresh: true,
108                seen: Instant::now(),
109                metrics_seen: None,
110                stop: false,
111            }),
112            Condvar::new(),
113        ));
114        let worker = Arc::clone(&shared);
115        std::thread::Builder::new()
116            .name("mortise-runtime".to_owned())
117            .spawn(move || {
118                run(
119                    &worker,
120                    &environment,
121                    &secret,
122                    pace,
123                    &on_change,
124                    &mut on_metrics,
125                );
126            })
127            .expect("a thread can be started");
128        Self { shared }
129    }
130
131    /// The current state. Cheap: an answer is shared, not copied.
132    pub fn state(&self) -> RuntimeState {
133        self.lock().state.clone()
134    }
135
136    /// Asks for everything again, now.
137    pub fn refresh(&self) {
138        self.lock().refresh = true;
139        self.shared.1.notify_all();
140    }
141
142    /// Tells the worker that the interface drew itself: the window is visible.
143    /// Without this the worker stops asking.
144    pub fn seen(&self) {
145        self.lock().seen = Instant::now();
146        self.shared.1.notify_all();
147    }
148
149    /// Tells the worker that the Metrics tab drew itself. Without this it does not ask for
150    /// `prometheus`.
151    pub fn metrics_seen(&self) {
152        self.lock().metrics_seen = Some(Instant::now());
153        self.shared.1.notify_all();
154    }
155
156    /// Tells the worker that the Metrics tab is not drawn: no read of `prometheus` starts after
157    /// this, until `metrics_seen()` is called again. A read on its way ends.
158    pub fn metrics_closed(&self) {
159        let open = self.lock().metrics_seen.take().is_some();
160        if open {
161            self.shared.1.notify_all();
162        }
163    }
164
165    fn lock(&self) -> std::sync::MutexGuard<'_, Shared> {
166        self.shared
167            .0
168            .lock()
169            .expect("the runtime state is never poisoned")
170    }
171}
172
173impl Drop for LiveRuntime {
174    fn drop(&mut self) {
175        self.lock().stop = true;
176        self.shared.1.notify_all();
177    }
178}
179
180fn run(
181    shared: &(Mutex<Shared>, Condvar),
182    environment: &Environment,
183    secret: &Secret,
184    pace: Pace,
185    on_change: &dyn Fn(),
186    on_metrics: &mut dyn FnMut(Result<String, NoMetrics>),
187) {
188    let (lock, wake) = shared;
189    let mut last_status: Option<Instant> = None;
190    let mut last_everything: Option<Instant> = None;
191    // When the last read of `prometheus` ended.
192    let mut last_metrics: Option<Instant> = None;
193    loop {
194        // Wait until something is due.
195        let mut metrics = false;
196        let (everything, earlier) = {
197            let mut shared = lock.lock().expect("the runtime state is never poisoned");
198            loop {
199                if shared.stop {
200                    return;
201                }
202                let visible = shared.seen.elapsed() < pace.seen;
203                let answered = matches!(shared.state.answer.as_deref(), Some(Answer::Answered(_)));
204                let due = |last: Option<Instant>, every: Duration| {
205                    last.is_none_or(|last| last.elapsed() >= every)
206                };
207                if shared.refresh {
208                    // Metrics are read again too, right after.
209                    last_metrics = None;
210                    break;
211                }
212                if visible && due(last_status, pace.status) {
213                    // Without an answer to add the status to, everything is asked for.
214                    if !answered || due(last_everything, pace.everything) {
215                        shared.refresh = true;
216                    }
217                    break;
218                }
219                // `prometheus` comes after `health`, while the Metrics tab is open and the
220                // last answer lists it.
221                let tab = visible
222                    && shared
223                        .metrics_seen
224                        .is_some_and(|seen| seen.elapsed() < pace.seen)
225                    && matches!(shared.state.answer.as_deref(),
226                        Some(Answer::Answered(runtime)) if runtime.exposes("prometheus"));
227                if tab && due(last_metrics, pace.metrics) {
228                    metrics = true;
229                    break;
230                }
231                // Sleep until the next request is due, or until the window is seen again.
232                let nap = if visible {
233                    last_status.map_or(Duration::ZERO, |last| {
234                        pace.status.saturating_sub(last.elapsed())
235                    })
236                } else {
237                    Duration::from_secs(3600)
238                };
239                // Or until metrics are due.
240                let nap = match last_metrics {
241                    Some(last) if tab => nap.min(pace.metrics.saturating_sub(last.elapsed())),
242                    _ => nap,
243                };
244                shared = wake
245                    .wait_timeout(shared, nap.max(Duration::from_millis(5)))
246                    .expect("the runtime state is never poisoned")
247                    .0;
248            }
249            if metrics {
250                (false, None)
251            } else {
252                let everything = std::mem::take(&mut shared.refresh);
253                shared.state.asking = true;
254                (everything, shared.state.answer.clone())
255            }
256        };
257        if metrics {
258            // A read of metrics leaves the state of the runtime as it is.
259            on_metrics(ask_metrics(environment, secret));
260            last_metrics = Some(Instant::now());
261            on_change();
262            continue;
263        }
264        on_change();
265
266        let answer = match earlier.as_deref() {
267            Some(Answer::Answered(earlier)) if !everything => {
268                ask_status(environment, secret, earlier)
269            }
270            _ => ask(environment, secret),
271        };
272        let now = Instant::now();
273        last_status = Some(now);
274        if everything {
275            last_everything = Some(now);
276        }
277        {
278            let mut shared = lock.lock().expect("the runtime state is never poisoned");
279            shared.state = RuntimeState {
280                answer: Some(Arc::new(answer)),
281                checked: Some(now),
282                asking: false,
283            };
284        }
285        on_change();
286    }
287}
288
289/// The module a class belongs to: the one whose namespace the class name starts with.
290pub fn module_of<'a>(app: &'a AppSnapshot, class: &str) -> Option<&'a Module> {
291    let class = class.trim_start_matches('\\');
292    app.modules.iter().find(|module| {
293        let namespace = module.namespace.trim_matches('\\');
294        !namespace.is_empty()
295            && class
296                .strip_prefix(namespace)
297                .is_some_and(|rest| rest.starts_with('\\'))
298    })
299}
300
301/// The routes of one module: those whose action is a class of the module.
302pub fn routes_of<'a>(app: &AppSnapshot, module: &str, routes: &'a [Route]) -> Vec<&'a Route> {
303    routes
304        .iter()
305        .filter(|route| module_of(app, &route.action).is_some_and(|found| found.name == module))
306        .collect()
307}
308
309/// How many routes each module has, most first, and how many are in no module:
310/// closures and the routes of other packages.
311pub fn routes_by_module(app: &AppSnapshot, routes: &[Route]) -> (Vec<(String, usize)>, usize) {
312    let mut counts: Vec<(String, usize)> = Vec::new();
313    let mut outside = 0;
314    for route in routes {
315        match module_of(app, &route.action) {
316            Some(module) => match counts.iter_mut().find(|(name, _)| *name == module.name) {
317                Some((_, count)) => *count += 1,
318                None => counts.push((module.name.clone(), 1)),
319            },
320            None => outside += 1,
321        }
322    }
323    counts.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
324    (counts, outside)
325}
326
327/// The module a scheduled task belongs to. The module its `module` tag names wins, compared
328/// without case. Without the tag, or when the tag names no module of the app, it is the module
329/// of its class, or the module that declares the command of `php artisan <name>`. Then a task
330/// with a description, a closure or a shell command belongs to none.
331pub fn module_of_task<'a>(app: &'a AppSnapshot, task: &Task) -> Option<&'a Module> {
332    let tagged = task.module.as_deref().and_then(|name| {
333        app.modules
334            .iter()
335            .find(|module| module.name.eq_ignore_ascii_case(name))
336    });
337    tagged.or_else(|| module_of(app, &task.target)).or_else(|| {
338        let name = artisan_command(&task.target)?;
339        app.modules
340            .iter()
341            .find(|module| module.commands.iter().any(|command| command == name))
342    })
343}
344
345/// The scheduled tasks of one module.
346pub fn tasks_of<'a>(app: &AppSnapshot, module: &str, tasks: &'a [Task]) -> Vec<&'a Task> {
347    tasks
348        .iter()
349        .filter(|task| module_of_task(app, task).is_some_and(|found| found.name == module))
350        .collect()
351}