nntp-proxy 0.5.1

NNTP proxy server with per-command backend multiplexing, caching, metrics, and TUI dashboard
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
//! Serializable dashboard state shared between local and attached TUI modes.

use crate::metrics::{
    BackendHealthStatus, BackendStats, CommandCount, DiskCacheStats, ErrorCount, MetricsSnapshot,
    UserStats,
};
use crate::tui::app::{ThroughputPoint, ViewMode};
use crate::tui::system_stats::SystemStats;
use crate::types::{
    BackendToClientBytes, BytesPerSecondRate, BytesReceived, BytesSent, ClientToBackendBytes,
    HostName, MaxConnections, Port, ServerName, TotalConnections,
};
use std::time::Duration;

/// Snapshot of the I/O buffer pool used by the summary panel.
#[derive(Debug, Clone, Copy, Default, serde::Serialize, serde::Deserialize)]
pub struct BufferPoolStats {
    pub available: usize,
    pub in_use: usize,
    pub total: usize,
}

/// A backend entry rendered in the backend list and chart panels.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct BackendDisplay {
    pub host: HostName,
    pub port: Port,
    pub name: ServerName,
    pub max_connections: MaxConnections,
}

/// A backend entry rendered in the backend list and chart panels.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct BackendView {
    pub server: BackendDisplay,
    pub stats: BackendStats,
    pub active_connections: usize,
    pub health_status: BackendHealthStatus,
    pub pending_count: usize,
    pub load_ratio: Option<f64>,
    pub stateful_count: usize,
    pub traffic_share: Option<f64>,
    pub history: Vec<ThroughputPoint>,
}

impl BackendView {
    #[must_use]
    pub fn latest_throughput(&self) -> Option<&ThroughputPoint> {
        self.history.last()
    }
}

/// A backend entry sent to attached dashboard clients.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RemoteBackendView {
    pub server: BackendDisplay,
    pub stats: BackendStats,
    pub active_connections: usize,
    pub health_status: BackendHealthStatus,
    pub pending_count: usize,
    pub stateful_count: usize,
    pub traffic_share: Option<f64>,
    pub history: Vec<ThroughputPoint>,
}

impl RemoteBackendView {
    #[must_use]
    pub fn latest_throughput(&self) -> Option<&ThroughputPoint> {
        self.history.last()
    }
}

/// Serialized user stats used by the dashboard payload.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DashboardUserStats {
    pub username: String,
    pub active_connections: usize,
    pub total_connections: TotalConnections,
    pub bytes_sent: BytesSent,
    pub bytes_received: BytesReceived,
    pub bytes_sent_per_sec: BytesPerSecondRate,
    pub bytes_received_per_sec: BytesPerSecondRate,
    pub total_commands: CommandCount,
    pub errors: ErrorCount,
}

impl DashboardUserStats {
    #[must_use]
    pub fn from_user_stats(user: &UserStats) -> Self {
        Self {
            username: user.username.clone(),
            active_connections: user.active_connections,
            total_connections: user.total_connections,
            bytes_sent: user.bytes_sent,
            bytes_received: user.bytes_received,
            bytes_sent_per_sec: user.bytes_sent_per_sec,
            bytes_received_per_sec: user.bytes_received_per_sec,
            total_commands: user.total_commands,
            errors: user.errors,
        }
    }

    #[must_use]
    pub const fn total_bytes(&self) -> u64 {
        self.bytes_sent
            .as_u64()
            .saturating_add(self.bytes_received.as_u64())
    }
}

/// Serialized metrics used by the dashboard payload.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct DashboardMetrics {
    pub total_connections: u64,
    pub active_connections: usize,
    pub stateful_sessions: usize,
    pub client_to_backend_bytes: ClientToBackendBytes,
    pub backend_to_client_bytes: BackendToClientBytes,
    pub uptime: Duration,
    pub cache_entries: u64,
    pub cache_size_bytes: u64,
    pub cache_hit_rate: f64,
    pub disk_cache: Option<DiskCacheStats>,
    pub pipeline_batches: u64,
    pub pipeline_commands: u64,
    pub pipeline_requests_queued: u64,
    pub pipeline_requests_completed: u64,
    #[serde(default)]
    pub in_flight_requests: usize,
}

impl DashboardMetrics {
    #[must_use]
    pub fn from_snapshot(snapshot: &MetricsSnapshot) -> Self {
        Self {
            total_connections: snapshot.total_connections,
            active_connections: snapshot.active_connections,
            stateful_sessions: snapshot.stateful_sessions,
            client_to_backend_bytes: snapshot.client_to_backend_bytes,
            backend_to_client_bytes: snapshot.backend_to_client_bytes,
            uptime: snapshot.uptime,
            cache_entries: snapshot.cache_entries,
            cache_size_bytes: snapshot.cache_size_bytes,
            cache_hit_rate: snapshot.cache_hit_rate,
            disk_cache: snapshot.disk_cache,
            pipeline_batches: snapshot.pipeline_batches,
            pipeline_commands: snapshot.pipeline_commands,
            pipeline_requests_queued: snapshot.pipeline_requests_queued,
            pipeline_requests_completed: snapshot.pipeline_requests_completed,
            in_flight_requests: 0,
        }
    }

    #[must_use]
    pub fn format_uptime(&self) -> String {
        let secs = self.uptime.as_secs();
        let hours = secs / 3600;
        let minutes = (secs % 3600) / 60;
        let seconds = secs % 60;

        if hours > 0 {
            format!("{hours}h {minutes}m {seconds}s")
        } else if minutes > 0 {
            format!("{minutes}m {seconds}s")
        } else {
            format!("{seconds}s")
        }
    }

    #[must_use]
    pub const fn total_bytes(&self) -> u64 {
        self.client_to_backend_bytes.as_u64() + self.backend_to_client_bytes.as_u64()
    }
}

/// Full dashboard state, suitable for rendering locally or over websocket.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DashboardState {
    pub metrics: DashboardMetrics,
    pub backend_views: Vec<BackendView>,
    pub top_users: Vec<DashboardUserStats>,
    pub client_history: Vec<ThroughputPoint>,
    pub system_stats: SystemStats,
    pub view_mode: ViewMode,
    pub show_details: bool,
    pub log_lines: Vec<String>,
    pub buffer_pool: Option<BufferPoolStats>,
}

/// Slim dashboard state sent to attached dashboard clients.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RemoteDashboardState {
    pub metrics: DashboardMetrics,
    pub backend_views: Vec<RemoteBackendView>,
    pub top_users: Vec<DashboardUserStats>,
    pub latest_client_throughput: Option<ThroughputPoint>,
    pub system_stats: SystemStats,
    pub log_lines: Vec<String>,
}

impl DashboardState {
    #[must_use]
    fn backend_view(&self, backend_idx: usize) -> Option<&BackendView> {
        self.backend_views.get(backend_idx)
    }

    #[must_use]
    pub fn latest_client_throughput(&self) -> Option<&ThroughputPoint> {
        self.client_history.last()
    }

    #[must_use]
    pub fn latest_backend_throughput(&self, backend_idx: usize) -> Option<&ThroughputPoint> {
        self.backend_view(backend_idx)
            .and_then(BackendView::latest_throughput)
    }

    #[must_use]
    pub fn throughput_history(&self, backend_idx: usize) -> Option<&[ThroughputPoint]> {
        self.backend_view(backend_idx)
            .map(|view| view.history.as_slice())
    }

    #[must_use]
    pub fn backend_pending_count(&self, backend_idx: usize) -> usize {
        self.backend_view(backend_idx)
            .map_or(0, |view| view.pending_count)
    }

    #[must_use]
    pub fn backend_load_ratio(&self, backend_idx: usize) -> Option<f64> {
        self.backend_view(backend_idx)
            .and_then(|view| view.load_ratio)
    }

    #[must_use]
    pub fn backend_stateful_count(&self, backend_idx: usize) -> usize {
        self.backend_view(backend_idx)
            .map_or(0, |view| view.stateful_count)
    }

    #[must_use]
    pub fn backend_traffic_share(&self, backend_idx: usize) -> Option<f64> {
        self.backend_view(backend_idx)
            .and_then(|view| view.traffic_share)
    }

    #[must_use]
    pub fn buffer_pool(&self) -> Option<&BufferPoolStats> {
        self.buffer_pool.as_ref()
    }
}

impl RemoteDashboardState {
    #[must_use]
    fn backend_view(&self, backend_idx: usize) -> Option<&RemoteBackendView> {
        self.backend_views.get(backend_idx)
    }

    #[must_use]
    pub fn latest_client_throughput(&self) -> Option<&ThroughputPoint> {
        self.latest_client_throughput.as_ref()
    }

    #[must_use]
    pub fn backend_pending_count(&self, backend_idx: usize) -> usize {
        self.backend_view(backend_idx)
            .map_or(0, |view| view.pending_count)
    }

    #[must_use]
    pub fn backend_stateful_count(&self, backend_idx: usize) -> usize {
        self.backend_view(backend_idx)
            .map_or(0, |view| view.stateful_count)
    }

    #[must_use]
    pub fn backend_traffic_share(&self, backend_idx: usize) -> Option<f64> {
        self.backend_view(backend_idx)
            .and_then(|view| view.traffic_share)
    }
}

impl From<BackendView> for RemoteBackendView {
    fn from(view: BackendView) -> Self {
        Self {
            server: view.server,
            stats: view.stats,
            active_connections: view.active_connections,
            health_status: view.health_status,
            pending_count: view.pending_count,
            stateful_count: view.stateful_count,
            traffic_share: view.traffic_share,
            history: view.history,
        }
    }
}

impl From<DashboardState> for RemoteDashboardState {
    fn from(state: DashboardState) -> Self {
        Self {
            metrics: state.metrics,
            backend_views: state
                .backend_views
                .into_iter()
                .map(RemoteBackendView::from)
                .collect(),
            top_users: state.top_users,
            latest_client_throughput: state.client_history.last().cloned(),
            system_stats: state.system_stats,
            log_lines: state.log_lines,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::metrics::{BackendHealthStatus, BackendStats};
    use crate::tui::app::{ThroughputPoint, ViewMode};
    use crate::types::Port;
    use crate::types::tui::{Throughput, Timestamp};

    fn sample_backend_view() -> BackendView {
        BackendView {
            server: BackendDisplay {
                host: HostName::try_new("backend.example.com".to_string()).unwrap(),
                port: Port::try_new(119).unwrap(),
                name: ServerName::try_new("Backend".to_string()).unwrap(),
                max_connections: MaxConnections::try_new(10).unwrap(),
            },
            stats: BackendStats::default(),
            active_connections: 1,
            health_status: BackendHealthStatus::Healthy,
            pending_count: 2,
            load_ratio: Some(0.5),
            stateful_count: 3,
            traffic_share: Some(42.0),
            history: vec![ThroughputPoint::new_backend(
                Timestamp::now(),
                Throughput::new(1.0),
                Throughput::new(2.0),
                crate::types::tui::CommandsPerSecond::new(3.0),
            )],
        }
    }

    #[test]
    fn backend_accessors_handle_out_of_range_indices() {
        let state = DashboardState {
            metrics: DashboardMetrics::default(),
            backend_views: vec![sample_backend_view()],
            top_users: Vec::new(),
            client_history: Vec::new(),
            system_stats: SystemStats::default(),
            view_mode: ViewMode::Normal,
            show_details: false,
            log_lines: Vec::new(),
            buffer_pool: None,
        };

        assert!(state.latest_backend_throughput(1).is_none());
        assert!(state.throughput_history(1).is_none());
        assert_eq!(state.backend_pending_count(1), 0);
        assert!(state.backend_load_ratio(1).is_none());
        assert_eq!(state.backend_stateful_count(1), 0);
        assert!(state.backend_traffic_share(1).is_none());
    }

    #[test]
    fn remote_dashboard_state_keeps_latest_client_point_and_drops_local_only_fields() {
        let latest_client = ThroughputPoint::new_client(
            Timestamp::now(),
            Throughput::new(10.0),
            Throughput::new(20.0),
        );
        let state = DashboardState {
            metrics: DashboardMetrics::default(),
            backend_views: vec![sample_backend_view()],
            top_users: Vec::new(),
            client_history: vec![
                ThroughputPoint::new_client(
                    Timestamp::now(),
                    Throughput::new(1.0),
                    Throughput::new(2.0),
                ),
                latest_client.clone(),
            ],
            system_stats: SystemStats::default(),
            view_mode: ViewMode::LogFullscreen,
            show_details: true,
            log_lines: vec!["hello".to_string()],
            buffer_pool: Some(BufferPoolStats {
                available: 1,
                in_use: 2,
                total: 3,
            }),
        };

        let remote = RemoteDashboardState::from(state);

        assert_eq!(remote.backend_views.len(), 1);
        assert_eq!(remote.log_lines, vec!["hello".to_string()]);
        assert_eq!(
            remote
                .latest_client_throughput()
                .map(|point| point.sent_per_sec().get()),
            Some(latest_client.sent_per_sec().get())
        );
    }
}