Skip to main content

ggen_core/lifecycle/
exec.rs

1//! Phase execution with hooks and state management
2//!
3//! This module provides the core execution engine for lifecycle phases, including
4//! hook execution (before/after), state persistence, and deterministic caching.
5//!
6//! ## Features
7//!
8//! - **Phase execution**: Run lifecycle phases with command execution
9//! - **Hook support**: Execute before/after hooks for phases
10//! - **State persistence**: Track phase history and generated files
11//! - **Deterministic caching**: Cache key generation for reproducible builds
12//! - **Thread-safe**: Support for parallel workspace execution
13//!
14//! ## Examples
15//!
16//! ### Running a Phase
17//!
18//! ```rust,no_run
19//! use crate::lifecycle::exec::Context;
20//! use crate::lifecycle::exec::run_phase;
21//! use crate::lifecycle::Result;
22//! use std::path::PathBuf;
23//! use std::sync::Arc;
24//!
25//! # fn main() -> Result<()> {
26//! // Create execution context
27//! let root = PathBuf::from(".");
28//! let make = Arc::new(crate::lifecycle::loader::load_make("make.toml")?);
29//! let state_path = root.join(".ggen/state.json");
30//! let ctx = Context::new(root, make, state_path, vec![]);
31//!
32//! // Run a phase
33//! run_phase(&ctx, "build")?;
34//! # Ok(())
35//! # }
36//! ```
37//!
38//! ### Running Multiple Phases
39//!
40//! ```rust,no_run
41//! use crate::lifecycle::exec::run_pipeline;
42//! use crate::lifecycle::Result;
43//! use std::path::PathBuf;
44//! use std::sync::Arc;
45//!
46//! # fn main() -> Result<()> {
47//! // Create context (same as above)
48//! let root = PathBuf::from(".");
49//! let make = Arc::new(crate::lifecycle::loader::load_make("make.toml")?);
50//! let state_path = root.join(".ggen/state.json");
51//! let ctx = crate::lifecycle::exec::Context::new(root, make, state_path, vec![]);
52//!
53//! // Run multiple phases in sequence
54//! run_pipeline(&ctx, &vec!["test".to_string(), "lint".to_string(), "build".to_string()])?;
55//! # Ok(())
56//! # }
57//! ```
58
59use super::{cache::cache_key, error::*, loader::load_make, model::*, state::*};
60use std::path::{Path, PathBuf};
61use std::process::Command;
62use std::time::Instant;
63
64use std::collections::HashSet;
65use std::sync::{Arc, Mutex};
66
67/// Execution context for lifecycle phases (thread-safe)
68pub struct Context {
69    pub root: PathBuf,
70    pub make: Arc<Make>,
71    pub state_path: PathBuf,
72    pub env: Vec<(String, String)>,
73    /// Hook recursion guard (thread-safe for parallel execution)
74    hook_guard: Arc<Mutex<HashSet<String>>>,
75    /// Call chain tracking for better error messages (thread-safe)
76    /// **DfLSS Fix**: Tracks full call chain to show complete cycle path in error messages
77    call_chain: Arc<Mutex<Vec<String>>>,
78}
79
80impl Context {
81    /// Create new context with empty hook guard and call chain
82    pub fn new(
83        root: PathBuf, make: Arc<Make>, state_path: PathBuf, env: Vec<(String, String)>,
84    ) -> Self {
85        Self {
86            root,
87            make,
88            state_path,
89            env,
90            hook_guard: Arc::new(Mutex::new(HashSet::new())),
91            call_chain: Arc::new(Mutex::new(Vec::new())),
92        }
93    }
94
95    /// Check for hook recursion and add to guard
96    ///
97    /// **DfLSS Fix**: Now tracks full call chain for better error messages
98    fn enter_phase(&self, phase: &str) -> Result<()> {
99        let mut guard = self
100            .hook_guard
101            .lock()
102            .map_err(|_| LifecycleError::MutexPoisoned {
103                phase: phase.to_string(),
104            })?;
105
106        let mut chain = self
107            .call_chain
108            .lock()
109            .map_err(|_| LifecycleError::MutexPoisoned {
110                phase: phase.to_string(),
111            })?;
112
113        if guard.contains(phase) {
114            // Build cycle chain: find where cycle starts and build full path
115            let cycle_start = chain.iter().position(|p| p == phase).unwrap_or(0);
116            let mut cycle = chain[cycle_start..].to_vec();
117            cycle.push(phase.to_string());
118
119            return Err(LifecycleError::hook_recursion_with_chain(
120                phase.to_string(),
121                cycle,
122            ));
123        }
124
125        guard.insert(phase.to_string());
126        chain.push(phase.to_string());
127        Ok(())
128    }
129
130    /// Remove phase from guard after completion
131    ///
132    /// **DfLSS Fix**: Also removes phase from call chain
133    fn exit_phase(&self, phase: &str) {
134        match self.hook_guard.lock() {
135            Ok(mut guard) => {
136                guard.remove(phase);
137            }
138            Err(e) => {
139                // Log mutex poisoning for debugging, but don't fail
140                // If mutex is poisoned, we're in a panic scenario anyway
141                tracing::error!(
142                    phase = %phase,
143                    error = %e,
144                    "CRITICAL: Hook guard mutex poisoned - system may be in inconsistent state"
145                );
146            }
147        }
148
149        // Remove from call chain
150        match self.call_chain.lock() {
151            Ok(mut chain) => {
152                if chain.last().map(|s| s.as_str()) == Some(phase) {
153                    chain.pop();
154                }
155            }
156            Err(e) => {
157                tracing::error!(
158                    phase = %phase,
159                    error = %e,
160                    "CRITICAL: Call chain mutex poisoned - system may be in inconsistent state"
161                );
162            }
163        }
164    }
165}
166
167/// Run a single lifecycle phase with hooks
168#[tracing::instrument(name = "ggen.lifecycle.phase", skip(ctx), fields(phase = phase_name, duration_ms, status))]
169pub fn run_phase(ctx: &Context, phase_name: &str) -> Result<()> {
170    tracing::info!(phase = phase_name, "lifecycle phase starting");
171
172    // Check for hook recursion FIRST
173    ctx.enter_phase(phase_name)?;
174
175    // Ensure we exit phase even on error
176    let result = run_phase_internal(ctx, phase_name);
177    ctx.exit_phase(phase_name);
178
179    // Record status in span
180    match &result {
181        Ok(()) => {
182            tracing::Span::current().record("status", "success");
183            tracing::info!(phase = phase_name, "lifecycle phase completed");
184        }
185        Err(e) => {
186            tracing::Span::current().record("status", "error");
187            tracing::error!(phase = phase_name, error = %e, "lifecycle phase failed");
188        }
189    }
190
191    result
192}
193
194/// Internal phase execution (called after recursion check)
195fn run_phase_internal(ctx: &Context, phase_name: &str) -> Result<()> {
196    let phase = ctx
197        .make
198        .lifecycle
199        .get(phase_name)
200        .ok_or_else(|| LifecycleError::phase_not_found(phase_name))?;
201
202    // Run before hooks first
203    run_before_hooks(ctx, phase_name)?;
204
205    // Print phase start message for CLI output (after hooks)
206    crate::alert_info!(&format!("Running phase: {}", phase_name));
207
208    // Get commands for this phase using new Phase::commands() method
209    let cmds = phase.commands();
210    if cmds.is_empty() {
211        tracing::warn!(phase = %phase_name, "Phase has no commands");
212        return Ok(());
213    }
214
215    // Generate cache key
216    let key = cache_key(phase_name, &cmds, &ctx.env, &[]);
217
218    // Execute phase commands
219    let started = current_time_ms()?;
220    let timer = Instant::now();
221
222    tracing::info!(phase = %phase_name, "Starting phase execution");
223    for cmd in &cmds {
224        tracing::debug!(phase = %phase_name, command = %cmd, "Executing command");
225        execute_command(cmd, &ctx.root, &ctx.env)?;
226    }
227
228    let duration = timer.elapsed().as_millis();
229
230    // Record duration in parent span
231    tracing::Span::current().record("duration_ms", duration);
232
233    tracing::info!(
234        phase = %phase_name,
235        duration_ms = duration,
236        "Phase completed successfully"
237    );
238
239    // Update state with validation (poka-yoke)
240    let mut state = load_state(&ctx.state_path)?;
241    state.record_run(phase_name.to_string(), started, duration, true);
242    state.add_cache_key(phase_name.to_string(), key);
243
244    // Validate state before saving (poka-yoke)
245    use super::state_validation::ValidatedLifecycleState;
246    let validated_state = ValidatedLifecycleState::new(state.clone())
247        .map_err(|e| LifecycleError::Other(format!("State validation failed: {}", e)))?;
248
249    save_state(&ctx.state_path, validated_state.state())?;
250
251    // Run after hooks
252    run_after_hooks(ctx, phase_name)?;
253
254    Ok(())
255}
256
257/// Run a pipeline of phases sequentially
258#[tracing::instrument(name = "ggen.lifecycle.pipeline", skip(ctx), fields(phases = ?phases, phase_count = phases.len()))]
259pub fn run_pipeline(ctx: &Context, phases: &[String]) -> Result<()> {
260    tracing::info!(phases = ?phases, "starting lifecycle pipeline");
261    if let Some(workspaces) = &ctx.make.workspace {
262        // Check if parallel execution is requested
263        let parallel = phases
264            .first()
265            .and_then(|p| ctx.make.lifecycle.get(p))
266            .and_then(|ph| ph.parallel)
267            .unwrap_or(false);
268
269        if parallel {
270            // PRODUCTION FIX: Bounded thread pool to prevent resource exhaustion
271            use rayon::prelude::*;
272            use rayon::ThreadPoolBuilder;
273
274            // Limit to max 8 threads to prevent fork bomb with many workspaces
275            let max_threads = 8.min(num_cpus::get());
276            let pool = ThreadPoolBuilder::new()
277                .num_threads(max_threads)
278                .build()
279                .map_err(|e| {
280                    LifecycleError::Other(format!("Failed to create thread pool: {}", e))
281                })?;
282
283            let results: Vec<Result<()>> = pool.install(|| {
284                workspaces
285                    .par_iter()
286                    .map(|(ws_name, workspace)| {
287                        tracing::info!(workspace = %ws_name, "Processing workspace");
288                        let ws_ctx = create_workspace_context(
289                            &ctx.root, ws_name, workspace, &ctx.make, &ctx.env,
290                        )?;
291
292                        for phase in phases {
293                            run_phase(&ws_ctx, phase)?;
294                        }
295                        Ok(())
296                    })
297                    .collect()
298            });
299
300            // Check for errors
301            for result in results {
302                result?;
303            }
304        } else {
305            // Sequential execution
306            for (ws_name, workspace) in workspaces {
307                tracing::info!(workspace = %ws_name, "Processing workspace");
308                let ws_ctx =
309                    create_workspace_context(&ctx.root, ws_name, workspace, &ctx.make, &ctx.env)?;
310
311                for phase in phases {
312                    run_phase(&ws_ctx, phase)?;
313                }
314            }
315        }
316    } else {
317        // No workspaces, run directly
318        for phase in phases {
319            run_phase(ctx, phase)?;
320        }
321    }
322
323    Ok(())
324}
325
326/// Create workspace context with security validation
327///
328/// SECURITY: Validates workspace paths to prevent directory traversal attacks
329fn create_workspace_context(
330    root: &Path, ws_name: &str, workspace: &super::model::Workspace, root_make: &Arc<Make>,
331    env: &[(String, String)],
332) -> Result<Context> {
333    let ws_path = root.join(&workspace.path);
334
335    // SECURITY: Canonicalize and validate paths to prevent traversal
336    let canonical_root = root
337        .canonicalize()
338        .map_err(|e| LifecycleError::Other(format!("Failed to canonicalize root path: {}", e)))?;
339
340    let canonical_ws = ws_path.canonicalize().map_err(|e| {
341        LifecycleError::Other(format!(
342            "Failed to canonicalize workspace '{}' path: {}",
343            ws_name, e
344        ))
345    })?;
346
347    // SECURITY: Ensure workspace path is within project root
348    if !canonical_ws.starts_with(&canonical_root) {
349        return Err(LifecycleError::Other(format!(
350            "Security violation: workspace '{}' path '{}' is outside project root",
351            ws_name, workspace.path
352        )));
353    }
354
355    let ws_make_path = canonical_ws.join("make.toml");
356
357    // Load workspace-specific make.toml if it exists, otherwise use root
358    let ws_make = if ws_make_path.exists() {
359        Arc::new(load_make(&ws_make_path)?)
360    } else {
361        Arc::clone(root_make)
362    };
363
364    let ws_state_path = canonical_ws.join(".ggen/state.json");
365
366    Ok(Context::new(
367        canonical_ws,
368        ws_make,
369        ws_state_path,
370        env.to_vec(),
371    ))
372}
373
374/// Run before hooks for a phase
375///
376/// **DfLSS Fix**: Now supports both predefined phases (backward compatibility)
377/// and custom phases via dynamic HashMap lookup.
378fn run_before_hooks(ctx: &Context, phase_name: &str) -> Result<()> {
379    if let Some(hooks) = &ctx.make.hooks {
380        // Global before_all
381        if let Some(before_all) = &hooks.before_all {
382            for hook_phase in before_all {
383                run_phase(ctx, hook_phase)?;
384            }
385        }
386
387        // Phase-specific before hooks
388        // First check explicit fields (backward compatibility)
389        let before_hooks = match phase_name {
390            "init" => hooks.before_init.as_ref(),
391            "setup" => hooks.before_setup.as_ref(),
392            "build" => hooks.before_build.as_ref(),
393            "test" => hooks.before_test.as_ref(),
394            "deploy" => hooks.before_deploy.as_ref(),
395            _ => None,
396        };
397
398        // If not found in explicit fields, try dynamic lookup (supports custom phases)
399        let hooks_list = before_hooks.or_else(|| {
400            let hook_key = format!("before_{}", phase_name);
401            hooks.phase_hooks.get(&hook_key)
402        });
403
404        if let Some(hooks_list) = hooks_list {
405            for hook_phase in hooks_list {
406                run_phase(ctx, hook_phase)?;
407            }
408        }
409    }
410
411    Ok(())
412}
413
414/// Run after hooks for a phase
415///
416/// **DfLSS Fix**: Now supports both predefined phases (backward compatibility)
417/// and custom phases via dynamic HashMap lookup.
418fn run_after_hooks(ctx: &Context, phase_name: &str) -> Result<()> {
419    if let Some(hooks) = &ctx.make.hooks {
420        // Phase-specific after hooks
421        // First check explicit fields (backward compatibility)
422        let after_hooks = match phase_name {
423            "init" => hooks.after_init.as_ref(),
424            "setup" => hooks.after_setup.as_ref(),
425            "build" => hooks.after_build.as_ref(),
426            "test" => hooks.after_test.as_ref(),
427            "deploy" => hooks.after_deploy.as_ref(),
428            _ => None,
429        };
430
431        // If not found in explicit fields, try dynamic lookup (supports custom phases)
432        let hooks_list = after_hooks.or_else(|| {
433            let hook_key = format!("after_{}", phase_name);
434            hooks.phase_hooks.get(&hook_key)
435        });
436
437        if let Some(hooks_list) = hooks_list {
438            for hook_phase in hooks_list {
439                run_phase(ctx, hook_phase)?;
440            }
441        }
442
443        // Global after_all
444        if let Some(after_all) = &hooks.after_all {
445            for hook_phase in after_all {
446                run_phase(ctx, hook_phase)?;
447            }
448        }
449    }
450
451    Ok(())
452}
453
454/// Execute a shell command with streaming output and timeout
455///
456/// PRODUCTION FIX: Commands now have 5-minute timeout to prevent hung processes
457fn execute_command(cmd: &str, cwd: &Path, env: &[(String, String)]) -> Result<()> {
458    use std::time::Duration;
459
460    let mut command = if cfg!(target_os = "windows") {
461        let mut c = Command::new("cmd");
462        c.arg("/C");
463        c
464    } else {
465        let mut c = Command::new("sh");
466        c.arg("-c"); // Changed from -lc to -c (don't load profile - faster)
467        c
468    };
469
470    command.current_dir(cwd).arg(cmd);
471
472    for (key, value) in env {
473        command.env(key, value);
474    }
475
476    // PRODUCTION FIX: Stream output to user (80/20 - visibility over capture)
477    let mut child = command
478        .stdout(std::process::Stdio::inherit()) // Show stdout in real-time
479        .stderr(std::process::Stdio::inherit()) // Show stderr in real-time
480        .spawn()
481        .map_err(|e| LifecycleError::command_spawn("unknown", cmd, e))?;
482
483    // PRODUCTION FIX: Implement timeout to prevent hung processes
484    /// Default command execution timeout: 5 minutes
485    const DEFAULT_COMMAND_TIMEOUT_SECS: u64 = 300;
486
487    let timeout = Duration::from_secs(DEFAULT_COMMAND_TIMEOUT_SECS);
488    let start = Instant::now();
489
490    loop {
491        match child
492            .try_wait()
493            .map_err(|e| LifecycleError::command_spawn("unknown", cmd, e))?
494        {
495            Some(status) => {
496                if !status.success() {
497                    let exit_code = status.code().unwrap_or(-1);
498                    return Err(LifecycleError::command_failed(
499                        "unknown",
500                        cmd,
501                        exit_code,
502                        "Command output shown above".to_string(),
503                    ));
504                }
505                return Ok(());
506            }
507            None if start.elapsed() > timeout => {
508                // Timeout exceeded - kill the process
509                let _ = child.kill(); // Ignore kill errors
510                return Err(LifecycleError::Other(format!(
511                    "Command timeout after {}s: {}",
512                    timeout.as_secs(),
513                    cmd
514                )));
515            }
516            None => {
517                // Still running, sleep briefly and check again
518                std::thread::sleep(Duration::from_millis(100));
519            }
520        }
521    }
522}
523
524/// Get current time in milliseconds since epoch
525fn current_time_ms() -> Result<u128> {
526    std::time::SystemTime::now()
527        .duration_since(std::time::UNIX_EPOCH)
528        .map(|d| d.as_millis())
529        .map_err(|_| LifecycleError::Other("System clock error: time is before UNIX epoch".into()))
530}
531
532// Unit tests removed - covered by integration_test.rs:
533// - test_phase_commands_extraction (tests both single and multiple commands)
534// This provides better coverage with actual make.toml parsing