ggen_core/lifecycle/state_validation.rs
1//! State validation for poka-yoke error prevention
2//!
3//! This module provides validation logic for lifecycle state to prevent using
4//! corrupted or invalid state data.
5
6use super::error::{LifecycleError, Result};
7use super::state::LifecycleState;
8
9/// Validation error for lifecycle state
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum StateValidationError {
12 /// Phase history shows invalid transition
13 InvalidTransition { from: String, to: String },
14 /// Cache key references non-existent phase
15 InvalidCacheKey { phase: String },
16 /// State shows phase completed but required prerequisite not completed
17 MissingPrerequisite { phase: String, prerequisite: String },
18 /// Phase history is inconsistent (e.g., deploy before build)
19 InconsistentHistory { message: String },
20}
21
22impl std::fmt::Display for StateValidationError {
23 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24 match self {
25 Self::InvalidTransition { from, to } => {
26 write!(f, "Invalid transition from '{}' to '{}'", from, to)
27 }
28 Self::InvalidCacheKey { phase } => {
29 write!(f, "Cache key references non-existent phase: '{}'", phase)
30 }
31 Self::MissingPrerequisite {
32 phase,
33 prerequisite,
34 } => {
35 write!(
36 f,
37 "Phase '{}' completed but prerequisite '{}' not completed",
38 phase, prerequisite
39 )
40 }
41 Self::InconsistentHistory { message } => {
42 write!(f, "Inconsistent phase history: {}", message)
43 }
44 }
45 }
46}
47
48impl std::error::Error for StateValidationError {}
49
50/// Validated lifecycle state wrapper
51///
52/// **Poka-yoke**: Only `ValidatedLifecycleState` can be used in operations that
53/// require valid state. This prevents using corrupted or invalid state.
54#[derive(Debug, Clone)]
55pub struct ValidatedLifecycleState {
56 state: LifecycleState,
57}
58
59impl ValidatedLifecycleState {
60 /// Create validated state from raw state
61 ///
62 /// Validates the state before wrapping it. Returns error if validation fails.
63 pub fn new(state: LifecycleState) -> Result<Self> {
64 Self::validate(&state)?;
65 Ok(Self { state })
66 }
67
68 /// Get the underlying state
69 pub fn state(&self) -> &LifecycleState {
70 &self.state
71 }
72
73 /// Modify state with automatic re-validation
74 ///
75 /// **Poka-yoke**: Modification happens inside closure, then state is re-validated.
76 /// If validation fails, state modification is NOT applied (transaction-like behavior).
77 ///
78 /// # Example
79 ///
80 /// ```rust
81 /// # use crate::lifecycle::state_validation::ValidatedLifecycleState;
82 /// # use crate::lifecycle::state::LifecycleState;
83 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
84 /// let mut state = LifecycleState::default();
85 /// state.record_run("init".to_string(), 0, 100, true);
86 /// let mut validated = ValidatedLifecycleState::new(state)?;
87 ///
88 /// // Safe modification with automatic re-validation
89 /// validated.modify(|state| {
90 /// state.record_run("setup".to_string(), 100, 200, true);
91 /// })?;
92 /// # Ok(())
93 /// # }
94 /// ```
95 pub fn modify<F>(&mut self, f: F) -> Result<()>
96 where
97 F: FnOnce(&mut LifecycleState),
98 {
99 // Clone state for transactional modification
100 let mut new_state = self.state.clone();
101
102 // Apply modification
103 f(&mut new_state);
104
105 // Validate modified state
106 Self::validate(&new_state)?;
107
108 // Only commit if validation passes
109 self.state = new_state;
110
111 Ok(())
112 }
113
114 /// Get mutable access to state (DEPRECATED - use modify() instead)
115 ///
116 /// **Warning**: This method is deprecated. Use `modify()` for safe mutation.
117 /// Direct mutation can break validation invariants.
118 ///
119 /// **Poka-yoke**: Prefer `modify()` which re-validates after changes.
120 #[deprecated(
121 since = "0.1.0",
122 note = "Use modify() instead for automatic re-validation"
123 )]
124 pub fn state_mut(&mut self) -> &mut LifecycleState {
125 &mut self.state
126 }
127
128 /// Validate state invariants
129 ///
130 /// Checks:
131 /// - Phase history consistency
132 /// - Cache keys reference valid phases
133 /// - Basic invariants (deploy requires test, but hooks can run phases out of order)
134 ///
135 /// **Note**: Prerequisites are not strictly enforced because hooks can run phases
136 /// in any order. This validation only checks for truly invalid states.
137 pub fn validate(state: &LifecycleState) -> Result<()> {
138 let completed_phases: std::collections::HashSet<&str> = state
139 .phase_history
140 .iter()
141 .filter(|r| r.success)
142 .map(|r| r.phase.as_str())
143 .collect();
144
145 // Only check critical prerequisites that should never be violated:
146 // - deploy should not run without test (critical safety check)
147 // Note: Hooks can run phases out of order, so we don't check all prerequisites
148 if completed_phases.contains("deploy") && !completed_phases.contains("test") {
149 return Err(LifecycleError::Other(format!(
150 "{}",
151 StateValidationError::MissingPrerequisite {
152 phase: "deploy".to_string(),
153 prerequisite: "test".to_string(),
154 }
155 )));
156 }
157
158 // Check cache keys reference valid phases
159 for cache_key in &state.cache_keys {
160 if !completed_phases.contains(cache_key.phase.as_str()) {
161 return Err(LifecycleError::Other(format!(
162 "{}",
163 StateValidationError::InvalidCacheKey {
164 phase: cache_key.phase.clone(),
165 }
166 )));
167 }
168 }
169
170 // Note: We don't check for inconsistent history (e.g., deploy before build)
171 // because hooks can run phases in any order. The type-level state machine
172 // prevents invalid transitions at compile time for direct phase execution,
173 // but hooks can violate the normal order.
174
175 Ok(())
176 }
177}
178
179impl AsRef<LifecycleState> for ValidatedLifecycleState {
180 fn as_ref(&self) -> &LifecycleState {
181 &self.state
182 }
183}
184
185#[cfg(test)]
186mod tests {
187 use super::*;
188
189 #[test]
190 fn test_valid_state_passes_validation() {
191 let mut state = LifecycleState::default();
192 state.record_run("init".to_string(), 0, 100, true);
193 state.record_run("setup".to_string(), 100, 200, true);
194 state.record_run("build".to_string(), 200, 300, true);
195
196 assert!(ValidatedLifecycleState::validate(&state).is_ok());
197 }
198
199 #[test]
200 fn test_missing_prerequisite_fails_validation() {
201 let mut state = LifecycleState::default();
202 // Deploy without test should fail (critical safety check)
203 state.record_run("deploy".to_string(), 0, 100, true);
204
205 assert!(ValidatedLifecycleState::validate(&state).is_err());
206 }
207
208 #[test]
209 fn test_invalid_cache_key_fails_validation() {
210 let mut state = LifecycleState::default();
211 state.record_run("init".to_string(), 0, 100, true);
212 state.add_cache_key("nonexistent".to_string(), "key".to_string());
213
214 assert!(ValidatedLifecycleState::validate(&state).is_err());
215 }
216
217 #[test]
218 fn test_inconsistent_history_allowed_for_hooks() {
219 // Hooks can run phases out of order, so this should be allowed
220 let mut state = LifecycleState::default();
221 state.record_run("build".to_string(), 0, 100, true);
222 state.record_run("init".to_string(), 100, 200, true); // init after build (via hook)
223
224 // This should pass because hooks can run phases in any order
225 assert!(ValidatedLifecycleState::validate(&state).is_ok());
226 }
227
228 #[test]
229 fn test_validated_state_wrapper() {
230 let mut state = LifecycleState::default();
231 state.record_run("init".to_string(), 0, 100, true);
232
233 let validated = ValidatedLifecycleState::new(state).unwrap();
234 assert!(validated.state().has_completed_phase("init"));
235 }
236}