devsandbox 0.7.0

Manage devcontainer-style sandboxes on docker, podman, or Apple container — many throwaway instances per repo from one TOML config.
//! `inbox.json`, next to `state.toml`: the one host-wide Inbox, shared by
//! every dashboard, the daemon and the CLI. It holds the history across
//! dashboard sessions — the container outbox forgets a record once a bridge
//! took it — so an in-memory copy per dashboard would mean last writer wins,
//! bringing back records another one dismissed.
//!
//! Every change is a read-modify-write under an exclusive lock on the sibling
//! `inbox.lock` ([`update_at`]), written to a temp file and renamed, so a crash
//! mid-write can't leave a truncated file and a reader never sees a partial
//! one. A store that doesn't exist yet but has an older `inbox.toml` beside it
//! starts from that file's notify records ([`Inbox::import_v2`]); the first
//! write then creates `inbox.json`. The old file is left where it is. Readers ([`load_at`]) take a shared lock and are best-effort about it:
//! the atomic rename already makes an unlocked read safe. [`stamp_at`] is the
//! cheap "did it change" check dashboards run each tick. Callers outside
//! tests go through [`super::ops`], which names each read and mutation.
//!
//! [`generation`] / [`wait_changed`] are the in-process change notification:
//! every write [`update_at`] makes bumps a counter and wakes its waiters, so
//! a long-polling `events --wait` in the daemon hears the notify sink's and
//! the acks' writes at once. Writes by other processes don't reach it; they
//! still need the [`stamp_at`] check.

use std::collections::BTreeMap;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::sync::{Condvar, Mutex};
use std::time::{Duration, Instant, SystemTime};

use anyhow::{Context, Result};

use super::Inbox;
use crate::state::State;

/// The store path: `inbox.json` beside the state file.
pub fn path() -> Result<PathBuf> {
    Ok(State::path()?.with_file_name("inbox.json"))
}

/// The v1/v2 store beside a store file, imported when the store is missing.
fn legacy_path(path: &Path) -> PathBuf {
    path.with_file_name("inbox.toml")
}

/// The lock beside a store file. Separate from the store itself, which the
/// atomic write replaces (locking a file that gets renamed away locks nothing).
/// The same name the v2 store used, so an older build writing `inbox.toml`
/// and this one importing it can't interleave.
fn lock_path(path: &Path) -> PathBuf {
    path.with_file_name("inbox.lock")
}

/// The saved Inbox at `path`; a missing file is an empty one.
pub fn load_at(path: &Path) -> Result<Inbox> {
    let _shared = lock(path, false);
    read(path).map(|(inbox, _)| inbox)
}

/// Read and parse without locking (the caller holds one, or doesn't need it).
/// The flag is set when the content was imported from `inbox.toml`, which
/// [`update_at`] then writes out as `inbox.json` so the import (and a v1
/// file's fresh thread ids) happens once, not on every read.
fn read(path: &Path) -> Result<(Inbox, bool)> {
    match read_text(path)? {
        Some(text) => {
            let inbox = Inbox::from_json(&text).map_err(|e| anyhow::anyhow!("invalid {}: {e}", path.display()))?;
            Ok((inbox, false))
        }
        None => {
            let legacy = legacy_path(path);
            let Some(text) = read_text(&legacy)? else { return Ok((Inbox::default(), false)) };
            // Only a v1 file needs the name -> instance_id map, so the state
            // file is read for that, not on every import.
            let names = if toml_version(&text) < 2 { names_from_state() } else { BTreeMap::new() };
            let inbox = Inbox::import_v2(&text, &names)
                .map_err(|e| anyhow::anyhow!("invalid {}: {e}", legacy.display()))?;
            Ok((inbox, true))
        }
    }
}

/// A file's contents, `None` when it doesn't exist.
fn read_text(path: &Path) -> Result<Option<String>> {
    match std::fs::read_to_string(path) {
        Ok(text) => Ok(Some(text)),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(e).with_context(|| format!("cannot read {}", path.display())),
    }
}

/// An `inbox.toml`'s `version`, 0 (i.e. v1) when absent or unparsable; a real
/// parse error is reported by [`Inbox::import_v2`] right after.
fn toml_version(text: &str) -> u32 {
    #[derive(serde::Deserialize)]
    struct Probe {
        #[serde(default)]
        version: u32,
    }
    toml::from_str::<Probe>(text).map_or(0, |p| p.version)
}

/// Instance name (state key) -> `instance_id`, for importing a v1 file. A
/// state that won't load leaves every thread unresolved rather than failing
/// the Inbox.
fn names_from_state() -> BTreeMap<String, String> {
    State::load().map_or_else(
        |_| BTreeMap::new(),
        |s| s.instances.iter().map(|(k, i)| (k.clone(), i.instance_id.clone())).collect(),
    )
}

/// Read-modify-write under the exclusive lock: load, run `f`, and save only if
/// the content changed, so an update that decides to do nothing doesn't bump
/// the mtime other dashboards poll.
pub fn update_at<T>(path: &Path, f: impl FnOnce(&mut Inbox) -> T) -> Result<T> {
    let dir = path.parent().context("inbox path has no parent")?;
    std::fs::create_dir_all(dir).with_context(|| format!("cannot create {}", dir.display()))?;
    let _exclusive = lock(path, true).with_context(|| format!("cannot lock {}", lock_path(path).display()))?;
    let (mut inbox, migrated) = read(path)?;
    let before = serialize(&inbox)?;
    let out = f(&mut inbox);
    let after = serialize(&inbox)?;
    if after != before || migrated {
        write_atomic(path, &after)?;
        bump();
    }
    Ok(out)
}

/// Store writes made by this process, any path. Process-wide rather than
/// per path: there is one store outside tests, and a spurious wake only costs
/// a waiter one re-read.
static CHANGES: (Mutex<u64>, Condvar) = (Mutex::new(0), Condvar::new());

fn bump() {
    let (lock, cvar) = &CHANGES;
    *lock.lock().unwrap_or_else(|e| e.into_inner()) += 1;
    cvar.notify_all();
}

/// The current write generation. Take it *before* reading the store, then
/// pass it to [`wait_changed`], so a write in between isn't slept through.
pub fn generation() -> u64 {
    *CHANGES.0.lock().unwrap_or_else(|e| e.into_inner())
}

/// Block until this process wrote the store since generation `seen`, or
/// `timeout` passed; the generation at return either way.
pub fn wait_changed(seen: u64, timeout: Duration) -> u64 {
    let (lock, cvar) = &CHANGES;
    let deadline = Instant::now() + timeout;
    let mut current = lock.lock().unwrap_or_else(|e| e.into_inner());
    while *current == seen {
        let left = deadline.saturating_duration_since(Instant::now());
        if left.is_zero() {
            break;
        }
        current = cvar.wait_timeout(current, left).unwrap_or_else(|e| e.into_inner()).0;
    }
    *current
}

fn serialize(inbox: &Inbox) -> Result<String> {
    inbox.to_json().map_err(|e| anyhow::anyhow!("cannot serialize inbox: {e}"))
}

/// Hold the store lock until the returned file is dropped. A shared lock that
/// can't be taken (read-only dir, exotic filesystem) is not fatal: the atomic
/// write means an unlocked read is still consistent.
fn lock(path: &Path, exclusive: bool) -> Result<File> {
    let file = File::options()
        .create(true)
        .read(true)
        .write(true)
        .open(lock_path(path))
        .with_context(|| format!("cannot open {}", lock_path(path).display()))?;
    if exclusive { file.lock() } else { file.lock_shared() }.context("cannot lock the inbox")?;
    Ok(file)
}

/// Write `text` through a temp file + rename, so readers only ever see a
/// complete file. The temp name (`.inbox.json.<pid>.tmp`) carries the pid:
/// the lock already serializes writers, but a stale temp from a killed
/// process must not be reused.
fn write_atomic(path: &Path, text: &str) -> Result<()> {
    let name = path.file_name().map_or("inbox.json".into(), |n| n.to_string_lossy());
    let tmp = path.with_file_name(format!(".{name}.{}.tmp", std::process::id()));
    std::fs::write(&tmp, text).with_context(|| format!("cannot write {}", tmp.display()))?;
    std::fs::rename(&tmp, path).with_context(|| format!("cannot write {}", path.display()))
}

/// Cheap change check: the store's mtime and length, `None` when it doesn't
/// exist yet. Dashboards compare it each tick and reload when it moves.
pub fn stamp_at(path: &Path) -> Option<(SystemTime, u64)> {
    let meta = std::fs::metadata(path).ok()?;
    Some((meta.modified().ok()?, meta.len()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::devsbd::notify::{Level, Record};
    use crate::inbox::Op;

    fn rec(msg: &str) -> Record {
        Record { level: Level::Info, key: None, link: None, msg: msg.into(), at: 0 }
    }

    /// A unique empty directory under the test tmp dir.
    fn tmpdir(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("devsandbox-inbox-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn a_write_wakes_a_waiter_and_a_quiet_store_times_out() {
        let path = tmpdir("notify").join("inbox.json");
        let seen = generation();
        let writer = {
            let path = path.clone();
            std::thread::spawn(move || {
                std::thread::sleep(Duration::from_millis(100));
                update_at(&path, |i| i.push("a-id".into(), "a".into(), rec("one"), true)).unwrap();
            })
        };
        let started = Instant::now();
        assert!(wait_changed(seen, Duration::from_secs(10)) > seen);
        assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed());
        writer.join().unwrap();

        // A no-op update writes nothing, so it wakes nobody. Other tests in
        // this process may write their own stores meanwhile, so only bound
        // the wait from above: it returns by the timeout at the latest.
        update_at(&path, |_| {}).unwrap();
        let started = Instant::now();
        wait_changed(generation(), Duration::from_millis(200));
        assert!(started.elapsed() < Duration::from_secs(2));
        // An already-passed generation returns at once.
        let started = Instant::now();
        assert!(wait_changed(seen, Duration::from_secs(10)) > seen);
        assert!(started.elapsed() < Duration::from_millis(100));
    }

    #[test]
    fn missing_file_loads_empty_and_update_creates_it() {
        let path = tmpdir("create").join("inbox.json");
        assert!(load_at(&path).unwrap().threads.is_empty());
        assert_eq!(stamp_at(&path), None);
        update_at(&path, |i| i.push("a-id".into(), "a".into(), rec("one"), true)).unwrap();
        let loaded = load_at(&path).unwrap();
        assert_eq!(loaded.threads.len(), 1);
        assert_eq!(loaded.threads[0].head().unwrap().msg, "one");
        assert!(stamp_at(&path).is_some());
    }

    #[test]
    fn save_only_when_the_content_changed() {
        let path = tmpdir("unchanged").join("inbox.json");
        update_at(&path, |i| i.push("a-id".into(), "a".into(), rec("one"), true)).unwrap();
        let before = stamp_at(&path).unwrap();
        // Far enough apart that a coarse mtime would still move.
        std::thread::sleep(std::time::Duration::from_millis(1100));
        // A no-op closure, and an op that matches nothing.
        update_at(&path, |_| {}).unwrap();
        update_at(&path, |i| i.apply(&Op::RemoveThread(9999), 0, "tui")).unwrap();
        assert_eq!(stamp_at(&path).unwrap(), before, "no write, no mtime bump");
        let out = update_at(&path, |i| {
            i.apply(&Op::MarkNotifyRead, 0, "tui");
            42
        })
        .unwrap();
        assert_eq!(out, 42, "update returns the closure's value");
        assert_ne!(stamp_at(&path).unwrap(), before, "a real change writes");
    }

    /// Two writers interleaving read-modify-writes: the lock makes every push
    /// land, instead of one process's copy overwriting the other's.
    #[test]
    fn concurrent_updates_lose_nothing() {
        let path = tmpdir("concurrent").join("inbox.json");
        std::thread::scope(|s| {
            for who in ["a", "b"] {
                let path = path.clone();
                s.spawn(move || {
                    for i in 0..50 {
                        update_at(&path, |inbox| {
                            inbox.push(format!("{who}-id"), who.into(), rec(&format!("{who}{i}")), true)
                        })
                        .unwrap();
                    }
                });
            }
        });
        let inbox = load_at(&path).unwrap();
        assert_eq!(inbox.threads.len(), 100);
        assert_eq!(inbox.threads.iter().filter(|t| t.owner == "a-id").count(), 50);
        assert_eq!(inbox.threads.iter().filter(|t| t.owner == "b-id").count(), 50);
        let mut msgs: Vec<&str> = inbox.threads.iter().map(|t| t.head().unwrap().msg.as_str()).collect();
        msgs.sort_unstable();
        msgs.dedup();
        assert_eq!(msgs.len(), 100, "every push is distinct and present");
        // Ids stay unique across writers, so selection can't alias.
        let mut ids: Vec<u64> = inbox.threads.iter().map(|t| t.id).collect();
        ids.sort_unstable();
        ids.dedup();
        assert_eq!(ids.len(), 100);
    }

    /// A dispatcher re-asserting its threads every pass must cost nothing: an
    /// identical put leaves the file byte for byte as it was, so no dashboard
    /// polling the mtime even reloads.
    #[test]
    fn an_identical_put_does_not_touch_the_file() {
        use crate::inbox::{State, ThreadPut};
        let path = tmpdir("idempotent-put").join("inbox.json");
        let put = || ThreadPut {
            key: "pr-1".into(),
            title: "PR 1".into(),
            state: State::NeedsYou,
            status: Some("review".into()),
            ..ThreadPut::default()
        };
        update_at(&path, |i| i.put("web-id", "web", 10, put())).unwrap();
        let before = stamp_at(&path).unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        // Far enough apart that a coarse mtime would still move.
        std::thread::sleep(std::time::Duration::from_millis(1100));
        let out = update_at(&path, |i| i.put("web-id", "web", 99, put())).unwrap();
        assert_eq!(out, crate::inbox::PutOutcome::Unchanged);
        assert_eq!(stamp_at(&path).unwrap(), before, "no write, no mtime bump");
        assert_eq!(std::fs::read_to_string(&path).unwrap(), text);
        // A real change does write.
        let changed = ThreadPut { status: Some("merged".into()), ..put() };
        update_at(&path, |i| i.put("web-id", "web", 99, changed)).unwrap();
        assert_ne!(stamp_at(&path).unwrap(), before);
    }

    /// No `inbox.json` yet but a v2 `inbox.toml` beside it: its notify
    /// records load (owner threads dropped), and the next update writes them
    /// out as `inbox.json`, even one that changes nothing, so the import
    /// happens once. The old file is left untouched.
    #[test]
    fn imports_a_v2_store_once_and_leaves_it_alone() {
        let dir = tmpdir("v2");
        let (path, legacy) = (dir.join("inbox.json"), dir.join("inbox.toml"));
        let v2 = "version = 2\n\n[[thread]]\nid = 1\nowner = \"web-id\"\nowner_name = \"web\"\nunread = true\n\n[[thread.note]]\nseq = 3\nlevel = \"info\"\nat = 0\nmsg = \"hi\"\n\n[[thread]]\nid = 2\nowner = \"web-id\"\nowner_name = \"web\"\nkind = \"thread\"\nkey = \"pr-1\"\ntitle = \"PR 1\"\nstate = \"active\"\n";
        std::fs::write(&legacy, v2).unwrap();
        let inbox = load_at(&path).unwrap();
        assert_eq!(inbox.threads.len(), 1, "the owner thread is dropped");
        assert_eq!(inbox.threads[0].head().unwrap().msg, "hi");
        assert_eq!(stamp_at(&path), None, "a read writes nothing");
        update_at(&path, |_| {}).unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        assert!(text.contains("\"version\": 3"), "{text}");
        assert_eq!(std::fs::read_to_string(&legacy).unwrap(), v2, "inbox.toml is left as it was");
        // From now on `inbox.json` is the store: the old file is not read.
        update_at(&path, |i| i.apply(&Op::ClearNotify, 0, "tui")).unwrap();
        assert!(load_at(&path).unwrap().threads.is_empty());
        // A v1 file imports the same way.
        let dir = tmpdir("v1");
        std::fs::write(
            dir.join("inbox.toml"),
            "[[thread]]\ninstance = \"web\"\nunread = true\n[[thread.note]]\nseq = 3\nlevel = \"info\"\nat = 0\nmsg = \"hi\"\n",
        )
        .unwrap();
        assert_eq!(load_at(&dir.join("inbox.json")).unwrap().threads[0].owner_name, "web");
    }

    #[test]
    fn a_store_of_another_version_is_an_error() {
        let path = tmpdir("v4").join("inbox.json");
        std::fs::write(&path, r#"{"version":4,"threads":[]}"#).unwrap();
        let err = format!("{:#}", load_at(&path).unwrap_err());
        assert!(err.contains("version 4"), "{err}");
        assert!(update_at(&path, |_| {}).is_err(), "and is never overwritten");
        assert!(std::fs::read_to_string(&path).unwrap().contains("\"version\":4"));
    }
}