use std::error::Error;
use std::fmt::{self, Display, Formatter};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum StopState {
#[default]
Running,
StopRequested,
IntentConfirmed,
StoppedConfirmed,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum StopAction {
RequestStop,
ConfirmIntent,
Verify,
Cancel,
Resume,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum StopEventKind {
StopRequested,
IntentConfirmed,
StoppedObserved,
RequestCancelled,
Resumed,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct StopEvent {
kind: StopEventKind,
note: String,
}
impl StopEvent {
pub const fn kind(&self) -> StopEventKind {
self.kind
}
pub fn note(&self) -> &str {
&self.note
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Observation {
Active(String),
Stopped(String),
}
impl Observation {
pub fn active(evidence: impl Into<String>) -> Self {
Self::Active(evidence.into())
}
pub fn stopped(evidence: impl Into<String>) -> Self {
Self::Stopped(evidence.into())
}
fn evidence(&self) -> &str {
match self {
Self::Active(evidence) | Self::Stopped(evidence) => evidence,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StopConfirmation {
subject: String,
state: StopState,
events: Vec<StopEvent>,
}
impl StopConfirmation {
pub fn new(subject: impl Into<String>) -> Result<Self, StopError> {
let subject = subject.into();
require_text(&subject, TextField::Subject)?;
Ok(Self {
subject,
state: StopState::Running,
events: Vec::new(),
})
}
pub fn subject(&self) -> &str {
&self.subject
}
pub const fn state(&self) -> StopState {
self.state
}
pub fn events(&self) -> &[StopEvent] {
&self.events
}
pub const fn is_stopped_confirmed(&self) -> bool {
matches!(self.state, StopState::StoppedConfirmed)
}
pub fn request_stop(&mut self, reason: impl Into<String>) -> Result<(), StopError> {
self.require_state(StopAction::RequestStop, StopState::Running)?;
let reason = reason.into();
require_text(&reason, TextField::Reason)?;
self.transition(
StopState::StopRequested,
StopEventKind::StopRequested,
reason,
);
Ok(())
}
pub fn confirm_intent(&mut self, acknowledgement: impl Into<String>) -> Result<(), StopError> {
self.require_state(StopAction::ConfirmIntent, StopState::StopRequested)?;
let acknowledgement = acknowledgement.into();
require_text(&acknowledgement, TextField::Acknowledgement)?;
self.transition(
StopState::IntentConfirmed,
StopEventKind::IntentConfirmed,
acknowledgement,
);
Ok(())
}
pub fn verify(&mut self, observation: Observation) -> Result<(), StopError> {
self.require_state(StopAction::Verify, StopState::IntentConfirmed)?;
require_text(observation.evidence(), TextField::Evidence)?;
match observation {
Observation::Active(evidence) => Err(StopError::StillActive { evidence }),
Observation::Stopped(evidence) => {
self.transition(
StopState::StoppedConfirmed,
StopEventKind::StoppedObserved,
evidence,
);
Ok(())
}
}
}
pub fn cancel(&mut self, note: impl Into<String>) -> Result<(), StopError> {
if !matches!(
self.state,
StopState::StopRequested | StopState::IntentConfirmed
) {
return Err(StopError::InvalidTransition {
action: StopAction::Cancel,
state: self.state,
});
}
let note = note.into();
require_text(¬e, TextField::Note)?;
self.transition(StopState::Running, StopEventKind::RequestCancelled, note);
Ok(())
}
pub fn resume(&mut self, note: impl Into<String>) -> Result<(), StopError> {
self.require_state(StopAction::Resume, StopState::StoppedConfirmed)?;
let note = note.into();
require_text(¬e, TextField::Note)?;
self.transition(StopState::Running, StopEventKind::Resumed, note);
Ok(())
}
fn require_state(&self, action: StopAction, expected: StopState) -> Result<(), StopError> {
if self.state != expected {
return Err(StopError::InvalidTransition {
action,
state: self.state,
});
}
Ok(())
}
fn transition(&mut self, state: StopState, kind: StopEventKind, note: String) {
self.events.push(StopEvent { kind, note });
self.state = state;
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TextField {
Subject,
Reason,
Acknowledgement,
Evidence,
Note,
}
fn require_text(value: &str, field: TextField) -> Result<(), StopError> {
if value.trim().is_empty() {
return Err(match field {
TextField::Subject => StopError::EmptySubject,
TextField::Reason => StopError::EmptyReason,
TextField::Acknowledgement => StopError::EmptyAcknowledgement,
TextField::Evidence => StopError::EmptyEvidence,
TextField::Note => StopError::EmptyNote,
});
}
Ok(())
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum StopError {
EmptySubject,
EmptyReason,
EmptyAcknowledgement,
EmptyEvidence,
EmptyNote,
InvalidTransition {
action: StopAction,
state: StopState,
},
StillActive {
evidence: String,
},
}
impl Display for StopError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::EmptySubject => f.write_str("stop subject cannot be empty"),
Self::EmptyReason => f.write_str("stop reason cannot be empty"),
Self::EmptyAcknowledgement => f.write_str("stop acknowledgement cannot be empty"),
Self::EmptyEvidence => f.write_str("observation evidence cannot be empty"),
Self::EmptyNote => f.write_str("transition note cannot be empty"),
Self::InvalidTransition { action, state } => {
write!(f, "action {action:?} is invalid in state {state:?}")
}
Self::StillActive { evidence } => {
write!(
f,
"stop is not confirmed; subject remains active: {evidence}"
)
}
}
}
}
impl Error for StopError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn complete_confirmation_requires_three_steps() {
let mut stop = StopConfirmation::new("motor").unwrap();
stop.request_stop("guard opened").unwrap();
stop.confirm_intent("controller acknowledged").unwrap();
stop.verify(Observation::stopped("encoder reads zero"))
.unwrap();
assert_eq!(stop.state(), StopState::StoppedConfirmed);
assert!(stop.is_stopped_confirmed());
assert_eq!(stop.events().len(), 3);
assert_eq!(stop.events()[2].kind(), StopEventKind::StoppedObserved);
}
#[test]
fn acknowledgement_alone_is_not_a_confirmed_stop() {
let mut stop = StopConfirmation::new("worker").unwrap();
stop.request_stop("shutdown").unwrap();
stop.confirm_intent("message received").unwrap();
assert!(!stop.is_stopped_confirmed());
assert_eq!(stop.state(), StopState::IntentConfirmed);
}
#[test]
fn active_observation_preserves_retry_state_and_audit_log() {
let mut stop = StopConfirmation::new("fan").unwrap();
stop.request_stop("inspection").unwrap();
stop.confirm_intent("relay opened").unwrap();
let before = stop.events().len();
assert_eq!(
stop.verify(Observation::active("fan still coasting")),
Err(StopError::StillActive {
evidence: "fan still coasting".into()
})
);
assert_eq!(stop.state(), StopState::IntentConfirmed);
assert_eq!(stop.events().len(), before);
stop.verify(Observation::stopped("fan is motionless"))
.unwrap();
}
#[test]
fn transitions_cannot_be_skipped() {
let mut stop = StopConfirmation::new("job").unwrap();
assert_eq!(
stop.confirm_intent("accepted"),
Err(StopError::InvalidTransition {
action: StopAction::ConfirmIntent,
state: StopState::Running
})
);
assert_eq!(stop.events().len(), 0);
}
#[test]
fn pending_request_can_be_cancelled() {
let mut stop = StopConfirmation::new("job").unwrap();
stop.request_stop("mistake").unwrap();
stop.cancel("false alarm").unwrap();
assert_eq!(stop.state(), StopState::Running);
assert_eq!(stop.events()[1].kind(), StopEventKind::RequestCancelled);
}
#[test]
fn confirmed_stop_can_resume_and_start_another_cycle() {
let mut stop = StopConfirmation::new("service").unwrap();
stop.request_stop("deploy").unwrap();
stop.confirm_intent("signal handled").unwrap();
stop.verify(Observation::stopped("health check is down"))
.unwrap();
stop.resume("deploy finished").unwrap();
stop.request_stop("second deploy").unwrap();
assert_eq!(stop.state(), StopState::StopRequested);
assert_eq!(stop.events().len(), 5);
}
#[test]
fn empty_descriptions_are_rejected_without_transition() {
assert_eq!(StopConfirmation::new(" "), Err(StopError::EmptySubject));
let mut stop = StopConfirmation::new("job").unwrap();
assert_eq!(stop.request_stop(""), Err(StopError::EmptyReason));
assert_eq!(stop.state(), StopState::Running);
stop.request_stop("requested").unwrap();
assert_eq!(
stop.confirm_intent(" "),
Err(StopError::EmptyAcknowledgement)
);
}
#[test]
fn event_notes_are_preserved_in_order() {
let mut stop = StopConfirmation::new("task").unwrap();
stop.request_stop("first").unwrap();
stop.confirm_intent("second").unwrap();
stop.verify(Observation::stopped("third")).unwrap();
let notes: Vec<_> = stop.events().iter().map(StopEvent::note).collect();
assert_eq!(notes, ["first", "second", "third"]);
}
}