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
128pub async fn view(context: &Context, id: &RunId) -> Result<RunView, String> {
129    let view = store::read_run(&context.state, id).await?;
130    if !crate::platform::paths_equal(&view.run.repo_path, &context.repo) {
131        return Err("Run not found in this repository.".into());
132    }
133    super::reconcile(&context.state, view).await
134}
135pub async fn status(context: &Context, id: &RunId) -> Result<RunObservation, String> {
136    const NEXT_CHECK: Duration = Duration::from_secs(30); // One ordinary bounded observation, not a polling cadence.
137    let mut saved = store::run_control::observe(&context.state, id).await?;
138    if !crate::platform::paths_equal(&saved.repo, &context.repo) {
139        return Err("Run not found in this repository.".into());
140    }
141    let owner = saved
142        .control
143        .as_ref()
144        .and_then(|control| match control.worker {
145            super::Worker::Starting { launcher } => Some(launcher),
146            super::Worker::Admitted { owner } => Some(owner),
147            super::Worker::Legacy => None,
148        });
149    if saved.status.is_open()
150        && owner.is_some()
151        && !crate::process::is_alive(owner).map_err(|e| e.to_string())?
152    {
153        view(context, id).await?;
154        saved = store::run_control::observe(&context.state, id).await?;
155    }
156    let counts = counts(saved.counts);
157    let state = state_for(saved.status, saved.control.as_ref(), &counts);
158    Ok(RunObservation {
159        run: id.clone(),
160        state,
161        counts,
162        elapsed: saved
163            .completed_at
164            .unwrap_or_else(Timestamp::now)
165            .since(saved.created_at),
166        next_check: if state.is_terminal() {
167            Duration::ZERO
168        } else {
169            NEXT_CHECK
170        },
171    })
172}
173
174/// The optional bound covers registration and all reads. At its deadline return the last
175/// authoritative snapshot; cancellation disposes only this observer, never the Run.
176pub async fn wait(
177    context: &Context,
178    id: &RunId,
179    bound: Option<Duration>,
180    cancellation: CancellationToken,
181) -> Result<RunObservation, String> {
182    wait_observing(context, id, bound, cancellation, |_| {}).await
183}
184
185/// Like [`wait`], with each successfully read snapshot available to a caller while it waits.
186pub async fn wait_observing(
187    context: &Context,
188    id: &RunId,
189    bound: Option<Duration>,
190    cancellation: CancellationToken,
191    mut observe: impl FnMut(&RunObservation),
192) -> Result<RunObservation, String> {
193    if bound.is_some_and(|bound| bound.is_zero()) {
194        let snapshot = status(context, id).await?;
195        observe(&snapshot);
196        return Ok(snapshot);
197    }
198    let deadline = bound
199        .map(|bound| {
200            tokio::time::Instant::now()
201                .checked_add(bound)
202                .ok_or("Run observation bound is too large.")
203        })
204        .transpose()?;
205    let mut last = None;
206    let mut subscription = None;
207    let result = {
208        let observing = async {
209            let changes =
210                subscription.insert(crate::changes::Subscription::new(&context.state).await);
211            loop {
212                let current = status(context, id).await?;
213                let ended = current.state.is_terminal();
214                observe(&current);
215                last = Some(current);
216                if ended {
217                    return Ok::<(), String>(());
218                }
219                changes.next_reconciled().await;
220            }
221        };
222        tokio::pin!(observing);
223        tokio::select! {
224            result = &mut observing => result,
225            _ = cancellation.cancelled() => Err("Run observation was cancelled.".into()),
226            _ = async { if let Some(deadline) = deadline { tokio::time::sleep_until(deadline).await; } else { std::future::pending::<()>().await; } } => Ok(()),
227        }
228    };
229    // Completion, deadline and cancellation all release this observer before returning.
230    // Otherwise CLI runtime shutdown can interrupt the detached watch's SQLite cleanup.
231    let closed = match subscription {
232        Some(changes) => changes.close().await,
233        None => Ok(()),
234    };
235    match (result, closed) {
236        (Ok(()), Ok(())) => {
237            last.ok_or_else(|| "State unavailable within the observation bound.".into())
238        }
239        (Err(error), Ok(())) | (Ok(()), Err(error)) => Err(error),
240        (Err(error), Err(close)) => Err(format!(
241            "{error}; closing observation subscription: {close}"
242        )),
243    }
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249    use std::path::Path;
250
251    #[tokio::test]
252    async fn an_unrepresentable_wait_bound_is_an_input_error() {
253        let scratch = crate::test_os::tempdir();
254        let context = Context::new(scratch.path(), Some(scratch.path()), Path::new("")).unwrap();
255        let error = wait(
256            &context,
257            &"run-missing".parse().unwrap(),
258            Some(Duration::MAX),
259            CancellationToken::new(),
260        )
261        .await
262        .unwrap_err();
263        assert_eq!(error, "Run observation bound is too large.");
264    }
265
266    #[test]
267    fn core_durations_keep_the_existing_integer_second_wire_values() {
268        let observed = RunObservation {
269            run: "run-wire".parse().unwrap(),
270            state: State::Running,
271            counts: Counts::default(),
272            elapsed: Duration::from_millis(1250),
273            next_check: Duration::from_secs(30),
274        };
275        let wire = serde_json::to_value(observed).unwrap();
276        assert_eq!(wire["elapsed"], 1);
277        assert_eq!(wire["next_check"], 30);
278    }
279}