use std::fmt;
use serde::{Deserialize, Serialize};
use super::{Op, RunState};
use crate::error::ErrorCode;
use crate::store::OperationId;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Desired {
Running,
Parked,
Gone,
}
impl Desired {
#[must_use]
pub fn after(op: Op) -> Option<Desired> {
match op {
Op::Up | Op::Resume => Some(Desired::Running),
Op::Park => Some(Desired::Parked),
Op::Down => Some(Desired::Gone),
Op::Check | Op::Provision | Op::Attach | Op::Detach | Op::Update | Op::Retire | Op::Package => None,
}
}
#[must_use]
pub fn met_by(self) -> RunState {
match self {
Desired::Running => RunState::Ready,
Desired::Parked => RunState::Parked,
Desired::Gone => RunState::Absent,
}
}
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Desired::Running => "running",
Desired::Parked => "parked",
Desired::Gone => "gone",
}
}
}
impl fmt::Display for Desired {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(tag = "by", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Cause {
Operation {
id: OperationId,
op: Op,
},
Observation,
Recovery {
id: OperationId,
},
}
impl Cause {
#[must_use]
pub fn operation(self) -> Option<OperationId> {
match self {
Cause::Operation { id, .. } | Cause::Recovery { id } => Some(id),
Cause::Observation => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("a run {from} can't {what}")]
pub struct IllegalTransition {
pub from: RunState,
pub what: &'static str,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Transition {
from: RunState,
to: RunState,
cause: Option<ErrorCode>,
by: Cause,
}
fn begins_from(op: Op) -> (&'static [RunState], &'static str) {
use RunState::{Absent, Failed, Parked, Ready};
match op {
Op::Up => (&[Absent, Failed, Ready, Parked], "be brought up"),
Op::Resume => (&[Parked, Failed, Ready], "be resumed"),
Op::Park => (&[Ready], "be parked"),
Op::Update => (&[Ready], "be updated"),
Op::Down => (&[Ready, Parked, Failed, Absent], "be brought down"),
Op::Check | Op::Provision | Op::Attach | Op::Detach | Op::Retire | Op::Package => (&[], "be moved by this operation"),
}
}
fn observable(from: RunState, to: RunState) -> bool {
use RunState::{Absent, Failed, Parked, Ready};
matches!(
(from, to),
(Ready, Failed | Absent | Parked) | (Failed, Ready | Absent) | (Parked, Ready | Absent | Failed)
)
}
impl Transition {
pub fn begin(from: RunState, op: Op, id: OperationId) -> Result<Transition, IllegalTransition> {
let (allowed, what) = begins_from(op);
match op.during() {
Some(to) if allowed.contains(&from) => Ok(Transition {
from,
to,
cause: None,
by: Cause::Operation { id, op },
}),
_ => Err(IllegalTransition { from, what }),
}
}
#[must_use]
pub fn succeed(begun: Transition) -> Transition {
let to = match begun.to {
RunState::Parking => RunState::Parked,
RunState::Destroying => RunState::Absent,
_ => RunState::Ready,
};
Transition {
from: begun.to,
to,
cause: None,
by: begun.by,
}
}
#[must_use]
pub fn undone(begun: Transition) -> Transition {
Transition {
from: begun.to,
to: begun.from,
cause: None,
by: begun.by,
}
}
#[must_use]
pub fn fail(begun: Transition, cause: ErrorCode) -> Transition {
Transition {
from: begun.to,
to: RunState::Failed,
cause: Some(cause),
by: begun.by,
}
}
pub fn cut_off(from: RunState, id: OperationId) -> Result<Transition, IllegalTransition> {
if !from.is_moving() {
return Err(IllegalTransition {
from,
what: "be recovered (it isn't moving)",
});
}
Ok(Transition {
from,
to: RunState::Failed,
cause: Some(ErrorCode::Cancelled),
by: Cause::Recovery { id },
})
}
pub fn observed(from: RunState, to: RunState) -> Result<Transition, IllegalTransition> {
if !observable(from, to) {
return Err(IllegalTransition {
from,
what: "be moved there by an observation",
});
}
Ok(Transition {
from,
to,
cause: (to == RunState::Failed).then_some(ErrorCode::NotReady),
by: Cause::Observation,
})
}
pub fn adopted(from: RunState) -> Result<Transition, IllegalTransition> {
if from != RunState::Absent {
return Err(IllegalTransition {
from,
what: "take a deployment over",
});
}
Ok(Transition {
from,
to: RunState::Ready,
cause: None,
by: Cause::Observation,
})
}
#[must_use]
pub fn from(&self) -> RunState {
self.from
}
#[must_use]
pub fn to(&self) -> RunState {
self.to
}
#[must_use]
pub fn cause(&self) -> Option<ErrorCode> {
self.cause
}
#[must_use]
pub fn by(&self) -> Cause {
self.by
}
}
#[cfg(test)]
mod tests {
use super::*;
const OP: OperationId = OperationId(7);
fn every_state() -> Vec<RunState> {
crate::testing::every_variant::<RunState>()
}
#[test]
fn an_illegal_transition_is_refused() {
for (from, op) in [
(RunState::Parked, Op::Park),
(RunState::Absent, Op::Resume),
(RunState::Absent, Op::Update),
(RunState::Creating, Op::Up),
(RunState::Creating, Op::Down),
(RunState::Ready, Op::Check),
] {
let refused = Transition::begin(from, op, OP).unwrap_err();
assert_eq!(refused.from, from, "{op}");
}
let settled = Transition::cut_off(RunState::Ready, OP).unwrap_err();
assert_eq!((settled.from, settled.what), (RunState::Ready, "be recovered (it isn't moving)"));
for from in [RunState::Creating, RunState::Absent] {
let refused = Transition::observed(from, RunState::Ready).unwrap_err();
assert_eq!((refused.from, refused.what), (from, "be moved there by an observation"), "a moving or gone run");
}
assert_eq!(
Transition::begin(RunState::Parked, Op::Park, OP).unwrap_err().to_string(),
"a run parked can't be parked"
);
}
#[test]
fn each_op_moves_through_its_state_to_its_goal_or_to_failed() {
let cases = [
(RunState::Absent, Op::Up, RunState::Creating, RunState::Ready),
(RunState::Failed, Op::Up, RunState::Creating, RunState::Ready),
(RunState::Parked, Op::Resume, RunState::Resuming, RunState::Ready),
(RunState::Ready, Op::Park, RunState::Parking, RunState::Parked),
(RunState::Ready, Op::Update, RunState::Updating, RunState::Ready),
(RunState::Parked, Op::Down, RunState::Destroying, RunState::Absent),
];
for (from, op, during, goal) in cases {
let begun = Transition::begin(from, op, OP).unwrap();
assert_eq!((begun.from(), begun.to()), (from, during), "{op}");
assert_eq!(begun.by(), Cause::Operation { id: OP, op });
let ok = Transition::succeed(begun);
assert_eq!((ok.from(), ok.to(), ok.cause()), (during, goal, None), "{op}");
let failed = Transition::fail(begun, ErrorCode::Timeout);
assert_eq!((failed.to(), failed.cause()), (RunState::Failed, Some(ErrorCode::Timeout)), "{op}");
}
}
#[test]
fn every_moving_state_is_recovered_to_failed_cancelled_and_nothing_else_is() {
for from in every_state() {
match Transition::cut_off(from, OP) {
Ok(t) => {
assert!(from.is_moving());
assert_eq!(
(t.to(), t.cause(), t.by()),
(RunState::Failed, Some(ErrorCode::Cancelled), Cause::Recovery { id: OP })
);
}
Err(_) => assert!(!from.is_moving(), "{from}"),
}
}
}
#[test]
fn the_wish_after_each_op_is_met_by_its_goal() {
assert_eq!(Desired::after(Op::Up).map(Desired::met_by), Some(RunState::Ready));
assert_eq!(Desired::after(Op::Park).map(Desired::met_by), Some(RunState::Parked));
assert_eq!(Desired::after(Op::Down).map(Desired::met_by), Some(RunState::Absent));
assert_eq!(Desired::after(Op::Check), None);
crate::testing::assert_named_as_serde(Desired::as_str);
}
}