1use 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#[derive(Debug, Clone, Copy)]
21pub struct Pace {
22 pub status: Duration,
24 pub everything: Duration,
26 pub seen: Duration,
29 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#[derive(Debug, Clone, Default)]
46pub struct RuntimeState {
47 pub answer: Option<Arc<Answer>>,
49 pub checked: Option<Instant>,
51 pub asking: bool,
53}
54
55struct Shared {
56 state: RuntimeState,
57 refresh: bool,
59 seen: Instant,
61 metrics_seen: Option<Instant>,
63 stop: bool,
64}
65
66pub struct LiveRuntime {
68 shared: Arc<(Mutex<Shared>, Condvar)>,
69}
70
71impl LiveRuntime {
72 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 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 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 pub fn state(&self) -> RuntimeState {
133 self.lock().state.clone()
134 }
135
136 pub fn refresh(&self) {
138 self.lock().refresh = true;
139 self.shared.1.notify_all();
140 }
141
142 pub fn seen(&self) {
145 self.lock().seen = Instant::now();
146 self.shared.1.notify_all();
147 }
148
149 pub fn metrics_seen(&self) {
152 self.lock().metrics_seen = Some(Instant::now());
153 self.shared.1.notify_all();
154 }
155
156 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 let mut last_metrics: Option<Instant> = None;
193 loop {
194 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 last_metrics = None;
210 break;
211 }
212 if visible && due(last_status, pace.status) {
213 if !answered || due(last_everything, pace.everything) {
215 shared.refresh = true;
216 }
217 break;
218 }
219 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 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 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 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
289pub 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
301pub 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
309pub 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
327pub 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
345pub 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}