Skip to main content

artifactize_core/store/
lifecycle.rs

1//! Payload-carrying lifecycle states; the legacy flat JSON is parsed at the edge.
2
3use super::ExecutionResult;
4use crate::types::{ExecutionStatus, FailureCode, RequestStatus, RunStatus, Timestamp};
5
6/// Non-active, non-verdict request states historically allow an optional completion time.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum PendingRequest {
9    Blocked,
10    BudgetExhausted,
11    Stale,
12    Unreviewed,
13    WaitDependency,
14}
15
16#[derive(Debug, Clone)]
17pub enum ExecutionState {
18    Running,
19    WaitingHuman,
20    Completed {
21        result: ExecutionResult,
22        at: Timestamp,
23    },
24    Failed {
25        error: String,
26        code: Option<FailureCode>,
27        at: Timestamp,
28    },
29}
30
31/// Evidence that has passed its criteria, while a dependency sign-off is still pending.
32/// The private payload keeps a RED result out of the public provisional state.
33#[derive(Debug, Clone, PartialEq)]
34pub struct GreenResult(ExecutionResult);
35
36impl TryFrom<ExecutionResult> for GreenResult {
37    type Error = String;
38    fn try_from(result: ExecutionResult) -> Result<Self, Self::Error> {
39        if result.verdict() != crate::runtime::Verdict::Green {
40            return Err("A provisional request requires GREEN evidence.".into());
41        }
42        Ok(Self(result))
43    }
44}
45impl AsRef<ExecutionResult> for GreenResult {
46    fn as_ref(&self) -> &ExecutionResult {
47        &self.0
48    }
49}
50impl From<GreenResult> for ExecutionResult {
51    fn from(result: GreenResult) -> Self {
52        result.0
53    }
54}
55
56#[derive(Debug, Clone)]
57pub enum RequestState {
58    Queued {
59        at: Option<Timestamp>,
60        reason: Option<super::QueueReason>,
61    },
62    Running,
63    WaitingHuman,
64    Deferred,
65    Provisional {
66        result: GreenResult,
67        at: Timestamp,
68    },
69    Pending {
70        kind: PendingRequest,
71        at: Option<Timestamp>,
72    },
73    Completed {
74        result: ExecutionResult,
75        at: Timestamp,
76    },
77    Failed {
78        error: String,
79        code: Option<FailureCode>,
80        at: Timestamp,
81    },
82}
83
84impl RequestState {
85    /// Construct a pending state without inventing result or error data.
86    pub fn pending(status: RequestStatus, at: Option<Timestamp>) -> Result<Self, String> {
87        Self::from_parts(status, None, None, None, at)
88    }
89
90    pub fn completed(result: ExecutionResult, at: Timestamp) -> Self {
91        Self::Completed { result, at }
92    }
93
94    pub fn failed(error: String, code: Option<FailureCode>, at: Timestamp) -> Self {
95        Self::Failed { error, code, at }
96    }
97
98    pub(super) fn from_parts(
99        status: RequestStatus,
100        result: Option<ExecutionResult>,
101        error: Option<String>,
102        code: Option<FailureCode>,
103        at: Option<Timestamp>,
104    ) -> Result<Self, String> {
105        super::validation::result(
106            status,
107            result.as_ref(),
108            error.as_deref(),
109            code.map(FailureCode::as_str),
110        )?;
111        match status {
112            RequestStatus::Provisional => Ok(Self::Provisional {
113                result: result.expect("validated provisional GREEN").try_into()?,
114                at: at.ok_or("A provisional request needs its completion time.")?,
115            }),
116            RequestStatus::Green | RequestStatus::Red => Ok(Self::Completed {
117                result: result.expect("validated verdict"),
118                at: at.ok_or("A finished request needs its completion time.")?,
119            }),
120            RequestStatus::Error => Ok(Self::Failed {
121                error: error.expect("validated error"),
122                code,
123                at: at.ok_or("A finished request needs its completion time.")?,
124            }),
125            RequestStatus::Running | RequestStatus::WaitingHuman | RequestStatus::Deferred
126                if at.is_some() =>
127            {
128                Err("An active request cannot have a completion time.".into())
129            }
130            RequestStatus::Running => Ok(Self::Running),
131            RequestStatus::WaitingHuman => Ok(Self::WaitingHuman),
132            RequestStatus::Deferred => Ok(Self::Deferred),
133            RequestStatus::Queued => Ok(Self::Queued { at, reason: None }),
134            _ => Ok(Self::Pending {
135                kind: match status {
136                    RequestStatus::Blocked => PendingRequest::Blocked,
137                    RequestStatus::BudgetExhausted => PendingRequest::BudgetExhausted,
138                    RequestStatus::Stale => PendingRequest::Stale,
139                    RequestStatus::Unreviewed => PendingRequest::Unreviewed,
140                    RequestStatus::WaitDependency => PendingRequest::WaitDependency,
141                    _ => unreachable!("terminal and active states handled above"),
142                },
143                at,
144            }),
145        }
146    }
147
148    pub fn queue_reason(&self) -> Option<&super::QueueReason> {
149        match self {
150            Self::Queued { reason, .. } => reason.as_ref(),
151            _ => None,
152        }
153    }
154
155    pub fn status(&self) -> RequestStatus {
156        match self {
157            Self::Queued { .. } => RequestStatus::Queued,
158            Self::Running => RequestStatus::Running,
159            Self::WaitingHuman => RequestStatus::WaitingHuman,
160            Self::Deferred => RequestStatus::Deferred,
161            Self::Provisional { .. } => RequestStatus::Provisional,
162            Self::Completed { result, .. } => match result.verdict() {
163                crate::runtime::Verdict::Green => RequestStatus::Green,
164                crate::runtime::Verdict::Red => RequestStatus::Red,
165            },
166            Self::Failed { .. } => RequestStatus::Error,
167            Self::Pending { kind, .. } => match kind {
168                PendingRequest::Blocked => RequestStatus::Blocked,
169                PendingRequest::BudgetExhausted => RequestStatus::BudgetExhausted,
170                PendingRequest::Stale => RequestStatus::Stale,
171                PendingRequest::Unreviewed => RequestStatus::Unreviewed,
172                PendingRequest::WaitDependency => RequestStatus::WaitDependency,
173            },
174        }
175    }
176    pub fn result(&self) -> Option<&ExecutionResult> {
177        match self {
178            Self::Completed { result, .. } => Some(result),
179            Self::Provisional { result, .. } => Some(result.as_ref()),
180            _ => None,
181        }
182    }
183    pub fn error(&self) -> Option<&str> {
184        match self {
185            Self::Failed { error, .. } => Some(error),
186            _ => None,
187        }
188    }
189    pub fn error_code(&self) -> Option<FailureCode> {
190        match self {
191            Self::Failed { code, .. } => *code,
192            _ => None,
193        }
194    }
195    pub fn completed_at(&self) -> Option<Timestamp> {
196        match self {
197            Self::Completed { at, .. } | Self::Provisional { at, .. } | Self::Failed { at, .. } => {
198                Some(*at)
199            }
200            Self::Pending { at, .. } | Self::Queued { at, .. } => *at,
201            _ => None,
202        }
203    }
204}
205
206impl ExecutionState {
207    pub(super) fn from_parts(
208        status: ExecutionStatus,
209        result: Option<ExecutionResult>,
210        error: Option<String>,
211        code: Option<FailureCode>,
212        at: Option<Timestamp>,
213    ) -> Result<Self, String> {
214        let state = RequestState::from_parts(status.into(), result, error, code, at)?;
215        Self::try_from(state)
216    }
217    pub fn status(&self) -> ExecutionStatus {
218        match self {
219            Self::Running => ExecutionStatus::Running,
220            Self::WaitingHuman => ExecutionStatus::WaitingHuman,
221            Self::Completed { result, .. } => match result.verdict() {
222                crate::runtime::Verdict::Green => ExecutionStatus::Green,
223                crate::runtime::Verdict::Red => ExecutionStatus::Red,
224            },
225            Self::Failed { .. } => ExecutionStatus::Error,
226        }
227    }
228    pub fn result(&self) -> Option<&ExecutionResult> {
229        match self {
230            Self::Completed { result, .. } => Some(result),
231            _ => None,
232        }
233    }
234    pub fn error(&self) -> Option<&str> {
235        match self {
236            Self::Failed { error, .. } => Some(error),
237            _ => None,
238        }
239    }
240    pub fn error_code(&self) -> Option<FailureCode> {
241        match self {
242            Self::Failed { code, .. } => *code,
243            _ => None,
244        }
245    }
246    pub fn completed_at(&self) -> Option<Timestamp> {
247        match self {
248            Self::Completed { at, .. } | Self::Failed { at, .. } => Some(*at),
249            _ => None,
250        }
251    }
252}
253impl TryFrom<RequestState> for ExecutionState {
254    type Error = String;
255    fn try_from(state: RequestState) -> Result<Self, String> {
256        match state {
257            RequestState::Running => Ok(Self::Running),
258            RequestState::WaitingHuman | RequestState::Deferred => Ok(Self::WaitingHuman),
259            RequestState::Provisional { result, at } => Ok(Self::Completed {
260                result: result.into(),
261                at,
262            }),
263            RequestState::Completed { result, at } => Ok(Self::Completed { result, at }),
264            RequestState::Failed { error, code, at } => Ok(Self::Failed { error, code, at }),
265            RequestState::Pending { .. } | RequestState::Queued { .. } => {
266                Err("A pending request has no execution lifecycle state.".into())
267            }
268        }
269    }
270}
271impl From<ExecutionState> for RequestState {
272    fn from(state: ExecutionState) -> Self {
273        match state {
274            ExecutionState::Running => Self::Running,
275            ExecutionState::WaitingHuman => Self::WaitingHuman,
276            ExecutionState::Completed { result, at } => Self::Completed { result, at },
277            ExecutionState::Failed { error, code, at } => Self::Failed { error, code, at },
278        }
279    }
280}
281
282/// Run completion data exists only in a finished lifecycle state.
283#[derive(Debug, Clone)]
284pub enum RunState {
285    Running,
286    /// Still open with a sign-off request unsubmitted. Readers derive it from the Run's
287    /// requests ([`RunStatus::with_signoffs`]); it is never saved, and an open Run is saved
288    /// RUNNING. The Run ends once nothing but unclaimed sign-offs is left for its idle grace.
289    WaitingHuman,
290    /// Ended with every result but its sign-offs GREEN and a sign-off unsubmitted.
291    Yellow {
292        at: Timestamp,
293    },
294    Green {
295        at: Timestamp,
296    },
297    Red {
298        at: Timestamp,
299    },
300    Error {
301        at: Timestamp,
302        error: Option<String>,
303    },
304    Incomplete {
305        at: Timestamp,
306        error: Option<String>,
307    },
308}
309
310impl RunState {
311    pub(super) fn from_parts(
312        status: RunStatus,
313        at: Option<Timestamp>,
314        error: Option<String>,
315    ) -> Result<Self, String> {
316        match status {
317            RunStatus::Running | RunStatus::WaitingHuman if at.is_some() || error.is_some() => {
318                Err("An open Run cannot be completed or carry an error.".into())
319            }
320            RunStatus::Running => Ok(Self::Running),
321            RunStatus::WaitingHuman => Ok(Self::WaitingHuman),
322            RunStatus::Green | RunStatus::Red | RunStatus::Yellow
323                if error.is_some() || at.is_none() =>
324            {
325                Err(
326                    "A completed verdict Run needs a completion time and cannot carry an error."
327                        .into(),
328                )
329            }
330            RunStatus::Yellow => Ok(Self::Yellow {
331                at: at.expect("validated completion time"),
332            }),
333            RunStatus::Green => Ok(Self::Green {
334                at: at.expect("validated completion time"),
335            }),
336            RunStatus::Red => Ok(Self::Red {
337                at: at.expect("validated completion time"),
338            }),
339            RunStatus::Error => Ok(Self::Error {
340                at: at.ok_or("A finished Run needs its completion time.")?,
341                error,
342            }),
343            RunStatus::Incomplete => Ok(Self::Incomplete {
344                at: at.ok_or("A finished Run needs its completion time.")?,
345                error,
346            }),
347        }
348    }
349    pub fn status(&self) -> RunStatus {
350        match self {
351            Self::Running => RunStatus::Running,
352            Self::WaitingHuman => RunStatus::WaitingHuman,
353            Self::Yellow { .. } => RunStatus::Yellow,
354            Self::Green { .. } => RunStatus::Green,
355            Self::Red { .. } => RunStatus::Red,
356            Self::Error { .. } => RunStatus::Error,
357            Self::Incomplete { .. } => RunStatus::Incomplete,
358        }
359    }
360    /// The state readers show while `signoff_open` says whether a sign-off request of the Run
361    /// is unsubmitted; an ended Run keeps its own.
362    pub fn with_signoffs(self, signoff_open: bool) -> Self {
363        match self.status().with_signoffs(signoff_open) {
364            RunStatus::WaitingHuman => Self::WaitingHuman,
365            RunStatus::Running => Self::Running,
366            _ => self,
367        }
368    }
369    pub fn completed_at(&self) -> Option<Timestamp> {
370        match self {
371            Self::Running | Self::WaitingHuman => None,
372            Self::Yellow { at }
373            | Self::Green { at }
374            | Self::Red { at }
375            | Self::Error { at, .. }
376            | Self::Incomplete { at, .. } => Some(*at),
377        }
378    }
379    pub fn error(&self) -> Option<&str> {
380        match self {
381            Self::Error { error, .. } | Self::Incomplete { error, .. } => error.as_deref(),
382            _ => None,
383        }
384    }
385}
386
387#[cfg(test)]
388mod tests {
389    use super::*;
390    use serde_json::json;
391
392    #[test]
393    fn provisional_constructor_rejects_red_and_preserves_green_evidence_when_promoted() {
394        let red = ExecutionResult::try_from(json!({"verdict":"RED","reason":"failed"})).unwrap();
395        assert!(GreenResult::try_from(red).is_err());
396        let expected = json!({"verdict":"GREEN","summary":"criteria met"});
397        let green = ExecutionResult::try_from(expected.clone()).unwrap();
398        let provisional = RequestState::Provisional {
399            result: green.try_into().unwrap(),
400            at: "2026-01-01T00:00:00Z".parse().unwrap(),
401        };
402        assert_eq!(provisional.status(), RequestStatus::Provisional);
403        assert_eq!(provisional.result().unwrap().to_json(), expected);
404        let execution = ExecutionState::try_from(provisional).unwrap();
405        assert_eq!(execution.status(), ExecutionStatus::Green);
406        assert_eq!(execution.result().unwrap().to_json(), expected);
407    }
408}