apiforge 0.4.0

Production-grade API release automation CLI. From merged code to healthy pods in production — one command.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
use std::collections::HashMap;
use std::time::Instant;

use crate::config::Config;
use crate::error::{ApiForgeError, Result};
use crate::output::OutputManager;
use crate::steps::{Step, StepContext, StepOutput, StepStatus};
use crate::utils::sanitize_message;

/// Outcome of a full pipeline run, including partial progress on failure.
///
/// `steps` contains one entry per attempted step (name + output), including
/// a `Failed` entry for the step that aborted the run, so callers can render
/// accurate summaries and audit records for both success and failure paths.
pub struct RunReport {
    pub steps: Vec<(String, StepOutput)>,
    pub error: Option<ApiForgeError>,
    pub rolled_back: bool,
}

impl RunReport {
    pub fn success(&self) -> bool {
        self.error.is_none()
    }

    /// Consume the report, returning step outputs on success or the error.
    pub fn into_result(self) -> Result<Vec<StepOutput>> {
        match self.error {
            Some(e) => Err(e),
            None => Ok(self.steps.into_iter().map(|(_, out)| out).collect()),
        }
    }
}

pub struct ReleaseOrchestrator {
    steps: Vec<Box<dyn Step>>,
    config: Config,
    dry_run: bool,
    auto_rollback: bool,
    output: OutputManager,
}

impl ReleaseOrchestrator {
    /// Create a new orchestrator with the provided config and mode.
    pub fn new(config: Config, dry_run: bool) -> Self {
        Self {
            steps: Vec::new(),
            config,
            dry_run,
            auto_rollback: true, // Enable by default
            output: OutputManager::new(),
        }
    }

    /// Enable or disable automatic rollback on step failure.
    pub fn with_auto_rollback(mut self, enabled: bool) -> Self {
        self.auto_rollback = enabled;
        self
    }

    /// Route human-readable progress output to stderr, keeping stdout clean
    /// for machine-readable output modes such as `--output json`.
    pub fn with_stderr_output(mut self) -> Self {
        self.output = OutputManager::stderr();
        self
    }

    /// Append a step to the execution pipeline.
    pub fn add_step(&mut self, step: Box<dyn Step>) {
        self.steps.push(step);
    }

    /// Run preflight validation for each configured step.
    pub async fn preflight(&self, ctx: &StepContext) -> Result<()> {
        self.output.section("Pre-flight checks");
        for step in &self.steps {
            self.output.step_status(step.name(), "validating...");
            step.validate(ctx).await?;
            self.output.step_ok(step.name());
        }
        self.output.blank_line();
        Ok(())
    }

    /// Rollback completed steps in reverse order
    async fn rollback_steps(&self, ctx: &StepContext, completed_indices: &[usize]) {
        if completed_indices.is_empty() {
            return;
        }

        self.output.blank_line();
        self.output.section("Rolling back completed steps");

        // Rollback in reverse order
        for &idx in completed_indices.iter().rev() {
            let step = &self.steps[idx];
            self.output.step_status(step.name(), "rolling back...");

            match step.rollback(ctx).await {
                Ok(()) => {
                    self.output
                        .step_ok(&format!("{} (rolled back)", step.name()));
                }
                Err(e) => {
                    // Log rollback failure but continue with other rollbacks.
                    let safe_error = sanitize_message(&e.to_string());
                    self.output
                        .step_fail(step.name(), &format!("rollback failed: {}", safe_error));
                    tracing::error!("Failed to rollback step '{}': {}", step.name(), safe_error);
                }
            }
        }
    }

    /// Execute the configured step pipeline and return a full run report.
    ///
    /// In normal mode, failures trigger rollback of already completed steps
    /// when `auto_rollback` is enabled. The report always carries per-step
    /// outputs (including the failed step), the error if any, and whether
    /// rollback was performed — callers decide how to surface it.
    pub async fn run(&self) -> RunReport {
        let ctx = StepContext {
            config: self.config.clone(),
            dry_run: self.dry_run,
            state: HashMap::new(),
            progress: Some(self.output.progress_reporter()),
        };

        if let Err(e) = self.preflight(&ctx).await {
            return RunReport {
                steps: Vec::new(),
                error: Some(e),
                rolled_back: false,
            };
        }

        let mode = if self.dry_run { "Dry-run" } else { "Executing" };
        self.output.section(&format!("{} release pipeline", mode));

        let mut outputs: Vec<(String, StepOutput)> = Vec::new();
        let mut completed_indices: Vec<usize> = Vec::new();

        for (idx, step) in self.steps.iter().enumerate() {
            let step_start = Instant::now();
            self.output.step_status(step.name(), "running...");

            let result = if self.dry_run {
                step.dry_run(&ctx).await
            } else {
                step.execute(&ctx).await
            };

            let elapsed = step_start.elapsed();

            match result {
                Ok(mut out) => {
                    out.duration_ms = elapsed.as_millis() as u64;
                    self.output.step_done(step.name(), &out);
                    outputs.push((step.name().to_string(), out));
                    completed_indices.push(idx);
                }
                Err(e) => {
                    let safe_error = sanitize_message(&e.to_string());
                    self.output.step_fail(step.name(), &safe_error);

                    outputs.push((
                        step.name().to_string(),
                        StepOutput {
                            status: StepStatus::Failed,
                            message: safe_error,
                            duration_ms: elapsed.as_millis() as u64,
                            dry_run_details: None,
                        },
                    ));

                    // Perform automatic rollback if enabled and not in dry-run mode
                    let mut rolled_back = false;
                    if self.auto_rollback && !self.dry_run && !completed_indices.is_empty() {
                        self.output.blank_line();
                        self.output.warn(&format!(
                            "Step '{}' failed, initiating automatic rollback of {} completed step(s)...",
                            step.name(),
                            completed_indices.len()
                        ));
                        self.rollback_steps(&ctx, &completed_indices).await;
                        rolled_back = true;
                    }

                    return RunReport {
                        steps: outputs,
                        error: Some(e),
                        rolled_back,
                    };
                }
            }
        }

        self.output.blank_line();
        RunReport {
            steps: outputs,
            error: None,
            rolled_back: false,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{
        AwsConfig, Config, DockerConfig, DockerRegistry, GitConfig, KubernetesConfig, Language,
        ProjectConfig,
    };
    use crate::error::ApiForgeError;
    use async_trait::async_trait;
    use std::collections::HashMap;
    use std::sync::{Arc, Mutex};

    struct MockStep {
        name: &'static str,
        fail_on_execute: bool,
        events: Arc<Mutex<Vec<String>>>,
    }

    impl MockStep {
        fn new(name: &'static str, fail_on_execute: bool, events: Arc<Mutex<Vec<String>>>) -> Self {
            Self {
                name,
                fail_on_execute,
                events,
            }
        }
    }

    #[async_trait]
    impl Step for MockStep {
        fn name(&self) -> &str {
            self.name
        }

        fn description(&self) -> &str {
            "mock test step"
        }

        async fn validate(&self, _ctx: &StepContext) -> Result<()> {
            Ok(())
        }

        async fn execute(&self, _ctx: &StepContext) -> Result<StepOutput> {
            self.events
                .lock()
                .unwrap()
                .push(format!("execute:{}", self.name));

            if self.fail_on_execute {
                return Err(ApiForgeError::StepFailed(format!(
                    "step {} failed",
                    self.name
                )));
            }

            Ok(StepOutput::ok(format!("{} executed", self.name)))
        }

        async fn dry_run(&self, _ctx: &StepContext) -> Result<StepOutput> {
            self.events
                .lock()
                .unwrap()
                .push(format!("dry_run:{}", self.name));
            Ok(StepOutput::ok(format!("{} dry-run", self.name)))
        }

        async fn rollback(&self, _ctx: &StepContext) -> Result<()> {
            self.events
                .lock()
                .unwrap()
                .push(format!("rollback:{}", self.name));
            Ok(())
        }
    }

    fn test_config() -> Config {
        Config {
            project: ProjectConfig {
                name: "test-project".to_string(),
                language: Language::Rust,
            },
            git: GitConfig {
                main_branch: "main".to_string(),
                tag_format: "v{version}".to_string(),
                changelog: true,
                commit_message: "release {{ version }}".to_string(),
                remote: "origin".to_string(),
                require_clean: false,
                require_main_branch: false,
                fetch_timeout_secs: 60,
                push_timeout_secs: 120,
                operation_timeout_secs: 30,
            },
            docker: DockerConfig {
                registry: DockerRegistry::AwsEcr,
                repository: "test-repo".to_string(),
                dockerfile: "Dockerfile".to_string(),
                context: ".".to_string(),
                tags: vec!["{version}".to_string(), "latest".to_string()],
                build_args: Some(HashMap::new()),
            },
            kubernetes: KubernetesConfig {
                context: "test".to_string(),
                namespace: "default".to_string(),
                deployment: "test-project".to_string(),
                manifest_path: "k8s/deployment.yaml".to_string(),
                image_field: ".spec.template.spec.containers[0].image".to_string(),
                rollout_timeout: 300,
                min_ready_percent: 100,
            },
            aws: AwsConfig {
                region: "us-east-1".to_string(),
                profile: None,
            },
            cloudfront: None,
            github: None,
            notifications: None,
            health_check: None,
        }
    }

    #[tokio::test]
    async fn test_run_executes_all_steps_successfully() {
        let events = Arc::new(Mutex::new(Vec::new()));
        let mut orchestrator = ReleaseOrchestrator::new(test_config(), false);
        orchestrator.add_step(Box::new(MockStep::new("step-a", false, events.clone())));
        orchestrator.add_step(Box::new(MockStep::new("step-b", false, events.clone())));

        let report = orchestrator.run().await;
        assert!(report.success());
        assert!(!report.rolled_back);

        let outputs = report.into_result().unwrap();
        assert_eq!(outputs.len(), 2);
        assert!(outputs
            .iter()
            .all(|output| output.status == crate::steps::StepStatus::Success));
        assert_eq!(
            events.lock().unwrap().clone(),
            vec!["execute:step-a", "execute:step-b"]
        );
    }

    #[tokio::test]
    async fn test_run_rolls_back_completed_steps_in_reverse_order() {
        let events = Arc::new(Mutex::new(Vec::new()));
        let mut orchestrator = ReleaseOrchestrator::new(test_config(), false);
        orchestrator.add_step(Box::new(MockStep::new("step-a", false, events.clone())));
        orchestrator.add_step(Box::new(MockStep::new("step-b", false, events.clone())));
        orchestrator.add_step(Box::new(MockStep::new("step-c", true, events.clone())));

        let report = orchestrator.run().await;
        assert!(report.error.is_some());
        assert!(report.rolled_back);

        // Report includes the failed step so audit/history can record it.
        assert_eq!(report.steps.len(), 3);
        assert_eq!(report.steps[2].0, "step-c");
        assert_eq!(report.steps[2].1.status, crate::steps::StepStatus::Failed);

        assert_eq!(
            events.lock().unwrap().clone(),
            vec![
                "execute:step-a",
                "execute:step-b",
                "execute:step-c",
                "rollback:step-b",
                "rollback:step-a"
            ]
        );
    }

    #[tokio::test]
    async fn test_run_does_not_rollback_when_disabled() {
        let events = Arc::new(Mutex::new(Vec::new()));
        let mut orchestrator =
            ReleaseOrchestrator::new(test_config(), false).with_auto_rollback(false);
        orchestrator.add_step(Box::new(MockStep::new("step-a", false, events.clone())));
        orchestrator.add_step(Box::new(MockStep::new("step-b", true, events.clone())));

        let report = orchestrator.run().await;
        assert!(report.error.is_some());
        assert!(!report.rolled_back);

        assert_eq!(
            events.lock().unwrap().clone(),
            vec!["execute:step-a", "execute:step-b"]
        );
    }

    #[tokio::test]
    async fn test_dry_run_uses_dry_run_paths() {
        let events = Arc::new(Mutex::new(Vec::new()));
        let mut orchestrator = ReleaseOrchestrator::new(test_config(), true);
        orchestrator.add_step(Box::new(MockStep::new("step-a", false, events.clone())));
        orchestrator.add_step(Box::new(MockStep::new("step-b", false, events.clone())));

        let report = orchestrator.run().await;
        assert!(report.success());

        let outputs = report.into_result().unwrap();
        assert_eq!(outputs.len(), 2);
        assert_eq!(
            events.lock().unwrap().clone(),
            vec!["dry_run:step-a", "dry_run:step-b"]
        );
    }
}