bgpkit-broker 0.11.0

A library and command-line to provide indexing and searching functionalities for public BGP data archive files over time.
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
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
/*!
# Overview

[bgpkit-broker][crate] is a package that allows accessing the BGPKIT Broker API and search for BGP archive
files with different search parameters available.

# Examples

## Basic Usage with Iterator

The recommended usage to collect [BrokerItem]s is to use the built-in iterator. The
[BrokerItemIterator] handles making API queries so that it can continuously stream new items until
it reaches the end of items. This is useful for simply getting **all** matching items without need
to worry about pagination.

```no_run
use bgpkit_broker::{BgpkitBroker, BrokerItem};

let broker = BgpkitBroker::new()
    .ts_start("2022-01-01")
    .ts_end("2022-01-02")
    .collector_id("route-views2");

// Iterate by reference (reusable broker)
for item in &broker {
    println!("BGP file: {} from {} ({})",
             item.url, item.collector_id, item.data_type);
}

// Or collect into vector
let items: Vec<BrokerItem> = broker.into_iter().collect();
println!("Found {} BGP archive files", items.len());
```

## Practical BGP Data Analysis with Shortcuts

The SDK provides convenient shortcuts for common BGP data analysis patterns:

### Daily RIB Analysis Across Diverse Collectors

```no_run
use bgpkit_broker::BgpkitBroker;

// Find the most diverse collectors for comprehensive analysis
let broker = BgpkitBroker::new()
    .ts_start("2024-01-01")
    .ts_end("2024-01-31");

let diverse_collectors = broker.most_diverse_collectors(5, None).unwrap();
println!("Selected {} diverse collectors: {:?}",
         diverse_collectors.len(), diverse_collectors);

// Get daily RIB snapshots from these collectors
let daily_ribs = broker
    .clone()
    .collector_id(&diverse_collectors.join(","))
    .daily_ribs().unwrap();

println!("Found {} daily RIB snapshots for analysis", daily_ribs.len());
for rib in daily_ribs.iter().take(3) {
    println!("Daily snapshot: {} from {} at {}",
             rib.collector_id,
             rib.ts_start.format("%Y-%m-%d"),
             rib.url);
}
```

### Recent BGP Updates Monitoring

```no_run
use bgpkit_broker::BgpkitBroker;

// Monitor recent BGP updates from multiple collectors
let recent_updates = BgpkitBroker::new()
    .collector_id("route-views2,rrc00,route-views6")
    .recent_updates(6).unwrap(); // last 6 hours

println!("Found {} recent BGP update files", recent_updates.len());
for update in recent_updates.iter().take(5) {
    println!("Update: {} from {} at {}",
             update.collector_id,
             update.ts_start.format("%Y-%m-%d %H:%M:%S"),
             update.url);
}
```

### Project-specific Analysis

```no_run
use bgpkit_broker::BgpkitBroker;

// Compare RouteViews vs RIPE RIS daily snapshots
let routeviews_ribs = BgpkitBroker::new()
    .ts_start("2024-01-01")
    .ts_end("2024-01-07")
    .project("routeviews")
    .daily_ribs().unwrap();

let ripe_ribs = BgpkitBroker::new()
    .ts_start("2024-01-01")
    .ts_end("2024-01-07")
    .project("riperis")
    .daily_ribs().unwrap();

println!("RouteViews daily RIBs: {}", routeviews_ribs.len());
println!("RIPE RIS daily RIBs: {}", ripe_ribs.len());
```

### Advanced Collector Selection

```no_run
use bgpkit_broker::BgpkitBroker;

let broker = BgpkitBroker::new();

// Get diverse RouteViews collectors for focused analysis
let rv_collectors = broker.most_diverse_collectors(3, Some("routeviews")).unwrap();
println!("Diverse RouteViews collectors: {:?}", rv_collectors);

// Use them to get comprehensive recent updates
let comprehensive_updates = broker
    .clone()
    .collector_id(&rv_collectors.join(","))
    .recent_updates(12).unwrap(); // last 12 hours

println!("Got {} updates from {} collectors",
         comprehensive_updates.len(), rv_collectors.len());
```

### Routing Table Snapshot Reconstruction

```no_run
use bgpkit_broker::BgpkitBroker;

// Get the MRT files needed to construct a routing table snapshot
let broker = BgpkitBroker::new();
let snapshots = broker.get_snapshot_files(
    &["route-views2", "rrc00"],
    "2024-01-01T12:00:00Z"
).unwrap();

for snapshot in snapshots {
    println!("Collector: {}", snapshot.collector_id);
    println!("RIB dump: {}", snapshot.rib_url);
    println!("Updates to apply: {}", snapshot.updates_urls.len());

    // Use with bgpkit-parser to reconstruct routing table:
    // 1. Parse RIB dump for initial state
    // 2. Apply updates in order to reach target timestamp
}
```

## Manual Page Queries

For fine-grained control over pagination or custom iteration patterns:

```rust,no_run
use bgpkit_broker::BgpkitBroker;

let mut broker = BgpkitBroker::new()
    .ts_start("2022-01-01")
    .ts_end("2022-01-02")
    .page(1)
    .page_size(50);

// Query specific page
let page1_items = broker.query_single_page().unwrap();
println!("Page 1: {} items", page1_items.len());

// Move to next page
broker.turn_page(2);
let page2_items = broker.query_single_page().unwrap();
println!("Page 2: {} items", page2_items.len());
```

## Getting Latest Files and Peer Information

Access the most recent data and peer information:

```rust,no_run
use bgpkit_broker::BgpkitBroker;

// Get latest files from all collectors
let broker = BgpkitBroker::new();
let latest_files = broker.latest().unwrap();
println!("Latest files from {} collectors", latest_files.len());

// Get full-feed peers from specific collector
let peers = BgpkitBroker::new()
    .collector_id("route-views2")
    .peers_only_full_feed(true)
    .get_peers().unwrap();

println!("Found {} full-feed peers", peers.len());
for peer in peers.iter().take(3) {
    println!("Peer: AS{} ({}) - v4: {}, v6: {}",
             peer.asn, peer.ip, peer.num_v4_pfxs, peer.num_v6_pfxs);
}
```
*/

#![doc(
    html_logo_url = "https://raw.githubusercontent.com/bgpkit/assets/main/logos/icon-transparent.png",
    html_favicon_url = "https://raw.githubusercontent.com/bgpkit/assets/main/logos/favicon.ico"
)]
#![allow(unknown_lints)]

mod collector;
#[cfg(feature = "cli")]
pub mod config;
#[cfg(feature = "cli")]
mod crawler;
#[cfg(feature = "backend")]
pub mod db;
mod error;
mod item;
mod peer;
mod query;
mod shortcuts;
#[cfg(feature = "sse")]
mod sse;

use crate::collector::DEFAULT_COLLECTORS_CONFIG;
use crate::peer::BrokerPeersResult;
use crate::query::{BrokerQueryResult, CollectorLatestResult};
use chrono::{DateTime, NaiveDate, TimeZone, Utc};
pub use collector::{load_collectors, Collector};

#[cfg(feature = "cli")]
pub use config::BrokerConfig;
#[cfg(feature = "cli")]
pub use crawler::crawl_collector;
#[cfg(feature = "backend")]
pub use db::{LocalBrokerDb, UpdatesMeta, DEFAULT_PAGE_SIZE};
pub use error::BrokerError;
pub use item::BrokerItem;
pub use peer::BrokerPeer;
pub use query::{QueryParams, SortOrder};
pub use shortcuts::SnapshotFiles;
#[cfg(feature = "sse")]
pub use sse::{BrokerItemSubscription, SseSubscriptionOptions};
use std::collections::{HashMap, HashSet};
use std::fmt::Display;
use std::net::IpAddr;
use std::path::PathBuf;

const SDK_USER_AGENT: &str = concat!("bgpkit-broker/", env!("CARGO_PKG_VERSION"));

/// BgpkitBroker struct maintains the broker's URL and handles making API queries.
///
/// See [module doc][crate#examples] for usage examples.
#[derive(Clone)]
pub struct BgpkitBroker {
    pub broker_url: String,
    pub query_params: QueryParams,
    client: reqwest::blocking::Client,
    collector_project_map: HashMap<String, String>,
    accept_invalid_certs: bool,
    cache_dir: Option<PathBuf>,
}

impl Default for BgpkitBroker {
    fn default() -> Self {
        dotenvy::dotenv().ok();
        let url = match std::env::var("BGPKIT_BROKER_URL") {
            Ok(url) => url.trim_end_matches('/').to_string(),
            Err(_) => "https://api.bgpkit.com/v3/broker".to_string(),
        };

        let collector_project_map = DEFAULT_COLLECTORS_CONFIG.clone().to_project_map();

        let accept_invalid_certs = read_accept_invalid_certs_from_env();
        let client = build_blocking_client(accept_invalid_certs);

        Self {
            broker_url: url,
            query_params: Default::default(),
            client,
            collector_project_map,
            accept_invalid_certs,
            cache_dir: None,
        }
    }
}

fn read_accept_invalid_certs_from_env() -> bool {
    match std::env::var("ONEIO_ACCEPT_INVALID_CERTS") {
        Ok(t) => {
            let l = t.to_lowercase();
            l.starts_with("true") || l.starts_with("y")
        }
        Err(_) => false,
    }
}

fn build_blocking_client(accept_invalid_certs: bool) -> reqwest::blocking::Client {
    match reqwest::blocking::ClientBuilder::new()
        .danger_accept_invalid_certs(accept_invalid_certs)
        .user_agent(SDK_USER_AGENT)
        .build()
    {
        Ok(c) => c,
        Err(e) => {
            panic!("Failed to build HTTP client for broker requests: {}", e);
        }
    }
}

#[cfg(feature = "sse")]
pub(crate) fn build_async_client(
    accept_invalid_certs: bool,
) -> Result<reqwest::Client, BrokerError> {
    reqwest::ClientBuilder::new()
        .danger_accept_invalid_certs(accept_invalid_certs)
        .user_agent(SDK_USER_AGENT)
        .build()
        .map_err(BrokerError::NetworkError)
}

impl BgpkitBroker {
    /// Construct a new BgpkitBroker object.
    ///
    /// The URL and query parameters can be adjusted with other functions.
    ///
    /// Users can opt in to accept invalid SSL certificates by setting the environment variable
    /// `ONEIO_ACCEPT_INVALID_CERTS` to `true`.
    ///
    /// # Examples
    /// ```
    /// use bgpkit_broker::BgpkitBroker;
    /// let broker = BgpkitBroker::new();
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Configure broker URL.
    ///
    /// You can change the default broker URL to point to your own broker instance.
    /// You can also change the URL by setting the environment variable `BGPKIT_BROKER_URL`.
    ///
    /// # Examples
    /// ```
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///     .broker_url("api.broker.example.com/v3");
    /// ```
    pub fn broker_url<S: Display>(self, url: S) -> Self {
        let broker_url = url.to_string().trim_end_matches('/').to_string();
        Self {
            broker_url,
            query_params: self.query_params,
            client: self.client,
            collector_project_map: self.collector_project_map,
            accept_invalid_certs: self.accept_invalid_certs,
            cache_dir: self.cache_dir,
        }
    }

    /// DANGER: Accept invalid SSL certificates.
    pub fn accept_invalid_certs(self) -> Self {
        Self {
            broker_url: self.broker_url,
            query_params: self.query_params,
            client: build_blocking_client(true),
            collector_project_map: self.collector_project_map,
            accept_invalid_certs: true,
            cache_dir: self.cache_dir,
        }
    }

    /// Disable SSL certificate check.
    #[deprecated(since = "0.7.1", note = "Please use `accept_invalid_certs` instead.")]
    pub fn disable_ssl_check(self) -> Self {
        Self::accept_invalid_certs(self)
    }

    /// Set the cache directory for storing query results.
    ///
    /// When a cache directory is specified, query results will be cached to disk
    /// and loaded from cache on subsequent queries with the same parameters.
    /// This is useful for development and offline usage.
    ///
    /// The directory will be created if it doesn't exist. Panics if unable to create.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///     .cache_dir("/tmp/bgpkit-cache");
    /// ```
    pub fn cache_dir<P: Into<PathBuf>>(mut self, path: P) -> Self {
        let path = path.into();
        if !path.exists() {
            std::fs::create_dir_all(&path).expect("Failed to create cache directory");
        }
        self.cache_dir = Some(path);
        self
    }

    /// Generate cache key from current query parameters.
    fn cache_key(&self) -> String {
        use sha2::{Digest, Sha256};
        
        let params_str = format!(
            "{}:{}:{}:{}:{}:{}:{}:{}",
            self.broker_url,
            self.query_params.ts_start.as_deref().unwrap_or(""),
            self.query_params.ts_end.as_deref().unwrap_or(""),
            self.query_params.collector_id.as_deref().unwrap_or(""),
            self.query_params.project.as_deref().unwrap_or(""),
            self.query_params.data_type.as_deref().unwrap_or(""),
            self.query_params.page,
            self.query_params.page_size
        );
        
        let mut hasher = Sha256::new();
        hasher.update(params_str.as_bytes());
        format!("{:x}", hasher.finalize())
    }

    /// Try to load cached results for current query parameters.
    fn load_cache(&self) -> Option<Vec<BrokerItem>> {
        let cache_dir = self.cache_dir.as_ref()?;
        let cache_file = cache_dir.join(self.cache_key()).with_extension("json");
        
        if !cache_file.exists() {
            return None;
        }
        
        match std::fs::read_to_string(&cache_file) {
            Ok(contents) => {
                match serde_json::from_str::<Vec<BrokerItem>>(&contents) {
                    Ok(items) => {
                        log::info!("Loaded {} items from cache", items.len());
                        Some(items)
                    }
                    Err(e) => {
                        log::warn!("Failed to deserialize cache file: {}", e);
                        None
                    }
                }
            }
            Err(e) => {
                log::warn!("Failed to read cache file: {}", e);
                None
            }
        }
    }

    /// Save results to cache for current query parameters.
    fn save_cache(&self, items: &[BrokerItem]) {
        let Some(cache_dir) = self.cache_dir.as_ref() else {
            return;
        };
        
        let cache_file = cache_dir.join(self.cache_key()).with_extension("json");
        
        match serde_json::to_string(items) {
            Ok(json) => {
                if let Err(e) = std::fs::write(&cache_file, json) {
                    log::warn!("Failed to write cache file: {}", e);
                } else {
                    log::info!("Saved {} items to cache", items.len());
                }
            }
            Err(e) => {
                log::warn!("Failed to serialize items for cache: {}", e);
            }
        }
    }

    /// Parse and validate timestamp string with support for multiple formats.
    ///
    /// Supported formats:
    /// - Unix timestamp: "1640995200"
    /// - RFC3339/ISO8601: "2022-01-01T00:00:00Z", "2022-01-01T12:30:45Z"
    /// - RFC3339 without Z: "2022-01-01T00:00:00", "2022-01-01T12:30:45"
    /// - Date with time: "2022-01-01 00:00:00", "2022-01-01 12:30:45"
    /// - Pure date (start of day): "2022-01-01", "2022/01/01"
    /// - Pure date with dots: "2022.01.01"
    /// - Compact date: "20220101"
    ///
    /// For pure date formats, the time component defaults to 00:00:00 (start of day).
    /// Returns a `DateTime<Utc>` for consistent handling and formatting.
    fn parse_timestamp(timestamp: &str) -> Result<DateTime<Utc>, BrokerError> {
        let ts_str = timestamp.trim();

        // Try parsing as RFC3339 with timezone (including +00:00, -05:00, Z, etc.)
        if let Ok(dt_with_tz) = DateTime::parse_from_rfc3339(ts_str) {
            return Ok(dt_with_tz.with_timezone(&Utc));
        }

        // Try parsing as RFC3339/ISO8601 with Z
        if let Ok(naive_dt) = chrono::NaiveDateTime::parse_from_str(ts_str, "%Y-%m-%dT%H:%M:%SZ") {
            return Ok(Utc.from_utc_datetime(&naive_dt));
        }

        // Try parsing as RFC3339 without Z (assume UTC)
        if let Ok(naive_dt) = chrono::NaiveDateTime::parse_from_str(ts_str, "%Y-%m-%dT%H:%M:%S") {
            return Ok(Utc.from_utc_datetime(&naive_dt));
        }

        // Try parsing as "YYYY-MM-DD HH:MM:SS" (assume UTC)
        if let Ok(naive_dt) = chrono::NaiveDateTime::parse_from_str(ts_str, "%Y-%m-%d %H:%M:%S") {
            return Ok(Utc.from_utc_datetime(&naive_dt));
        }

        // Try parsing pure date formats and convert to start of day
        let date_formats = [
            "%Y-%m-%d", // 2022-01-01
            "%Y/%m/%d", // 2022/01/01
            "%Y.%m.%d", // 2022.01.01
            "%Y%m%d",   // 20220101 - must be exactly 8 digits
        ];

        for format in &date_formats {
            if let Ok(date) = NaiveDate::parse_from_str(ts_str, format) {
                // Additional validation for compact format to ensure it's actually a date
                if format == &"%Y%m%d" && ts_str.len() != 8 {
                    continue;
                }
                // Convert to start of day in UTC
                if let Some(naive_datetime) = date.and_hms_opt(0, 0, 0) {
                    return Ok(Utc.from_utc_datetime(&naive_datetime));
                }
            }
        }

        // Finally, try parsing as Unix timestamp (only if it's reasonable length and all digits)
        if ts_str.len() >= 9 && ts_str.len() <= 13 && ts_str.chars().all(|c| c.is_ascii_digit()) {
            if let Ok(timestamp) = ts_str.parse::<i64>() {
                if let Some(dt) = Utc.timestamp_opt(timestamp, 0).single() {
                    return Ok(dt);
                }
            }
        }

        Err(BrokerError::ConfigurationError(format!(
            "Invalid timestamp format '{ts_str}'. Supported formats:\n\
                - Unix timestamp: '1640995200'\n\
                - RFC3339 with timezone: '2022-01-01T00:00:00+00:00', '2022-01-01T00:00:00Z', '2022-01-01T05:00:00-05:00'\n\
                - RFC3339 without timezone: '2022-01-01T00:00:00' (assumes UTC)\n\
                - Date with time: '2022-01-01 00:00:00'\n\
                - Pure date: '2022-01-01', '2022/01/01', '2022.01.01', '20220101'"
        )))
    }

    /// Validate all configuration parameters before making API calls.
    ///
    /// This performs the same validation that was previously done at configuration time,
    /// but now happens just before queries are executed. Returns normalized query parameters.
    fn validate_configuration(&self) -> Result<QueryParams, BrokerError> {
        // Validate timestamps and normalize them
        let mut normalized_params = self.query_params.clone();

        if let Some(ts) = &self.query_params.ts_start {
            let parsed_datetime = Self::parse_timestamp(ts)?;
            normalized_params.ts_start =
                Some(parsed_datetime.format("%Y-%m-%dT%H:%M:%SZ").to_string());
        }

        if let Some(ts) = &self.query_params.ts_end {
            let parsed_datetime = Self::parse_timestamp(ts)?;
            normalized_params.ts_end =
                Some(parsed_datetime.format("%Y-%m-%dT%H:%M:%SZ").to_string());
        }

        // Permissive collector validation: normalize only, no network I/O
        if let Some(collector_str) = &self.query_params.collector_id {
            let collectors: Vec<String> = collector_str
                .split(',')
                .map(|s| s.trim())
                .filter(|s| !s.is_empty())
                .map(|s| s.to_string())
                .collect();

            if collectors.is_empty() {
                return Err(BrokerError::ConfigurationError(
                    "Collector ID cannot be empty".to_string(),
                ));
            }

            // Deduplicate while preserving order
            let mut seen = HashSet::new();
            let mut deduped = Vec::with_capacity(collectors.len());
            for c in collectors {
                if seen.insert(c.clone()) {
                    deduped.push(c);
                }
            }

            normalized_params.collector_id = Some(deduped.join(","));
        }

        // Validate project
        if let Some(project_str) = &self.query_params.project {
            let project_lower = project_str.to_lowercase();
            match project_lower.as_str() {
                "rrc" | "riperis" | "ripe_ris" | "routeviews" | "route_views" | "rv" => {
                    // Valid project
                }
                _ => {
                    return Err(BrokerError::ConfigurationError(format!(
                        "Invalid project '{project_str}'. Valid projects are: 'riperis' (aliases: 'rrc', 'ripe_ris') or 'routeviews' (aliases: 'route_views', 'rv')"
                    )));
                }
            }
        }

        // Validate data type
        if let Some(data_type_str) = &self.query_params.data_type {
            let data_type_lower = data_type_str.to_lowercase();
            match data_type_lower.as_str() {
                "rib" | "ribs" | "r" | "update" | "updates" => {
                    // Valid data type
                }
                _ => {
                    return Err(BrokerError::ConfigurationError(format!(
                        "Invalid data type '{data_type_str}'. Valid data types are: 'rib' (aliases: 'ribs', 'r') or 'updates' (alias: 'update')"
                    )));
                }
            }
        }

        // Validate page number
        if self.query_params.page < 1 {
            return Err(BrokerError::ConfigurationError(format!(
                "Invalid page number {}. Page number must be >= 1",
                self.query_params.page
            )));
        }

        // Validate page size
        if !(1..=100000).contains(&self.query_params.page_size) {
            return Err(BrokerError::ConfigurationError(format!(
                "Invalid page size {}. Page size must be between 1 and 100000",
                self.query_params.page_size
            )));
        }

        Ok(normalized_params)
    }

    /// Add a filter of starting timestamp.
    ///
    /// Supports multiple timestamp formats including Unix timestamps, RFC3339 dates, and pure dates.
    /// Validation occurs at query time.
    ///
    /// # Examples
    ///
    /// Specify a Unix timestamp:
    /// ```
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///     .ts_start("1640995200");
    /// ```
    ///
    /// Specify a RFC3339-formatted time string:
    /// ```
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///     .ts_start("2022-01-01T00:00:00Z");
    /// ```
    ///
    /// Specify a pure date (defaults to start of day):
    /// ```
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///     .ts_start("2022-01-01");
    /// ```
    ///
    /// Other supported formats:
    /// ```
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///     .ts_start("2022/01/01")  // slash format
    ///     .ts_start("2022.01.01")  // dot format
    ///     .ts_start("20220101");   // compact format
    /// ```
    pub fn ts_start<S: Display>(self, ts_start: S) -> Self {
        let mut query_params = self.query_params;
        query_params.ts_start = Some(ts_start.to_string());
        Self {
            broker_url: self.broker_url,
            query_params,
            client: self.client,
            collector_project_map: self.collector_project_map,
            accept_invalid_certs: self.accept_invalid_certs,
            cache_dir: self.cache_dir,
        }
    }

    /// Add a filter of ending timestamp.
    ///
    /// Supports the same multiple timestamp formats as `ts_start`.
    /// Validation occurs at query time.
    ///
    /// # Examples
    ///
    /// Specify a Unix timestamp:
    /// ```
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///     .ts_end("1640995200");
    /// ```
    ///
    /// Specify a RFC3339-formatted time string:
    /// ```
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///     .ts_end("2022-01-01T00:00:00Z");
    /// ```
    ///
    /// Specify a pure date (defaults to start of day):
    /// ```
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///     .ts_end("2022-01-01");
    /// ```
    pub fn ts_end<S: Display>(self, ts_end: S) -> Self {
        let mut query_params = self.query_params;
        query_params.ts_end = Some(ts_end.to_string());
        Self {
            broker_url: self.broker_url,
            client: self.client,
            query_params,
            collector_project_map: self.collector_project_map,
            accept_invalid_certs: self.accept_invalid_certs,
            cache_dir: self.cache_dir,
        }
    }

    /// Add a filter of collector ID (e.g. `rrc00` or `route-views2`).
    ///
    /// See the full list of collectors [here](https://github.com/bgpkit/bgpkit-broker-backend/blob/main/deployment/full-config.json).
    /// Validation occurs at query time.
    ///
    /// # Examples
    ///
    /// filter by single collector
    /// ```
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///     .collector_id("rrc00");
    /// ```
    ///
    /// filter by multiple collector
    /// ```
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///     .collector_id("route-views2,route-views6");
    /// ```
    pub fn collector_id<S: Display>(self, collector_id: S) -> Self {
        let mut query_params = self.query_params;
        query_params.collector_id = Some(collector_id.to_string());
        Self {
            client: self.client,
            broker_url: self.broker_url,
            query_params,
            collector_project_map: self.collector_project_map,
            accept_invalid_certs: self.accept_invalid_certs,
            cache_dir: self.cache_dir,
        }
    }

    /// Add a filter of project name with validation, i.e. `riperis` or `routeviews`.
    ///
    /// # Examples
    ///
    /// ```
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///     .project("riperis");
    /// ```
    ///
    /// ```
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///     .project("routeviews");
    /// ```
    pub fn project<S: Display>(self, project: S) -> Self {
        let mut query_params = self.query_params;
        query_params.project = Some(project.to_string());
        Self {
            client: self.client,
            broker_url: self.broker_url,
            query_params,
            collector_project_map: self.collector_project_map,
            accept_invalid_certs: self.accept_invalid_certs,
            cache_dir: self.cache_dir,
        }
    }

    /// Add filter of data type, i.e. `rib` or `updates`.
    ///
    /// Validation occurs at query time.
    ///
    /// # Examples
    ///
    /// ```
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///     .data_type("rib");
    /// ```
    ///
    /// ```
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///     .data_type("updates");
    /// ```
    pub fn data_type<S: Display>(self, data_type: S) -> Self {
        let mut query_params = self.query_params;
        query_params.data_type = Some(data_type.to_string());
        Self {
            broker_url: self.broker_url,
            client: self.client,
            query_params,
            collector_project_map: self.collector_project_map,
            accept_invalid_certs: self.accept_invalid_certs,
            cache_dir: self.cache_dir,
        }
    }

    /// Change the current page number, starting from 1.
    ///
    /// Validation occurs at query time.
    ///
    /// # Examples
    ///
    /// Start iterating with page 2.
    /// ```
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///     .page(2);
    /// ```
    pub fn page(self, page: i64) -> Self {
        let mut query_params = self.query_params;
        query_params.page = page;
        Self {
            broker_url: self.broker_url,
            client: self.client,
            query_params,
            collector_project_map: self.collector_project_map,
            accept_invalid_certs: self.accept_invalid_certs,
            cache_dir: self.cache_dir,
        }
    }

    /// Change current page size, default 100.
    ///
    /// Validation occurs at query time.
    ///
    /// # Examples
    ///
    /// Set page size to 20.
    /// ```
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///     .page_size(10);
    /// ```
    pub fn page_size(self, page_size: i64) -> Self {
        let mut query_params = self.query_params;
        query_params.page_size = page_size;
        Self {
            broker_url: self.broker_url,
            client: self.client,
            query_params,
            collector_project_map: self.collector_project_map,
            accept_invalid_certs: self.accept_invalid_certs,
            cache_dir: self.cache_dir,
        }
    }

    /// Add a filter of peer IP address when listing peers.
    ///
    /// # Examples
    ///
    /// ```
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///    .peers_ip("192.168.1.1".parse().unwrap());
    /// ```
    pub fn peers_ip(self, peer_ip: IpAddr) -> Self {
        let mut query_params = self.query_params;
        query_params.peers_ip = Some(peer_ip);
        Self {
            broker_url: self.broker_url,
            client: self.client,
            query_params,
            collector_project_map: self.collector_project_map,
            accept_invalid_certs: self.accept_invalid_certs,
            cache_dir: self.cache_dir,
        }
    }

    /// Add a filter of peer ASN when listing peers.
    ///
    /// # Examples
    ///
    /// ```
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///    .peers_asn(64496);
    /// ```
    pub fn peers_asn(self, peer_asn: u32) -> Self {
        let mut query_params = self.query_params;
        query_params.peers_asn = Some(peer_asn);
        Self {
            broker_url: self.broker_url,
            client: self.client,
            query_params,
            collector_project_map: self.collector_project_map,
            accept_invalid_certs: self.accept_invalid_certs,
            cache_dir: self.cache_dir,
        }
    }

    /// Add a filter of peer full feed status when listing peers.
    ///
    /// # Examples
    ///
    /// ```
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///   .peers_only_full_feed(true);
    /// ```
    pub fn peers_only_full_feed(self, peer_full_feed: bool) -> Self {
        let mut query_params = self.query_params;
        query_params.peers_only_full_feed = peer_full_feed;
        Self {
            broker_url: self.broker_url,
            client: self.client,
            query_params,
            collector_project_map: self.collector_project_map,
            accept_invalid_certs: self.accept_invalid_certs,
            cache_dir: self.cache_dir,
        }
    }

    /// Turn to specified page, page starting from 1.
    ///
    /// This works with [Self::query_single_page] function to manually paginate.
    ///
    /// # Examples
    ///
    /// Manually get the first two pages of items.
    /// ```no_run
    /// let mut broker = bgpkit_broker::BgpkitBroker::new();
    /// let mut items = vec![];
    /// items.extend(broker.query_single_page().unwrap());
    /// broker.turn_page(2);
    /// items.extend(broker.query_single_page().unwrap());
    /// ```
    pub fn turn_page(&mut self, page: i64) {
        self.query_params.page = page;
    }

    /// Send API for a single page of items.
    ///
    /// # Examples
    ///
    /// Manually get the first page of items.
    /// ```no_run
    /// let broker = bgpkit_broker::BgpkitBroker::new();
    /// let items = broker.query_single_page().unwrap();
    /// ```
    pub fn query_single_page(&self) -> Result<Vec<BrokerItem>, BrokerError> {
        // Try to load from cache first
        if let Some(cached_items) = self.load_cache() {
            return Ok(cached_items);
        }
        
        let validated_params = self.validate_configuration()?;
        let url = format!("{}/search{}", &self.broker_url, &validated_params);
        log::info!("sending broker query to {}", &url);
        match self.run_files_query(url.as_str()) {
            Ok(res) => {
                // Save to cache if cache_dir is set
                self.save_cache(&res.data);
                Ok(res.data)
            }
            Err(e) => Err(e),
        }
    }

    /// Query the total count of items matching the current search criteria without fetching the items.
    ///
    /// This method is useful when you need to know how many items match your search criteria
    /// without downloading all the items. It performs the same validation as a regular query
    /// but only returns the count.
    ///
    /// # Returns
    /// - `Ok(i64)`: The total number of matching items
    /// - `Err(BrokerError)`: If the query fails or the count is missing from the response
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use bgpkit_broker::BgpkitBroker;
    ///
    /// let broker = BgpkitBroker::new()
    ///     .ts_start("2024-01-01")
    ///     .ts_end("2024-01-02")
    ///     .collector_id("route-views2");
    ///
    /// let count = broker.query_total_count().unwrap();
    /// println!("Found {} matching items", count);
    /// ```
    pub fn query_total_count(&self) -> Result<i64, BrokerError> {
        let validated_params = self.validate_configuration()?;
        let url = format!("{}/search{}", &self.broker_url, &validated_params);
        match self.run_files_query(url.as_str()) {
            Ok(res) => res.total.ok_or(BrokerError::BrokerError(
                "count not found in response".to_string(),
            )),
            Err(e) => Err(e),
        }
    }

    /// Check if the broker instance is healthy.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let broker = bgpkit_broker::BgpkitBroker::new();
    /// assert!(broker.health_check().is_ok())
    /// ```
    pub fn health_check(&self) -> Result<(), BrokerError> {
        let url = format!("{}/health", &self.broker_url.trim_end_matches('/'));
        match self.client.get(url.as_str()).send() {
            Ok(response) => {
                if response.status() == reqwest::StatusCode::OK {
                    Ok(())
                } else {
                    Err(BrokerError::BrokerError(format!(
                        "endpoint unhealthy {}",
                        self.broker_url
                    )))
                }
            }
            Err(_e) => Err(BrokerError::BrokerError(format!(
                "endpoint unhealthy {}",
                self.broker_url
            ))),
        }
    }

    /// Send a query to get **all** data times returned.
    ///
    /// This usually is what one needs.
    ///
    /// # Examples
    ///
    /// Get all RIB files on 2022-01-01 from route-views2.
    /// ```no_run
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///     .ts_start("2022-01-01T00:00:00Z")
    ///     .ts_end("2022-01-01T23:59:00Z")
    ///     .data_type("rib")
    ///     .collector_id("route-views2");
    /// let items = broker.query().unwrap();
    ///
    /// // 1 RIB dump very 2 hours, total of 12 files for 1 day
    /// assert_eq!(items.len(), 12);
    /// ```
    pub fn query(&self) -> Result<Vec<BrokerItem>, BrokerError> {
        let mut p = self.validate_configuration()?;

        let mut items = vec![];
        loop {
            let url = format!("{}/search{}", &self.broker_url, &p);

            let res_items = self.run_files_query(url.as_str())?.data;

            let items_count = res_items.len() as i64;

            if items_count == 0 {
                // reaches the end
                break;
            }

            items.extend(res_items);
            let cur_page = p.page;
            p = p.page(cur_page + 1);

            if items_count < p.page_size {
                // reaches the end
                break;
            }
        }
        Ok(items)
    }

    /// Send a query to get the **latest** data for each collector.
    ///
    /// The returning result is structured as a vector of [CollectorLatestItem] objects.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let broker = bgpkit_broker::BgpkitBroker::new();
    /// let latest_items = broker.latest().unwrap();
    /// for item in &latest_items {
    ///     println!("{}", item);
    /// }
    /// ```
    pub fn latest(&self) -> Result<Vec<BrokerItem>, BrokerError> {
        let latest_query_url = format!("{}/latest", self.broker_url);
        let mut items = match self.client.get(latest_query_url.as_str()).send() {
            Ok(response) => match response.json::<CollectorLatestResult>() {
                Ok(result) => result.data,
                Err(_) => {
                    return Err(BrokerError::BrokerError(
                        "Error parsing response".to_string(),
                    ));
                }
            },
            Err(e) => {
                return Err(BrokerError::BrokerError(format!(
                    "Unable to connect to the URL ({latest_query_url}): {e}"
                )));
            }
        };

        items.retain(|item| {
            let mut matches = true;
            if let Some(project) = &self.query_params.project {
                match project.to_lowercase().as_str() {
                    "rrc" | "riperis" | "ripe_ris" => {
                        matches = self
                            .collector_project_map
                            .get(&item.collector_id)
                            .cloned()
                            .unwrap_or_default()
                            .as_str()
                            == "riperis";
                    }
                    "routeviews" | "route_views" | "rv" => {
                        matches = self
                            .collector_project_map
                            .get(&item.collector_id)
                            .cloned()
                            .unwrap_or_default()
                            .as_str()
                            == "routeviews";
                    }
                    _ => {}
                }
            }

            if let Some(data_type) = &self.query_params.data_type {
                match data_type.to_lowercase().as_str() {
                    "rib" | "ribs" | "r" => {
                        if !item.is_rib() {
                            // if not RIB file, not match
                            matches = false
                        }
                    }
                    "update" | "updates" => {
                        if item.is_rib() {
                            // if is RIB file, not match
                            matches = false
                        }
                    }
                    _ => {}
                }
            }

            if let Some(collector_id) = &self.query_params.collector_id {
                let wanted: HashSet<&str> = collector_id
                    .split(',')
                    .map(|s| s.trim())
                    .filter(|s| !s.is_empty())
                    .collect();

                if !wanted.contains(item.collector_id.as_str()) {
                    return false;
                }
            }

            matches
        });

        Ok(items)
    }

    /// Get the most recent information for collector peers.
    ///
    /// The returning result is structured as a vector of [BrokerPeer] objects.
    ///
    /// # Examples
    ///
    /// ## Get all peers
    ///
    /// ```no_run
    /// let broker = bgpkit_broker::BgpkitBroker::new();
    /// let peers = broker.get_peers().unwrap();
    /// for peer in &peers {
    ///     println!("{:?}", peer);
    /// }
    /// ```
    ///
    /// ## Get peers from a specific collector
    ///
    /// ```no_run
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///    .collector_id("route-views2");
    /// let peers = broker.get_peers().unwrap();
    /// for peer in &peers {
    ///    println!("{:?}", peer);
    /// }
    /// ```
    ///
    /// ## Get peers from a specific ASN
    ///
    /// ```no_run
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///   .peers_asn(64496);
    /// let peers = broker.get_peers().unwrap();
    /// for peer in &peers {
    ///    println!("{:?}", peer);
    /// }
    /// ```
    ///
    /// ## Get peers from a specific IP address
    ///
    /// ```no_run
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///   .peers_ip("192.168.1.1".parse().unwrap());
    /// let peers = broker.get_peers().unwrap();
    /// for peer in &peers {
    ///   println!("{:?}", peer);
    /// }
    /// ```
    ///
    /// ## Get peers with full feed
    ///
    /// ```no_run
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///  .peers_only_full_feed(true);
    /// let peers = broker.get_peers().unwrap();
    /// for peer in &peers {
    ///     println!("{:?}", peer);
    /// }
    /// ```
    ///
    /// ## Get peers from a specific collector with full feed
    ///
    /// ```no_run
    /// let broker = bgpkit_broker::BgpkitBroker::new()
    ///  .collector_id("route-views2")
    /// .peers_only_full_feed(true);
    /// let peers = broker.get_peers().unwrap();
    /// for peer in &peers {
    ///    println!("{:?}", peer);
    /// }
    /// ```
    pub fn get_peers(&self) -> Result<Vec<BrokerPeer>, BrokerError> {
        let mut url = format!("{}/peers", self.broker_url);
        let mut param_strings = vec![];
        if let Some(ip) = &self.query_params.peers_ip {
            param_strings.push(format!("ip={ip}"));
        }
        if let Some(asn) = &self.query_params.peers_asn {
            param_strings.push(format!("asn={asn}"));
        }
        if self.query_params.peers_only_full_feed {
            param_strings.push("full_feed=true".to_string());
        }
        if let Some(collector_id) = &self.query_params.collector_id {
            param_strings.push(format!("collector={collector_id}"));
        }
        if !param_strings.is_empty() {
            let param_string = param_strings.join("&");
            url = format!("{url}?{param_string}");
        }

        let peers = match self.client.get(url.as_str()).send() {
            Ok(response) => match response.json::<BrokerPeersResult>() {
                Ok(result) => result.data,
                Err(_) => {
                    return Err(BrokerError::BrokerError(
                        "Error parsing response".to_string(),
                    ));
                }
            },
            Err(e) => {
                return Err(BrokerError::BrokerError(format!(
                    "Unable to connect to the URL ({url}): {e}"
                )));
            }
        };
        Ok(peers)
    }

    fn run_files_query(&self, url: &str) -> Result<BrokerQueryResult, BrokerError> {
        log::info!("sending broker query to {}", &url);
        match self.client.get(url).send() {
            Ok(res) => match res.json::<BrokerQueryResult>() {
                Ok(res) => {
                    if let Some(e) = res.error {
                        Err(BrokerError::BrokerError(e))
                    } else {
                        Ok(res)
                    }
                }
                Err(e) => {
                    // json decoding error. most likely the service returns an error message without
                    // `data` field.
                    Err(BrokerError::BrokerError(e.to_string()))
                }
            },
            Err(e) => Err(BrokerError::from(e)),
        }
    }
}

/// Iterator for BGPKIT Broker that iterates through one [BrokerItem] at a time.
///
/// The [IntoIterator] trait is implemented for both the struct and the reference, so that you can
/// either iterate through items by taking the ownership of the broker, or use the reference to broker
/// to iterate.
///
/// ```no_run
/// use bgpkit_broker::{BgpkitBroker, BrokerItem};
///
/// let mut broker = BgpkitBroker::new()
///     .ts_start("1634693400")
///     .ts_end("1634693400")
///     .page_size(10)
///     .page(2);
///
/// // create iterator from reference (so that you can reuse the broker object)
/// // same as `&broker.into_intr()`
/// for item in &broker {
///     println!("{}", item);
/// }
///
/// // create iterator from the broker object (taking ownership)
/// let items = broker.into_iter().collect::<Vec<BrokerItem>>();
///
/// assert_eq!(items.len(), 43);
/// ```
pub struct BrokerItemIterator {
    broker: BgpkitBroker,
    cached_items: Vec<BrokerItem>,
    first_run: bool,
}

impl BrokerItemIterator {
    pub fn new(broker: BgpkitBroker) -> BrokerItemIterator {
        BrokerItemIterator {
            broker,
            cached_items: vec![],
            first_run: true,
        }
    }
}

impl Iterator for BrokerItemIterator {
    type Item = BrokerItem;

    fn next(&mut self) -> Option<Self::Item> {
        // if we have cached items, simply pop and return
        if let Some(item) = self.cached_items.pop() {
            return Some(item);
        }

        // no more cached items, refill cache by one more broker query
        if self.first_run {
            // if it's the first time running, do not change page, and switch the flag.
            self.first_run = false;
        } else {
            // if it's not the first time running, add page number by one.
            self.broker.query_params.page += 1;
        }

        // query the current page
        let items = match self.broker.query_single_page() {
            Ok(i) => i,
            Err(_) => return None,
        };

        if items.is_empty() {
            // break out the iteration
            return None;
        } else {
            // fill the cache
            self.cached_items = items;
            self.cached_items.reverse();
        }

        #[allow(clippy::unwrap_used)]
        Some(self.cached_items.pop().unwrap())
    }
}

impl IntoIterator for BgpkitBroker {
    type Item = BrokerItem;
    type IntoIter = BrokerItemIterator;

    fn into_iter(self) -> Self::IntoIter {
        BrokerItemIterator::new(self)
    }
}

impl IntoIterator for &BgpkitBroker {
    type Item = BrokerItem;
    type IntoIter = BrokerItemIterator;

    fn into_iter(self) -> Self::IntoIter {
        BrokerItemIterator::new(self.clone())
    }
}

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

    #[test]
    fn test_query() {
        let broker = BgpkitBroker::new()
            .ts_start("1634693400")
            .ts_end("1634693400");
        let res = broker.query();
        assert!(&res.is_ok());
        let data = res.unwrap();
        assert!(!data.is_empty());
    }

    #[test]
    fn test_network_error() {
        let broker = BgpkitBroker::new().broker_url("https://api.broker.example.com/v2");
        let res = broker.query();
        // when testing a must-fail query, you could use `matches!` macro to do so
        assert!(res.is_err());
        assert!(matches!(res.err(), Some(BrokerError::NetworkError(_))));
    }

    #[test]
    fn test_broker_error() {
        let broker = BgpkitBroker::new().page(-1);
        let result = broker.query();
        assert!(result.is_err());
        assert!(matches!(
            result.err(),
            Some(BrokerError::ConfigurationError(_))
        ));
    }

    #[test]
    fn test_query_all() {
        let broker = BgpkitBroker::new()
            .ts_start("1634693400")
            .ts_end("1634693400")
            .page_size(100);
        let res = broker.query();
        assert!(res.is_ok());
        assert!(res.ok().unwrap().len() >= 54);
    }

    #[test]
    fn test_iterator() {
        let broker = BgpkitBroker::new()
            .ts_start("1634693400")
            .ts_end("1634693400");
        assert!(broker.into_iter().count() >= 54);
    }

    #[test]
    fn test_filters() {
        let broker = BgpkitBroker::new()
            .ts_start("1634693400")
            .ts_end("1634693400");
        let items = broker.query().unwrap();
        assert!(items.len() >= 54);

        let broker = BgpkitBroker::new()
            .ts_start("1634693400")
            .ts_end("1634693400")
            .collector_id("rrc00");
        let items = broker.query().unwrap();
        assert_eq!(items.len(), 1);

        let broker = BgpkitBroker::new()
            .ts_start("1634693400")
            .ts_end("1634693400")
            .project("riperis");
        let items = broker.query().unwrap();
        assert_eq!(items.len(), 23);
    }

    #[test]
    fn test_latest() {
        let broker = BgpkitBroker::new();
        let items = broker.latest().unwrap();
        assert!(items.len() >= 125);

        let broker = BgpkitBroker::new().project("routeviews".to_string());
        let items = broker.latest().unwrap();
        assert!(!items.is_empty());
        assert!(items
            .iter()
            .all(|item| !item.collector_id.starts_with("rrc")));

        let broker = BgpkitBroker::new().project("riperis".to_string());
        let items = broker.latest().unwrap();
        assert!(!items.is_empty());
        assert!(items
            .iter()
            .all(|item| item.collector_id.starts_with("rrc")));

        let broker = BgpkitBroker::new().data_type("rib".to_string());
        let items = broker.latest().unwrap();
        assert!(!items.is_empty());
        assert!(items.iter().all(|item| item.is_rib()));

        let broker = BgpkitBroker::new().data_type("update".to_string());
        let items = broker.latest().unwrap();
        assert!(!items.is_empty());
        assert!(items.iter().all(|item| !item.is_rib()));

        let broker = BgpkitBroker::new().collector_id("rrc00".to_string());
        let items = broker.latest().unwrap();
        assert!(!items.is_empty());
        assert!(items
            .iter()
            .all(|item| item.collector_id.as_str() == "rrc00"));
        assert_eq!(items.len(), 2);
    }

    #[test]
    fn test_latest_no_ssl() {
        let broker = BgpkitBroker::new().accept_invalid_certs();
        let items = broker.latest().unwrap();
        assert!(items.len() >= 125);
    }

    #[test]
    fn test_health_check() {
        let broker = BgpkitBroker::new();
        let res = broker.health_check();
        assert!(res.is_ok());
    }

    #[test]
    fn test_peers() {
        let broker = BgpkitBroker::new();
        let all_peers = broker.get_peers().unwrap();
        assert!(!all_peers.is_empty());
        let first_peer = all_peers.first().unwrap();
        let first_ip = first_peer.ip;
        let first_asn = first_peer.asn;

        let broker = BgpkitBroker::new().peers_ip(first_ip);
        let peers = broker.get_peers().unwrap();
        assert!(!peers.is_empty());

        let broker = BgpkitBroker::new().peers_asn(first_asn);
        let peers = broker.get_peers().unwrap();
        assert!(!peers.is_empty());

        let broker = BgpkitBroker::new().peers_only_full_feed(true);
        let full_feed_peers = broker.get_peers().unwrap();
        assert!(!full_feed_peers.is_empty());
        assert!(full_feed_peers.len() < all_peers.len());

        let broker = BgpkitBroker::new().collector_id("rrc00");
        let rrc_peers = broker.get_peers().unwrap();
        assert!(!rrc_peers.is_empty());
        assert!(rrc_peers.iter().all(|peer| peer.collector == "rrc00"));

        let broker = BgpkitBroker::new().collector_id("rrc00,route-views2");
        let rrc_rv_peers = broker.get_peers().unwrap();
        assert!(!rrc_rv_peers.is_empty());
        assert!(rrc_rv_peers
            .iter()
            .any(|peer| peer.collector == "rrc00" || peer.collector == "route-views2"));

        assert!(rrc_rv_peers.len() > rrc_peers.len());
    }

    #[test]
    fn test_timestamp_parsing_unix() {
        let broker = BgpkitBroker::new();

        // Valid Unix timestamps - configuration succeeds, normalization happens at query time
        let result = broker.clone().ts_start("1640995200");
        // Raw input is stored during configuration
        assert_eq!(result.query_params.ts_start, Some("1640995200".to_string()));

        let result = broker.clone().ts_end("1640995200");
        assert_eq!(result.query_params.ts_end, Some("1640995200".to_string()));
    }

    #[test]
    fn test_timestamp_parsing_rfc3339() {
        let broker = BgpkitBroker::new();

        // RFC3339 with Z - raw input stored during configuration
        let result = broker.clone().ts_start("2022-01-01T00:00:00Z");
        assert_eq!(
            result.query_params.ts_start,
            Some("2022-01-01T00:00:00Z".to_string())
        );

        // RFC3339 without Z - raw input stored during configuration
        let result = broker.clone().ts_start("2022-01-01T12:30:45");
        assert_eq!(
            result.query_params.ts_start,
            Some("2022-01-01T12:30:45".to_string())
        );

        // Date with time format - raw input stored during configuration
        let result = broker.clone().ts_end("2022-01-01 12:30:45");
        assert_eq!(
            result.query_params.ts_end,
            Some("2022-01-01 12:30:45".to_string())
        );
    }

    #[test]
    fn test_timestamp_parsing_pure_dates() {
        let broker = BgpkitBroker::new();

        // Standard date format - raw input stored during configuration
        let result = broker.clone().ts_start("2022-01-01");
        assert_eq!(result.query_params.ts_start, Some("2022-01-01".to_string()));

        // Slash format
        let result = broker.clone().ts_start("2022/01/01");
        assert_eq!(result.query_params.ts_start, Some("2022/01/01".to_string()));

        // Dot format
        let result = broker.clone().ts_end("2022.01.01");
        assert_eq!(result.query_params.ts_end, Some("2022.01.01".to_string()));

        // Compact format
        let result = broker.clone().ts_end("20220101");
        assert_eq!(result.query_params.ts_end, Some("20220101".to_string()));
    }

    #[test]
    fn test_timestamp_parsing_whitespace() {
        let broker = BgpkitBroker::new();

        // Test that raw input with whitespace is stored during configuration
        let result = broker.clone().ts_start("  2022-01-01  ");
        assert_eq!(
            result.query_params.ts_start,
            Some("  2022-01-01  ".to_string())
        );

        let result = broker.clone().ts_end("\t1640995200\n");
        assert_eq!(
            result.query_params.ts_end,
            Some("\t1640995200\n".to_string())
        );
    }

    #[test]
    fn test_timestamp_parsing_errors() {
        let broker = BgpkitBroker::new();

        // Invalid format - error occurs at query time
        let broker_with_invalid = broker.clone().ts_start("invalid-timestamp");
        let result = broker_with_invalid.query();
        assert!(result.is_err());
        assert!(matches!(
            result.err(),
            Some(BrokerError::ConfigurationError(_))
        ));

        // Invalid date - error occurs at query time
        let broker_with_invalid = broker.clone().ts_end("2022-13-01");
        let result = broker_with_invalid.query();
        assert!(result.is_err());
        assert!(matches!(
            result.err(),
            Some(BrokerError::ConfigurationError(_))
        ));

        // Invalid compact date - error occurs at query time
        let broker_with_invalid = broker.clone().ts_start("20221301");
        let result = broker_with_invalid.query();
        assert!(result.is_err());
        assert!(matches!(
            result.err(),
            Some(BrokerError::ConfigurationError(_))
        ));

        // Partially valid format - error occurs at query time
        let broker_with_invalid = broker.clone().ts_start("2022-01");
        let result = broker_with_invalid.query();
        assert!(result.is_err());
        assert!(matches!(
            result.err(),
            Some(BrokerError::ConfigurationError(_))
        ));
    }

    #[test]
    fn test_parse_timestamp_direct() {
        use chrono::{NaiveDate, NaiveDateTime};

        // Test the parse_timestamp function directly - it now returns DateTime<Utc>

        // Unix timestamp
        let expected_unix = Utc.timestamp_opt(1640995200, 0).single().unwrap();
        assert_eq!(
            BgpkitBroker::parse_timestamp("1640995200").unwrap(),
            expected_unix
        );

        // RFC3339 formats
        let expected_rfc3339_z = Utc.from_utc_datetime(
            &NaiveDateTime::parse_from_str("2022-01-01T00:00:00", "%Y-%m-%dT%H:%M:%S").unwrap(),
        );
        assert_eq!(
            BgpkitBroker::parse_timestamp("2022-01-01T00:00:00Z").unwrap(),
            expected_rfc3339_z
        );

        let expected_rfc3339_no_z = Utc.from_utc_datetime(
            &NaiveDateTime::parse_from_str("2022-01-01T12:30:45", "%Y-%m-%dT%H:%M:%S").unwrap(),
        );
        assert_eq!(
            BgpkitBroker::parse_timestamp("2022-01-01T12:30:45").unwrap(),
            expected_rfc3339_no_z
        );

        let expected_space_format = Utc.from_utc_datetime(
            &NaiveDateTime::parse_from_str("2022-01-01 12:30:45", "%Y-%m-%d %H:%M:%S").unwrap(),
        );
        assert_eq!(
            BgpkitBroker::parse_timestamp("2022-01-01 12:30:45").unwrap(),
            expected_space_format
        );

        // Pure date formats (all convert to start of day in UTC)
        let expected_date = Utc.from_utc_datetime(
            &NaiveDate::from_ymd_opt(2022, 1, 1)
                .unwrap()
                .and_hms_opt(0, 0, 0)
                .unwrap(),
        );
        assert_eq!(
            BgpkitBroker::parse_timestamp("2022-01-01").unwrap(),
            expected_date
        );
        assert_eq!(
            BgpkitBroker::parse_timestamp("2022/01/01").unwrap(),
            expected_date
        );
        assert_eq!(
            BgpkitBroker::parse_timestamp("2022.01.01").unwrap(),
            expected_date
        );
        assert_eq!(
            BgpkitBroker::parse_timestamp("20220101").unwrap(),
            expected_date
        );

        // Test timezone formats - these should now work
        let result_plus_tz = BgpkitBroker::parse_timestamp("2022-01-01T00:00:00+00:00").unwrap();
        assert_eq!(result_plus_tz, expected_date);
        println!("✓ +00:00 timezone format works");

        // Test timezone conversion: 2022-01-01T05:00:00-05:00 = 2022-01-01T10:00:00Z
        let result_minus_tz = BgpkitBroker::parse_timestamp("2022-01-01T05:00:00-05:00").unwrap();
        let expected_10am = Utc.with_ymd_and_hms(2022, 1, 1, 10, 0, 0).unwrap();
        assert_eq!(result_minus_tz, expected_10am);
        println!("✓ -05:00 timezone format works (05:00-05:00 = 10:00Z)");

        // Error cases
        assert!(BgpkitBroker::parse_timestamp("invalid").is_err());
        assert!(BgpkitBroker::parse_timestamp("2022-13-01").is_err());
        assert!(BgpkitBroker::parse_timestamp("2022-01").is_err());
    }

    #[test]
    fn test_collector_id_validation() {
        let broker = BgpkitBroker::new();

        // Valid single collector - no error at validation time
        let broker_valid = broker.clone().collector_id("rrc00");
        let result = broker_valid.validate_configuration();
        assert!(result.is_ok());

        // Valid multiple collectors - no error at validation time
        let broker_valid = broker.clone().collector_id("rrc00,route-views2");
        let result = broker_valid.validate_configuration();
        assert!(result.is_ok());

        // Unknown collector should be allowed (permissive behavior)
        let broker_unknown = broker.clone().collector_id("brand-new-collector");
        let result = broker_unknown.validate_configuration();
        assert!(result.is_ok());

        // Mixed known and unknown collectors should be allowed
        let broker_mixed = broker.clone().collector_id("rrc00,brand-new-collector");
        let result = broker_mixed.validate_configuration();
        assert!(result.is_ok());

        // Empty/whitespace-only should error
        let broker_empty = broker.clone().collector_id(", ,  ,");
        let result = broker_empty.validate_configuration();
        assert!(result.is_err());
        assert!(matches!(
            result.err(),
            Some(BrokerError::ConfigurationError(_))
        ));
    }

    #[test]
    fn test_project_validation() {
        let broker = BgpkitBroker::new();

        // Valid projects - no error at configuration time
        let broker_valid = broker.clone().project("riperis");
        let result = broker_valid.validate_configuration();
        assert!(result.is_ok());

        let broker_valid = broker.clone().project("routeviews");
        let result = broker_valid.validate_configuration();
        assert!(result.is_ok());

        // Valid aliases - no error at configuration time
        let broker_valid = broker.clone().project("rrc");
        let result = broker_valid.validate_configuration();
        assert!(result.is_ok());

        let broker_valid = broker.clone().project("rv");
        let result = broker_valid.validate_configuration();
        assert!(result.is_ok());

        // Invalid project - error occurs at validation
        let broker_invalid = broker.clone().project("invalid-project");
        let result = broker_invalid.validate_configuration();
        assert!(result.is_err());
        assert!(matches!(
            result.err(),
            Some(BrokerError::ConfigurationError(_))
        ));
    }

    #[test]
    fn test_data_type_validation() {
        let broker = BgpkitBroker::new();

        // Valid data types - no error at configuration time
        let broker_valid = broker.clone().data_type("rib");
        let result = broker_valid.validate_configuration();
        assert!(result.is_ok());

        let broker_valid = broker.clone().data_type("updates");
        let result = broker_valid.validate_configuration();
        assert!(result.is_ok());

        // Valid aliases - no error at configuration time
        let broker_valid = broker.clone().data_type("ribs");
        let result = broker_valid.validate_configuration();
        assert!(result.is_ok());

        let broker_valid = broker.clone().data_type("update");
        let result = broker_valid.validate_configuration();
        assert!(result.is_ok());

        // Invalid data type - error occurs at validation
        let broker_invalid = broker.clone().data_type("invalid-type");
        let result = broker_invalid.validate_configuration();
        assert!(result.is_err());
        assert!(matches!(
            result.err(),
            Some(BrokerError::ConfigurationError(_))
        ));
    }

    #[test]
    fn test_page_validation() {
        let broker = BgpkitBroker::new();

        // Valid page number - no error at configuration time
        let broker_valid = broker.clone().page(1);
        let result = broker_valid.validate_configuration();
        assert!(result.is_ok());

        let broker_valid = broker.clone().page(100);
        let result = broker_valid.validate_configuration();
        assert!(result.is_ok());

        // Invalid page number - error occurs at validation
        let broker_invalid = broker.clone().page(0);
        let result = broker_invalid.validate_configuration();
        assert!(result.is_err());
        assert!(matches!(
            result.err(),
            Some(BrokerError::ConfigurationError(_))
        ));
    }

    #[test]
    fn test_page_size_validation() {
        let broker = BgpkitBroker::new();

        // Valid page sizes - no error at configuration time
        let broker_valid = broker.clone().page_size(1);
        let result = broker_valid.validate_configuration();
        assert!(result.is_ok());

        let broker_valid = broker.clone().page_size(100);
        let result = broker_valid.validate_configuration();
        assert!(result.is_ok());

        let broker_valid = broker.clone().page_size(100000);
        let result = broker_valid.validate_configuration();
        assert!(result.is_ok());

        // Invalid page sizes - error occurs at validation
        let broker_invalid = broker.clone().page_size(0);
        let result = broker_invalid.validate_configuration();
        assert!(result.is_err());
        assert!(matches!(
            result.err(),
            Some(BrokerError::ConfigurationError(_))
        ));

        let broker_invalid = broker.clone().page_size(100001);
        let result = broker_invalid.validate_configuration();
        assert!(result.is_err());
        assert!(matches!(
            result.err(),
            Some(BrokerError::ConfigurationError(_))
        ));
    }

    #[test]
    fn test_method_chaining() {
        let broker = BgpkitBroker::new()
            .ts_start("1634693400")
            .ts_end("1634693400")
            .collector_id("rrc00")
            .project("riperis")
            .data_type("rib")
            .page(1)
            .page_size(10);

        // Raw input is stored during configuration
        assert_eq!(broker.query_params.ts_start, Some("1634693400".to_string()));
        assert_eq!(broker.query_params.ts_end, Some("1634693400".to_string()));
        assert_eq!(broker.query_params.collector_id, Some("rrc00".to_string()));
        assert_eq!(broker.query_params.project, Some("riperis".to_string()));
        assert_eq!(broker.query_params.data_type, Some("rib".to_string()));
        assert_eq!(broker.query_params.page, 1);
        assert_eq!(broker.query_params.page_size, 10);
    }
}