use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};
use crate::app::AppSnapshot;
use crate::modules::module::{Module, artisan_command};
use crate::runtime::actuator::{
Answer, NoMetrics, Route, Secret, Task, ask, ask_metrics, ask_status,
};
use crate::runtime::environment::Environment;
#[derive(Debug, Clone, Copy)]
pub struct Pace {
pub status: Duration,
pub everything: Duration,
pub seen: Duration,
pub metrics: Duration,
}
impl Default for Pace {
fn default() -> Self {
Self {
status: Duration::from_secs(15),
everything: Duration::from_secs(5 * 60),
seen: Duration::from_secs(3),
metrics: Duration::from_secs(15),
}
}
}
#[derive(Debug, Clone, Default)]
pub struct RuntimeState {
pub answer: Option<Arc<Answer>>,
pub checked: Option<Instant>,
pub asking: bool,
}
struct Shared {
state: RuntimeState,
refresh: bool,
seen: Instant,
metrics_seen: Option<Instant>,
stop: bool,
}
pub struct LiveRuntime {
shared: Arc<(Mutex<Shared>, Condvar)>,
}
impl LiveRuntime {
pub fn open(
environment: Environment,
secret: Secret,
on_change: impl Fn() + Send + 'static,
) -> Self {
Self::open_with(environment, secret, Pace::default(), on_change)
}
pub fn open_with(
environment: Environment,
secret: Secret,
pace: Pace,
on_change: impl Fn() + Send + 'static,
) -> Self {
Self::open_with_metrics(environment, secret, pace, on_change, |_| {})
}
pub fn open_with_metrics(
environment: Environment,
secret: Secret,
pace: Pace,
on_change: impl Fn() + Send + 'static,
mut on_metrics: impl FnMut(Result<String, NoMetrics>) + Send + 'static,
) -> Self {
let shared = Arc::new((
Mutex::new(Shared {
state: RuntimeState {
asking: true,
..RuntimeState::default()
},
refresh: true,
seen: Instant::now(),
metrics_seen: None,
stop: false,
}),
Condvar::new(),
));
let worker = Arc::clone(&shared);
std::thread::Builder::new()
.name("mortise-runtime".to_owned())
.spawn(move || {
run(
&worker,
&environment,
&secret,
pace,
&on_change,
&mut on_metrics,
);
})
.expect("a thread can be started");
Self { shared }
}
pub fn state(&self) -> RuntimeState {
self.lock().state.clone()
}
pub fn refresh(&self) {
self.lock().refresh = true;
self.shared.1.notify_all();
}
pub fn seen(&self) {
self.lock().seen = Instant::now();
self.shared.1.notify_all();
}
pub fn metrics_seen(&self) {
self.lock().metrics_seen = Some(Instant::now());
self.shared.1.notify_all();
}
pub fn metrics_closed(&self) {
let open = self.lock().metrics_seen.take().is_some();
if open {
self.shared.1.notify_all();
}
}
fn lock(&self) -> std::sync::MutexGuard<'_, Shared> {
self.shared
.0
.lock()
.expect("the runtime state is never poisoned")
}
}
impl Drop for LiveRuntime {
fn drop(&mut self) {
self.lock().stop = true;
self.shared.1.notify_all();
}
}
fn run(
shared: &(Mutex<Shared>, Condvar),
environment: &Environment,
secret: &Secret,
pace: Pace,
on_change: &dyn Fn(),
on_metrics: &mut dyn FnMut(Result<String, NoMetrics>),
) {
let (lock, wake) = shared;
let mut last_status: Option<Instant> = None;
let mut last_everything: Option<Instant> = None;
let mut last_metrics: Option<Instant> = None;
loop {
let mut metrics = false;
let (everything, earlier) = {
let mut shared = lock.lock().expect("the runtime state is never poisoned");
loop {
if shared.stop {
return;
}
let visible = shared.seen.elapsed() < pace.seen;
let answered = matches!(shared.state.answer.as_deref(), Some(Answer::Answered(_)));
let due = |last: Option<Instant>, every: Duration| {
last.is_none_or(|last| last.elapsed() >= every)
};
if shared.refresh {
last_metrics = None;
break;
}
if visible && due(last_status, pace.status) {
if !answered || due(last_everything, pace.everything) {
shared.refresh = true;
}
break;
}
let tab = visible
&& shared
.metrics_seen
.is_some_and(|seen| seen.elapsed() < pace.seen)
&& matches!(shared.state.answer.as_deref(),
Some(Answer::Answered(runtime)) if runtime.exposes("prometheus"));
if tab && due(last_metrics, pace.metrics) {
metrics = true;
break;
}
let nap = if visible {
last_status.map_or(Duration::ZERO, |last| {
pace.status.saturating_sub(last.elapsed())
})
} else {
Duration::from_secs(3600)
};
let nap = match last_metrics {
Some(last) if tab => nap.min(pace.metrics.saturating_sub(last.elapsed())),
_ => nap,
};
shared = wake
.wait_timeout(shared, nap.max(Duration::from_millis(5)))
.expect("the runtime state is never poisoned")
.0;
}
if metrics {
(false, None)
} else {
let everything = std::mem::take(&mut shared.refresh);
shared.state.asking = true;
(everything, shared.state.answer.clone())
}
};
if metrics {
on_metrics(ask_metrics(environment, secret));
last_metrics = Some(Instant::now());
on_change();
continue;
}
on_change();
let answer = match earlier.as_deref() {
Some(Answer::Answered(earlier)) if !everything => {
ask_status(environment, secret, earlier)
}
_ => ask(environment, secret),
};
let now = Instant::now();
last_status = Some(now);
if everything {
last_everything = Some(now);
}
{
let mut shared = lock.lock().expect("the runtime state is never poisoned");
shared.state = RuntimeState {
answer: Some(Arc::new(answer)),
checked: Some(now),
asking: false,
};
}
on_change();
}
}
pub fn module_of<'a>(app: &'a AppSnapshot, class: &str) -> Option<&'a Module> {
let class = class.trim_start_matches('\\');
app.modules.iter().find(|module| {
let namespace = module.namespace.trim_matches('\\');
!namespace.is_empty()
&& class
.strip_prefix(namespace)
.is_some_and(|rest| rest.starts_with('\\'))
})
}
pub fn routes_of<'a>(app: &AppSnapshot, module: &str, routes: &'a [Route]) -> Vec<&'a Route> {
routes
.iter()
.filter(|route| module_of(app, &route.action).is_some_and(|found| found.name == module))
.collect()
}
pub fn routes_by_module(app: &AppSnapshot, routes: &[Route]) -> (Vec<(String, usize)>, usize) {
let mut counts: Vec<(String, usize)> = Vec::new();
let mut outside = 0;
for route in routes {
match module_of(app, &route.action) {
Some(module) => match counts.iter_mut().find(|(name, _)| *name == module.name) {
Some((_, count)) => *count += 1,
None => counts.push((module.name.clone(), 1)),
},
None => outside += 1,
}
}
counts.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
(counts, outside)
}
pub fn module_of_task<'a>(app: &'a AppSnapshot, task: &Task) -> Option<&'a Module> {
module_of(app, &task.target).or_else(|| {
let name = artisan_command(&task.target)?;
app.modules
.iter()
.find(|module| module.commands.iter().any(|command| command == name))
})
}
pub fn tasks_of<'a>(app: &AppSnapshot, module: &str, tasks: &'a [Task]) -> Vec<&'a Task> {
tasks
.iter()
.filter(|task| module_of_task(app, task).is_some_and(|found| found.name == module))
.collect()
}