artifactize-core 0.27.1

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
//! State-wide Run observation, including owner death and removed workspaces with no writer.
use std::{
    collections::BTreeSet,
    path::{Path, PathBuf},
    time::Duration,
};

use crate::{
    changes::{Change, Subscription},
    monitor::live::Place,
    store::{self, CatalogRun},
    types::{RunId, Timestamp},
};

/// Owner death and workspace removal don't themselves write state. Bound how long an idle
/// observer waits before the engine checks for them and retries a failed completion read.
const CHECK: Duration = Duration::from_secs(2);

/// The workspaces recorded by Runs, even when a workspace is gone or hidden by a filter.
pub async fn workspaces(state: &Path) -> Result<BTreeSet<PathBuf>, String> {
    Ok(store::read_catalog(state)
        .await?
        .into_iter()
        .map(|run| run.repo_path)
        .collect())
}

/// Recover interrupted Runs before explicitly refreshing a state-wide view. One broken Run
/// must not stop the engine from checking the other owners; subsequent reads retry failures.
pub async fn reconcile_open(state: &Path) {
    if let Ok(open) = store::read_open_run_ids(state).await {
        for id in open {
            let _ = super::reconcile_interrupted(state, &id).await;
        }
    }
}

/// A Run that finished while this observer was attached, with its recorded branch or folder.
#[derive(Debug, PartialEq, Eq)]
pub struct RunFinished {
    pub run: RunId,
    pub place: Place,
}

/// Authoritative completions accompany a change hint, or arrive alone after a read retry.
pub struct FollowUpdate {
    pub change: Option<Change>,
    pub finished: Vec<RunFinished>,
}

/// Follow all Runs in one state, regardless of the surface's selection. The engine reconciles
/// interrupted owners and retires removed sign-offs; those commits notify every observer.
/// Dropping the follower stops observation without cancelling any Run or review.
pub struct Follow {
    state: PathBuf,
    changes: Subscription,
    ticks: tokio::time::Interval,
    finished: Finished,
    retry: bool,
}

impl Follow {
    pub async fn new(state: &Path) -> Self {
        let finished = Finished {
            since: Timestamp::now(),
            seen: BTreeSet::new(),
        };
        // The first hint is a resync. Register before reading so commits during startup are
        // covered by either the first snapshot or a queued hint.
        let changes = Subscription::new(state).await;
        let mut ticks = tokio::time::interval(CHECK);
        ticks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
        Self {
            state: state.to_owned(),
            changes,
            ticks,
            finished,
            retry: false,
        }
    }

    pub async fn next(&mut self) -> FollowUpdate {
        loop {
            let change = tokio::select! {
                _ = self.ticks.tick() => {
                    reconcile_open(&self.state).await;
                    let _ = store::retire_removed_signoffs(&self.state).await;
                    None
                }
                change = self.changes.next() => Some(change),
            };
            let runs = match &change {
                _ if self.retry => store::read_catalog(&self.state).await,
                Some(Change::StateInvalidated | Change::Resync) => {
                    store::read_catalog(&self.state).await
                }
                Some(Change::RunInvalidated(id)) => store::read_catalog_run(&self.state, id)
                    .await
                    .map(|run| run.into_iter().collect()),
                _ => Ok(Vec::new()),
            };
            self.retry = runs.is_err();
            let mut finished = Vec::new();
            for run in runs.unwrap_or_default() {
                if let Some(completion) = self.finished.observe(run).await {
                    finished.push(completion);
                }
            }
            if change.is_some() || !finished.is_empty() {
                return FollowUpdate { change, finished };
            }
        }
    }

    /// Stop the follower and release its probe and hub connection before deleting the state.
    pub async fn close(self) -> Result<(), String> {
        self.changes.close().await
    }
}

struct Finished {
    since: Timestamp,
    seen: BTreeSet<RunId>,
}

impl Finished {
    async fn observe(&mut self, run: CatalogRun) -> Option<RunFinished> {
        if run.completed_at? < self.since || self.seen.contains(&run.id) {
            return None;
        }
        let place = run.branch().await.ok()?;
        self.seen.insert(run.id.clone());
        Some(RunFinished { run: run.id, place })
    }
}