1use 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 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
64pub(super) fn 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); let saved = read(context, id, false).await?;
139 let counts = counts(saved.counts);
140 let state = state_for(saved.status, saved.control.as_ref(), &counts);
141 Ok(RunObservation {
142 run: id.clone(),
143 state,
144 counts,
145 elapsed: saved
146 .completed_at
147 .unwrap_or_else(Timestamp::now)
148 .since(saved.created_at),
149 next_check: if state.is_terminal() {
150 Duration::ZERO
151 } else {
152 NEXT_CHECK
153 },
154 })
155}
156
157pub(super) async fn read(
158 context: &Context,
159 id: &RunId,
160 errors: bool,
161) -> Result<store::run_control::Observation, String> {
162 let mut saved = store::run_control::observe_with_errors(&context.state, id, errors).await?;
163 if !crate::platform::paths_equal(&saved.repo, &context.repo) {
164 return Err("Run not found in this repository.".into());
165 }
166 if super::owner_died(saved.status, saved.control.as_ref())? {
167 view(context, id).await?;
168 saved = store::run_control::observe_with_errors(&context.state, id, errors).await?;
169 }
170 Ok(saved)
171}
172
173pub async fn reconcile_interrupted(state: &std::path::Path, id: &RunId) -> Result<bool, String> {
176 let saved = store::run_control::observe(state, id).await?;
177 if !super::owner_died(saved.status, saved.control.as_ref())? {
178 return Ok(false);
179 }
180 let settled = super::reconcile(state, store::read_run(state, id).await?).await?;
181 Ok(!settled.run.status().is_open())
182}
183
184pub async fn wait(
188 context: &Context,
189 id: &RunId,
190 bound: Option<Duration>,
191 cancellation: CancellationToken,
192) -> Result<RunObservation, String> {
193 wait_observing(context, id, bound, cancellation, |_| {}).await
194}
195
196pub async fn wait_observing(
198 context: &Context,
199 id: &RunId,
200 bound: Option<Duration>,
201 cancellation: CancellationToken,
202 mut observe: impl FnMut(&RunObservation),
203) -> Result<RunObservation, String> {
204 wait_until(context, id, bound, cancellation, status, |snapshot, _| {
205 observe(snapshot);
206 snapshot.state.is_terminal()
207 })
208 .await
209}
210
211pub async fn wait_for_change(
213 context: &Context,
214 id: &RunId,
215 bound: Duration,
216 cancellation: CancellationToken,
217) -> Result<RunObservation, String> {
218 let mut initial = None;
219 wait_until(
220 context,
221 id,
222 Some(bound),
223 cancellation,
224 status,
225 |snapshot, change| {
226 let signature = (snapshot.state, snapshot.counts.clone());
227 snapshot.state.is_terminal()
228 || matches!(change, Some(Change::RunInvalidated(changed)) if changed == id)
229 || initial.get_or_insert_with(|| signature.clone()) != &signature
230 },
231 )
232 .await
233}
234
235pub(super) async fn wait_until<T>(
236 context: &Context,
237 id: &RunId,
238 bound: Option<Duration>,
239 cancellation: CancellationToken,
240 read: impl AsyncFn(&Context, &RunId) -> Result<T, String>,
241 mut stop: impl FnMut(&T, Option<&Change>) -> bool,
242) -> Result<T, String> {
243 if bound.is_some_and(|bound| bound.is_zero()) {
244 let snapshot = read(context, id).await?;
245 stop(&snapshot, None);
246 return Ok(snapshot);
247 }
248 let deadline = bound
249 .map(|bound| {
250 tokio::time::Instant::now()
251 .checked_add(bound)
252 .ok_or("Run observation bound is too large.")
253 })
254 .transpose()?;
255 let mut last = None;
256 let mut subscription = None;
257 let result = {
258 let observing = async {
259 let changes =
260 subscription.insert(crate::changes::Subscription::new(&context.state).await);
261 let mut change = None;
262 loop {
263 let current = read(context, id).await?;
264 let ended = stop(¤t, change.as_ref());
265 last = Some(current);
266 if ended {
267 return Ok::<(), String>(());
268 }
269 change = Some(changes.next_reconciled().await);
270 }
271 };
272 tokio::pin!(observing);
273 tokio::select! {
274 result = &mut observing => result,
275 _ = cancellation.cancelled() => Err("Run observation was cancelled.".into()),
276 _ = async { if let Some(deadline) = deadline { tokio::time::sleep_until(deadline).await; } else { std::future::pending::<()>().await; } } => Ok(()),
277 }
278 };
279 let closed = match subscription {
282 Some(changes) => changes.close().await,
283 None => Ok(()),
284 };
285 match (result, closed) {
286 (Ok(()), Ok(())) => match last {
287 Some(snapshot) => Ok(snapshot),
288 None => {
289 let snapshot = read(context, id).await?;
290 stop(&snapshot, None);
291 Ok(snapshot)
292 }
293 },
294 (Err(error), Ok(())) | (Ok(()), Err(error)) => Err(error),
295 (Err(error), Err(close)) => Err(format!(
296 "{error}; closing observation subscription: {close}"
297 )),
298 }
299}
300
301#[cfg(test)]
302mod tests;