1use std::io::Read;
15use std::path::Path;
16
17use fallow_types::flag_retirement::{
18 FlagSiteRole, RetirementEvidence, RetirementFlag, RetirementFlagKind, RetirementReason,
19 RetirementVendor, RetirementVendorState, VendorFlagState,
20};
21use rustc_hash::{FxHashMap, FxHashSet};
22use serde::Deserialize;
23
24const FLAG_STATE_SCHEMA_VERSION: u32 = 1;
26
27pub const MAX_FLAG_STATE_BYTES: u64 = 16 * 1024 * 1024;
29
30pub const STALE_EXPORT_DAYS: u64 = 30;
32
33const SECS_PER_DAY: u64 = 86_400;
35
36const FLAG_STATE_HELP: &str = "See https://fallow.tools/docs/cli/flags/#vendor-flag-state for the schema and a jq recipe for each vendor.";
38
39#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct FlagStateError {
42 pub message: String,
44 pub help: &'static str,
46}
47
48impl FlagStateError {
49 fn new(message: impl Into<String>) -> Self {
50 Self {
51 message: message.into(),
52 help: FLAG_STATE_HELP,
53 }
54 }
55}
56
57#[derive(Debug, Deserialize)]
58#[serde(deny_unknown_fields)]
59struct FlagStateFile {
60 schema_version: u32,
61 source: String,
62 exported_at: String,
63 flags: Vec<FlagStateEntry>,
64}
65
66#[derive(Debug, Deserialize)]
67#[serde(deny_unknown_fields)]
68struct FlagStateEntry {
69 key: String,
70 state: VendorFlagState,
71 #[serde(default)]
72 serves_single_variation: Option<bool>,
73 #[serde(default)]
74 created_at: Option<String>,
75 #[serde(default)]
76 last_evaluated_at: Option<String>,
77}
78
79#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct VendorFlag {
82 pub state: RetirementVendor,
84 pub line: u32,
86}
87
88#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct VendorExport {
91 pub source: String,
93 pub exported_at: String,
95 pub display_path: String,
98 pub flags: Vec<VendorFlag>,
100}
101
102pub fn load_flag_state(path: &Path, root: &Path) -> Result<VendorExport, FlagStateError> {
109 let file = std::fs::File::open(path).map_err(|error| {
110 FlagStateError::new(format!(
111 "cannot read the flag state file {}: {error}",
112 path.display()
113 ))
114 })?;
115 let mut bytes = Vec::new();
116 file.take(MAX_FLAG_STATE_BYTES + 1)
117 .read_to_end(&mut bytes)
118 .map_err(|error| {
119 FlagStateError::new(format!(
120 "cannot read the flag state file {}: {error}",
121 path.display()
122 ))
123 })?;
124 if bytes.len() as u64 > MAX_FLAG_STATE_BYTES {
125 return Err(FlagStateError::new(format!(
126 "the flag state file {} is larger than {} MiB",
127 path.display(),
128 MAX_FLAG_STATE_BYTES / (1024 * 1024)
129 )));
130 }
131 parse_flag_state(&bytes, display_path(path, root))
132}
133
134fn display_path(path: &Path, root: &Path) -> String {
140 let canonical_path = dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
141 let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
142 let shown = match canonical_path.strip_prefix(&canonical_root) {
143 Ok(relative) => relative.to_path_buf(),
144 Err(_) => canonical_path
145 .file_name()
146 .map_or_else(|| path.to_path_buf(), std::path::PathBuf::from),
147 };
148 shown.to_string_lossy().replace('\\', "/")
149}
150
151fn parse_flag_state(bytes: &[u8], display_path: String) -> Result<VendorExport, FlagStateError> {
159 let text = std::str::from_utf8(bytes)
160 .map_err(|_| FlagStateError::new(format!("{display_path} is not UTF-8 text")))?;
161 let file: FlagStateFile = serde_json::from_str(text)
162 .map_err(|error| FlagStateError::new(format!("{display_path} is not valid: {error}")))?;
163 if file.schema_version != FLAG_STATE_SCHEMA_VERSION {
164 return Err(FlagStateError::new(format!(
165 "{display_path} has schema_version {}, but this build reads schema_version {FLAG_STATE_SCHEMA_VERSION}",
166 file.schema_version
167 )));
168 }
169 if file.source.trim().is_empty() {
170 return Err(FlagStateError::new(format!(
171 "{display_path} has an empty source"
172 )));
173 }
174 if date_epoch(&file.exported_at).is_none() {
175 return Err(FlagStateError::new(format!(
176 "{display_path} has exported_at {:?}, which does not start with a YYYY-MM-DD date",
177 file.exported_at
178 )));
179 }
180 let lines = key_lines(text);
181 let mut seen: FxHashSet<&str> = FxHashSet::default();
182 for entry in &file.flags {
183 if entry.key.is_empty() {
184 return Err(FlagStateError::new(format!(
185 "{display_path} has a flag with an empty key"
186 )));
187 }
188 if !seen.insert(entry.key.as_str()) {
189 return Err(FlagStateError::new(format!(
190 "{display_path} has the key {:?} more than one time",
191 entry.key
192 )));
193 }
194 }
195 let flags = file
196 .flags
197 .into_iter()
198 .map(|entry| VendorFlag {
199 line: lines.get(entry.key.as_str()).copied().unwrap_or(1),
200 state: RetirementVendor {
201 key: entry.key,
202 state: entry.state,
203 serves_single_variation: entry.serves_single_variation,
204 created_at: entry.created_at,
205 last_evaluated_at: entry.last_evaluated_at,
206 },
207 })
208 .collect();
209 Ok(VendorExport {
210 source: file.source,
211 exported_at: file.exported_at,
212 display_path,
213 flags,
214 })
215}
216
217fn key_lines(text: &str) -> FxHashMap<String, u32> {
219 const KEY_TOKEN: &str = "\"key\"";
220 let mut lines = FxHashMap::default();
221 let mut from = 0;
222 while let Some(offset) = text[from..].find(KEY_TOKEN) {
223 let start = from + offset;
224 from = start + KEY_TOKEN.len();
225 let rest = text[from..].trim_start();
226 let Some(value) = rest.strip_prefix(':') else {
227 continue;
228 };
229 let mut values =
230 serde_json::Deserializer::from_str(value.trim_start()).into_iter::<String>();
231 let Some(Ok(key)) = values.next() else {
232 continue;
233 };
234 let line = u32::try_from(text[..start].matches('\n').count() + 1).unwrap_or(u32::MAX);
235 lines.entry(key).or_insert(line);
236 }
237 lines
238}
239
240fn date_epoch(text: &str) -> Option<u64> {
242 crate::clock::utc_midnight_epoch(text.get(..10)?)
243}
244
245pub struct VendorMatch<'a> {
247 pub export: &'a VendorExport,
249 pub key_prefix: Option<&'a str>,
252 pub code_flag_names: &'a FxHashSet<String>,
254 pub project_sdk_labels: &'a FxHashSet<String>,
257 pub add_vendor_only: bool,
260 pub clock_epoch_secs: u64,
262}
263
264pub(crate) fn apply_vendor_state(
274 rows: &mut Vec<RetirementFlag>,
275 input: &VendorMatch<'_>,
276) -> RetirementVendorState {
277 let export = input.export;
278 let by_name: FxHashMap<&str, &VendorFlag> = export
279 .flags
280 .iter()
281 .map(|flag| (code_name(&flag.state.key, input.key_prefix), flag))
282 .collect();
283 let source = normalize_label(&export.source);
284 let source_is_project_sdk = input
285 .project_sdk_labels
286 .iter()
287 .any(|sdk| label_matches_source(sdk, &source));
288 for row in rows.iter_mut() {
289 if row.kind != RetirementFlagKind::SdkCall
290 || (source_is_project_sdk
291 && row.sdk_name.is_some()
292 && !sdk_matches_source(row, &source))
293 {
294 continue;
295 }
296 match by_name.get(row.flag_name.as_str()) {
297 Some(flag) => add_state_reasons(row, flag, export),
298 None => add_missing_reason(row, export),
299 }
300 }
301 if input.add_vendor_only {
302 for flag in &export.flags {
303 let name = code_name(&flag.state.key, input.key_prefix);
304 if !input.code_flag_names.contains(name) {
305 rows.push(vendor_only_row(name, flag, export));
306 }
307 }
308 }
309 RetirementVendorState {
310 source: export.source.clone(),
311 exported_at: export.exported_at.clone(),
312 export_age_days: date_epoch(&export.exported_at)
313 .map(|epoch| input.clock_epoch_secs.saturating_sub(epoch) / SECS_PER_DAY),
314 flags: export.flags.len(),
315 }
316}
317
318fn code_name<'k>(key: &'k str, prefix: Option<&str>) -> &'k str {
320 prefix
321 .filter(|prefix| !prefix.is_empty())
322 .and_then(|prefix| key.strip_prefix(prefix))
323 .filter(|name| !name.is_empty())
324 .unwrap_or(key)
325}
326
327fn normalize_label(label: &str) -> String {
330 label
331 .chars()
332 .filter(char::is_ascii_alphanumeric)
333 .map(|c| c.to_ascii_lowercase())
334 .collect()
335}
336
337fn sdk_matches_source(row: &RetirementFlag, source: &str) -> bool {
338 if row.kind != RetirementFlagKind::SdkCall || source.is_empty() {
339 return false;
340 }
341 row.sdk_name
342 .as_deref()
343 .is_some_and(|sdk| label_matches_source(sdk, source))
344}
345
346fn label_matches_source(sdk: &str, source: &str) -> bool {
349 if source.is_empty() {
350 return false;
351 }
352 let sdk = normalize_label(sdk);
353 !sdk.is_empty() && (sdk.starts_with(source) || source.starts_with(&sdk))
354}
355
356fn evidence_site(row: &RetirementFlag) -> Option<(String, u32)> {
359 row.sites
360 .iter()
361 .find(|site| site.role == FlagSiteRole::Read)
362 .or_else(|| row.sites.first())
363 .map(|site| (site.path.clone(), site.line))
364}
365
366fn add_state_reasons(row: &mut RetirementFlag, flag: &VendorFlag, export: &VendorExport) {
367 row.vendor = Some(flag.state.clone());
368 let Some((path, line)) = evidence_site(row) else {
369 return;
370 };
371 let state = &flag.state;
372 let single = state.serves_single_variation == Some(true);
373 if state.state == VendorFlagState::RolledOut || single {
374 let mut detail = format!("{} state {}", export.source, state_code(state.state));
375 if single {
376 detail.push_str(", serves one variation");
377 }
378 push_reason(row, RetirementReason::FullyRolledOut, &path, line, detail);
379 }
380 if state.state == VendorFlagState::Archived {
381 let detail = format!("{} state archived", export.source);
382 push_reason(row, RetirementReason::ArchivedInVendor, &path, line, detail);
383 }
384}
385
386fn add_missing_reason(row: &mut RetirementFlag, export: &VendorExport) {
387 let Some((path, line)) = evidence_site(row) else {
388 return;
389 };
390 let detail = format!(
391 "the key is not in the {} export ({})",
392 export.source, export.display_path
393 );
394 push_reason(row, RetirementReason::MissingInVendor, &path, line, detail);
395}
396
397fn push_reason(
398 row: &mut RetirementFlag,
399 reason: RetirementReason,
400 path: &str,
401 line: u32,
402 detail: String,
403) {
404 if !row.reasons.contains(&reason) {
405 row.reasons.push(reason);
406 }
407 row.evidence.push(RetirementEvidence {
408 reason,
409 path: path.to_string(),
410 line,
411 detail,
412 });
413}
414
415fn vendor_only_row(name: &str, flag: &VendorFlag, export: &VendorExport) -> RetirementFlag {
416 RetirementFlag {
417 flag_name: name.to_string(),
418 kind: RetirementFlagKind::VendorExport,
419 sdk_name: None,
420 workspace: None,
421 sites: Vec::new(),
422 read_sites: 0,
423 test_only: false,
424 first_seen: None,
425 oldest_surviving_site: None,
426 last_touched: None,
427 age_days: None,
428 reasons: vec![RetirementReason::VendorOnly],
429 evidence: vec![RetirementEvidence {
430 reason: RetirementReason::VendorOnly,
431 path: export.display_path.clone(),
432 line: flag.line,
433 detail: format!(
434 "the key is in the {} export, but no code reads it",
435 export.source
436 ),
437 }],
438 actions: Vec::new(),
439 vendor: Some(flag.state.clone()),
440 }
441}
442
443const fn state_code(state: VendorFlagState) -> &'static str {
444 match state {
445 VendorFlagState::On => "on",
446 VendorFlagState::Off => "off",
447 VendorFlagState::RolledOut => "rolled_out",
448 VendorFlagState::Archived => "archived",
449 VendorFlagState::Experiment => "experiment",
450 }
451}
452
453#[cfg(test)]
454mod tests {
455 use super::*;
456 use fallow_types::flag_retirement::RetirementSite;
457
458 const EXPORT: &str = r#"{
459 "schema_version": 1,
460 "source": "launchdarkly",
461 "exported_at": "2026-09-20T00:00:00Z",
462 "flags": [
463 { "key": "web.rolled", "state": "rolled_out" },
464 { "key": "web.single", "state": "off", "serves_single_variation": true },
465 { "key": "web.archived", "state": "archived" },
466 { "key": "web.live", "state": "on", "serves_single_variation": false },
467 { "key": "web.orphan", "state": "on" }
468 ]
469}"#;
470
471 const CLOCK: u64 = 1_790_294_400;
473
474 fn export() -> VendorExport {
475 parse_flag_state(EXPORT.as_bytes(), "flag-state.json".to_string()).expect("valid export")
476 }
477
478 fn sdk_row(name: &str, sdk: Option<&str>) -> RetirementFlag {
479 RetirementFlag {
480 flag_name: name.to_string(),
481 kind: RetirementFlagKind::SdkCall,
482 sdk_name: sdk.map(str::to_string),
483 workspace: None,
484 sites: vec![RetirementSite {
485 path: "src/app.ts".to_string(),
486 line: 3,
487 col: 2,
488 role: FlagSiteRole::Read,
489 in_test: false,
490 }],
491 read_sites: 1,
492 test_only: false,
493 first_seen: None,
494 oldest_surviving_site: None,
495 last_touched: None,
496 age_days: None,
497 reasons: Vec::new(),
498 evidence: Vec::new(),
499 actions: Vec::new(),
500 vendor: None,
501 }
502 }
503
504 fn apply(rows: &mut Vec<RetirementFlag>, add_vendor_only: bool) -> RetirementVendorState {
505 let labels: FxHashSet<String> =
506 rows.iter().filter_map(|row| row.sdk_name.clone()).collect();
507 apply_with_labels(rows, add_vendor_only, &labels)
508 }
509
510 fn apply_with_labels(
511 rows: &mut Vec<RetirementFlag>,
512 add_vendor_only: bool,
513 labels: &FxHashSet<String>,
514 ) -> RetirementVendorState {
515 let export = export();
516 let names: FxHashSet<String> = rows.iter().map(|row| row.flag_name.clone()).collect();
517 apply_vendor_state(
518 rows,
519 &VendorMatch {
520 export: &export,
521 key_prefix: Some("web."),
522 code_flag_names: &names,
523 project_sdk_labels: labels,
524 add_vendor_only,
525 clock_epoch_secs: CLOCK,
526 },
527 )
528 }
529
530 fn reasons_of<'r>(rows: &'r [RetirementFlag], name: &str) -> &'r [RetirementReason] {
531 &rows
532 .iter()
533 .find(|row| row.flag_name == name)
534 .unwrap_or_else(|| panic!("no row {name}"))
535 .reasons
536 }
537
538 #[test]
539 fn vendor_states_give_the_vendor_reasons() {
540 let mut rows = vec![
541 sdk_row("rolled", Some("LaunchDarkly")),
542 sdk_row("single", Some("LaunchDarkly")),
543 sdk_row("archived", Some("LaunchDarkly")),
544 sdk_row("live", Some("LaunchDarkly")),
545 sdk_row("typo", Some("LaunchDarkly")),
546 ];
547 let state = apply(&mut rows, true);
548 assert_eq!(
549 reasons_of(&rows, "rolled"),
550 [RetirementReason::FullyRolledOut]
551 );
552 assert_eq!(
553 reasons_of(&rows, "single"),
554 [RetirementReason::FullyRolledOut]
555 );
556 assert_eq!(
557 reasons_of(&rows, "archived"),
558 [RetirementReason::ArchivedInVendor]
559 );
560 assert!(reasons_of(&rows, "live").is_empty());
561 assert_eq!(
562 reasons_of(&rows, "typo"),
563 [RetirementReason::MissingInVendor]
564 );
565 assert_eq!(reasons_of(&rows, "orphan"), [RetirementReason::VendorOnly]);
566
567 let single = rows
568 .iter()
569 .find(|row| row.flag_name == "single")
570 .expect("row");
571 assert_eq!(
572 single.evidence[0].detail,
573 "launchdarkly state off, serves one variation"
574 );
575 assert_eq!(
576 single.vendor.as_ref().map(|v| v.key.as_str()),
577 Some("web.single")
578 );
579
580 let orphan = rows
581 .iter()
582 .find(|row| row.flag_name == "orphan")
583 .expect("row");
584 assert_eq!(orphan.kind, RetirementFlagKind::VendorExport);
585 assert!(orphan.sites.is_empty());
586 assert_eq!(orphan.evidence[0].path, "flag-state.json");
587 assert_eq!(orphan.evidence[0].line, 10, "the line of the orphan key");
588
589 assert_eq!(state.source, "launchdarkly");
590 assert_eq!(state.flags, 5);
591 assert_eq!(state.export_age_days, Some(5));
592 }
593
594 #[test]
595 fn a_narrowed_run_adds_no_vendor_only_rows() {
596 let mut rows = vec![sdk_row("rolled", Some("LaunchDarkly"))];
597 apply(&mut rows, false);
598 assert_eq!(rows.len(), 1);
599 }
600
601 #[test]
602 fn a_key_that_the_code_reads_under_another_kind_is_not_vendor_only() {
603 let mut rows = vec![RetirementFlag {
604 kind: RetirementFlagKind::EnvironmentVariable,
605 ..sdk_row("orphan", None)
606 }];
607 apply(&mut rows, true);
608 assert_eq!(
609 rows.len(),
610 1 + 4,
611 "the env row and four keys that no code reads"
612 );
613 assert!(
614 reasons_of(&rows, "orphan").is_empty(),
615 "an env row never matches the export"
616 );
617 }
618
619 #[test]
620 fn an_export_of_one_vendor_leaves_other_sdks_alone() {
621 let mut rows = vec![
622 sdk_row("typo", Some("LaunchDarkly")),
623 sdk_row("other", Some("Statsig")),
624 sdk_row("custom", None),
625 ];
626 apply(&mut rows, false);
627 assert_eq!(
628 reasons_of(&rows, "typo"),
629 [RetirementReason::MissingInVendor]
630 );
631 assert!(reasons_of(&rows, "other").is_empty());
632 assert_eq!(
633 reasons_of(&rows, "custom"),
634 [RetirementReason::MissingInVendor],
635 "an SDK row without a label can belong to the vendor"
636 );
637 }
638
639 #[test]
640 fn a_narrowed_run_reads_the_sdk_labels_of_the_whole_project() {
641 let mut rows = vec![sdk_row("other", Some("Statsig"))];
644 let labels: FxHashSet<String> = ["Statsig", "LaunchDarkly"]
645 .into_iter()
646 .map(str::to_string)
647 .collect();
648 apply_with_labels(&mut rows, false, &labels);
649 assert!(
650 reasons_of(&rows, "other").is_empty(),
651 "{:?}",
652 rows[0].reasons
653 );
654 }
655
656 #[test]
657 fn an_export_of_an_unknown_vendor_matches_every_sdk_row() {
658 let mut rows = vec![sdk_row("typo", Some("Statsig"))];
659 let export = parse_flag_state(
660 br#"{"schema_version":1,"source":"in-house","exported_at":"2026-09-20","flags":[]}"#,
661 "state.json".to_string(),
662 )
663 .expect("valid");
664 apply_vendor_state(
665 &mut rows,
666 &VendorMatch {
667 export: &export,
668 key_prefix: None,
669 code_flag_names: &FxHashSet::default(),
670 project_sdk_labels: &std::iter::once("Statsig".to_string()).collect(),
671 add_vendor_only: true,
672 clock_epoch_secs: CLOCK,
673 },
674 );
675 assert_eq!(
676 reasons_of(&rows, "typo"),
677 [RetirementReason::MissingInVendor]
678 );
679 }
680
681 #[test]
682 fn invalid_exports_are_rejected() {
683 let cases: [(&str, &str); 6] = [
684 ("not json", "is not valid"),
685 (
686 r#"{"schema_version":2,"source":"x","exported_at":"2026-01-01","flags":[]}"#,
687 "schema_version 2",
688 ),
689 (
690 r#"{"schema_version":1,"source":"x","exported_at":"yesterday","flags":[]}"#,
691 "YYYY-MM-DD",
692 ),
693 (
694 r#"{"schema_version":1,"source":"x","exported_at":"2026-01-01","flags":[{"key":"a","state":"paused"}]}"#,
695 "unknown variant",
696 ),
697 (
698 r#"{"schema_version":1,"source":"x","exported_at":"2026-01-01","flags":[{"key":"a","state":"on"},{"key":"a","state":"off"}]}"#,
699 "more than one time",
700 ),
701 (
702 r#"{"schema_version":1,"source":"x","exported_at":"2026-01-01","flags":[{"key":"a","state":"on","enabled":true}]}"#,
703 "unknown field",
704 ),
705 ];
706 for (input, expected) in cases {
707 let error =
708 parse_flag_state(input.as_bytes(), "state.json".to_string()).expect_err(input);
709 assert!(
710 error.message.contains(expected),
711 "{input}: {}",
712 error.message
713 );
714 }
715 }
716
717 #[test]
718 fn an_oversized_export_is_rejected_before_parse() {
719 let dir = tempfile::tempdir().expect("temp dir");
720 let path = dir.path().join("state.json");
721 let file = std::fs::File::create(&path).expect("create");
722 file.set_len(MAX_FLAG_STATE_BYTES + 1).expect("grow");
723 let error = load_flag_state(&path, dir.path()).expect_err("too large");
724 assert!(
725 error.message.contains("larger than 16 MiB"),
726 "{}",
727 error.message
728 );
729 }
730
731 #[test]
732 fn the_display_path_is_relative_to_the_root_only_inside_it() {
733 let dir = tempfile::tempdir().expect("temp dir");
734 let inside = dir.path().join("state.json");
735 std::fs::write(&inside, "{}").expect("write");
736 assert_eq!(display_path(&inside, dir.path()), "state.json");
737 let other = tempfile::tempdir().expect("temp dir");
738 let outside = other.path().join("state.json");
739 std::fs::write(&outside, "{}").expect("write");
740 assert_eq!(
741 display_path(&outside, dir.path()),
742 "state.json",
743 "a file outside the root shows its file name only"
744 );
745 }
746
747 #[test]
748 fn a_prefix_that_is_the_whole_key_keeps_the_key() {
749 assert_eq!(code_name("web.", Some("web.")), "web.");
750 assert_eq!(code_name("web.a", Some("")), "web.a");
751 assert_eq!(code_name("app.a", Some("web.")), "app.a");
752 }
753}