1use std::fmt;
18
19use serde::{Deserialize, Serialize};
20
21use super::{Op, RunState};
22use crate::error::ErrorCode;
23use crate::store::OperationId;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
27#[serde(rename_all = "snake_case")]
28#[non_exhaustive]
29pub enum Desired {
30 Running,
32 Parked,
34 Gone,
36}
37
38impl Desired {
39 #[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 #[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 #[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#[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 Operation {
84 id: OperationId,
86 op: Op,
88 },
89 Observation,
91 Recovery {
93 id: OperationId,
95 },
96}
97
98impl Cause {
99 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
111#[error("a run {from} can't {what}")]
112pub struct IllegalTransition {
113 pub from: RunState,
115 pub what: &'static str,
117}
118
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub struct Transition {
123 from: RunState,
124 to: RunState,
125 cause: Option<ErrorCode>,
126 by: Cause,
127}
128
129fn begins_from(op: Op) -> (&'static [RunState], &'static str) {
131 use RunState::{Absent, Failed, Parked, Ready};
132 match op {
133 Op::Up => (&[Absent, Failed, Ready, Parked], "be brought up"),
136 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
146fn 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 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 #[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 _ => RunState::Ready,
183 };
184 Transition {
185 from: begun.to,
186 to,
187 cause: None,
188 by: begun.by,
189 }
190 }
191
192 #[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 #[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 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 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 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 #[must_use]
280 pub fn from(&self) -> RunState {
281 self.from
282 }
283
284 #[must_use]
286 pub fn to(&self) -> RunState {
287 self.to
288 }
289
290 #[must_use]
292 pub fn cause(&self) -> Option<ErrorCode> {
293 self.cause
294 }
295
296 #[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}