Skip to main content

artifactize_core/runs/
observe.rs

1//! One subscribed observer, independent of execution and Eval kind.
2use super::{Activity, Context};
3use crate::{
4    changes::Change,
5    store::{self, Request, Run, RunView},
6    types::{FailureCode, RequestStatus, RunId, RunStatus, Timestamp},
7};
8use serde::Serialize;
9use std::time::Duration;
10use tokio_util::sync::CancellationToken;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
13#[serde(rename_all = "snake_case")]
14pub enum State {
15    Preparing,
16    Running,
17    Waiting,
18    /// Open while its sign-offs are claimed or its idle grace runs.
19    WaitingHuman,
20    Cancelling,
21    Green,
22    Red,
23    Incomplete,
24    Yellow,
25    Error,
26    Cancelled,
27}
28impl State {
29    pub fn is_terminal(self) -> bool {
30        matches!(
31            self,
32            Self::Green
33                | Self::Red
34                | Self::Incomplete
35                | Self::Yellow
36                | Self::Error
37                | Self::Cancelled
38        )
39    }
40}
41#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
42pub struct Counts {
43    pub total: u64,
44    pub completed: u64,
45    pub running: u64,
46    pub waiting: u64,
47    pub pending: u64,
48}
49#[derive(Debug, Clone, Serialize)]
50pub struct RunObservation {
51    pub run: RunId,
52    pub state: State,
53    pub counts: Counts,
54    #[serde(serialize_with = "seconds")]
55    pub elapsed: Duration,
56    #[serde(serialize_with = "seconds")]
57    pub next_check: Duration,
58}
59
60fn seconds<S: serde::Serializer>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error> {
61    serializer.serialize_u64(duration.as_secs())
62}
63
64fn counts(states: impl IntoIterator<Item = (RequestStatus, u64)>) -> Counts {
65    states
66        .into_iter()
67        .fold(Counts::default(), |mut counts, (state, count)| {
68            counts.total += count;
69            match state {
70                RequestStatus::Green
71                | RequestStatus::Provisional
72                | RequestStatus::Red
73                | RequestStatus::Error => counts.completed += count,
74                RequestStatus::Running => counts.running += count,
75                RequestStatus::WaitingHuman
76                | RequestStatus::Deferred
77                | RequestStatus::WaitDependency => counts.waiting += count,
78                _ => counts.pending += count,
79            }
80            counts
81        })
82}
83pub(super) fn state_for(
84    status: RunStatus,
85    control: Option<&super::Control>,
86    counts: &Counts,
87) -> State {
88    match status {
89        RunStatus::Green => State::Green,
90        RunStatus::Red => State::Red,
91        RunStatus::Incomplete => State::Incomplete,
92        RunStatus::Yellow => State::Yellow,
93        RunStatus::Error
94            if control
95                .is_some_and(|control| control.failure_code == Some(FailureCode::Cancelled)) =>
96        {
97            State::Cancelled
98        }
99        RunStatus::Error => State::Error,
100        RunStatus::WaitingHuman if control.is_some_and(super::Control::is_cancelling) => {
101            State::Cancelling
102        }
103        RunStatus::WaitingHuman => State::WaitingHuman,
104        RunStatus::Running => {
105            if let Some(control) = control {
106                return match control.activity {
107                    Activity::Preparing => State::Preparing,
108                    Activity::Executing | Activity::Publishing => State::Running,
109                    Activity::Waiting => State::Waiting,
110                    Activity::Cancelling => State::Cancelling,
111                };
112            }
113            if counts.waiting > 0 && counts.running == 0 {
114                State::Waiting
115            } else {
116                State::Running
117            }
118        }
119    }
120}
121pub(super) fn state(run: &Run, requests: &[std::sync::Arc<Request>]) -> State {
122    state_for(
123        run.status(),
124        run.control.as_ref(),
125        &counts(requests.iter().map(|request| (request.status(), 1))),
126    )
127}
128
129pub async fn view(context: &Context, id: &RunId) -> Result<RunView, String> {
130    let view = store::read_run(&context.state, id).await?;
131    if !crate::platform::paths_equal(&view.run.repo_path, &context.repo) {
132        return Err("Run not found in this repository.".into());
133    }
134    super::reconcile(&context.state, view).await
135}
136pub async fn status(context: &Context, id: &RunId) -> Result<RunObservation, String> {
137    const NEXT_CHECK: Duration = Duration::from_secs(30); // One ordinary bounded observation, not a polling cadence.
138    let mut saved = store::run_control::observe(&context.state, id).await?;
139    if !crate::platform::paths_equal(&saved.repo, &context.repo) {
140        return Err("Run not found in this repository.".into());
141    }
142    if super::owner_died(saved.status, saved.control.as_ref())? {
143        view(context, id).await?;
144        saved = store::run_control::observe(&context.state, id).await?;
145    }
146    let counts = counts(saved.counts);
147    let state = state_for(saved.status, saved.control.as_ref(), &counts);
148    Ok(RunObservation {
149        run: id.clone(),
150        state,
151        counts,
152        elapsed: saved
153            .completed_at
154            .unwrap_or_else(Timestamp::now)
155            .since(saved.created_at),
156        next_check: if state.is_terminal() {
157            Duration::ZERO
158        } else {
159            NEXT_CHECK
160        },
161    })
162}
163
164/// Reconcile a known open Run if its owning process died without committing a result.
165/// The cheap observation does not decode the saved graph unless recovery is needed.
166pub async fn reconcile_interrupted(state: &std::path::Path, id: &RunId) -> Result<bool, String> {
167    let saved = store::run_control::observe(state, id).await?;
168    if !super::owner_died(saved.status, saved.control.as_ref())? {
169        return Ok(false);
170    }
171    let settled = super::reconcile(state, store::read_run(state, id).await?).await?;
172    Ok(!settled.run.status().is_open())
173}
174
175/// The optional bound covers following changes. At its deadline return the last
176/// snapshot (or read one if the bound expired before the first read). Cancelling
177/// disposes only this observer, never the Run.
178pub async fn wait(
179    context: &Context,
180    id: &RunId,
181    bound: Option<Duration>,
182    cancellation: CancellationToken,
183) -> Result<RunObservation, String> {
184    wait_observing(context, id, bound, cancellation, |_| {}).await
185}
186
187/// Like [`wait`], with each successfully read snapshot available to a caller while it waits.
188pub async fn wait_observing(
189    context: &Context,
190    id: &RunId,
191    bound: Option<Duration>,
192    cancellation: CancellationToken,
193    mut observe: impl FnMut(&RunObservation),
194) -> Result<RunObservation, String> {
195    wait_until(context, id, bound, cancellation, |snapshot, _| {
196        observe(snapshot);
197        snapshot.state.is_terminal()
198    })
199    .await
200}
201
202/// Wait for an update to this Run (ignoring clock-only changes), or for settlement.
203pub async fn wait_for_change(
204    context: &Context,
205    id: &RunId,
206    bound: Duration,
207    cancellation: CancellationToken,
208) -> Result<RunObservation, String> {
209    let mut initial = None;
210    wait_until(
211        context,
212        id,
213        Some(bound),
214        cancellation,
215        |snapshot, change| {
216            let signature = (snapshot.state, snapshot.counts.clone());
217            snapshot.state.is_terminal()
218                || matches!(change, Some(Change::RunInvalidated(changed)) if changed == id)
219                || initial.get_or_insert_with(|| signature.clone()) != &signature
220        },
221    )
222    .await
223}
224
225async fn wait_until(
226    context: &Context,
227    id: &RunId,
228    bound: Option<Duration>,
229    cancellation: CancellationToken,
230    mut stop: impl FnMut(&RunObservation, Option<&Change>) -> bool,
231) -> Result<RunObservation, String> {
232    if bound.is_some_and(|bound| bound.is_zero()) {
233        let snapshot = status(context, id).await?;
234        stop(&snapshot, None);
235        return Ok(snapshot);
236    }
237    let deadline = bound
238        .map(|bound| {
239            tokio::time::Instant::now()
240                .checked_add(bound)
241                .ok_or("Run observation bound is too large.")
242        })
243        .transpose()?;
244    let mut last = None;
245    let mut subscription = None;
246    let result = {
247        let observing = async {
248            let changes =
249                subscription.insert(crate::changes::Subscription::new(&context.state).await);
250            let mut change = None;
251            loop {
252                let current = status(context, id).await?;
253                let ended = stop(&current, change.as_ref());
254                last = Some(current);
255                if ended {
256                    return Ok::<(), String>(());
257                }
258                change = Some(changes.next_reconciled().await);
259            }
260        };
261        tokio::pin!(observing);
262        tokio::select! {
263            result = &mut observing => result,
264            _ = cancellation.cancelled() => Err("Run observation was cancelled.".into()),
265            _ = async { if let Some(deadline) = deadline { tokio::time::sleep_until(deadline).await; } else { std::future::pending::<()>().await; } } => Ok(()),
266        }
267    };
268    // Completion, deadline and cancellation all release this observer before returning.
269    // Otherwise CLI runtime shutdown can interrupt the detached watch's SQLite cleanup.
270    let closed = match subscription {
271        Some(changes) => changes.close().await,
272        None => Ok(()),
273    };
274    match (result, closed) {
275        (Ok(()), Ok(())) => match last {
276            Some(snapshot) => Ok(snapshot),
277            None => {
278                let snapshot = status(context, id).await?;
279                stop(&snapshot, None);
280                Ok(snapshot)
281            }
282        },
283        (Err(error), Ok(())) | (Ok(()), Err(error)) => Err(error),
284        (Err(error), Err(close)) => Err(format!(
285            "{error}; closing observation subscription: {close}"
286        )),
287    }
288}
289
290#[cfg(test)]
291mod tests;