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