#[cfg(any(windows, test))]
mod acl;
mod fs;
mod lock;
mod transient;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use isoloom_manifest::{Cloud, Driver, Provider, Target};
use serde::{Deserialize, Serialize};
pub(crate) use fs::{create_private, if_there, private_dir, remove_path, write_private};
pub(crate) use transient::Transient;
pub(crate) fn create_dir(dir: &Path) -> Result<()> {
private_dir(dir).map_err(Error::io(dir, "created"))
}
pub(crate) fn write(path: &Path, contents: &[u8]) -> Result<()> {
write_private(path, contents).map_err(Error::io(path, "written"))
}
pub(crate) fn remove(path: &Path) -> Result<()> {
remove_path(path).map_err(Error::io(path, "removed"))
}
pub(crate) use lock::{RunLocks, SlotsLock};
use crate::Result;
use crate::error::{Error, ErrorCode};
use crate::events::EventLog;
use crate::name::RunName;
use crate::state::{Op, RunState};
use crate::status::MachineStatus;
const RECORD_VERSION: u32 = 0;
const RECORD_FILE: &str = "record.json";
const EVENTS_FILE: &str = "events.jsonl";
const SEEN_FILE: &str = "seen.json";
const LOCK_FILE: &str = "lock";
pub(crate) const EVENTS_KEPT: usize = 4000;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LastOp {
pub op: Op,
pub ok: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<ErrorCode>,
pub at: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct RunRecord {
pub version: u32,
pub name: RunName,
pub manifest: PathBuf,
pub target: Target,
pub driver: Driver,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cloud: Option<Cloud>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<Provider>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub host_label: Option<String>,
pub state: RunState,
pub params: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub vm_host_ports: BTreeMap<String, u16>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub vm_boot_digests: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub started_at: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub slot: Option<u8>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ssh_jump: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last: Option<LastOp>,
}
impl RunRecord {
pub(crate) fn replayed_params(&self) -> Option<&BTreeMap<String, String>> {
self.started_at.is_some().then_some(&self.params)
}
pub(crate) fn fresh(name: RunName, manifest: PathBuf, target: Target, driver: Driver) -> RunRecord {
RunRecord {
version: RECORD_VERSION,
name,
manifest,
target,
driver,
cloud: None,
provider: None,
host_label: None,
state: RunState::Absent,
params: BTreeMap::new(),
vm_host_ports: BTreeMap::new(),
vm_boot_digests: BTreeMap::new(),
started_at: None,
slot: None,
ssh_jump: None,
expires_at: None,
last: None,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct Seen {
pub(crate) machines: Vec<MachineStatus>,
pub(crate) published: Vec<(String, String, u16)>,
pub(crate) hosts: BTreeMap<String, String>,
}
#[derive(Debug, Clone)]
pub(crate) struct Store {
runs: PathBuf,
slots_lock: PathBuf,
}
impl Store {
pub(crate) fn open(home: &Path, profile: Option<&Path>) -> Result<Store> {
fs::private_home(home, profile).map_err(Error::io(home, "made owner-only"))?;
let runs = home.join("runs");
create_dir(&runs)?;
Ok(Store {
runs,
slots_lock: home.join("slots.lock"),
})
}
pub(crate) async fn hold_slots(&self) -> Result<SlotsLock> {
lock::hold_slots(&self.slots_lock).await
}
pub(crate) fn run_dir(&self, name: &RunName) -> Result<PathBuf> {
let dir = self.run_dir_path(name);
create_dir(&dir)?;
Ok(dir)
}
pub(crate) fn run_dir_path(&self, name: &RunName) -> PathBuf {
self.runs.join(name.as_str())
}
fn record_path(&self, name: &RunName) -> PathBuf {
self.run_dir_path(name).join(RECORD_FILE)
}
fn events_path(&self, name: &RunName) -> PathBuf {
self.run_dir_path(name).join(EVENTS_FILE)
}
pub(crate) fn lock_path(&self, name: &RunName) -> PathBuf {
self.run_dir_path(name).join(LOCK_FILE)
}
pub(crate) fn held(&self, name: &RunName) -> Result<bool> {
let path = self.lock_path(name);
lock::held(&path).map_err(Error::io(&path, "read"))
}
fn seen_path(&self, name: &RunName) -> PathBuf {
self.run_dir_path(name).join(SEEN_FILE)
}
pub(crate) fn seen(&self, name: &RunName) -> Result<Option<Seen>> {
read_json(&self.seen_path(name))
}
pub(crate) fn keep_seen(&self, name: &RunName, seen: &Seen) -> Result<()> {
self.run_dir(name)?;
write_json(&self.seen_path(name), seen)
}
pub(crate) fn forget_seen(&self, name: &RunName) -> Result<()> {
let path = self.seen_path(name);
remove(&path)
}
pub(crate) fn record(&self, name: &RunName) -> Result<Option<RunRecord>> {
read_json(&self.record_path(name))
}
pub(crate) fn save(&self, record: &RunRecord) -> Result<()> {
self.run_dir(&record.name)?;
write_json(&self.record_path(&record.name), record)
}
pub(crate) fn records(&self) -> Result<Vec<RunRecord>> {
let entries = std::fs::read_dir(&self.runs).map_err(Error::io(&self.runs, "read"))?;
let mut names = Vec::new();
for entry in entries {
let entry = entry.map_err(Error::io(&self.runs, "read"))?;
names.extend(RunName::new(&entry.file_name().to_string_lossy()).ok());
}
names.sort();
let mut records = Vec::new();
for name in names {
records.extend(self.record(&name)?);
}
Ok(records)
}
pub(crate) fn event_log(&self, name: &RunName) -> Result<std::fs::File> {
self.run_dir(name)?;
let path = self.events_path(name);
fs::append_private(&path).map_err(Error::io(&path, "written"))
}
pub(crate) fn trim_event_log(&self, name: &RunName) -> Result<()> {
self.run_dir(name)?;
let path = self.events_path(name);
let lines = read_lines(&path)?;
if lines.len() > EVENTS_KEPT {
let mut kept = Vec::new();
for line in lines.iter().skip(lines.len().saturating_sub(EVENTS_KEPT / 2)) {
kept.extend_from_slice(line);
kept.push(b'\n');
}
write(&path, &kept)?;
}
Ok(())
}
pub(crate) fn events(&self, name: &RunName) -> Result<EventLog> {
let path = self.events_path(name);
let mut log = EventLog::default();
for (n, line) in read_lines(&path)?.iter().enumerate().filter(|(_, l)| !l.trim_ascii().is_empty()) {
match serde_json::from_slice(line) {
Ok(event) => log.events.push(event),
Err(e) => {
tracing::debug!(line = n + 1, error = %e, path = %path.display(), "a line of the event log isn't an event this runner reads");
log.unreadable += 1;
}
}
}
Ok(log)
}
}
fn read_lines(path: &Path) -> Result<Vec<Vec<u8>>> {
let Some(bytes) = if_there(std::fs::read(path)).map_err(Error::io(path, "read"))? else {
return Ok(Vec::new());
};
let body = bytes.strip_suffix(b"\n").unwrap_or(&bytes);
if body.is_empty() {
return Ok(Vec::new());
}
Ok(body
.split(|b| *b == b'\n')
.map(|line| line.strip_suffix(b"\r").unwrap_or(line).to_vec())
.collect())
}
pub(crate) fn read_json<T: serde::de::DeserializeOwned>(path: &Path) -> Result<Option<T>> {
let Some(bytes) = if_there(std::fs::read(path)).map_err(Error::io(path, "read"))? else {
return Ok(None);
};
serde_json::from_slice(&bytes).map(Some).map_err(|e| Error::io(path, "read")(e.into()))
}
fn write_json<T: Serialize>(path: &Path, value: &T) -> Result<()> {
let text = serde_json::to_vec_pretty(value).map_err(|e| Error::io(path, "written")(e.into()))?;
write(path, &text)
}
#[cfg(test)]
mod tests {
use std::io::Write;
use super::*;
fn record(name: &str) -> RunRecord {
RunRecord::fresh(
RunName::new(name).unwrap(),
"/work/x/.isoloom/docker/run.json".into(),
Target::Docker,
Driver::Compose,
)
}
#[test]
fn records_are_kept_per_run_and_listed_by_name() {
let home = tempfile::tempdir().unwrap();
let store = Store::open(home.path(), None).unwrap();
assert_eq!(store.record(&RunName::new("b").unwrap()).unwrap(), None);
let mut b = record("b");
b.params.insert("ISOLOOM_PUBLISH_FIXED".into(), "1".into());
store.save(&b).unwrap();
store.save(&record("a")).unwrap();
std::fs::create_dir_all(home.path().join("runs").join("Not A Run")).unwrap();
let names: Vec<String> = store.records().unwrap().iter().map(|r| r.name.to_string()).collect();
assert_eq!(names, ["a", "b"]);
assert_eq!(store.record(&b.name).unwrap(), Some(b));
}
fn run_r() -> (tempfile::TempDir, Store, RunName) {
let home = tempfile::tempdir().unwrap();
let store = Store::open(home.path(), None).unwrap();
(home, store, RunName::new("r").unwrap())
}
#[test]
fn the_event_log_is_trimmed_to_its_newer_half() {
let (home, store, name) = run_r();
let mut log = store.event_log(&name).unwrap();
for seq in 0..=EVENTS_KEPT {
writeln!(log, "{{\"seq\":{seq}}}").unwrap();
}
drop(log);
store.trim_event_log(&name).unwrap();
let lines = read_lines(&home.path().join("runs/r/events.jsonl")).unwrap();
assert_eq!(lines.len(), EVENTS_KEPT / 2);
assert_eq!(lines.last().unwrap(), format!("{{\"seq\":{EVENTS_KEPT}}}").as_bytes());
}
#[tokio::test]
async fn an_event_log_line_this_runner_cant_read_is_counted_not_dropped_unsaid() {
let (_home, store, name) = run_r();
let mut log = store.event_log(&name).unwrap();
let read = r#"{"v":0,"seq":1,"time":"2026-10-15T12:00:00Z","run":"r","op":"up","event":"result","ok":true,"data":null}"#;
let older = r#"{"v":0,"seq":2,"time":"2026-10-15T12:00:01Z","run":"r","op":"up","event":"warning","code":"hook_failed","message":"x"}"#;
writeln!(log, "{read}\n{older}\n{{\"v\":0,\"se\n").unwrap();
drop(log);
let (events, traced) = crate::testing::traced(async { store.events(&name) }).await;
let events = events.unwrap();
assert_eq!((events.events.len(), events.unreadable), (1, 2));
assert!(traced.contains("line=2") && traced.contains("hook_failed"), "{traced}");
assert!(traced.contains("line=3"), "{traced}");
}
#[test]
fn a_line_cut_mid_character_is_unreadable_and_the_log_goes_on() {
let (home, store, name) = run_r();
let read = r#"{"v":0,"seq":1,"time":"2026-10-15T12:00:00Z","run":"r","op":"up","event":"result","ok":true,"data":null}"#;
let mut log = store.event_log(&name).unwrap();
log.write_all(format!("{read}\n").as_bytes()).unwrap();
log.write_all(b"{\"v\":0,\"message\":\"d\xC3").unwrap();
drop(log);
let mut reopened = store.event_log(&name).expect("the log opens to append");
reopened.write_all(format!("\n{read}\n").as_bytes()).unwrap();
drop(reopened);
let events = store.events(&name).unwrap();
assert_eq!((events.events.len(), events.unreadable), (2, 1));
let mut many = store.event_log(&name).unwrap();
for seq in 0..=EVENTS_KEPT {
writeln!(many, "{{\"seq\":{seq}}}").unwrap();
}
drop(many);
store.trim_event_log(&name).expect("a long log with such a line is trimmed");
assert_eq!(read_lines(&home.path().join("runs/r/events.jsonl")).unwrap().len(), EVENTS_KEPT / 2);
}
#[test]
fn a_files_lines_are_split_on_line_feeds() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("f");
assert_eq!(read_lines(&path).unwrap(), Vec::<Vec<u8>>::new(), "no file, no line");
for (text, lines) in [
(&b""[..], vec![]),
(b"a\n", vec![b"a".to_vec()]),
(b"a\r\nb", vec![b"a".to_vec(), b"b".to_vec()]),
(b"a\n\nb\n", vec![b"a".to_vec(), b"".to_vec(), b"b".to_vec()]),
] {
std::fs::write(&path, text).unwrap();
assert_eq!(read_lines(&path).unwrap(), lines, "{text:?}");
}
}
}