use serde_json::{Value, json};
use std::sync::{Arc, Condvar, Mutex, PoisonError};
use std::time::{Duration, Instant};
pub const NOTICE_WAIT: Duration = Duration::from_secs(5);
pub const LOKI_MESSAGE_TYPE: &str = "loki";
#[derive(Default)]
struct State {
known: Option<Option<String>>,
shown: bool,
}
#[derive(Clone)]
pub struct LokiNotice {
state: Arc<(Mutex<State>, Condvar)>,
}
impl Default for LokiNotice {
fn default() -> Self {
LokiNotice::known(None)
}
}
impl LokiNotice {
fn pending() -> LokiNotice {
LokiNotice { state: Arc::default() }
}
pub fn known(text: Option<String>) -> LokiNotice {
let notice = LokiNotice::pending();
notice.settle(text);
notice
}
fn settle(&self, text: Option<String>) {
let (state, changed) = &*self.state;
let mut state = state.lock().unwrap_or_else(PoisonError::into_inner);
state.shown = state.shown || text.is_none();
state.known = Some(text);
changed.notify_all();
}
pub fn start(config: &crate::compose::Config) -> LokiNotice {
if config.loki == host::loki_guard::LokiMode::Off {
return LokiNotice::known(None);
}
let settings = config::settings::SettingsManager::for_worker(&config.cwd, &config.agent_dir, &config.home);
let settings = Value::Object(loki::settings::saved(settings.global_settings()));
let (cwd, home, var) = (config.cwd.clone(), config.home.clone(), config.var.clone());
let lookup = move |key: &str| var(key);
let context = loki::auto_setup::SetupContext {
cwd: &cwd,
home: &home,
var: &lookup,
settings: &settings,
};
match loki::auto_setup::setup(&context) {
loki::auto_setup::Setup::Quiet => LokiNotice::known(None),
loki::auto_setup::Setup::Notice(text) => LokiNotice::known(Some(text)),
loki::auto_setup::Setup::Commit(root) => {
let notice = LokiNotice::pending();
let committing = notice.clone();
let outside = config.outside_changes.begin();
std::thread::spawn(move || {
let context = loki::auto_setup::SetupContext {
cwd: &cwd,
home: &home,
var: &lookup,
settings: &settings,
};
let snapshot = crate::compose::workspace_snapshotter();
let text = outside.record(&root.join(".loki"), &snapshot, || {
loki::auto_setup::commit_notice(&context, &root)
});
committing.settle(Some(text));
});
notice
}
}
}
pub fn take(&self, wait: Duration) -> Option<String> {
let (state, changed) = &*self.state;
let mut state = state.lock().unwrap_or_else(PoisonError::into_inner);
let end = Instant::now() + wait;
while state.known.is_none() && !state.shown {
let left = end.saturating_duration_since(Instant::now());
if left.is_zero() {
return None;
}
state = changed
.wait_timeout(state, left)
.unwrap_or_else(PoisonError::into_inner)
.0;
}
if state.shown {
return None;
}
state.shown = true;
state.known.clone().flatten()
}
}
pub fn notice_message(text: &str, timestamp: u64) -> Value {
json!({
"role": "custom",
"customType": LOKI_MESSAGE_TYPE,
"content": text,
"display": true,
"details": {},
"timestamp": timestamp,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn session_core_loki_notice_waits_briefly_then_opens_a_later_turn_once() {
let notice = LokiNotice::pending();
assert_eq!(notice.take(Duration::ZERO), None);
let committing = notice.clone();
let commit = std::thread::spawn(move || committing.settle(Some("committed".into())));
assert_eq!(notice.take(Duration::from_secs(120)).as_deref(), Some("committed"));
commit.join().unwrap();
assert_eq!(notice.take(Duration::from_secs(120)), None);
let none = LokiNotice::known(None);
assert_eq!(
none.take(Duration::from_secs(24 * 60 * 60)),
None,
"a known absence is not waited for (a wait would hang the test)"
);
assert_eq!(LokiNotice::default().take(Duration::from_secs(120)), None);
}
}