lazydns 0.3.20

A light and fast DNS server/forwarder implementation in Rust
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
//! Event bus for audit events
//!
//! Provides a publish-subscribe mechanism for distributing audit events
//! to multiple consumers (WebUI, metrics, alerts) with backpressure handling.

use super::event::{AuditEvent, QueryLogEntry};
use parking_lot::RwLock;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use tokio::sync::broadcast;
use tracing::{debug, trace, warn};

/// Default channel capacity for the event bus
const DEFAULT_CAPACITY: usize = 1024;

/// Event types that can be published to the bus
#[derive(Debug, Clone)]
pub enum BusEvent {
    /// Query log entry
    QueryLog(QueryLogEntry),
    /// Security audit event
    Security(AuditEvent),
}

/// Statistics for the event bus
#[derive(Debug, Default)]
pub struct EventBusStats {
    /// Total events published
    pub events_published: AtomicU64,
    /// Events dropped due to slow subscribers (lagged)
    pub events_dropped: AtomicU64,
    /// Current number of active subscribers
    pub active_subscribers: AtomicUsize,
    /// Peak number of subscribers
    pub peak_subscribers: AtomicUsize,
}

impl EventBusStats {
    /// Get a snapshot of the statistics
    pub fn snapshot(&self) -> EventBusStatsSnapshot {
        EventBusStatsSnapshot {
            events_published: self.events_published.load(Ordering::Relaxed),
            events_dropped: self.events_dropped.load(Ordering::Relaxed),
            active_subscribers: self.active_subscribers.load(Ordering::Relaxed),
            peak_subscribers: self.peak_subscribers.load(Ordering::Relaxed),
        }
    }
}

/// Snapshot of event bus statistics
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct EventBusStatsSnapshot {
    pub events_published: u64,
    pub events_dropped: u64,
    pub active_subscribers: usize,
    pub peak_subscribers: usize,
}

/// Event bus for distributing audit events to multiple subscribers
///
/// Uses a broadcast channel with configurable capacity. When a subscriber
/// falls behind, older events are dropped (backpressure handling).
#[derive(Debug)]
pub struct AuditEventBus {
    /// Broadcast sender for query log events
    query_tx: broadcast::Sender<QueryLogEntry>,
    /// Broadcast sender for security events
    security_tx: broadcast::Sender<AuditEvent>,
    /// Statistics
    stats: Arc<EventBusStats>,
    /// Channel capacity
    capacity: usize,
}

impl AuditEventBus {
    /// Create a new event bus with default capacity
    pub fn new() -> Self {
        Self::with_capacity(DEFAULT_CAPACITY)
    }

    /// Create a new event bus with specified capacity
    pub fn with_capacity(capacity: usize) -> Self {
        let (query_tx, _) = broadcast::channel(capacity);
        let (security_tx, _) = broadcast::channel(capacity);

        debug!(capacity, "Created audit event bus");

        Self {
            query_tx,
            security_tx,
            stats: Arc::new(EventBusStats::default()),
            capacity,
        }
    }

    /// Publish a query log entry to the bus
    ///
    /// Returns the number of subscribers that received the event.
    /// If there are no subscribers, returns 0 (event is silently dropped).
    pub fn publish_query(&self, entry: QueryLogEntry) -> usize {
        match self.query_tx.send(entry) {
            Ok(count) => {
                self.stats.events_published.fetch_add(1, Ordering::Relaxed);
                trace!(subscribers = count, "Published query log entry");
                count
            }
            Err(_) => {
                // No active receivers - this is normal if no WebUI clients are connected
                trace!("No subscribers for query log event");
                0
            }
        }
    }

    /// Publish a security event to the bus
    ///
    /// Returns the number of subscribers that received the event.
    pub fn publish_security(&self, event: AuditEvent) -> usize {
        match self.security_tx.send(event) {
            Ok(count) => {
                self.stats.events_published.fetch_add(1, Ordering::Relaxed);
                trace!(subscribers = count, "Published security event");
                count
            }
            Err(_) => {
                trace!("No subscribers for security event");
                0
            }
        }
    }

    /// Subscribe to query log events
    ///
    /// Returns a receiver that will receive all future query log events.
    /// If the receiver falls behind by more than `capacity` events,
    /// older events will be dropped and a `Lagged` error will be returned.
    pub fn subscribe_queries(&self) -> QueryLogSubscriber {
        let rx = self.query_tx.subscribe();
        let stats = Arc::clone(&self.stats);

        // Update subscriber count
        let current = stats.active_subscribers.fetch_add(1, Ordering::Relaxed) + 1;
        let peak = stats.peak_subscribers.load(Ordering::Relaxed);
        if current > peak {
            stats.peak_subscribers.store(current, Ordering::Relaxed);
        }

        debug!(active = current, "New query log subscriber");

        QueryLogSubscriber { rx, stats }
    }

    /// Subscribe to security events
    pub fn subscribe_security(&self) -> SecurityEventSubscriber {
        let rx = self.security_tx.subscribe();
        let stats = Arc::clone(&self.stats);

        let current = stats.active_subscribers.fetch_add(1, Ordering::Relaxed) + 1;
        let peak = stats.peak_subscribers.load(Ordering::Relaxed);
        if current > peak {
            stats.peak_subscribers.store(current, Ordering::Relaxed);
        }

        debug!(active = current, "New security event subscriber");

        SecurityEventSubscriber { rx, stats }
    }

    /// Get statistics snapshot
    pub fn stats(&self) -> EventBusStatsSnapshot {
        self.stats.snapshot()
    }

    /// Get the number of active query log subscribers
    pub fn query_subscriber_count(&self) -> usize {
        self.query_tx.receiver_count()
    }

    /// Get the number of active security event subscribers
    pub fn security_subscriber_count(&self) -> usize {
        self.security_tx.receiver_count()
    }

    /// Get channel capacity
    pub fn capacity(&self) -> usize {
        self.capacity
    }
}

impl Default for AuditEventBus {
    fn default() -> Self {
        Self::new()
    }
}

impl Clone for AuditEventBus {
    fn clone(&self) -> Self {
        Self {
            query_tx: self.query_tx.clone(),
            security_tx: self.security_tx.clone(),
            stats: Arc::clone(&self.stats),
            capacity: self.capacity,
        }
    }
}

/// Subscriber for query log events
pub struct QueryLogSubscriber {
    rx: broadcast::Receiver<QueryLogEntry>,
    stats: Arc<EventBusStats>,
}

impl QueryLogSubscriber {
    /// Receive the next query log entry
    ///
    /// Returns `None` if the sender has been dropped.
    /// If the subscriber has lagged behind, drops the missed events
    /// and returns the next available event.
    pub async fn recv(&mut self) -> Option<QueryLogEntry> {
        loop {
            match self.rx.recv().await {
                Ok(entry) => return Some(entry),
                Err(broadcast::error::RecvError::Lagged(count)) => {
                    warn!(
                        lagged = count,
                        "Query log subscriber lagged, dropped events"
                    );
                    self.stats
                        .events_dropped
                        .fetch_add(count, Ordering::Relaxed);
                    // Continue to receive the next available event
                }
                Err(broadcast::error::RecvError::Closed) => {
                    debug!("Query log channel closed");
                    return None;
                }
            }
        }
    }

    /// Try to receive without blocking
    pub fn try_recv(&mut self) -> Option<QueryLogEntry> {
        loop {
            match self.rx.try_recv() {
                Ok(entry) => return Some(entry),
                Err(broadcast::error::TryRecvError::Lagged(count)) => {
                    self.stats
                        .events_dropped
                        .fetch_add(count, Ordering::Relaxed);
                    // Try again
                }
                Err(_) => return None,
            }
        }
    }
}

impl Drop for QueryLogSubscriber {
    fn drop(&mut self) {
        self.stats
            .active_subscribers
            .fetch_sub(1, Ordering::Relaxed);
        debug!("Query log subscriber dropped");
    }
}

/// Subscriber for security events
pub struct SecurityEventSubscriber {
    rx: broadcast::Receiver<AuditEvent>,
    stats: Arc<EventBusStats>,
}

impl SecurityEventSubscriber {
    /// Receive the next security event
    pub async fn recv(&mut self) -> Option<AuditEvent> {
        loop {
            match self.rx.recv().await {
                Ok(event) => return Some(event),
                Err(broadcast::error::RecvError::Lagged(count)) => {
                    warn!(
                        lagged = count,
                        "Security event subscriber lagged, dropped events"
                    );
                    self.stats
                        .events_dropped
                        .fetch_add(count, Ordering::Relaxed);
                }
                Err(broadcast::error::RecvError::Closed) => {
                    debug!("Security event channel closed");
                    return None;
                }
            }
        }
    }

    /// Try to receive without blocking
    pub fn try_recv(&mut self) -> Option<AuditEvent> {
        loop {
            match self.rx.try_recv() {
                Ok(event) => return Some(event),
                Err(broadcast::error::TryRecvError::Lagged(count)) => {
                    self.stats
                        .events_dropped
                        .fetch_add(count, Ordering::Relaxed);
                }
                Err(_) => return None,
            }
        }
    }
}

impl Drop for SecurityEventSubscriber {
    fn drop(&mut self) {
        self.stats
            .active_subscribers
            .fetch_sub(1, Ordering::Relaxed);
        debug!("Security event subscriber dropped");
    }
}

/// Global event bus instance
static EVENT_BUS: once_cell::sync::Lazy<RwLock<Option<AuditEventBus>>> =
    once_cell::sync::Lazy::new(|| RwLock::new(None));

/// Initialize the global event bus
pub fn init_event_bus(capacity: usize) {
    let mut bus = EVENT_BUS.write();
    *bus = Some(AuditEventBus::with_capacity(capacity));
    debug!(capacity, "Initialized global event bus");
}

/// Get a reference to the global event bus
pub fn event_bus() -> Option<AuditEventBus> {
    EVENT_BUS.read().clone()
}

/// Publish a query log entry to the global event bus
pub fn publish_query(entry: QueryLogEntry) -> usize {
    if let Some(bus) = EVENT_BUS.read().as_ref() {
        bus.publish_query(entry)
    } else {
        0
    }
}

/// Publish a security event to the global event bus
pub fn publish_security(event: AuditEvent) -> usize {
    if let Some(bus) = EVENT_BUS.read().as_ref() {
        bus.publish_security(event)
    } else {
        0
    }
}

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

    fn sample_query_entry() -> QueryLogEntry {
        QueryLogEntry::new(
            1234,
            "udp",
            "example.com".to_string(),
            "A".to_string(),
            "IN".to_string(),
        )
    }

    #[tokio::test]
    async fn test_publish_without_subscribers() {
        let bus = AuditEventBus::new();
        let count = bus.publish_query(sample_query_entry());
        assert_eq!(count, 0);
    }

    #[tokio::test]
    async fn test_single_subscriber() {
        let bus = AuditEventBus::new();
        let mut sub = bus.subscribe_queries();

        let entry = sample_query_entry();
        let count = bus.publish_query(entry.clone());
        assert_eq!(count, 1);

        let received = sub.recv().await.unwrap();
        assert_eq!(received.qname, "example.com");
    }

    #[tokio::test]
    async fn test_multiple_subscribers() {
        let bus = AuditEventBus::new();
        let mut sub1 = bus.subscribe_queries();
        let mut sub2 = bus.subscribe_queries();
        let mut sub3 = bus.subscribe_queries();

        assert_eq!(bus.query_subscriber_count(), 3);

        let entry = sample_query_entry();
        let count = bus.publish_query(entry);
        assert_eq!(count, 3);

        // All subscribers should receive the event
        assert!(sub1.recv().await.is_some());
        assert!(sub2.recv().await.is_some());
        assert!(sub3.recv().await.is_some());
    }

    #[tokio::test]
    async fn test_backpressure_handling() {
        let bus = AuditEventBus::with_capacity(2);
        let mut sub = bus.subscribe_queries();

        // Publish more events than capacity
        for i in 0..5 {
            let mut entry = sample_query_entry();
            entry.query_id = i;
            bus.publish_query(entry);
        }

        // Subscriber should handle lagged events gracefully
        let received = sub.recv().await;
        assert!(received.is_some());

        let stats = bus.stats();
        // Should have some dropped events due to capacity
        assert!(stats.events_dropped > 0 || stats.events_published == 5);
    }

    #[tokio::test]
    async fn test_subscriber_drop_updates_count() {
        let bus = AuditEventBus::new();

        {
            let _sub1 = bus.subscribe_queries();
            let _sub2 = bus.subscribe_queries();
            assert_eq!(bus.query_subscriber_count(), 2);
        }

        // After subscribers are dropped
        assert_eq!(bus.query_subscriber_count(), 0);
    }

    #[tokio::test]
    async fn test_stats_tracking() {
        let bus = AuditEventBus::new();
        let _sub = bus.subscribe_queries();

        for _ in 0..10 {
            bus.publish_query(sample_query_entry());
        }

        let stats = bus.stats();
        assert_eq!(stats.events_published, 10);
        assert_eq!(stats.active_subscribers, 1);
        assert_eq!(stats.peak_subscribers, 1);
    }
}