monocle 1.2.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
//! Database schema management
//!
//! This module provides schema definitions and management for the shared database.
//! All tables are defined here to ensure consistency and enable cross-table queries.

use anyhow::{anyhow, Result};
use rusqlite::Connection;

/// Current schema version
/// Increment this when making breaking schema changes
pub const SCHEMA_VERSION: u32 = 3;

/// Schema definitions for all tables in the shared database
pub struct SchemaDefinitions;

impl SchemaDefinitions {
    /// SQL for creating the meta table (tracks schema version and global metadata)
    pub const META_TABLE: &'static str = r#"
        CREATE TABLE IF NOT EXISTS monocle_meta (
            key TEXT PRIMARY KEY,
            value TEXT NOT NULL,
            updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
        );
    "#;

    /// SQL for creating AS2Org tables
    pub const AS2ORG_AS_TABLE: &'static str = r#"
        CREATE TABLE IF NOT EXISTS as2org_as (
            asn INTEGER PRIMARY KEY,
            name TEXT NOT NULL,
            org_id TEXT NOT NULL,
            source TEXT NOT NULL
        );
    "#;

    pub const AS2ORG_ORG_TABLE: &'static str = r#"
        CREATE TABLE IF NOT EXISTS as2org_org (
            org_id TEXT PRIMARY KEY,
            name TEXT NOT NULL,
            country TEXT NOT NULL,
            source TEXT NOT NULL
        );
    "#;

    /// SQL for creating AS2Org indexes
    pub const AS2ORG_INDEXES: &'static [&'static str] = &[
        "CREATE INDEX IF NOT EXISTS idx_as2org_as_org_id ON as2org_as(org_id)",
        "CREATE INDEX IF NOT EXISTS idx_as2org_as_name ON as2org_as(name)",
        "CREATE INDEX IF NOT EXISTS idx_as2org_org_name ON as2org_org(name)",
        "CREATE INDEX IF NOT EXISTS idx_as2org_org_country ON as2org_org(country)",
    ];

    /// SQL for creating AS2Org views
    pub const AS2ORG_VIEWS: &'static [&'static str] = &[
        r#"
        CREATE VIEW IF NOT EXISTS as2org_both AS
        SELECT a.asn, a.name AS 'as_name', b.name AS 'org_name', b.org_id, b.country
        FROM as2org_as AS a JOIN as2org_org AS b ON a.org_id = b.org_id;
        "#,
        r#"
        CREATE VIEW IF NOT EXISTS as2org_count AS
        SELECT org_id, org_name, COUNT(*) AS count
        FROM as2org_both GROUP BY org_name
        ORDER BY count DESC;
        "#,
        r#"
        CREATE VIEW IF NOT EXISTS as2org_all AS
        SELECT a.*, b.count
        FROM as2org_both AS a JOIN as2org_count AS b ON a.org_id = b.org_id;
        "#,
    ];

    /// SQL for creating AS2Rel tables
    pub const AS2REL_META_TABLE: &'static str = r#"
        CREATE TABLE IF NOT EXISTS as2rel_meta (
            id INTEGER PRIMARY KEY CHECK (id = 1),
            file_url TEXT NOT NULL,
            last_updated INTEGER NOT NULL,
            max_peers_count INTEGER NOT NULL DEFAULT 0
        );
    "#;

    pub const AS2REL_TABLE: &'static str = r#"
        CREATE TABLE IF NOT EXISTS as2rel (
            asn1 INTEGER NOT NULL,
            asn2 INTEGER NOT NULL,
            paths_count INTEGER NOT NULL,
            peers_count INTEGER NOT NULL,
            rel INTEGER NOT NULL,
            PRIMARY KEY (asn1, asn2, rel)
        );
    "#;

    /// SQL for creating AS2Rel indexes
    pub const AS2REL_INDEXES: &'static [&'static str] = &[
        "CREATE INDEX IF NOT EXISTS idx_as2rel_asn1 ON as2rel(asn1)",
        "CREATE INDEX IF NOT EXISTS idx_as2rel_asn2 ON as2rel(asn2)",
    ];

    /// SQL for creating the RPKI ROA table
    pub const RPKI_ROA_TABLE: &'static str = r#"
        CREATE TABLE IF NOT EXISTS rpki_roa (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            prefix_start BLOB NOT NULL,
            prefix_end BLOB NOT NULL,
            prefix_length INTEGER NOT NULL,
            max_length INTEGER NOT NULL,
            origin_asn INTEGER NOT NULL,
            ta TEXT NOT NULL,
            prefix_str TEXT NOT NULL
        );
    "#;

    /// SQL for creating the RPKI ASPA table
    pub const RPKI_ASPA_TABLE: &'static str = r#"
        CREATE TABLE IF NOT EXISTS rpki_aspa (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            customer_asn INTEGER NOT NULL,
            provider_asn INTEGER NOT NULL
        );
    "#;

    /// SQL for creating the RPKI meta table
    pub const RPKI_META_TABLE: &'static str = r#"
        CREATE TABLE IF NOT EXISTS rpki_meta (
            id INTEGER PRIMARY KEY CHECK (id = 1),
            updated_at INTEGER NOT NULL,
            roa_count INTEGER NOT NULL DEFAULT 0,
            aspa_count INTEGER NOT NULL DEFAULT 0,
            roa_source TEXT NOT NULL DEFAULT 'Cloudflare',
            aspa_source TEXT NOT NULL DEFAULT 'Cloudflare'
        );
    "#;

    /// SQL for creating RPKI indexes
    pub const RPKI_INDEXES: &'static [&'static str] = &[
        "CREATE INDEX IF NOT EXISTS idx_rpki_roa_prefix_range ON rpki_roa(prefix_start, prefix_end)",
        "CREATE INDEX IF NOT EXISTS idx_rpki_roa_origin_asn ON rpki_roa(origin_asn)",
        "CREATE INDEX IF NOT EXISTS idx_rpki_aspa_customer ON rpki_aspa(customer_asn)",
        "CREATE INDEX IF NOT EXISTS idx_rpki_aspa_provider ON rpki_aspa(provider_asn)",
    ];

    // =========================================================================
    // ASInfo Tables (normalized AS information from multiple sources)
    // =========================================================================

    /// Core AS table (always populated)
    pub const ASINFO_CORE_TABLE: &'static str = r#"
        CREATE TABLE IF NOT EXISTS asinfo_core (
            asn INTEGER PRIMARY KEY,
            name TEXT NOT NULL,
            country TEXT NOT NULL
        );
    "#;

    /// AS2Org data (from CAIDA)
    pub const ASINFO_AS2ORG_TABLE: &'static str = r#"
        CREATE TABLE IF NOT EXISTS asinfo_as2org (
            asn INTEGER PRIMARY KEY,
            name TEXT NOT NULL,
            org_id TEXT NOT NULL,
            org_name TEXT NOT NULL,
            country TEXT NOT NULL
        );
    "#;

    /// PeeringDB data
    pub const ASINFO_PEERINGDB_TABLE: &'static str = r#"
        CREATE TABLE IF NOT EXISTS asinfo_peeringdb (
            asn INTEGER PRIMARY KEY,
            name TEXT NOT NULL,
            name_long TEXT,
            aka TEXT,
            website TEXT,
            irr_as_set TEXT
        );
    "#;

    /// IHR Hegemony scores
    pub const ASINFO_HEGEMONY_TABLE: &'static str = r#"
        CREATE TABLE IF NOT EXISTS asinfo_hegemony (
            asn INTEGER PRIMARY KEY,
            ipv4 REAL NOT NULL,
            ipv6 REAL NOT NULL
        );
    "#;

    /// APNIC Population estimates
    pub const ASINFO_POPULATION_TABLE: &'static str = r#"
        CREATE TABLE IF NOT EXISTS asinfo_population (
            asn INTEGER PRIMARY KEY,
            percent_country REAL NOT NULL,
            percent_global REAL NOT NULL,
            sample_count INTEGER NOT NULL,
            user_count INTEGER NOT NULL
        );
    "#;

    /// ASInfo metadata table
    pub const ASINFO_META_TABLE: &'static str = r#"
        CREATE TABLE IF NOT EXISTS asinfo_meta (
            id INTEGER PRIMARY KEY CHECK (id = 1),
            source_url TEXT NOT NULL,
            last_updated INTEGER NOT NULL,
            core_count INTEGER NOT NULL,
            as2org_count INTEGER NOT NULL,
            peeringdb_count INTEGER NOT NULL,
            hegemony_count INTEGER NOT NULL,
            population_count INTEGER NOT NULL
        );
    "#;

    /// ASInfo indexes
    pub const ASINFO_INDEXES: &'static [&'static str] = &[
        "CREATE INDEX IF NOT EXISTS idx_asinfo_core_name ON asinfo_core(name)",
        "CREATE INDEX IF NOT EXISTS idx_asinfo_core_country ON asinfo_core(country)",
        "CREATE INDEX IF NOT EXISTS idx_asinfo_as2org_org_id ON asinfo_as2org(org_id)",
        "CREATE INDEX IF NOT EXISTS idx_asinfo_as2org_org_name ON asinfo_as2org(org_name)",
        "CREATE INDEX IF NOT EXISTS idx_asinfo_peeringdb_name ON asinfo_peeringdb(name)",
    ];
}

/// Schema manager for the shared database
///
/// Handles schema initialization, version checking, and migrations.
pub struct SchemaManager<'a> {
    conn: &'a Connection,
}

impl<'a> SchemaManager<'a> {
    /// Create a new schema manager for the given connection
    pub fn new(conn: &'a Connection) -> Self {
        Self { conn }
    }

    /// Initialize the database schema
    ///
    /// Creates all tables, indexes, and views if they don't exist.
    /// Sets the schema version in the meta table.
    pub fn initialize(&self) -> Result<()> {
        // Create meta table first
        self.conn
            .execute(SchemaDefinitions::META_TABLE, [])
            .map_err(|e| anyhow!("Failed to create meta table: {}", e))?;

        // Set schema version
        self.set_meta("schema_version", &SCHEMA_VERSION.to_string())?;

        // Create AS2Org tables
        self.conn
            .execute(SchemaDefinitions::AS2ORG_AS_TABLE, [])
            .map_err(|e| anyhow!("Failed to create as2org_as table: {}", e))?;

        self.conn
            .execute(SchemaDefinitions::AS2ORG_ORG_TABLE, [])
            .map_err(|e| anyhow!("Failed to create as2org_org table: {}", e))?;

        // Create AS2Org indexes
        for index_sql in SchemaDefinitions::AS2ORG_INDEXES {
            self.conn
                .execute(index_sql, [])
                .map_err(|e| anyhow!("Failed to create AS2Org index: {}", e))?;
        }

        // Create AS2Org views
        for view_sql in SchemaDefinitions::AS2ORG_VIEWS {
            self.conn
                .execute(view_sql, [])
                .map_err(|e| anyhow!("Failed to create AS2Org view: {}", e))?;
        }

        // Create AS2Rel tables
        self.conn
            .execute(SchemaDefinitions::AS2REL_META_TABLE, [])
            .map_err(|e| anyhow!("Failed to create as2rel_meta table: {}", e))?;

        self.conn
            .execute(SchemaDefinitions::AS2REL_TABLE, [])
            .map_err(|e| anyhow!("Failed to create as2rel table: {}", e))?;

        // Create AS2Rel indexes
        for index_sql in SchemaDefinitions::AS2REL_INDEXES {
            self.conn
                .execute(index_sql, [])
                .map_err(|e| anyhow!("Failed to create AS2Rel index: {}", e))?;
        }

        // Create RPKI tables
        self.conn
            .execute(SchemaDefinitions::RPKI_ROA_TABLE, [])
            .map_err(|e| anyhow!("Failed to create rpki_roa table: {}", e))?;

        self.conn
            .execute(SchemaDefinitions::RPKI_ASPA_TABLE, [])
            .map_err(|e| anyhow!("Failed to create rpki_aspa table: {}", e))?;

        self.conn
            .execute(SchemaDefinitions::RPKI_META_TABLE, [])
            .map_err(|e| anyhow!("Failed to create rpki_meta table: {}", e))?;

        // Create RPKI indexes
        for index_sql in SchemaDefinitions::RPKI_INDEXES {
            self.conn
                .execute(index_sql, [])
                .map_err(|e| anyhow!("Failed to create RPKI index: {}", e))?;
        }

        // Create ASInfo tables
        self.conn
            .execute(SchemaDefinitions::ASINFO_CORE_TABLE, [])
            .map_err(|e| anyhow!("Failed to create asinfo_core table: {}", e))?;

        self.conn
            .execute(SchemaDefinitions::ASINFO_AS2ORG_TABLE, [])
            .map_err(|e| anyhow!("Failed to create asinfo_as2org table: {}", e))?;

        self.conn
            .execute(SchemaDefinitions::ASINFO_PEERINGDB_TABLE, [])
            .map_err(|e| anyhow!("Failed to create asinfo_peeringdb table: {}", e))?;

        self.conn
            .execute(SchemaDefinitions::ASINFO_HEGEMONY_TABLE, [])
            .map_err(|e| anyhow!("Failed to create asinfo_hegemony table: {}", e))?;

        self.conn
            .execute(SchemaDefinitions::ASINFO_POPULATION_TABLE, [])
            .map_err(|e| anyhow!("Failed to create asinfo_population table: {}", e))?;

        self.conn
            .execute(SchemaDefinitions::ASINFO_META_TABLE, [])
            .map_err(|e| anyhow!("Failed to create asinfo_meta table: {}", e))?;

        // Create ASInfo indexes
        for index_sql in SchemaDefinitions::ASINFO_INDEXES {
            self.conn
                .execute(index_sql, [])
                .map_err(|e| anyhow!("Failed to create ASInfo index: {}", e))?;
        }

        Ok(())
    }

    /// Check the current schema status
    pub fn check_status(&self) -> Result<SchemaStatus> {
        // Check if meta table exists
        let meta_exists: i32 = self
            .conn
            .query_row(
                "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='monocle_meta'",
                [],
                |row| row.get(0),
            )
            .unwrap_or(0);

        if meta_exists == 0 {
            return Ok(SchemaStatus::NotInitialized);
        }

        // Get current schema version
        let current_version = self.get_schema_version()?;

        if current_version == SCHEMA_VERSION {
            // Verify schema integrity
            if self.verify_integrity()? {
                Ok(SchemaStatus::Current)
            } else {
                Ok(SchemaStatus::Corrupted)
            }
        } else if current_version < SCHEMA_VERSION {
            Ok(SchemaStatus::NeedsMigration {
                from: current_version,
                to: SCHEMA_VERSION,
            })
        } else {
            // Database is from a newer version
            Ok(SchemaStatus::Incompatible {
                database_version: current_version,
                required_version: SCHEMA_VERSION,
            })
        }
    }

    /// Get the current schema version from the database
    fn get_schema_version(&self) -> Result<u32> {
        let version: String = self
            .conn
            .query_row(
                "SELECT value FROM monocle_meta WHERE key = 'schema_version'",
                [],
                |row| row.get(0),
            )
            .unwrap_or_else(|_| "0".to_string());

        version
            .parse()
            .map_err(|e| anyhow!("Invalid schema version: {}", e))
    }

    /// Verify schema integrity by checking required tables exist
    fn verify_integrity(&self) -> Result<bool> {
        let required_tables = [
            "monocle_meta",
            "as2org_as",
            "as2org_org",
            "as2rel",
            "as2rel_meta",
            "rpki_roa",
            "rpki_aspa",
            "rpki_meta",
            "asinfo_core",
            "asinfo_as2org",
            "asinfo_peeringdb",
            "asinfo_hegemony",
            "asinfo_population",
            "asinfo_meta",
        ];

        for table in required_tables {
            let exists: i32 = self
                .conn
                .query_row(
                    "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?1",
                    [table],
                    |row| row.get(0),
                )
                .unwrap_or(0);

            if exists == 0 {
                return Ok(false);
            }
        }

        Ok(true)
    }

    /// Set a metadata value
    pub fn set_meta(&self, key: &str, value: &str) -> Result<()> {
        self.conn
            .execute(
                "INSERT OR REPLACE INTO monocle_meta (key, value, updated_at) VALUES (?1, ?2, strftime('%s', 'now'))",
                [key, value],
            )
            .map_err(|e| anyhow!("Failed to set meta value: {}", e))?;
        Ok(())
    }

    /// Get a metadata value
    pub fn get_meta(&self, key: &str) -> Result<Option<String>> {
        let result: Result<String, _> = self.conn.query_row(
            "SELECT value FROM monocle_meta WHERE key = ?1",
            [key],
            |row| row.get(0),
        );

        match result {
            Ok(value) => Ok(Some(value)),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(anyhow!("Failed to get meta value: {}", e)),
        }
    }

    /// Reset the database by dropping all tables
    pub fn reset(&self) -> Result<()> {
        // Drop views first (they depend on tables)
        self.conn.execute("DROP VIEW IF EXISTS as2org_all", [])?;
        self.conn.execute("DROP VIEW IF EXISTS as2org_count", [])?;
        self.conn.execute("DROP VIEW IF EXISTS as2org_both", [])?;

        // Drop tables
        self.conn.execute("DROP TABLE IF EXISTS as2rel", [])?;
        self.conn.execute("DROP TABLE IF EXISTS as2rel_meta", [])?;
        self.conn.execute("DROP TABLE IF EXISTS as2org_as", [])?;
        self.conn.execute("DROP TABLE IF EXISTS as2org_org", [])?;
        self.conn.execute("DROP TABLE IF EXISTS rpki_roa", [])?;
        self.conn.execute("DROP TABLE IF EXISTS rpki_aspa", [])?;
        self.conn.execute("DROP TABLE IF EXISTS rpki_meta", [])?;

        // Drop ASInfo tables
        self.conn.execute("DROP TABLE IF EXISTS asinfo_core", [])?;
        self.conn
            .execute("DROP TABLE IF EXISTS asinfo_as2org", [])?;
        self.conn
            .execute("DROP TABLE IF EXISTS asinfo_peeringdb", [])?;
        self.conn
            .execute("DROP TABLE IF EXISTS asinfo_hegemony", [])?;
        self.conn
            .execute("DROP TABLE IF EXISTS asinfo_population", [])?;
        self.conn.execute("DROP TABLE IF EXISTS asinfo_meta", [])?;

        self.conn.execute("DROP TABLE IF EXISTS monocle_meta", [])?;

        Ok(())
    }
}

/// Status of the database schema
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SchemaStatus {
    /// Database is not initialized (fresh database)
    NotInitialized,

    /// Schema is current and valid
    Current,

    /// Schema needs migration from an older version
    NeedsMigration { from: u32, to: u32 },

    /// Database is from a newer version (incompatible)
    Incompatible {
        database_version: u32,
        required_version: u32,
    },

    /// Schema is corrupted (missing tables)
    Corrupted,
}

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

    fn create_test_db() -> Connection {
        let conn = Connection::open_in_memory().unwrap();
        // Configure like MonocleDatabase would
        conn.execute("PRAGMA foreign_keys=ON", []).unwrap();
        conn
    }

    #[test]
    fn test_schema_not_initialized() {
        let conn = create_test_db();
        let manager = SchemaManager::new(&conn);

        assert_eq!(
            manager.check_status().unwrap(),
            SchemaStatus::NotInitialized
        );
    }

    #[test]
    fn test_schema_initialize() {
        let conn = create_test_db();
        let manager = SchemaManager::new(&conn);

        manager.initialize().unwrap();

        assert_eq!(manager.check_status().unwrap(), SchemaStatus::Current);
    }

    #[test]
    fn test_schema_version() {
        let conn = create_test_db();
        let manager = SchemaManager::new(&conn);

        manager.initialize().unwrap();

        let version = manager.get_schema_version().unwrap();
        assert_eq!(version, SCHEMA_VERSION);
    }

    #[test]
    fn test_meta_operations() {
        let conn = create_test_db();
        let manager = SchemaManager::new(&conn);

        manager.initialize().unwrap();

        // Set and get a meta value
        manager.set_meta("test_key", "test_value").unwrap();
        let value = manager.get_meta("test_key").unwrap();
        assert_eq!(value, Some("test_value".to_string()));

        // Non-existent key
        let missing = manager.get_meta("nonexistent").unwrap();
        assert_eq!(missing, None);
    }

    #[test]
    fn test_schema_reset() {
        let conn = create_test_db();
        let manager = SchemaManager::new(&conn);

        manager.initialize().unwrap();
        assert_eq!(manager.check_status().unwrap(), SchemaStatus::Current);

        manager.reset().unwrap();
        assert_eq!(
            manager.check_status().unwrap(),
            SchemaStatus::NotInitialized
        );
    }
}