sagittarius 0.1.0

A fast, self-hosted DNS sinkhole in a single Rust binary
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
//! Cohesive resolver state bundle: match sets, local-record matcher, cache,
//! and hot-swappable runtime settings.
//!
//! [`ResolverState`] is the single shared object that the DNS engine (E6) and
//! the web admin (E8) both hold via [`Arc`].  It owns:
//!
//! - Three [`MatchSet`] instances — admin blacklist, allowlist, and aggregated
//!   blocklist — each independently hot-swappable (SPEC §3.1, §3.2).
//! - A [`LocalMatcher`] for authoritative local records.
//! - A [`DnsCache`] for upstream response caching.
//! - An [`ArcSwap`]-protected [`RuntimeSettings`] snapshot for operational
//!   settings that can be swapped atomically without touching the cache.
//!
//! # Startup hydration
//!
//! Call [`ResolverState::hydrate`] once at startup.  It reads all tables from
//! SQLite and builds the in-memory state synchronously (from the caller's async
//! context).  The returned [`Arc<ResolverState>`] is then shared across tasks.
//!
//! # Live updates
//!
//! - E7 (blocklist refresh) calls `state.blocklist().store(new_set)`.
//! - E8 (admin blacklist/allowlist edits) calls `state.blacklist().store(…)` /
//!   `state.allowlist().store(…)`.
//! - E8 (settings change) calls `state.store_settings(new_settings)`.
//! - E8 (local-record edit) calls `state.local().store(new_records)`.
//!
//! **Precedence/ordering is NOT defined here.** That is the E6 pipeline layer's
//! concern.  This module just bundles the pieces and exposes lookups + swaps.

use std::{net::Ipv4Addr, net::Ipv6Addr, sync::Arc};

use arc_swap::ArcSwap;

use crate::{
    codec::synth::BlockMode,
    resolver::{
        self,
        cache::DnsCache,
        local::{LocalMatcher, LocalRecords, RecordData},
        matchset::MatchSet,
    },
    storage::{
        Db,
        lists::{
            AllowlistRepository, BlacklistRepository, SqliteAllowlistRepo, SqliteBlacklistRepo,
        },
        local_records::{LocalRecordRepository, RecordType, SqliteLocalRecordRepo},
        settings::{BlockingMode, Settings, SettingsRepository, SqliteSettingsRepo},
    },
};

// ── RuntimeSettings ───────────────────────────────────────────────────────────

/// A snapshot of operational runtime settings derived from [`Settings`].
///
/// Held inside an [`ArcSwap`] so that settings changes take effect atomically
/// on the hot path without restarting the server.
///
/// # Cache bounds vs. immediate-effect settings
///
/// The cache bounds (`cache_min_ttl`, `cache_max_ttl`, `cache_capacity`) are
/// stored here for reference, but **changing them requires rebuilding the
/// [`DnsCache`]** — `moka`'s capacity is fixed at build time (SPEC §3.2).
/// That rebuild is E8's concern and is out of scope here.
///
/// In contrast, `negative_ttl_cap`, `block_mode`, and
/// `blocklist_refresh_interval` take effect immediately on the next settings
/// swap without rebuilding anything.
#[derive(Debug, Clone, PartialEq)]
pub struct RuntimeSettings {
    /// Minimum TTL to serve from the cache, in seconds.
    pub cache_min_ttl: u32,
    /// Maximum TTL to serve from the cache, in seconds.
    pub cache_max_ttl: u32,
    /// Maximum number of cache entries (fixed at cache build time; see note).
    pub cache_capacity: u64,
    /// Cap applied to negative (NXDOMAIN/NODATA) cache entries, in seconds.
    ///
    /// Used by E6.3 at cache-store time. Takes effect immediately on a swap.
    pub negative_ttl_cap: u32,
    /// How blocked domains are answered.
    ///
    /// Derived from [`BlockingMode`] and the custom IP fields. Takes effect
    /// immediately on a swap.
    pub block_mode: BlockMode,
    /// How often blocklists are refreshed, in seconds. Used by E7.
    ///
    /// Takes effect immediately on a swap.
    pub blocklist_refresh_interval: u32,
}

impl From<&Settings> for RuntimeSettings {
    /// Derive a [`RuntimeSettings`] snapshot from a [`Settings`] row.
    ///
    /// `block_mode` derivation:
    /// - [`BlockingMode::NxDomain`] → [`BlockMode::NxDomain`]
    /// - [`BlockingMode::NullIp`] → [`BlockMode::null_ip()`] (`0.0.0.0` / `::`)
    /// - [`BlockingMode::Custom`] → [`BlockMode::Address`] with the configured
    ///   custom IPs, falling back to [`Ipv4Addr::UNSPECIFIED`] /
    ///   [`Ipv6Addr::UNSPECIFIED`] if either custom IP is `None`.
    fn from(s: &Settings) -> Self {
        let block_mode = match s.blocking_mode {
            BlockingMode::NxDomain => BlockMode::NxDomain,
            BlockingMode::NullIp => BlockMode::null_ip(),
            BlockingMode::Custom => BlockMode::Address {
                v4: s.custom_block_ipv4.unwrap_or(Ipv4Addr::UNSPECIFIED),
                v6: s.custom_block_ipv6.unwrap_or(Ipv6Addr::UNSPECIFIED),
            },
        };

        Self {
            cache_min_ttl: s.cache_min_ttl,
            cache_max_ttl: s.cache_max_ttl,
            cache_capacity: s.cache_capacity,
            negative_ttl_cap: s.cache_negative_ttl_cap,
            block_mode,
            blocklist_refresh_interval: s.blocklist_refresh_interval,
        }
    }
}

// ── ResolverState ─────────────────────────────────────────────────────────────

/// Shared, hot-path resolver state owned by both the DNS engine (E6) and the
/// web admin (E8).
///
/// All components are independently hot-swappable via their respective
/// `store` methods; readers never block.  See the module-level documentation
/// for the update protocol.
pub struct ResolverState {
    /// Admin-managed blacklist (exact domain names).
    blacklist: MatchSet,
    /// Admin-managed allowlist (exact domain names that bypass blocking).
    allowlist: MatchSet,
    /// Aggregated blocklist from external sources (filled by E7 on refresh).
    ///
    /// Starts empty at hydration; E7 installs the first set asynchronously.
    blocklist: MatchSet,
    /// Authoritative local-record matcher.
    local: LocalMatcher,
    /// Raw-bytes DNS response cache.
    cache: DnsCache,
    /// Hot-swappable operational settings snapshot.
    settings: ArcSwap<RuntimeSettings>,
}

impl ResolverState {
    // ── Component accessors ───────────────────────────────────────────────────

    /// The admin blacklist [`MatchSet`].
    ///
    /// E6 reads `blacklist().contains(name)`.
    /// E8 installs updated sets via `blacklist().store(new_set)`.
    #[must_use]
    pub fn blacklist(&self) -> &MatchSet {
        &self.blacklist
    }

    /// The admin allowlist [`MatchSet`].
    ///
    /// E6 reads `allowlist().contains(name)`.
    /// E8 installs updated sets via `allowlist().store(new_set)`.
    #[must_use]
    pub fn allowlist(&self) -> &MatchSet {
        &self.allowlist
    }

    /// The aggregated blocklist [`MatchSet`].
    ///
    /// Starts empty at hydration.
    /// E6 reads `blocklist().contains(name)`.
    /// E7 installs refreshed sets via `blocklist().store(new_set)`.
    #[must_use]
    pub fn blocklist(&self) -> &MatchSet {
        &self.blocklist
    }

    /// The local-record matcher.
    ///
    /// E6 reads `local().lookup(name, qtype)`.
    /// E8 installs updated snapshots via `local().store(new_records)`.
    #[must_use]
    pub fn local(&self) -> &LocalMatcher {
        &self.local
    }

    /// The DNS response cache.
    ///
    /// E6 reads `cache().get(…)` and writes `cache().insert(…)`.
    #[must_use]
    pub fn cache(&self) -> &DnsCache {
        &self.cache
    }

    // ── Settings accessors ────────────────────────────────────────────────────

    /// Load the current [`RuntimeSettings`] snapshot.
    ///
    /// Returns an [`arc_swap::Guard`] that holds a reference to the current
    /// [`Arc<RuntimeSettings>`] without incrementing the reference count.
    /// Prefer this for short-lived reads (single call); use
    /// [`ResolverState::settings_full`] when the snapshot must outlive an await
    /// point.
    #[must_use]
    pub fn settings(&self) -> arc_swap::Guard<Arc<RuntimeSettings>> {
        self.settings.load()
    }

    /// Load the current [`RuntimeSettings`] as a full, owned [`Arc`].
    ///
    /// Increments the reference count.  Use this when the snapshot must be
    /// kept alive across an await point or stored in another struct.
    #[must_use]
    pub fn settings_full(&self) -> Arc<RuntimeSettings> {
        self.settings.load_full()
    }

    /// Atomically replace the current [`RuntimeSettings`] with `new_settings`.
    ///
    /// E8 calls this after persisting a settings change to SQLite.
    /// The new settings take effect for all subsequent hot-path reads
    /// immediately (SPEC §3.2).
    pub fn store_settings(&self, new_settings: RuntimeSettings) {
        self.settings.store(Arc::new(new_settings));
    }

    // ── Startup hydration ─────────────────────────────────────────────────────

    /// Hydrate a [`ResolverState`] from the database and return it wrapped in
    /// an [`Arc`] ready for sharing across tasks.
    ///
    /// Reads:
    /// - [`Settings`] → builds the [`DnsCache`] and [`RuntimeSettings`].
    /// - Blacklist / allowlist rows → populates two [`MatchSet`]s.
    /// - The blocklist [`MatchSet`] is **intentionally left empty**; E7 fills
    ///   it on first refresh.
    /// - Local-record rows → builds a [`LocalRecords`] snapshot via the
    ///   [`LocalRecordsBuilder`](crate::resolver::local::LocalRecordsBuilder).
    ///
    /// # Errors
    ///
    /// Returns [`resolver::Error`] wrapping:
    /// - Storage errors from any repo call ([`resolver::Error::Storage`]).
    /// - A parse failure on a stored IP value or builder rejection
    ///   ([`resolver::Error::InvalidLocalRecord`]).
    pub async fn hydrate(db: &Db) -> resolver::Result<Arc<Self>> {
        let pool = db.pool().clone();

        // ── Settings ──────────────────────────────────────────────────────────
        let settings = SqliteSettingsRepo::new(pool.clone())
            .get()
            .await
            .map_err(resolver::Error::Storage)?;

        let cache = DnsCache::new(
            settings.cache_capacity,
            settings.cache_min_ttl,
            settings.cache_max_ttl,
        );

        let runtime_settings = RuntimeSettings::from(&settings);

        // ── Blacklist & allowlist ─────────────────────────────────────────────
        let blacklist_names = SqliteBlacklistRepo::new(pool.clone())
            .load_all()
            .await
            .map_err(resolver::Error::Storage)?;

        let blacklist = blacklist_names.into_iter().collect::<MatchSet>();

        let allowlist_names = SqliteAllowlistRepo::new(pool.clone())
            .load_all()
            .await
            .map_err(resolver::Error::Storage)?;

        let allowlist = allowlist_names.into_iter().collect::<MatchSet>();

        // Blocklist starts empty; E7 fills it on first refresh.
        let blocklist = MatchSet::empty();

        // ── Local records ─────────────────────────────────────────────────────
        let local_rows = SqliteLocalRecordRepo::new(pool)
            .load_all()
            .await
            .map_err(resolver::Error::Storage)?;

        let local = LocalMatcher::new(build_local_records(local_rows)?);

        Ok(Arc::new(Self {
            blacklist,
            allowlist,
            blocklist,
            local,
            cache,
            settings: ArcSwap::from_pointee(runtime_settings),
        }))
    }
}

/// Build an immutable [`LocalRecords`] snapshot from persisted rows.
///
/// Shared by [`ResolverState::hydrate`] and the web admin's local-record edits
/// (E8.8), which rebuilds the snapshot after a change and swaps it via
/// [`LocalMatcher::store`](crate::resolver::local::LocalMatcher::store).
///
/// # Errors
///
/// Returns [`resolver::Error::InvalidLocalRecord`] if a stored value is not a
/// valid IP for its record type or the builder rejects the name.
pub fn build_local_records(
    rows: Vec<crate::storage::local_records::LocalRecord>,
) -> resolver::Result<LocalRecords> {
    let mut builder = LocalRecords::builder();
    for row in rows {
        let data = match row.record_type {
            RecordType::A => {
                let addr: Ipv4Addr = row.value.parse().map_err(|e| {
                    resolver::Error::InvalidLocalRecord(format!(
                        "record {:?} has invalid A value {:?}: {e}",
                        row.name, row.value
                    ))
                })?;
                RecordData::A(addr)
            }
            RecordType::Aaaa => {
                let addr: Ipv6Addr = row.value.parse().map_err(|e| {
                    resolver::Error::InvalidLocalRecord(format!(
                        "record {:?} has invalid AAAA value {:?}: {e}",
                        row.name, row.value
                    ))
                })?;
                RecordData::Aaaa(addr)
            }
        };

        // Strip trailing dot for the builder (which normalizes internally).
        let name = row.name.trim_end_matches('.');
        builder.add(name, data, row.ttl).map_err(|e| {
            resolver::Error::InvalidLocalRecord(format!(
                "could not add local record {:?}: {e}",
                row.name
            ))
        })?;
    }
    Ok(builder.build())
}

impl std::fmt::Debug for ResolverState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ResolverState")
            .field("blacklist", &self.blacklist)
            .field("allowlist", &self.allowlist)
            .field("blocklist", &self.blocklist)
            .field("local", &self.local)
            .finish_non_exhaustive()
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use std::net::{Ipv4Addr, Ipv6Addr};

    use tempfile::TempDir;

    use super::*;
    use crate::{
        codec::{message::Qtype, name::Name},
        resolver::local::LocalMatch,
        storage::{
            Db,
            lists::{
                AllowlistRepository, BlacklistRepository, SqliteAllowlistRepo, SqliteBlacklistRepo,
            },
            local_records::{
                LocalRecordRepository, NewLocalRecord, RecordType, SqliteLocalRecordRepo,
            },
            settings::{BlockingMode, Settings},
        },
    };

    // ── Helpers ───────────────────────────────────────────────────────────────

    async fn open_temp_db() -> (TempDir, Db) {
        let dir = TempDir::new().expect("temp dir");
        let path = dir.path().join("test.db");
        let db = Db::connect(&path).await.expect("connect");
        (dir, db)
    }

    fn name(s: &str) -> Name {
        s.parse().expect("valid domain name")
    }

    // ── RuntimeSettings::from(&Settings) ─────────────────────────────────────

    fn base_settings() -> Settings {
        Settings {
            cache_min_ttl: 1,
            cache_max_ttl: 86400,
            cache_negative_ttl_cap: 3600,
            cache_capacity: 100_000,
            blocking_mode: BlockingMode::NullIp,
            custom_block_ipv4: None,
            custom_block_ipv6: None,
            blocklist_refresh_interval: 86400,
            ui_theme: "auto".to_owned(),
        }
    }

    #[test]
    fn runtime_settings_from_nxdomain() {
        let mut s = base_settings();
        s.blocking_mode = BlockingMode::NxDomain;
        let rs = RuntimeSettings::from(&s);
        assert_eq!(rs.block_mode, BlockMode::NxDomain);
        assert_eq!(rs.negative_ttl_cap, 3600);
        assert_eq!(rs.cache_max_ttl, 86400);
        assert_eq!(rs.blocklist_refresh_interval, 86400);
    }

    #[test]
    fn runtime_settings_from_null_ip() {
        let s = base_settings();
        let rs = RuntimeSettings::from(&s);
        assert_eq!(rs.block_mode, BlockMode::null_ip());
    }

    #[test]
    fn runtime_settings_from_custom_with_ips() {
        let mut s = base_settings();
        s.blocking_mode = BlockingMode::Custom;
        s.custom_block_ipv4 = Some("203.0.113.1".parse().unwrap());
        s.custom_block_ipv6 = Some("2001:db8::1".parse().unwrap());

        let rs = RuntimeSettings::from(&s);
        assert_eq!(
            rs.block_mode,
            BlockMode::Address {
                v4: "203.0.113.1".parse().unwrap(),
                v6: "2001:db8::1".parse().unwrap(),
            }
        );
    }

    #[test]
    fn runtime_settings_from_custom_none_ips_falls_back_to_unspecified() {
        let mut s = base_settings();
        s.blocking_mode = BlockingMode::Custom;
        s.custom_block_ipv4 = None;
        s.custom_block_ipv6 = None;

        let rs = RuntimeSettings::from(&s);
        assert_eq!(
            rs.block_mode,
            BlockMode::Address {
                v4: Ipv4Addr::UNSPECIFIED,
                v6: Ipv6Addr::UNSPECIFIED,
            }
        );
    }

    #[test]
    fn runtime_settings_from_custom_partial_ips() {
        let mut s = base_settings();
        s.blocking_mode = BlockingMode::Custom;
        s.custom_block_ipv4 = Some("10.0.0.1".parse().unwrap());
        s.custom_block_ipv6 = None;

        let rs = RuntimeSettings::from(&s);
        assert_eq!(
            rs.block_mode,
            BlockMode::Address {
                v4: "10.0.0.1".parse().unwrap(),
                v6: Ipv6Addr::UNSPECIFIED,
            }
        );
    }

    // ── Hydration: reflects rows ───────────────────────────────────────────────

    #[tokio::test]
    async fn hydration_reflects_blacklist_and_allowlist() {
        let (_dir, db) = open_temp_db().await;

        let bl = SqliteBlacklistRepo::new(db.pool().clone());
        bl.add("ads.example.com").await.expect("add to blacklist");
        bl.add("tracker.evil.net").await.expect("add to blacklist");

        let al = SqliteAllowlistRepo::new(db.pool().clone());
        al.add("safe.example.com").await.expect("add to allowlist");

        let state = ResolverState::hydrate(&db).await.expect("hydrate");

        assert!(state.blacklist().contains(&name("ads.example.com")));
        assert!(state.blacklist().contains(&name("tracker.evil.net")));
        assert!(!state.blacklist().contains(&name("safe.example.com")));

        assert!(state.allowlist().contains(&name("safe.example.com")));
        assert!(!state.allowlist().contains(&name("ads.example.com")));
    }

    #[tokio::test]
    async fn hydration_blocklist_is_empty() {
        let (_dir, db) = open_temp_db().await;
        let state = ResolverState::hydrate(&db).await.expect("hydrate");
        assert!(
            state.blocklist().is_empty(),
            "blocklist must be empty right after hydration"
        );
    }

    #[tokio::test]
    async fn hydration_reflects_local_records() {
        let (_dir, db) = open_temp_db().await;

        let repo = SqliteLocalRecordRepo::new(db.pool().clone());
        repo.add(NewLocalRecord {
            name: "router.home.lan".to_owned(),
            record_type: RecordType::A,
            value: "192.168.1.1".to_owned(),
            ttl: 300,
        })
        .await
        .expect("add A record");

        repo.add(NewLocalRecord {
            name: "router.home.lan".to_owned(),
            record_type: RecordType::Aaaa,
            value: "fd00::1".to_owned(),
            ttl: 600,
        })
        .await
        .expect("add AAAA record");

        let state = ResolverState::hydrate(&db).await.expect("hydrate");

        // A lookup
        let a_match = state.local().lookup(&name("router.home.lan"), Qtype::A);
        assert!(
            matches!(a_match, LocalMatch::Answer { data: crate::resolver::local::RecordData::A(addr), ttl: 300 } if addr == "192.168.1.1".parse::<Ipv4Addr>().unwrap()),
            "expected A answer, got: {a_match:?}"
        );

        // AAAA lookup
        let aaaa_match = state.local().lookup(&name("router.home.lan"), Qtype::Aaaa);
        assert!(
            matches!(aaaa_match, LocalMatch::Answer { data: crate::resolver::local::RecordData::Aaaa(addr), ttl: 600 } if addr == "fd00::1".parse::<Ipv6Addr>().unwrap()),
            "expected AAAA answer, got: {aaaa_match:?}"
        );
    }

    // ── Hydration: settings reflect seed ──────────────────────────────────────

    #[tokio::test]
    async fn hydration_settings_reflect_seed() {
        let (_dir, db) = open_temp_db().await;
        let state = ResolverState::hydrate(&db).await.expect("hydrate");

        let s = state.settings();
        assert_eq!(s.block_mode, BlockMode::null_ip(), "seed uses null-ip mode");
        assert_eq!(s.negative_ttl_cap, 3600);
        assert_eq!(s.cache_max_ttl, 86400);
        assert_eq!(s.blocklist_refresh_interval, 86400);
        assert_eq!(s.cache_min_ttl, 1);
        assert_eq!(s.cache_capacity, 100_000);
    }

    // ── Settings swap ──────────────────────────────────────────────────────────

    #[tokio::test]
    async fn settings_swap_is_visible_to_subsequent_readers() {
        let (_dir, db) = open_temp_db().await;
        let state = ResolverState::hydrate(&db).await.expect("hydrate");

        // Original: null-ip mode.
        assert_eq!(state.settings().block_mode, BlockMode::null_ip());

        // Swap to NxDomain.
        let new_settings = RuntimeSettings {
            block_mode: BlockMode::NxDomain,
            ..(*state.settings_full()).clone()
        };
        state.store_settings(new_settings);

        // Subsequent reader observes the swap.
        assert_eq!(state.settings().block_mode, BlockMode::NxDomain);
    }

    #[tokio::test]
    async fn settings_swap_concurrent_reader_observes_new_value() {
        use std::sync::atomic::{AtomicBool, Ordering};

        let (_dir, db) = open_temp_db().await;
        let state = Arc::new(ResolverState::hydrate(&db).await.expect("hydrate"));

        let state_r = Arc::clone(&state);
        let seen_nxdomain = Arc::new(AtomicBool::new(false));
        let seen_r = Arc::clone(&seen_nxdomain);

        // Spawn a reader that polls until it sees the NxDomain mode.
        let reader = tokio::spawn(async move {
            loop {
                if state_r.settings().block_mode == BlockMode::NxDomain {
                    seen_r.store(true, Ordering::Relaxed);
                    break;
                }
                tokio::task::yield_now().await;
            }
        });

        // Swap to NxDomain.
        let new_settings = RuntimeSettings {
            block_mode: BlockMode::NxDomain,
            ..(*state.settings_full()).clone()
        };
        state.store_settings(new_settings);

        reader.await.expect("reader task panicked");
        assert!(
            seen_nxdomain.load(Ordering::Relaxed),
            "reader must have observed NxDomain after swap"
        );
    }

    // ── Hydration with no rows ─────────────────────────────────────────────────

    #[tokio::test]
    async fn hydration_empty_db_succeeds() {
        let (_dir, db) = open_temp_db().await;
        let state = ResolverState::hydrate(&db).await.expect("hydrate empty db");

        assert!(state.blacklist().is_empty());
        assert!(state.allowlist().is_empty());
        assert!(state.blocklist().is_empty());
        // Local lookup for any name should miss.
        assert_eq!(
            state.local().lookup(&name("any.example.com"), Qtype::A),
            LocalMatch::Miss
        );
    }

    // ── Debug impl ─────────────────────────────────────────────────────────────

    #[tokio::test]
    async fn resolver_state_debug_does_not_panic() {
        let (_dir, db) = open_temp_db().await;
        let state = ResolverState::hydrate(&db).await.expect("hydrate");
        let s = format!("{state:?}");
        assert!(!s.is_empty());
    }

    // ── settings_full outlives await point ────────────────────────────────────

    #[tokio::test]
    async fn settings_full_arc_outlives_swap() {
        let (_dir, db) = open_temp_db().await;
        let state = ResolverState::hydrate(&db).await.expect("hydrate");

        // Hold a full Arc to the old settings snapshot.
        let old_settings = state.settings_full();
        let old_block_mode = old_settings.block_mode.clone();

        // Swap in new settings.
        let new_settings = RuntimeSettings {
            block_mode: BlockMode::NxDomain,
            ..(*state.settings_full()).clone()
        };
        state.store_settings(new_settings);

        // The old Arc is unaffected.
        assert_eq!(old_block_mode, BlockMode::null_ip());
        // The live view reflects the new settings.
        assert_eq!(state.settings().block_mode, BlockMode::NxDomain);
    }
}