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