Skip to main content

isothrum_runner/state/
transition.rs

1//! The run's state machine: every move a run can make, as a [`Transition`] whose only
2//! constructors check it against the table below, so the store can't be handed an illegal one.
3//!
4//! | Op | From | During | Success | Failure |
5//! |---|---|---|---|---|
6//! | `up` | absent, failed (ready, parked: replaced) | creating | ready | failed |
7//! | `resume` | parked | resuming | ready | failed |
8//! | `park` | ready | parking | parked | failed |
9//! | `update` | ready | updating | ready | failed |
10//! | `down` | ready, parked, failed, absent | destroying | absent | failed |
11//!
12//! A recovery moves a run caught in a moving state (its operation's process died) to `failed`,
13//! `cancelled`. An observation moves a settled run to what its machines show (never a moving
14//! one: an operation owns it). `check`, `provision`, `attach`, `detach` and `retire` don't move
15//! the run.
16
17use std::fmt;
18
19use serde::{Deserialize, Serialize};
20
21use super::{Op, RunState};
22use crate::error::ErrorCode;
23use crate::store::OperationId;
24
25/// What a user wants of a run: set by the commands, never by an observation.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
27#[serde(rename_all = "snake_case")]
28#[non_exhaustive]
29pub enum Desired {
30    /// Up and ready.
31    Running,
32    /// Parked: stopped, what it created kept.
33    Parked,
34    /// Nothing of it left.
35    Gone,
36}
37
38impl Desired {
39    /// What a successful `op` leaves the user wanting; None for an op that doesn't change it.
40    #[must_use]
41    pub fn after(op: Op) -> Option<Desired> {
42        match op {
43            Op::Up | Op::Resume => Some(Desired::Running),
44            Op::Park => Some(Desired::Parked),
45            Op::Down => Some(Desired::Gone),
46            Op::Check | Op::Provision | Op::Attach | Op::Detach | Op::Update | Op::Retire | Op::Package => None,
47        }
48    }
49
50    /// The settled state that meets this wish.
51    #[must_use]
52    pub fn met_by(self) -> RunState {
53        match self {
54            Desired::Running => RunState::Ready,
55            Desired::Parked => RunState::Parked,
56            Desired::Gone => RunState::Absent,
57        }
58    }
59
60    /// The word as written in the store and the events (`running`).
61    #[must_use]
62    pub fn as_str(self) -> &'static str {
63        match self {
64            Desired::Running => "running",
65            Desired::Parked => "parked",
66            Desired::Gone => "gone",
67        }
68    }
69}
70
71impl fmt::Display for Desired {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.write_str(self.as_str())
74    }
75}
76
77/// What moved a run.
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
79#[serde(tag = "by", rename_all = "snake_case")]
80#[non_exhaustive]
81pub enum Cause {
82    /// An operation, by its journal id.
83    Operation {
84        /// The operation's id.
85        id: OperationId,
86        /// What it is.
87        op: Op,
88    },
89    /// A status read: what the engine showed.
90    Observation,
91    /// The operation `id`, finding the run left moving by an operation whose process died.
92    Recovery {
93        /// The recovering operation's id.
94        id: OperationId,
95    },
96}
97
98impl Cause {
99    /// The operation behind the move, if one is.
100    #[must_use]
101    pub fn operation(self) -> Option<OperationId> {
102        match self {
103            Cause::Operation { id, .. } | Cause::Recovery { id } => Some(id),
104            Cause::Observation => None,
105        }
106    }
107}
108
109/// A move the table doesn't allow.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
111#[error("a run {from} can't {what}")]
112pub struct IllegalTransition {
113    /// Where the run stood.
114    pub from: RunState,
115    /// What was asked (`be parked`, `become ready by an observation`).
116    pub what: &'static str,
117}
118
119/// A legal move of a run, from one state to another, with what moved it. Its fields are
120/// private: the constructors are the only way to one, and each checks the move.
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub struct Transition {
123    from: RunState,
124    to: RunState,
125    cause: Option<ErrorCode>,
126    by: Cause,
127}
128
129/// The states `op` may begin from, and what asking it is called in an [`IllegalTransition`].
130fn begins_from(op: Op) -> (&'static [RunState], &'static str) {
131    use RunState::{Absent, Failed, Parked, Ready};
132    match op {
133        // A replacing `up` (or one over a failed start) removes what is there first: the op's own
134        // checks refuse a running run (`already_running`), not the table.
135        Op::Up => (&[Absent, Failed, Ready, Parked], "be brought up"),
136        // A resume also brings back a run whose machines were stopped outside the runner (failed),
137        // or starts again what of a ready run is stopped.
138        Op::Resume => (&[Parked, Failed, Ready], "be resumed"),
139        Op::Park => (&[Ready], "be parked"),
140        Op::Update => (&[Ready], "be updated"),
141        Op::Down => (&[Ready, Parked, Failed, Absent], "be brought down"),
142        Op::Check | Op::Provision | Op::Attach | Op::Detach | Op::Retire | Op::Package => (&[], "be moved by this operation"),
143    }
144}
145
146/// Whether an observation may move a settled run from `from` to `to`.
147fn observable(from: RunState, to: RunState) -> bool {
148    use RunState::{Absent, Failed, Parked, Ready};
149    matches!(
150        (from, to),
151        (Ready, Failed | Absent | Parked) | (Failed, Ready | Absent) | (Parked, Ready | Absent | Failed)
152    )
153}
154
155impl Transition {
156    /// Operation `op` (journal id `id`) begins acting on a run in `from`: the run moves to the
157    /// state the op holds it in.
158    ///
159    /// # Errors
160    ///
161    /// The table has no such move: the op doesn't move a run, or not from `from`.
162    pub fn begin(from: RunState, op: Op, id: OperationId) -> Result<Transition, IllegalTransition> {
163        let (allowed, what) = begins_from(op);
164        match op.during() {
165            Some(to) if allowed.contains(&from) => Ok(Transition {
166                from,
167                to,
168                cause: None,
169                by: Cause::Operation { id, op },
170            }),
171            _ => Err(IllegalTransition { from, what }),
172        }
173    }
174
175    /// The operation that made `begun` reached its goal: the run settles where the op leaves it.
176    #[must_use]
177    pub fn succeed(begun: Transition) -> Transition {
178        let to = match begun.to {
179            RunState::Parking => RunState::Parked,
180            RunState::Destroying => RunState::Absent,
181            // Creating, Resuming, Updating: and nothing else is a `begin`'s target.
182            _ => RunState::Ready,
183        };
184        Transition {
185            from: begun.to,
186            to,
187            cause: None,
188            by: begun.by,
189        }
190    }
191
192    /// The operation that made `begun` was refused before anything acted on the run: it stands
193    /// where it stood before.
194    #[must_use]
195    pub fn undone(begun: Transition) -> Transition {
196        Transition {
197            from: begun.to,
198            to: begun.from,
199            cause: None,
200            by: begun.by,
201        }
202    }
203
204    /// The operation that made `begun` failed with `cause` (`cancelled` when cut short).
205    #[must_use]
206    pub fn fail(begun: Transition, cause: ErrorCode) -> Transition {
207        Transition {
208            from: begun.to,
209            to: RunState::Failed,
210            cause: Some(cause),
211            by: begun.by,
212        }
213    }
214
215    /// Operation `id` found the run in `from`, a moving state whose operation's process died: it
216    /// failed, `cancelled`.
217    ///
218    /// # Errors
219    ///
220    /// `from` isn't a moving state.
221    pub fn cut_off(from: RunState, id: OperationId) -> Result<Transition, IllegalTransition> {
222        if !from.is_moving() {
223            return Err(IllegalTransition {
224                from,
225                what: "be recovered (it isn't moving)",
226            });
227        }
228        Ok(Transition {
229            from,
230            to: RunState::Failed,
231            cause: Some(ErrorCode::Cancelled),
232            by: Cause::Recovery { id },
233        })
234    }
235
236    /// A status read found a settled run in `from` to be `to` (a VM stopped outside the runner:
237    /// failed; everything gone: absent). A move to `failed` is `not_ready`.
238    ///
239    /// # Errors
240    ///
241    /// The move isn't one an observation makes (`from` is moving, or the pair isn't in the table).
242    pub fn observed(from: RunState, to: RunState) -> Result<Transition, IllegalTransition> {
243        if !observable(from, to) {
244            return Err(IllegalTransition {
245                from,
246                what: "be moved there by an observation",
247            });
248        }
249        Ok(Transition {
250            from,
251            to,
252            cause: (to == RunState::Failed).then_some(ErrorCode::NotReady),
253            by: Cause::Observation,
254        })
255    }
256
257    /// A deployment made outside the runner is taken over as a run that is up, from a run an
258    /// earlier `down` left absent.
259    ///
260    /// # Errors
261    ///
262    /// `from` isn't `absent`: something of the run is there already.
263    pub fn adopted(from: RunState) -> Result<Transition, IllegalTransition> {
264        if from != RunState::Absent {
265            return Err(IllegalTransition {
266                from,
267                what: "take a deployment over",
268            });
269        }
270        Ok(Transition {
271            from,
272            to: RunState::Ready,
273            cause: None,
274            by: Cause::Observation,
275        })
276    }
277
278    /// Where the run stood.
279    #[must_use]
280    pub fn from(&self) -> RunState {
281        self.from
282    }
283
284    /// Where it stands after.
285    #[must_use]
286    pub fn to(&self) -> RunState {
287        self.to
288    }
289
290    /// Why it failed, for a move to `failed`.
291    #[must_use]
292    pub fn cause(&self) -> Option<ErrorCode> {
293        self.cause
294    }
295
296    /// What moved it.
297    #[must_use]
298    pub fn by(&self) -> Cause {
299        self.by
300    }
301}
302
303#[cfg(test)]
304mod tests {
305    use super::*;
306
307    const OP: OperationId = OperationId(7);
308
309    fn every_state() -> Vec<RunState> {
310        crate::testing::every_variant::<RunState>()
311    }
312
313    #[test]
314    fn an_illegal_transition_is_refused() {
315        for (from, op) in [
316            (RunState::Parked, Op::Park),
317            (RunState::Absent, Op::Resume),
318            (RunState::Absent, Op::Update),
319            (RunState::Creating, Op::Up),
320            (RunState::Creating, Op::Down),
321            (RunState::Ready, Op::Check),
322        ] {
323            let refused = Transition::begin(from, op, OP).unwrap_err();
324            assert_eq!(refused.from, from, "{op}");
325        }
326        let settled = Transition::cut_off(RunState::Ready, OP).unwrap_err();
327        assert_eq!((settled.from, settled.what), (RunState::Ready, "be recovered (it isn't moving)"));
328        for from in [RunState::Creating, RunState::Absent] {
329            let refused = Transition::observed(from, RunState::Ready).unwrap_err();
330            assert_eq!((refused.from, refused.what), (from, "be moved there by an observation"), "a moving or gone run");
331        }
332        assert_eq!(
333            Transition::begin(RunState::Parked, Op::Park, OP).unwrap_err().to_string(),
334            "a run parked can't be parked"
335        );
336    }
337
338    #[test]
339    fn each_op_moves_through_its_state_to_its_goal_or_to_failed() {
340        let cases = [
341            (RunState::Absent, Op::Up, RunState::Creating, RunState::Ready),
342            (RunState::Failed, Op::Up, RunState::Creating, RunState::Ready),
343            (RunState::Parked, Op::Resume, RunState::Resuming, RunState::Ready),
344            (RunState::Ready, Op::Park, RunState::Parking, RunState::Parked),
345            (RunState::Ready, Op::Update, RunState::Updating, RunState::Ready),
346            (RunState::Parked, Op::Down, RunState::Destroying, RunState::Absent),
347        ];
348        for (from, op, during, goal) in cases {
349            let begun = Transition::begin(from, op, OP).unwrap();
350            assert_eq!((begun.from(), begun.to()), (from, during), "{op}");
351            assert_eq!(begun.by(), Cause::Operation { id: OP, op });
352            let ok = Transition::succeed(begun);
353            assert_eq!((ok.from(), ok.to(), ok.cause()), (during, goal, None), "{op}");
354            let failed = Transition::fail(begun, ErrorCode::Timeout);
355            assert_eq!((failed.to(), failed.cause()), (RunState::Failed, Some(ErrorCode::Timeout)), "{op}");
356        }
357    }
358
359    #[test]
360    fn every_moving_state_is_recovered_to_failed_cancelled_and_nothing_else_is() {
361        for from in every_state() {
362            match Transition::cut_off(from, OP) {
363                Ok(t) => {
364                    assert!(from.is_moving());
365                    assert_eq!(
366                        (t.to(), t.cause(), t.by()),
367                        (RunState::Failed, Some(ErrorCode::Cancelled), Cause::Recovery { id: OP })
368                    );
369                }
370                Err(_) => assert!(!from.is_moving(), "{from}"),
371            }
372        }
373    }
374
375    #[test]
376    fn the_wish_after_each_op_is_met_by_its_goal() {
377        assert_eq!(Desired::after(Op::Up).map(Desired::met_by), Some(RunState::Ready));
378        assert_eq!(Desired::after(Op::Park).map(Desired::met_by), Some(RunState::Parked));
379        assert_eq!(Desired::after(Op::Down).map(Desired::met_by), Some(RunState::Absent));
380        assert_eq!(Desired::after(Op::Check), None);
381        crate::testing::assert_named_as_serde(Desired::as_str);
382    }
383}