monocle 1.3.0

A commandline application to search, parse, and process BGP information in public sources.
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
//! RIB reconstruction lens.
//!
//! This module reconstructs final RIB state at arbitrary timestamps by:
//! 1. Selecting the latest RIB before each target time
//! 2. Replaying overlapping updates up to the exact target time
//! 3. Materializing only the final route state for each requested `rib_ts`

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;

use anyhow::{anyhow, Result};
use bgpkit_broker::{BgpkitBroker, BrokerItem};
use bgpkit_parser::models::ElemType;
use bgpkit_parser::BgpElem;
use chrono::{DateTime, Duration};
use regex::Regex;
use serde::{Deserialize, Serialize};

use crate::config::MonocleConfig;
use crate::database::{
    MonocleDatabase, RibRouteKey, RibStateStore, StoredRibEntry, StoredRibUpdate,
};
use crate::lens::country::CountryLens;
use crate::lens::parse::ParseFilters;
use crate::lens::time::TimeLens;

#[cfg(feature = "cli")]
use clap::Args;

const FULL_FEED_V4_THRESHOLD: u32 = 800_000;
const FULL_FEED_V6_THRESHOLD: u32 = 100_000;
const RIB_LOOKBACK_HOURS: i64 = 24 * 30;

type FullFeedAllowlists = HashMap<String, HashSet<(String, u32)>>;

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "cli", derive(Args))]
pub struct RibFilters {
    /// Filter by origin AS Number(s), comma-separated. Prefix with ! to exclude.
    #[cfg_attr(feature = "cli", clap(short = 'o', long, value_delimiter = ','))]
    #[serde(default)]
    pub origin_asn: Vec<String>,

    /// Filter by origin ASN registration country.
    #[cfg_attr(feature = "cli", clap(short = 'C', long))]
    pub country: Option<String>,

    /// Filter by network prefix(es), comma-separated. Prefix with ! to exclude.
    #[cfg_attr(feature = "cli", clap(short = 'p', long, value_delimiter = ','))]
    #[serde(default)]
    pub prefix: Vec<String>,

    /// Include super-prefixes when filtering.
    #[cfg_attr(feature = "cli", clap(short = 's', long))]
    #[serde(default)]
    pub include_super: bool,

    /// Include sub-prefixes when filtering.
    #[cfg_attr(feature = "cli", clap(short = 'S', long))]
    #[serde(default)]
    pub include_sub: bool,

    /// Filter by peer ASN(s), comma-separated. Prefix with ! to exclude.
    #[cfg_attr(feature = "cli", clap(short = 'J', long, value_delimiter = ','))]
    #[serde(default)]
    pub peer_asn: Vec<String>,

    /// Filter by AS path regex string.
    #[cfg_attr(feature = "cli", clap(short = 'a', long))]
    pub as_path: Option<String>,

    /// Filter by collector, e.g., rrc00 or route-views2.
    #[cfg_attr(feature = "cli", clap(short = 'c', long))]
    pub collector: Option<String>,

    /// Filter by route collection project, i.e. riperis or routeviews.
    #[cfg_attr(feature = "cli", clap(short = 'P', long))]
    pub project: Option<String>,

    /// Keep only full-feed peers based on broker peer metadata.
    #[cfg_attr(feature = "cli", clap(long))]
    #[serde(default)]
    pub full_feed_only: bool,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "cli", derive(Args))]
pub struct RibArgs {
    /// Target RIB timestamp operand. Repeat to request multiple snapshots.
    #[cfg_attr(feature = "cli", clap(value_name = "RIB_TS", required = true))]
    #[serde(default)]
    pub rib_ts: Vec<String>,

    #[cfg_attr(feature = "cli", clap(flatten))]
    #[serde(flatten)]
    pub filters: RibFilters,

    /// SQLite output file path.
    #[cfg_attr(feature = "cli", clap(long))]
    pub sqlite_path: Option<PathBuf>,
}

impl RibArgs {
    pub fn normalized_rib_ts(&self) -> Result<Vec<i64>> {
        let time_lens = TimeLens::new();
        let mut timestamps = BTreeSet::new();

        for value in &self.rib_ts {
            let ts = time_lens
                .parse_time_string(value)
                .map_err(|e| anyhow!("Invalid RIB timestamp '{}': {}", value, e))?
                .timestamp();
            timestamps.insert(ts);
        }

        if timestamps.is_empty() {
            return Err(anyhow!("At least one RIB timestamp is required"));
        }

        Ok(timestamps.into_iter().collect())
    }

    pub fn validate(&self) -> Result<Vec<i64>> {
        let normalized_ts = self.normalized_rib_ts()?;

        let parse_filters = ParseFilters {
            origin_asn: self.filters.origin_asn.clone(),
            prefix: self.filters.prefix.clone(),
            include_super: self.filters.include_super,
            include_sub: self.filters.include_sub,
            peer_asn: self.filters.peer_asn.clone(),
            as_path: self.filters.as_path.clone(),
            ..Default::default()
        };
        parse_filters.validate()?;

        if let Some(as_path) = &self.filters.as_path {
            Regex::new(as_path)
                .map_err(|e| anyhow!("Invalid --as-path regex '{}': {}", as_path, e))?;
        }

        if normalized_ts.len() > 1 && self.sqlite_path.is_none() {
            return Err(anyhow!("Multiple RIB timestamps require --sqlite-path."));
        }

        Ok(normalized_ts)
    }
}

#[derive(Debug, Clone)]
pub struct RibRunSummary {
    pub rib_ts: Vec<i64>,
    pub collectors_processed: usize,
    pub groups_processed: usize,
}

#[derive(Debug, Clone)]
struct RibReplayGroup {
    collector: String,
    rib_item: BrokerItem,
    rib_ts: Vec<i64>,
    updates: Vec<BrokerItem>,
}

#[derive(Debug, Clone)]
enum DeltaOp {
    Upsert(StoredRibEntry),
    Delete(RibRouteKey),
}

#[derive(Debug, Clone)]
struct OriginFilter {
    values: HashSet<u32>,
    negated: bool,
}

pub struct RibLens<'a> {
    db: &'a MonocleDatabase,
    config: &'a MonocleConfig,
}

impl<'a> RibLens<'a> {
    pub fn new(db: &'a MonocleDatabase, config: &'a MonocleConfig) -> Self {
        Self { db, config }
    }

    /// Reconstruct RIB snapshots at specified timestamps.
    ///
    /// The `snapshot_visitor` callback is invoked for each snapshot with:
    /// - `i64`: The target RIB timestamp
    /// - `&RibStateStore`: The final reconstructed RIB state
    /// - `&[StoredRibUpdate]`: Filtered updates that contributed to this snapshot
    ///   (empty for the first/base RIB, populated for subsequent RIBs)
    pub fn reconstruct_snapshots<F>(
        &self,
        args: &RibArgs,
        no_update: bool,
        mut snapshot_visitor: F,
    ) -> Result<RibRunSummary>
    where
        F: FnMut(i64, &RibStateStore, &[StoredRibUpdate]) -> Result<()>,
    {
        let normalized_ts = args.validate()?;
        let country_asns = self.resolve_country_asns(args.filters.country.as_deref(), no_update)?;
        let origin_filter = Self::parse_origin_filter(&args.filters.origin_asn)?;
        let as_path_regex = Self::compile_as_path_regex(args.filters.as_path.as_deref())?;
        let groups = self.resolve_replay_groups(args, &normalized_ts)?;

        let allowlists = if args.filters.full_feed_only {
            self.build_full_feed_allowlists(&groups)?
        } else {
            HashMap::new()
        };

        for group in &groups {
            let mut state_store = RibStateStore::new_temp()?;
            let safe_base_filters = self.safe_parse_filters(
                args,
                group.rib_item.ts_start.and_utc().timestamp(),
                group.rib_item.ts_end.and_utc().timestamp(),
            );

            self.load_base_rib(
                &mut state_store,
                &group.collector,
                &group.rib_item,
                &safe_base_filters,
                country_asns.as_ref(),
                origin_filter.as_ref(),
                as_path_regex.as_ref(),
                allowlists.get(group.collector.as_str()),
            )?;

            // If the first target timestamp equals the RIB time, emit it immediately
            // with empty updates (it's the base RIB, not built from updates)
            let rib_ts = group.rib_item.ts_start.and_utc().timestamp();
            if group
                .rib_ts
                .first()
                .map(|&ts| ts == rib_ts)
                .unwrap_or(false)
            {
                snapshot_visitor(group.rib_ts[0], &state_store, &[])?;
                // Create a new group with remaining timestamps for replay
                let remaining_ts: Vec<i64> = group.rib_ts.iter().skip(1).copied().collect();
                if !remaining_ts.is_empty() {
                    let mut new_group = group.clone();
                    new_group.rib_ts = remaining_ts;
                    self.replay_updates(
                        &mut state_store,
                        &new_group,
                        args,
                        country_asns.as_ref(),
                        origin_filter.as_ref(),
                        as_path_regex.as_ref(),
                        allowlists.get(group.collector.as_str()),
                        &mut snapshot_visitor,
                    )?;
                }
            } else {
                self.replay_updates(
                    &mut state_store,
                    group,
                    args,
                    country_asns.as_ref(),
                    origin_filter.as_ref(),
                    as_path_regex.as_ref(),
                    allowlists.get(group.collector.as_str()),
                    &mut snapshot_visitor,
                )?;
            }
        }

        let collector_count = groups
            .iter()
            .map(|group| group.collector.as_str())
            .collect::<HashSet<_>>()
            .len();

        Ok(RibRunSummary {
            rib_ts: normalized_ts,
            collectors_processed: collector_count,
            groups_processed: groups.len(),
        })
    }

    pub fn file_name_prefix(&self, args: &RibArgs, rib_ts: &[i64]) -> Result<String> {
        let base = if rib_ts.len() == 1 {
            format!(
                "monocle-rib-{}",
                Self::format_rib_ts_for_filename(rib_ts[0])?
            )
        } else {
            format!(
                "monocle-rib-{}-{}",
                Self::format_rib_ts_for_filename(
                    *rib_ts
                        .first()
                        .ok_or_else(|| anyhow!("missing first rib_ts"))?
                )?,
                Self::format_rib_ts_for_filename(
                    *rib_ts
                        .last()
                        .ok_or_else(|| anyhow!("missing last rib_ts"))?
                )?,
            )
        };

        let slug = self.filter_slug(&args.filters)?;
        if slug.is_empty() {
            Ok(base)
        } else {
            Ok(format!("{}-{}", base, slug))
        }
    }

    fn resolve_country_asns(
        &self,
        country: Option<&str>,
        no_update: bool,
    ) -> Result<Option<HashSet<u32>>> {
        let Some(country) = country else {
            return Ok(None);
        };

        let country_code = self.resolve_country_code(country)?;
        let asinfo = self.db.asinfo();

        if asinfo.is_empty() {
            if no_update {
                return Err(anyhow!(
                    "ASInfo data is empty but --country was requested. Re-run without --no-update or refresh ASInfo first."
                ));
            }
            self.db
                .refresh_asinfo()
                .map_err(|e| anyhow!("Failed to refresh ASInfo data for country filter: {}", e))?;
        } else if !no_update && asinfo.needs_refresh(self.config.asinfo_cache_ttl()) {
            self.db.refresh_asinfo().map_err(|e| {
                anyhow!(
                    "Failed to refresh stale ASInfo data for country filter: {}",
                    e
                )
            })?;
        }

        let mut asns = HashSet::new();
        let mut stmt = self
            .db
            .connection()
            .prepare("SELECT asn FROM asinfo_core WHERE UPPER(country) = UPPER(?1) ORDER BY asn")
            .map_err(|e| anyhow!("Failed to prepare ASInfo country lookup: {}", e))?;
        let rows = stmt
            .query_map([country_code.clone()], |row| row.get::<_, u32>(0))
            .map_err(|e| {
                anyhow!(
                    "Failed to query ASInfo by country '{}': {}",
                    country_code,
                    e
                )
            })?;

        for row in rows {
            asns.insert(row.map_err(|e| anyhow!("Failed to decode ASInfo country row: {}", e))?);
        }

        Ok(Some(asns))
    }

    fn resolve_country_code(&self, input: &str) -> Result<String> {
        let lens = CountryLens::new();
        let matches = lens.lookup(input);

        if matches.is_empty() {
            if input.len() == 2 {
                return Ok(input.to_uppercase());
            }
            return Err(anyhow!("Unknown country filter '{}'", input));
        }

        let exact_name_matches: Vec<_> = matches
            .iter()
            .filter(|entry| entry.name.eq_ignore_ascii_case(input))
            .collect();
        if exact_name_matches.len() == 1 {
            return Ok(exact_name_matches[0].code.clone());
        }

        let exact_code_matches: Vec<_> = matches
            .iter()
            .filter(|entry| entry.code.eq_ignore_ascii_case(input))
            .collect();
        if exact_code_matches.len() == 1 {
            return Ok(exact_code_matches[0].code.clone());
        }

        if matches.len() == 1 {
            return Ok(matches[0].code.clone());
        }

        Err(anyhow!(
            "Country filter '{}' is ambiguous; matches: {}",
            input,
            matches
                .iter()
                .map(|entry| format!("{} ({})", entry.name, entry.code))
                .collect::<Vec<_>>()
                .join(", ")
        ))
    }

    fn parse_origin_filter(values: &[String]) -> Result<Option<OriginFilter>> {
        if values.is_empty() {
            return Ok(None);
        }

        let negated = values
            .first()
            .map(|value| value.starts_with('!'))
            .unwrap_or(false);
        let mut parsed = HashSet::new();

        for value in values {
            let asn = value
                .trim_start_matches('!')
                .parse::<u32>()
                .map_err(|e| anyhow!("Invalid origin ASN filter '{}': {}", value, e))?;
            parsed.insert(asn);
        }

        Ok(Some(OriginFilter {
            values: parsed,
            negated,
        }))
    }

    fn compile_as_path_regex(pattern: Option<&str>) -> Result<Option<Regex>> {
        pattern
            .map(|pattern| {
                Regex::new(pattern)
                    .map_err(|e| anyhow!("Invalid --as-path regex '{}': {}", pattern, e))
            })
            .transpose()
    }

    fn resolve_replay_groups(
        &self,
        args: &RibArgs,
        normalized_ts: &[i64],
    ) -> Result<Vec<RibReplayGroup>> {
        let first_ts = *normalized_ts
            .first()
            .ok_or_else(|| anyhow!("Missing earliest rib_ts after validation"))?;
        let last_ts = *normalized_ts
            .last()
            .ok_or_else(|| anyhow!("Missing latest rib_ts after validation"))?;

        let ribs = self
            .base_broker(args)
            .data_type("rib")
            .ts_start(Self::timestamp_to_broker_string(
                first_ts - Duration::hours(RIB_LOOKBACK_HOURS).num_seconds(),
            )?)
            .ts_end(Self::timestamp_to_broker_string(last_ts)?)
            .query()
            .map_err(|e| anyhow!("Failed to query broker for candidate RIB files: {}", e))?;

        let mut ribs_by_collector: BTreeMap<String, Vec<BrokerItem>> = BTreeMap::new();
        for item in ribs {
            ribs_by_collector
                .entry(item.collector_id.clone())
                .or_default()
                .push(item);
        }

        let mut groups = Vec::new();
        for (collector, mut collector_ribs) in ribs_by_collector {
            collector_ribs.sort_by_key(|item| item.ts_start);

            let mut timestamps_by_rib: BTreeMap<String, (BrokerItem, Vec<i64>)> = BTreeMap::new();
            for rib_ts in normalized_ts {
                let selected_rib = collector_ribs
                    .iter()
                    .filter(|item| item.ts_start.and_utc().timestamp() <= *rib_ts)
                    .max_by_key(|item| item.ts_start);

                let Some(selected_rib) = selected_rib else {
                    return Err(anyhow!(
                        "No RIB file found at or before {} for collector {}",
                        Self::format_rib_ts_for_error(*rib_ts)?,
                        collector
                    ));
                };

                timestamps_by_rib
                    .entry(selected_rib.url.clone())
                    .and_modify(|(_, timestamps)| timestamps.push(*rib_ts))
                    .or_insert_with(|| (selected_rib.clone(), vec![*rib_ts]));
            }

            for (_, (rib_item, mut group_ts)) in timestamps_by_rib {
                group_ts.sort_unstable();
                let group_max_ts = *group_ts
                    .last()
                    .ok_or_else(|| anyhow!("Replay group was created without any rib_ts"))?;
                let updates =
                    self.resolve_group_updates(args, &collector, &rib_item, group_max_ts)?;

                groups.push(RibReplayGroup {
                    collector: collector.clone(),
                    rib_item,
                    rib_ts: group_ts,
                    updates,
                });
            }
        }

        groups.sort_by(|a, b| {
            a.collector
                .cmp(&b.collector)
                .then(a.rib_item.ts_start.cmp(&b.rib_item.ts_start))
        });

        if groups.is_empty() {
            return Err(anyhow!(
                "No suitable RIB files were found for the requested timestamps and collector filters."
            ));
        }

        Ok(groups)
    }

    fn resolve_group_updates(
        &self,
        args: &RibArgs,
        collector: &str,
        rib_item: &BrokerItem,
        group_max_ts: i64,
    ) -> Result<Vec<BrokerItem>> {
        let rib_ts = rib_item.ts_start.and_utc().timestamp();

        let mut broker = self
            .base_broker(args)
            .collector_id(collector)
            .data_type("updates")
            .ts_start(Self::timestamp_to_broker_string(rib_ts)?)
            .ts_end(Self::timestamp_to_broker_string(group_max_ts)?);

        if let Some(project) = &args.filters.project {
            broker = broker.project(project);
        }

        let mut updates = broker.query().map_err(|e| {
            anyhow!(
                "Failed to query broker for updates for {}: {}",
                collector,
                e
            )
        })?;

        // Only keep update files that contain data up to and including the target timestamp.
        // An update file with ts_end <= group_max_ts has all elements with timestamp <= group_max_ts.
        updates.retain(|item| {
            let item_end = item.ts_end.and_utc().timestamp();
            item_end > rib_ts && item_end <= group_max_ts
        });
        updates.sort_by_key(|item| item.ts_start);
        Ok(updates)
    }

    fn build_full_feed_allowlists(&self, groups: &[RibReplayGroup]) -> Result<FullFeedAllowlists> {
        let mut allowlists = HashMap::new();

        for collector in groups
            .iter()
            .map(|group| group.collector.as_str())
            .collect::<BTreeSet<_>>()
        {
            let peers = BgpkitBroker::new()
                .collector_id(collector)
                .get_peers()
                .map_err(|e| {
                    anyhow!(
                        "Failed to fetch broker peer metadata for {}: {}",
                        collector,
                        e
                    )
                })?;

            let allowed = peers
                .into_iter()
                .filter(|peer| {
                    peer.num_v4_pfxs >= FULL_FEED_V4_THRESHOLD
                        || peer.num_v6_pfxs >= FULL_FEED_V6_THRESHOLD
                })
                .map(|peer| (peer.ip.to_string(), peer.asn))
                .collect::<HashSet<_>>();

            allowlists.insert(collector.to_string(), allowed);
        }

        Ok(allowlists)
    }

    #[allow(clippy::too_many_arguments)]
    fn load_base_rib(
        &self,
        state_store: &mut RibStateStore,
        collector: &str,
        rib_item: &BrokerItem,
        safe_filters: &ParseFilters,
        country_asns: Option<&HashSet<u32>>,
        origin_filter: Option<&OriginFilter>,
        as_path_regex: Option<&Regex>,
        full_feed_allowlist: Option<&HashSet<(String, u32)>>,
    ) -> Result<()> {
        let parser = safe_filters.to_parser(&rib_item.url).map_err(|e| {
            anyhow!(
                "Failed to build parser for base RIB {}: {}",
                rib_item.url,
                e
            )
        })?;

        let collector_arc = Arc::from(collector);
        let mut batch = Vec::new();
        for elem in parser {
            if elem.elem_type != ElemType::ANNOUNCE {
                continue;
            }
            if self.announce_matches(
                collector,
                &elem,
                country_asns,
                origin_filter,
                as_path_regex,
                full_feed_allowlist,
            ) {
                batch.push(StoredRibEntry::from_elem(Arc::clone(&collector_arc), elem));
            }
        }

        state_store.upsert_entries(batch)?;
        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    fn replay_updates<F>(
        &self,
        state_store: &mut RibStateStore,
        group: &RibReplayGroup,
        args: &RibArgs,
        country_asns: Option<&HashSet<u32>>,
        origin_filter: Option<&OriginFilter>,
        as_path_regex: Option<&Regex>,
        full_feed_allowlist: Option<&HashSet<(String, u32)>>,
        snapshot_visitor: &mut F,
    ) -> Result<()>
    where
        F: FnMut(i64, &RibStateStore, &[StoredRibUpdate]) -> Result<()>,
    {
        let mut pending = HashMap::<RibRouteKey, DeltaOp>::new();
        let mut next_snapshot_index = 0usize;
        let collector_arc = Arc::from(group.collector.as_str());

        // Track filtered updates for the current snapshot interval
        // These are updates that matched filters and affected the RIB state
        let mut filtered_updates: Vec<StoredRibUpdate> = Vec::new();

        for update in &group.updates {
            let safe_filters = self.safe_parse_filters(
                args,
                group.rib_item.ts_start.and_utc().timestamp(),
                *group
                    .rib_ts
                    .last()
                    .ok_or_else(|| anyhow!("Replay group missing max rib_ts"))?,
            );
            let parser = safe_filters.to_parser(&update.url).map_err(|e| {
                anyhow!(
                    "Failed to build parser for updates file {}: {}",
                    update.url,
                    e
                )
            })?;

            for elem in parser {
                while next_snapshot_index < group.rib_ts.len()
                    && elem.timestamp > group.rib_ts[next_snapshot_index] as f64
                {
                    self.flush_pending(state_store, &mut pending)?;
                    // For the first RIB (index 0), pass empty updates
                    // For subsequent RIBs, pass the collected filtered updates
                    snapshot_visitor(
                        group.rib_ts[next_snapshot_index],
                        state_store,
                        &filtered_updates,
                    )?;
                    // Clear updates after emitting snapshot (they belong to this snapshot)
                    filtered_updates.clear();
                    next_snapshot_index += 1;
                }

                // Apply update and track if it was filtered/matched
                let was_applied = self.apply_update_to_delta(
                    &mut pending,
                    state_store,
                    Arc::clone(&collector_arc),
                    &elem,
                    country_asns,
                    origin_filter,
                    as_path_regex,
                    full_feed_allowlist,
                )?;

                // If the update was applied (matched filters), track it for the updates table
                if was_applied {
                    let elem_type = elem.elem_type;
                    let update_record = StoredRibUpdate::from_elem(
                        group.rib_ts[next_snapshot_index.min(group.rib_ts.len() - 1)],
                        Arc::clone(&collector_arc),
                        elem,
                        elem_type,
                    );
                    filtered_updates.push(update_record);
                }
            }
        }

        while next_snapshot_index < group.rib_ts.len() {
            self.flush_pending(state_store, &mut pending)?;
            snapshot_visitor(
                group.rib_ts[next_snapshot_index],
                state_store,
                &filtered_updates,
            )?;
            filtered_updates.clear();
            next_snapshot_index += 1;
        }

        Ok(())
    }

    /// Apply an update to the pending delta and return whether it matched filters.
    ///
    /// Returns `true` if the update matched filters and was recorded in the delta,
    /// `false` if it was filtered out (doesn't mean it won't affect state - withdraws
    /// always check for existing routes).
    #[allow(clippy::too_many_arguments)]
    fn apply_update_to_delta(
        &self,
        pending: &mut HashMap<RibRouteKey, DeltaOp>,
        state_store: &RibStateStore,
        collector: Arc<str>,
        elem: &BgpElem,
        country_asns: Option<&HashSet<u32>>,
        origin_filter: Option<&OriginFilter>,
        as_path_regex: Option<&Regex>,
        full_feed_allowlist: Option<&HashSet<(String, u32)>>,
    ) -> Result<bool> {
        let route_key = RibRouteKey::from_elem(Arc::clone(&collector), elem);

        match elem.elem_type {
            ElemType::WITHDRAW => {
                if self.route_exists_in_state_or_delta(&route_key, state_store, pending)? {
                    pending.insert(route_key.clone(), DeltaOp::Delete(route_key));
                    Ok(true)
                } else {
                    Ok(false)
                }
            }
            ElemType::ANNOUNCE => {
                let matches = self.announce_matches(
                    &collector,
                    elem,
                    country_asns,
                    origin_filter,
                    as_path_regex,
                    full_feed_allowlist,
                );

                if matches {
                    pending.insert(
                        route_key,
                        DeltaOp::Upsert(StoredRibEntry::from_elem(collector, elem.clone())),
                    );
                    Ok(true)
                } else if self.route_exists_in_state_or_delta(&route_key, state_store, pending)? {
                    pending.insert(route_key.clone(), DeltaOp::Delete(route_key));
                    Ok(true)
                } else {
                    Ok(false)
                }
            }
        }
    }

    fn route_exists_in_state_or_delta(
        &self,
        route_key: &RibRouteKey,
        state_store: &RibStateStore,
        pending: &HashMap<RibRouteKey, DeltaOp>,
    ) -> Result<bool> {
        if let Some(delta) = pending.get(route_key) {
            return Ok(matches!(delta, DeltaOp::Upsert(_)));
        }
        state_store.route_exists(route_key)
    }

    fn flush_pending(
        &self,
        state_store: &mut RibStateStore,
        pending: &mut HashMap<RibRouteKey, DeltaOp>,
    ) -> Result<()> {
        if pending.is_empty() {
            return Ok(());
        }

        let mut upserts = Vec::new();
        let mut deletes = Vec::new();

        for delta in pending.values() {
            match delta {
                DeltaOp::Upsert(entry) => upserts.push(entry.clone()),
                DeltaOp::Delete(key) => deletes.push(key.clone()),
            }
        }

        if !upserts.is_empty() {
            state_store.upsert_entries(upserts)?;
        }
        if !deletes.is_empty() {
            state_store.delete_keys(deletes)?;
        }

        pending.clear();
        Ok(())
    }

    fn announce_matches(
        &self,
        collector: &str,
        elem: &BgpElem,
        country_asns: Option<&HashSet<u32>>,
        origin_filter: Option<&OriginFilter>,
        as_path_regex: Option<&Regex>,
        full_feed_allowlist: Option<&HashSet<(String, u32)>>,
    ) -> bool {
        if collector.is_empty() {
            return false;
        }

        if let Some(origin_filter) = origin_filter {
            let matches_origin = elem
                .origin_asns
                .as_ref()
                .map(|origins| {
                    origins
                        .iter()
                        .any(|asn| origin_filter.values.contains(&asn.to_u32()))
                })
                .unwrap_or(false);

            if origin_filter.negated {
                if matches_origin {
                    return false;
                }
            } else if !matches_origin {
                return false;
            }
        }

        if let Some(country_asns) = country_asns {
            let matches_country = elem
                .origin_asns
                .as_ref()
                .map(|origins| {
                    origins
                        .iter()
                        .any(|asn| country_asns.contains(&asn.to_u32()))
                })
                .unwrap_or(false);
            if !matches_country {
                return false;
            }
        }

        if let Some(as_path_regex) = as_path_regex {
            let as_path = elem
                .as_path
                .as_ref()
                .map(|path| path.to_string())
                .unwrap_or_default();
            if !as_path_regex.is_match(&as_path) {
                return false;
            }
        }

        if let Some(full_feed_allowlist) = full_feed_allowlist {
            let peer_key = (elem.peer_ip.to_string(), elem.peer_asn.to_u32());
            if !full_feed_allowlist.contains(&peer_key) {
                return false;
            }
        }

        true
    }

    fn safe_parse_filters(&self, args: &RibArgs, start_ts: i64, end_ts: i64) -> ParseFilters {
        ParseFilters {
            prefix: args.filters.prefix.clone(),
            include_super: args.filters.include_super,
            include_sub: args.filters.include_sub,
            peer_asn: args.filters.peer_asn.clone(),
            start_ts: Some(start_ts.to_string()),
            end_ts: Some(end_ts.to_string()),
            ..Default::default()
        }
    }

    fn base_broker(&self, args: &RibArgs) -> BgpkitBroker {
        let mut broker = BgpkitBroker::new().page_size(1000);
        if let Some(collector) = &args.filters.collector {
            broker = broker.collector_id(collector);
        }
        if let Some(project) = &args.filters.project {
            broker = broker.project(project);
        }
        broker
    }

    fn timestamp_to_broker_string(ts: i64) -> Result<String> {
        let timestamp = DateTime::from_timestamp(ts, 0)
            .ok_or_else(|| anyhow!("Invalid Unix timestamp {} for broker query", ts))?;
        Ok(timestamp.format("%Y-%m-%dT%H:%M:%SZ").to_string())
    }

    fn format_rib_ts_for_filename(rib_ts: i64) -> Result<String> {
        let timestamp = DateTime::from_timestamp(rib_ts, 0)
            .ok_or_else(|| anyhow!("Invalid Unix timestamp {} for file naming", rib_ts))?;
        Ok(timestamp.format("%Y%m%dT%H%M%SZ").to_string())
    }

    fn format_rib_ts_for_error(rib_ts: i64) -> Result<String> {
        let timestamp = DateTime::from_timestamp(rib_ts, 0)
            .ok_or_else(|| anyhow!("Invalid Unix timestamp {} for error reporting", rib_ts))?;
        Ok(timestamp.format("%Y-%m-%dT%H:%M:%SZ").to_string())
    }

    fn filter_slug(&self, filters: &RibFilters) -> Result<String> {
        let mut parts = Vec::new();

        if let Some(country) = &filters.country {
            parts.push(format!(
                "country-{}",
                Self::sanitize_slug_component(country)
            ));
        }
        if !filters.origin_asn.is_empty() {
            parts.push(format!(
                "origin-{}",
                Self::sanitize_list_component(&filters.origin_asn)
            ));
        }
        if !filters.peer_asn.is_empty() {
            parts.push(format!(
                "peer-{}",
                Self::sanitize_list_component(&filters.peer_asn)
            ));
        }
        if let Some(collector) = &filters.collector {
            let values = collector
                .split(',')
                .map(|value| value.trim().to_string())
                .collect::<Vec<_>>();
            parts.push(format!(
                "collector-{}",
                Self::sanitize_list_component(&values)
            ));
        }
        if let Some(project) = &filters.project {
            parts.push(format!(
                "project-{}",
                Self::sanitize_slug_component(project)
            ));
        }
        if !filters.prefix.is_empty() {
            parts.push(format!("prefix-{}", Self::hash8(&filters.prefix.join(","))));
        }
        if let Some(as_path) = &filters.as_path {
            parts.push(format!("aspath-{}", Self::hash8(as_path)));
        }
        if filters.full_feed_only {
            parts.push("fullfeed".to_string());
        }

        let slug = parts.join("-");
        if slug.len() <= 96 {
            return Ok(slug);
        }

        let truncated = slug
            .chars()
            .take(80)
            .collect::<String>()
            .trim_end_matches('-')
            .to_string();
        Ok(format!("{}-h{}", truncated, Self::hash8(&slug)))
    }

    fn sanitize_list_component(values: &[String]) -> String {
        let mut normalized = values
            .iter()
            .map(|value| Self::sanitize_slug_component(value))
            .collect::<Vec<_>>();
        normalized.sort();
        normalized.join("+")
    }

    fn sanitize_slug_component(input: &str) -> String {
        input
            .to_ascii_lowercase()
            .chars()
            .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '_' })
            .collect::<String>()
            .trim_matches('_')
            .to_string()
    }

    fn hash8(input: &str) -> String {
        let mut hash = 0xcbf29ce484222325_u64;
        for byte in input.as_bytes() {
            hash ^= u64::from(*byte);
            hash = hash.wrapping_mul(0x100000001b3);
        }
        format!("{:08x}", hash & 0xffff_ffff)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn base_args() -> RibArgs {
        RibArgs {
            rib_ts: vec!["2025-09-01T12:00:00Z".to_string()],
            filters: RibFilters {
                ..Default::default()
            },
            sqlite_path: None,
        }
    }

    #[test]
    fn test_validate_multi_ts_stdout_error() {
        let mut args = base_args();
        args.rib_ts.push("2025-09-01T13:00:00Z".to_string());
        assert!(args.validate().is_err());
    }

    #[test]
    fn test_validate_multi_ts_file_output_ok() -> Result<()> {
        let mut args = base_args();
        args.rib_ts.push("2025-09-01T13:00:00Z".to_string());
        args.sqlite_path = Some(PathBuf::from("/tmp/monocle-rib.sqlite3"));
        let values = args.validate()?;
        assert_eq!(values.len(), 2);
        Ok(())
    }

    #[test]
    fn test_filter_slug_order() -> Result<()> {
        let mut args = base_args();
        args.filters.country = Some("IR".to_string());
        args.filters.origin_asn = vec!["15169".to_string(), "13335".to_string()];
        args.filters.peer_asn = vec!["2914".to_string()];
        args.filters.collector = Some("rrc00,route-views2".to_string());
        args.filters.project = Some("riperis".to_string());
        args.filters.prefix = vec!["1.1.1.0/24".to_string()];
        args.filters.as_path = Some("^15169 ".to_string());
        args.filters.full_feed_only = true;

        let db = MonocleDatabase::open_in_memory()?;
        let config = MonocleConfig::default();
        let lens = RibLens::new(&db, &config);
        let slug = lens.filter_slug(&args.filters)?;

        assert!(slug
            .starts_with("country-ir-origin-13335+15169-peer-2914-collector-route_views2+rrc00"));
        assert!(slug.contains("-h"));
        Ok(())
    }

    #[test]
    fn test_hash8_is_stable() {
        assert_eq!(RibLens::hash8("a"), RibLens::hash8("a"));
    }

    #[test]
    fn test_file_name_prefix_includes_filters() -> Result<()> {
        let mut args = base_args();
        args.filters.country = Some("US".to_string());
        args.filters.origin_asn = vec!["13335".to_string()];
        args.filters.full_feed_only = true;

        let db = MonocleDatabase::open_in_memory()?;
        let config = MonocleConfig::default();
        let lens = RibLens::new(&db, &config);
        let file_name = format!(
            "{}.sqlite3",
            lens.file_name_prefix(&args, &[1_756_728_000])?
        );

        assert_eq!(
            file_name,
            "monocle-rib-20250901T120000Z-country-us-origin-13335-fullfeed.sqlite3"
        );
        Ok(())
    }
}