artifactize_core/runs/
follow.rs1use 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
15const CHECK: Duration = Duration::from_secs(2);
18
19pub 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
28pub 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#[derive(Debug, PartialEq, Eq)]
40pub struct RunFinished {
41 pub run: RunId,
42 pub place: Place,
43}
44
45pub struct FollowUpdate {
47 pub change: Option<Change>,
48 pub finished: Vec<RunFinished>,
49}
50
51pub 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 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 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}