mod config;
mod detach;
mod flush;
mod send;
mod sign;
mod state;
use std::fs::{File, TryLockError};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
use anyhow::{Context as _, Result};
pub use config::{Config, Sink, load_pinned};
pub use flush::{DELIVERY_HOST, SinkRun};
pub use send::{Ready, Sent};
pub use state::State;
use crate::home::{self, Home};
use crate::time;
const LOCK_FILE: &str = "run.lock";
const HOLD_FILE: &str = "hold";
const REFUSED_HOLD_MS: i64 = 5 * 60 * 1000;
const MIN_SPACING: Duration = Duration::from_secs(1);
const ERROR_HOLD_FIRST: Duration = Duration::from_mins(1);
const ERROR_HOLD_MAX: Duration = Duration::from_mins(15);
pub const BACKGROUND_BUDGET: Duration = Duration::from_secs(120);
const KEPT_ENV: &[&str] = &[
"HOME",
"USERPROFILE",
"SystemRoot",
"DBUS_SESSION_BUS_ADDRESS",
"XDG_RUNTIME_DIR",
];
pub fn kick_located() {
if let Ok(home) = Home::locate() {
kick(&home);
}
}
pub fn kick(home: &Home) {
if !home.delivery_config_path().is_file() {
return;
}
let dir = home.delivery_dir();
let changed = [home.delivery_config_path(), home.lock_path()];
if held(&dir, &changed, time::now_ms()) || running(&dir) {
return;
}
let Ok(exe) = std::env::current_exe() else {
return;
};
let mut command = Command::new(exe);
command
.args(["audit", "deliver", "flush", "--background"])
.env_clear()
.env(home::ENV, home.root());
for name in KEPT_ENV {
if let Some(value) = std::env::var_os(name) {
command.env(name, value);
}
}
detach::detach(&mut command);
let _ = command.spawn();
}
fn held(dir: &Path, changed: &[PathBuf], now_ms: i64) -> bool {
let hold = dir.join(HOLD_FILE);
let modified = |path: &Path| std::fs::metadata(path).and_then(|m| m.modified()).ok();
let Some(hold_at) = modified(&hold) else {
return false;
};
if changed
.iter()
.any(|path| modified(path).is_none_or(|at| at > hold_at))
{
return false;
}
read_hold(dir).is_some_and(|(until, _)| now_ms < until)
}
fn running(dir: &Path) -> bool {
match File::open(dir.join(LOCK_FILE)) {
Ok(file) => matches!(file.try_lock(), Err(TryLockError::WouldBlock)),
Err(_) => false,
}
}
pub fn run(home: &Home, forced: bool, budget: Duration) -> Result<Option<Vec<SinkRun>>> {
let dir = home.delivery_dir();
let (config, lock) = match load_pinned(home) {
Ok(Some(loaded)) => loaded,
Ok(None) => return Ok(Some(Vec::new())),
Err(error) => {
let until = time::now_ms().saturating_add(REFUSED_HOLD_MS);
let _ = home::write_private(&dir.join(HOLD_FILE), until.to_string().as_bytes());
return Err(error);
}
};
let ran = runs(home, &config, lock.pinned_at_ms, forced, budget);
held_after(&dir, ran, time::now_ms())
}
fn held_after<T>(dir: &Path, ran: Result<T>, now_ms: i64) -> Result<T> {
if ran.is_err() {
let _ = error_hold(dir, now_ms);
}
ran
}
fn runs(
home: &Home,
config: &Config,
accepted_ms: i64,
forced: bool,
budget: Duration,
) -> Result<Option<Vec<SinkRun>>> {
let dir = home.delivery_dir();
home::create_private_dir(&dir)?;
let started = std::time::Instant::now();
let mut all: Option<Vec<SinkRun>> = None;
loop {
let file = home::private_lock_options()
.open(dir.join(LOCK_FILE))
.with_context(|| format!("opening {}", dir.join(LOCK_FILE).display()))?;
match file.try_lock() {
Ok(()) => {}
Err(TryLockError::WouldBlock) => return Ok(all),
Err(TryLockError::Error(e)) => return Err(e).context("locking the delivery run"),
}
let left = budget.saturating_sub(started.elapsed());
let runs = flush::run(home, config, accepted_ms, forced, left)?;
write_hold(home, config, &dir, time::now_ms())?;
drop(file);
let behind = behind(home, config)?;
all.get_or_insert_with(Vec::new).extend(runs);
if !behind || started.elapsed() >= budget {
return Ok(all);
}
}
}
fn behind(home: &Home, config: &Config) -> Result<bool> {
let head = home.open_audit()?.latest_id()?.map_or(0, |id| id.0);
let now = time::now_ms();
for sink in &config.sinks {
let state = State::load(&State::path(home, &sink.id))?;
if state.due(now) && state.cursor.is_some_and(|c| c.0 < head) {
return Ok(true);
}
}
Ok(false)
}
fn write_hold(home: &Home, config: &Config, dir: &Path, now_ms: i64) -> Result<()> {
let mut until = i64::MAX;
for sink in &config.sinks {
let state = State::load(&State::path(home, &sink.id))?;
if state.paused.is_none() {
until = until.min(state.next_attempt_ms);
}
}
let spaced = now_ms.saturating_add(i64::try_from(MIN_SPACING.as_millis()).unwrap_or(0));
home::write_private(
&dir.join(HOLD_FILE),
format!("{} 0", until.max(spaced)).as_bytes(),
)
}
fn error_hold(dir: &Path, now_ms: i64) -> Result<()> {
let failures = read_hold(dir)
.map_or(0, |(_, failures)| failures)
.saturating_add(1);
let wait = ERROR_HOLD_FIRST
.saturating_mul(1u32 << failures.saturating_sub(1).min(16))
.min(ERROR_HOLD_MAX);
let until = now_ms.saturating_add(i64::try_from(wait.as_millis()).unwrap_or(i64::MAX));
home::create_private_dir(dir)?;
home::write_private(
&dir.join(HOLD_FILE),
format!("{until} {failures}").as_bytes(),
)
}
fn read_hold(dir: &Path) -> Option<(i64, u32)> {
let text = std::fs::read_to_string(dir.join(HOLD_FILE)).ok()?;
let mut words = text.split_whitespace();
let until = words.next()?.parse().ok()?;
let failures = words.next().and_then(|w| w.parse().ok()).unwrap_or(0);
Some((until, failures))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_hold_lasts_until_its_time_or_a_newer_configuration_or_lock() {
let dir = tempfile::tempdir().unwrap();
let config = dir.path().join("delivery.yaml");
let lock = dir.path().join("policy.lock");
std::fs::write(&config, "x").unwrap();
std::fs::write(&lock, "x").unwrap();
let changed = [config.clone(), lock.clone()];
assert!(!held(dir.path(), &changed, 0), "no hold file");
std::thread::sleep(Duration::from_millis(20));
std::fs::write(dir.path().join(HOLD_FILE), "1000").unwrap();
assert!(held(dir.path(), &changed, 999));
assert!(!held(dir.path(), &changed, 1000));
std::thread::sleep(Duration::from_millis(20));
std::fs::write(&lock, "re-pinned").unwrap();
assert!(!held(dir.path(), &changed, 999), "a person accepted since");
std::fs::remove_file(&config).unwrap();
assert!(!held(dir.path(), &changed, 999));
}
#[test]
fn every_run_writes_a_hold_and_failures_back_off() {
let dir = tempfile::tempdir().unwrap();
let home = Home::at(dir.path().join("state"));
let delivery = home.delivery_dir();
let config = config::parse(
"version: 1\nmachine: m\nsinks:\n - id: c\n otlp: http://127.0.0.1:9/v1/logs\n",
&home,
)
.unwrap();
let minute = 60_000;
let mut waits = Vec::new();
for _ in 0..6 {
error_hold(&delivery, 0).unwrap();
waits.push(read_hold(&delivery).unwrap().0);
}
assert_eq!(
waits,
[
minute,
2 * minute,
4 * minute,
8 * minute,
15 * minute,
15 * minute
]
);
write_hold(&home, &config, &delivery, 5_000).unwrap();
assert_eq!(read_hold(&delivery), Some((6_000, 0)));
error_hold(&delivery, 0).unwrap();
assert_eq!(read_hold(&delivery), Some((minute, 1)));
let mut state = State::default();
state.failed("HTTP 503".to_owned(), Some(120), 5_000, 0.0);
state.save(&State::path(&home, "c")).unwrap();
write_hold(&home, &config, &delivery, 5_000).unwrap();
assert_eq!(read_hold(&delivery), Some((125_000, 0)));
}
#[test]
fn a_run_that_fails_writes_a_hold() {
let dir = tempfile::tempdir().unwrap();
let home = Home::at(dir.path().join("state"));
let config = config::parse(
"version: 1\nmachine: m\nsinks:\n - id: c\n otlp: http://127.0.0.1:9/v1/logs\n",
&home,
)
.unwrap();
let changed = [home.delivery_config_path(), home.lock_path()];
std::fs::create_dir_all(home.root()).unwrap();
std::fs::write(&changed[0], "x").unwrap();
std::fs::write(&changed[1], "x").unwrap();
std::thread::sleep(Duration::from_millis(20));
let now = time::now_ms();
let ran = runs(&home, &config, 0, false, Duration::from_secs(1));
assert!(held_after(&home.delivery_dir(), ran, now).is_err());
let delivery = home.delivery_dir();
assert_eq!(read_hold(&delivery), Some((now + 60_000, 1)));
assert!(held(&delivery, &changed, now + 59_000));
assert!(!held(&delivery, &changed, now + 60_000));
}
}