Skip to main content

artifactize_core/runs/
follow.rs

1//! State-wide Run observation, including owner death and removed workspaces with no writer.
2use std::{
3    collections::BTreeSet,
4    path::{Path, PathBuf},
5    time::Duration,
6};
7
8use crate::{
9    changes::{Change, Subscription},
10    monitor::live::Place,
11    store::{self, CatalogRun},
12    types::{RunId, Timestamp},
13};
14
15/// Owner death and workspace removal don't themselves write state. Bound how long an idle
16/// observer waits before the engine checks for them and retries a failed completion read.
17const CHECK: Duration = Duration::from_secs(2);
18
19/// The workspaces recorded by Runs, even when a workspace is gone or hidden by a filter.
20pub async fn workspaces(state: &Path) -> Result<BTreeSet<PathBuf>, String> {
21    Ok(store::read_catalog(state)
22        .await?
23        .into_iter()
24        .map(|run| run.repo_path)
25        .collect())
26}
27
28/// Recover interrupted Runs before explicitly refreshing a state-wide view. One broken Run
29/// must not stop the engine from checking the other owners; subsequent reads retry failures.
30pub async fn reconcile_open(state: &Path) {
31    if let Ok(open) = store::read_open_run_ids(state).await {
32        for id in open {
33            let _ = super::reconcile_interrupted(state, &id).await;
34        }
35    }
36}
37
38/// A Run that finished while this observer was attached, with its recorded branch or folder.
39#[derive(Debug, PartialEq, Eq)]
40pub struct RunFinished {
41    pub run: RunId,
42    pub place: Place,
43}
44
45/// Authoritative completions accompany a change hint, or arrive alone after a read retry.
46pub struct FollowUpdate {
47    pub change: Option<Change>,
48    pub finished: Vec<RunFinished>,
49}
50
51/// Follow all Runs in one state, regardless of the surface's selection. The engine reconciles
52/// interrupted owners and retires removed sign-offs; those commits notify every observer.
53/// Dropping the follower stops observation without cancelling any Run or review.
54pub struct Follow {
55    state: PathBuf,
56    changes: Subscription,
57    ticks: tokio::time::Interval,
58    finished: Finished,
59    retry: bool,
60}
61
62impl Follow {
63    pub async fn new(state: &Path) -> Self {
64        let finished = Finished {
65            since: Timestamp::now(),
66            seen: BTreeSet::new(),
67        };
68        // The first hint is a resync. Register before reading so commits during startup are
69        // covered by either the first snapshot or a queued hint.
70        let changes = Subscription::new(state).await;
71        let mut ticks = tokio::time::interval(CHECK);
72        ticks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
73        Self {
74            state: state.to_owned(),
75            changes,
76            ticks,
77            finished,
78            retry: false,
79        }
80    }
81
82    pub async fn next(&mut self) -> FollowUpdate {
83        loop {
84            let change = tokio::select! {
85                _ = self.ticks.tick() => {
86                    reconcile_open(&self.state).await;
87                    let _ = store::retire_removed_signoffs(&self.state).await;
88                    None
89                }
90                change = self.changes.next() => Some(change),
91            };
92            let runs = match &change {
93                _ if self.retry => store::read_catalog(&self.state).await,
94                Some(Change::StateInvalidated | Change::Resync) => {
95                    store::read_catalog(&self.state).await
96                }
97                Some(Change::RunInvalidated(id)) => store::read_catalog_run(&self.state, id)
98                    .await
99                    .map(|run| run.into_iter().collect()),
100                _ => Ok(Vec::new()),
101            };
102            self.retry = runs.is_err();
103            let mut finished = Vec::new();
104            for run in runs.unwrap_or_default() {
105                if let Some(completion) = self.finished.observe(run).await {
106                    finished.push(completion);
107                }
108            }
109            if change.is_some() || !finished.is_empty() {
110                return FollowUpdate { change, finished };
111            }
112        }
113    }
114
115    /// Stop the follower and release its probe and hub connection before deleting the state.
116    pub async fn close(self) -> Result<(), String> {
117        self.changes.close().await
118    }
119}
120
121struct Finished {
122    since: Timestamp,
123    seen: BTreeSet<RunId>,
124}
125
126impl Finished {
127    async fn observe(&mut self, run: CatalogRun) -> Option<RunFinished> {
128        if run.completed_at? < self.since || self.seen.contains(&run.id) {
129            return None;
130        }
131        let place = run.branch().await.ok()?;
132        self.seen.insert(run.id.clone());
133        Some(RunFinished { run: run.id, place })
134    }
135}