Skip to main content

fallow_api/runtime/
feature_flags.rs

1use std::path::Path;
2use std::time::Instant;
3
4use fallow_engine::flag_report::{RetirementRequest, build_retirement_report};
5use fallow_engine::flag_retirement::{RetirementFacts, RetirementOptions};
6use fallow_engine::flag_vendor::{VendorExport, load_flag_state};
7
8use fallow_engine::{project_config::ProjectConfig, session::AnalysisSession};
9use fallow_output::{
10    DiffIndex, FEATURE_FLAGS_SCHEMA_VERSION, FeatureFlagsOutputInput, build_feature_flags_output,
11    feature_flags_meta,
12};
13use fallow_types::output_format::OutputFormat;
14use fallow_types::results::FeatureFlag;
15
16use crate::{
17    FeatureFlagsOptions, FeatureFlagsProgrammaticOutput, ProgrammaticError,
18    analysis_context::{
19        ProgrammaticAnalysisContext, changed_files_for_run, resolve_programmatic_analysis_context,
20        workspace_roots_for_session,
21    },
22};
23
24use super::ProgrammaticResult;
25
26/// Run feature-flag analysis and return typed API output before JSON.
27///
28/// # Errors
29///
30/// Returns a structured programmatic error for invalid options, config load
31/// failures, git changed-file failures, or analysis failures, and
32/// `FALLOW_CANCELLED` when the caller's cancellation token is set. The scan
33/// observes the token at its entry, on both sides of the parse loop, and at
34/// the stage boundaries of the dead-code correlation behind it.
35pub fn run_feature_flags(
36    options: &FeatureFlagsOptions,
37) -> ProgrammaticResult<FeatureFlagsProgrammaticOutput> {
38    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
39    resolved.install(|| run_feature_flags_inner(options, &resolved))
40}
41
42fn run_feature_flags_inner(
43    options: &FeatureFlagsOptions,
44    resolved: &ProgrammaticAnalysisContext,
45) -> ProgrammaticResult<FeatureFlagsProgrammaticOutput> {
46    let start = Instant::now();
47    let vendor_export = load_vendor_export(options, &resolved.root)?;
48    resolved.ensure_not_cancelled("config load and file discovery")?;
49    let session = load_feature_flags_session(resolved)?;
50    let scan = if options.retirement.is_some() {
51        fallow_engine::flags::analyze_feature_flags_for_retirement(&session)
52    } else {
53        fallow_engine::flags::analyze_feature_flags_with_session(&session)
54            .map(|analysis| (analysis, RetirementFacts::default()))
55    };
56    let (analysis, retirement_facts) = scan.map_err(|err| {
57        super::dead_code::map_engine_error(
58            &err,
59            "feature-flag analysis failed",
60            "FALLOW_FEATURE_FLAGS_FAILED",
61            "feature-flags",
62        )
63    })?;
64    if analysis.files_scanned == 0 {
65        return Err(ProgrammaticError::new("no files discovered", 2)
66            .with_code("FALLOW_NO_FILES_DISCOVERED")
67            .with_context("feature-flags"));
68    }
69
70    let scope = feature_flags_scope(resolved, &session)?;
71    let all_flags = if options.retirement.is_some() {
72        analysis.flags.clone()
73    } else {
74        Vec::new()
75    };
76    let mut flags = analysis.flags;
77    flags.retain(|flag| scope.contains(&flag.path, session.root()));
78    let mut workspace_diagnostics = session.current_workspace_diagnostics();
79    let retirement = options.retirement.as_ref().map(|retirement| {
80        let build = build_retirement_report(RetirementRequest {
81            root: session.root(),
82            workspaces: session.workspaces(),
83            sites: retirement_facts.sites_for(&all_flags),
84            in_scope: &|path| scope.contains(path, session.root()),
85            whole_project: scope.is_whole_project(),
86            age_mode: retirement.flag_age,
87            cache_dir: (!resolved.no_cache).then_some(session.config().cache_dir.as_path()),
88            progress: None,
89            vendor_export: vendor_export.as_ref(),
90            vendor_key_prefix: session.config().flags.vendor_key_prefix.as_deref(),
91            max_flag_age: retirement.max_flag_age,
92            options: RetirementOptions {
93                sort: retirement.sort,
94                min_age_days: retirement.min_age_days,
95                reasons: retirement.reasons.clone(),
96                top: options.top,
97            },
98        });
99        workspace_diagnostics.extend(build.diagnostics.into_iter().map(|kind| {
100            fallow_config::WorkspaceDiagnostic::new(
101                session.root(),
102                session.root().to_path_buf(),
103                kind,
104            )
105        }));
106        build.report
107    });
108    sort_and_limit_feature_flags(&mut flags, options.top);
109
110    let output = build_feature_flags_output(FeatureFlagsOutputInput {
111        schema_version: FEATURE_FLAGS_SCHEMA_VERSION,
112        version: env!("CARGO_PKG_VERSION").to_string(),
113        elapsed: start.elapsed(),
114        flags: &flags,
115        root: session.root(),
116        // Read live, like the dead-code route: the parse stage records
117        // `source-read-failure` and `source-parse-degraded` after the session
118        // captured its walk snapshot, and both are reasons a flag is missing.
119        workspace_diagnostics,
120        // The diff this route resolved and applied above, or the reason it
121        // stood down. This route filters flags by the diff, unlike the CLI
122        // `flags` command, so an applied entry states a real narrowing.
123        request_outcomes: resolved.request_outcomes(),
124        meta: resolved.explain_enabled().then(feature_flags_meta),
125        retirement,
126    });
127
128    Ok(FeatureFlagsProgrammaticOutput {
129        output,
130        telemetry_analysis_run_id: None,
131    })
132}
133
134fn load_feature_flags_session(
135    resolved: &ProgrammaticAnalysisContext,
136) -> ProgrammaticResult<AnalysisSession> {
137    let project_config = fallow_engine::project_config::config_for_project_with_production(
138        &resolved.root,
139        resolved.config_path.as_deref(),
140        fallow_config::ConfigLoadOptions {
141            allow_remote_extends: resolved.allow_remote_extends(),
142        },
143        fallow_engine::project_config::ProductionFlags {
144            global: resolved.production_override,
145            ..fallow_engine::project_config::ProductionFlags::default()
146        },
147    )
148    .map_err(|err| {
149        ProgrammaticError::new(format!("failed to load config: {err}"), 2)
150            .with_code("FALLOW_CONFIG_LOAD_FAILED")
151            .with_context("analysis.configPath")
152    })?;
153    Ok(super::dead_code::attach_cancellation(
154        AnalysisSession::from_config(configure_project_for_feature_flags(
155            project_config,
156            resolved,
157        )),
158        resolved,
159    ))
160}
161
162fn configure_project_for_feature_flags(
163    mut project_config: ProjectConfig,
164    resolved: &ProgrammaticAnalysisContext,
165) -> ProjectConfig {
166    project_config.config.output = OutputFormat::Json;
167    project_config.config.no_cache = resolved.no_cache;
168    project_config.config.threads = resolved.threads;
169    project_config
170}
171
172/// The files a flags run reports on, from the workspace, changed-since and
173/// diff options.
174struct FeatureFlagsScope<'a> {
175    workspace_roots: Option<Vec<std::path::PathBuf>>,
176    changed_files: Option<rustc_hash::FxHashSet<std::path::PathBuf>>,
177    diff: Option<&'a DiffIndex>,
178}
179
180impl FeatureFlagsScope<'_> {
181    fn is_whole_project(&self) -> bool {
182        self.workspace_roots.is_none() && self.changed_files.is_none() && self.diff.is_none()
183    }
184
185    fn contains(&self, path: &Path, root: &Path) -> bool {
186        self.workspace_roots
187            .as_ref()
188            .is_none_or(|roots| roots.iter().any(|workspace| path.starts_with(workspace)))
189            && self
190                .changed_files
191                .as_ref()
192                .is_none_or(|changed| changed.contains(path))
193            && self.diff.as_ref().is_none_or(|diff| {
194                diff.key_for(path, root)
195                    .is_none_or(|rel| diff.touches_file(&rel))
196            })
197    }
198}
199
200fn feature_flags_scope<'a>(
201    resolved: &'a ProgrammaticAnalysisContext,
202    session: &AnalysisSession,
203) -> ProgrammaticResult<FeatureFlagsScope<'a>> {
204    let workspace_roots = workspace_roots_for_session(resolved, session.workspaces())?;
205    let changed_files = changed_files_for_run(resolved)?;
206    if changed_files.is_some() {
207        resolved
208            .measure_changed_since_scope(session.files().iter().map(|file| file.path.as_path()));
209    }
210    Ok(FeatureFlagsScope {
211        workspace_roots,
212        changed_files,
213        diff: resolved.diff_index(),
214    })
215}
216
217/// Read the vendor export before the analysis, so an invalid file fails
218/// fast.
219fn load_vendor_export(
220    options: &FeatureFlagsOptions,
221    root: &Path,
222) -> ProgrammaticResult<Option<VendorExport>> {
223    let Some(path) = options
224        .retirement
225        .as_ref()
226        .and_then(|retirement| retirement.flag_state.as_deref())
227    else {
228        return Ok(None);
229    };
230    load_flag_state(path, root).map(Some).map_err(|error| {
231        ProgrammaticError::new(error.message, 2)
232            .with_code("FALLOW_FLAG_STATE_INVALID")
233            .with_help(error.help)
234            .with_context("feature-flags.retirement.flagState")
235    })
236}
237
238fn sort_and_limit_feature_flags(flags: &mut Vec<FeatureFlag>, top: Option<usize>) {
239    flags.sort_by(|a, b| {
240        a.path
241            .cmp(&b.path)
242            .then(a.line.cmp(&b.line))
243            .then(a.flag_name.cmp(&b.flag_name))
244    });
245
246    if let Some(top) = top {
247        flags.truncate(top);
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use crate::AnalysisOptions;
255
256    #[test]
257    fn production_override_gives_the_rules_of_production_mode() {
258        let project = tempfile::tempdir().expect("temp dir");
259        std::fs::write(project.path().join("package.json"), r#"{"name":"flags"}"#)
260            .expect("package");
261        let resolved = resolve_programmatic_analysis_context(&AnalysisOptions {
262            root: Some(project.path().to_path_buf()),
263            production_override: Some(true),
264            ..AnalysisOptions::default()
265        })
266        .expect("context resolves");
267
268        let session = load_feature_flags_session(&resolved).expect("session loads");
269
270        assert!(session.config().production);
271        assert_eq!(
272            session.config().rules.unused_dev_dependencies,
273            fallow_config::Severity::Off,
274            "production mode turns unused-dev-dependencies off, as `--production` does"
275        );
276    }
277}