proxybroker 0.4.6

Find, check, and serve public HTTP(S) and SOCKS4/5 proxies. Library + CLI.
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
//! Pure core of the `proxybroker top` terminal dashboard (F4).
//!
//! [`DashboardState`] holds everything the dashboard needs to draw a frame; [`DashboardState::apply`]
//! folds in a fresh [`Pool`](crate::server::Pool) snapshot, [`render`] draws it with ratatui, and
//! [`DashboardState::on_key`] turns a keypress into a state mutation. All three are pure/offline —
//! no terminal, no I/O, no tokio — so they are unit-tested directly (`render` via ratatui's
//! `TestBackend`). The event loop, raw-mode terminal guard, and the `top` CLI subcommand that drive
//! these are a separate, non-pure controller layer built on top of this module.

use crate::proxy::Proxy;
use crate::server::PoolSnapshot;
use crate::types::Scheme;
use ratatui::layout::{Constraint, Layout};
use ratatui::widgets::{Block, Paragraph, Row as TableRow, Sparkline, Table};
use std::collections::{HashMap, VecDeque};
use std::net::IpAddr;

/// One row of the dashboard's proxy table — a display-ready projection of a [`Proxy`].
pub struct Row {
    /// `(host, port)` — the [`DashboardState::history`] key for this row's sparkline (carried so
    /// `render` looks the ring up directly instead of re-parsing the display `addr`).
    pub key: (IpAddr, u16),
    pub addr: String,
    pub protos: String,
    pub error_rate: f64,
    pub resp_time: f64,
    pub country: String,
}

/// Which column [`DashboardState::rows`] is sorted by. `ErrorRate`/`RespTime` sort ascending
/// (best/fastest first); `Addr`/`Country` sort lexicographically.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum SortKey {
    Addr,
    ErrorRate,
    RespTime,
    Country,
}

/// Ring-buffer capacity for a proxy's response-time history (one sparkline's worth).
const RING_CAP: usize = 60;

/// Everything [`render`] needs to draw one frame. Rebuilt from a live `Pool` by [`Self::apply`];
/// mutated in place by [`Self::on_key`].
pub struct DashboardState {
    pub rows: Vec<Row>,
    pub snapshot: PoolSnapshot,
    pub sort: SortKey,
    /// Per-proxy response-time history, keyed by `(host, port)` so it survives a proxy dropping
    /// out and back into the pool. Capped at [`RING_CAP`] — oldest sample drops first.
    pub history: HashMap<(IpAddr, u16), VecDeque<f64>>,
    pub selected: usize,
}

impl Default for DashboardState {
    fn default() -> Self {
        DashboardState {
            rows: Vec::new(),
            snapshot: PoolSnapshot::default(),
            sort: SortKey::RespTime,
            history: HashMap::new(),
            selected: 0,
        }
    }
}

impl DashboardState {
    /// Rebuild [`Self::rows`] from one non-consuming pool read: one [`Row`] per proxy, each proxy's
    /// current `avg_resp_time()` pushed onto its history ring, the header [`PoolSnapshot`] derived
    /// from the SAME slice (so the header and table can't disagree within a frame — one lock, taken
    /// by the caller's `Pool::proxies()`), then re-sorted and [`Self::selected`] clamped.
    pub fn apply(&mut self, proxies: &[Proxy]) {
        self.rows = proxies
            .iter()
            .map(|p| Row {
                key: (p.host, p.port),
                addr: p.addr(),
                protos: p
                    .types()
                    .keys()
                    .map(|proto| proto.as_str())
                    .collect::<Vec<_>>()
                    .join(","),
                error_rate: p.error_rate(),
                resp_time: p.avg_resp_time(),
                country: p.geo.as_ref().map(|c| c.code.clone()).unwrap_or_default(),
            })
            .collect();

        for p in proxies {
            let ring = self.history.entry((p.host, p.port)).or_default();
            ring.push_back(p.avg_resp_time());
            while ring.len() > RING_CAP {
                ring.pop_front();
            }
        }

        // Derive the header counts from the same `proxies` slice — identical to `Pool::snapshot`'s
        // per-scheme counts + means, but atomic with the rows (no second pool lock to race).
        let total = proxies.len();
        let (mut http, mut https, mut err_sum, mut rt_sum, mut probe_sum) =
            (0usize, 0usize, 0.0_f64, 0.0_f64, 0.0_f64);
        for p in proxies {
            let schemes = p.schemes();
            if schemes.contains(&Scheme::Http) {
                http += 1;
            }
            if schemes.contains(&Scheme::Https) {
                https += 1;
            }
            err_sum += p.error_rate();
            rt_sum += p.avg_resp_time();
            probe_sum += p.probe_latency();
        }
        self.snapshot = PoolSnapshot {
            http,
            https,
            total,
            avg_error_rate: if total > 0 {
                err_sum / total as f64
            } else {
                0.0
            },
            avg_resp_time: if total > 0 {
                rt_sum / total as f64
            } else {
                0.0
            },
            probe_latency_avg: if total > 0 {
                probe_sum / total as f64
            } else {
                0.0
            },
        };
        self.sort_rows();
        self.selected = self.selected.min(self.rows.len().saturating_sub(1));
    }

    /// Re-sort [`Self::rows`] by the current [`Self::sort`] key. Factored out of [`Self::apply`]
    /// so [`Self::on_key`] can re-sort without re-fetching the pool.
    fn sort_rows(&mut self) {
        match self.sort {
            SortKey::Addr => self.rows.sort_by(|a, b| a.addr.cmp(&b.addr)),
            SortKey::ErrorRate => self
                .rows
                .sort_by(|a, b| a.error_rate.total_cmp(&b.error_rate)),
            SortKey::RespTime => self
                .rows
                .sort_by(|a, b| a.resp_time.total_cmp(&b.resp_time)),
            SortKey::Country => self.rows.sort_by(|a, b| a.country.cmp(&b.country)),
        }
    }

    /// Handle one keypress. Returns `false` to signal quit, `true` to keep running. `a`/`e`/`r`/`c`
    /// change [`Self::sort`] and re-sort in place; `Down`/`j` and `Up`/`k` move [`Self::selected`],
    /// clamped to the current row count. Anything else is a no-op.
    pub fn on_key(&mut self, key: crossterm::event::KeyCode) -> bool {
        use crossterm::event::KeyCode;
        match key {
            KeyCode::Char('q') | KeyCode::Esc => return false,
            KeyCode::Char('a') => {
                self.sort = SortKey::Addr;
                self.sort_rows();
            }
            KeyCode::Char('e') => {
                self.sort = SortKey::ErrorRate;
                self.sort_rows();
            }
            KeyCode::Char('r') => {
                self.sort = SortKey::RespTime;
                self.sort_rows();
            }
            KeyCode::Char('c') => {
                self.sort = SortKey::Country;
                self.sort_rows();
            }
            KeyCode::Down | KeyCode::Char('j') => {
                if !self.rows.is_empty() {
                    self.selected = (self.selected + 1).min(self.rows.len() - 1);
                }
            }
            KeyCode::Up | KeyCode::Char('k') => {
                self.selected = self.selected.saturating_sub(1);
            }
            _ => {}
        }
        true
    }
}

/// Draw one frame: a one-line pool summary, a `Table` of [`DashboardState::rows`] (sorted per
/// [`DashboardState::sort`]), and a `Sparkline` of the selected row's response-time history. Pure
/// — no I/O, safe to call against a [`ratatui::backend::TestBackend`].
pub fn render(frame: &mut ratatui::Frame, state: &DashboardState) {
    let [header_area, table_area, spark_area] = Layout::vertical([
        Constraint::Length(1),
        Constraint::Min(0),
        Constraint::Length(3),
    ])
    .areas(frame.area());

    let header_text = format!(
        "total {} | http {} | https {} | avg err {:.2} | avg resp {:.2}s",
        state.snapshot.total,
        state.snapshot.http,
        state.snapshot.https,
        state.snapshot.avg_error_rate,
        state.snapshot.avg_resp_time,
    );
    frame.render_widget(Paragraph::new(header_text), header_area);

    let widths = [
        Constraint::Length(21),
        Constraint::Length(16),
        Constraint::Length(8),
        Constraint::Length(8),
        Constraint::Length(8),
    ];
    let header_row = TableRow::new(["Addr", "Protos", "Err%", "Resp(s)", "Country"]);
    let rows = state.rows.iter().map(|r| {
        TableRow::new([
            r.addr.clone(),
            r.protos.clone(),
            format!("{:.2}", r.error_rate),
            format!("{:.2}", r.resp_time),
            r.country.clone(),
        ])
    });
    let table = Table::new(rows, widths)
        .header(header_row)
        .block(Block::bordered().title("Proxies"));
    frame.render_widget(table, table_area);

    let selected_ring = state
        .rows
        .get(state.selected)
        .and_then(|r| state.history.get(&r.key));
    let spark_data: Vec<u64> = selected_ring
        .map(|ring| {
            ring.iter()
                .map(|secs| (secs * 1000.0).round() as u64)
                .collect()
        })
        .unwrap_or_default();
    let sparkline = Sparkline::default()
        .block(Block::bordered().title("Selected resp time (ms)"))
        .data(spark_data);
    frame.render_widget(sparkline, spark_area);
}

/// A terminal-mode guard: enters raw mode + the alternate screen on construction and restores both
/// on `Drop`, so any exit path — return, quit, `?`, or panic — leaves the terminal usable.
struct TermGuard;

impl TermGuard {
    fn enter() -> std::io::Result<Self> {
        crossterm::terminal::enable_raw_mode()?;
        // Roll raw mode back if entering the alternate screen fails — otherwise we'd return Err
        // with no guard to restore it, leaving the shell wedged (no echo / line buffering).
        if let Err(e) =
            crossterm::execute!(std::io::stdout(), crossterm::terminal::EnterAlternateScreen)
        {
            let _ = crossterm::terminal::disable_raw_mode();
            return Err(e);
        }
        Ok(TermGuard)
    }
}

impl Drop for TermGuard {
    fn drop(&mut self) {
        let _ = crossterm::terminal::disable_raw_mode();
        let _ = crossterm::execute!(std::io::stdout(), crossterm::terminal::LeaveAlternateScreen);
    }
}

/// Restore the terminal on a panic before the default hook prints the backtrace — otherwise a panic
/// inside the raw-mode loop wedges the user's terminal.
fn install_panic_hook() {
    let default = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        let _ = crossterm::terminal::disable_raw_mode();
        let _ = crossterm::execute!(std::io::stdout(), crossterm::terminal::LeaveAlternateScreen);
        default(info);
    }));
}

/// Run the live dashboard against `pool`: redraw every `refresh` and on each keypress, until the
/// user quits (`q`/Esc) or the event stream ends. The [`TermGuard`] restores the terminal on exit.
pub async fn run_top(
    pool: std::sync::Arc<crate::server::Pool>,
    refresh: std::time::Duration,
) -> std::io::Result<()> {
    use futures_util::StreamExt;
    // `tokio::time::interval` panics on a zero period, so floor the (user-settable) refresh.
    let refresh = refresh.max(std::time::Duration::from_millis(100));
    install_panic_hook();
    let _guard = TermGuard::enter()?;
    let mut term =
        ratatui::Terminal::new(ratatui::backend::CrosstermBackend::new(std::io::stdout()))?;

    let mut state = DashboardState::default();
    state.apply(&pool.proxies());

    let mut ticker = tokio::time::interval(refresh);
    ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
    let mut events = crossterm::event::EventStream::new();

    loop {
        term.draw(|f| render(f, &state))?;
        tokio::select! {
            _ = ticker.tick() => state.apply(&pool.proxies()),
            ev = events.next() => match ev {
                // Filter to Press so terminals that also emit Repeat/Release don't double-handle.
                Some(Ok(crossterm::event::Event::Key(k)))
                    if k.kind == crossterm::event::KeyEventKind::Press =>
                {
                    if !state.on_key(k.code) {
                        break;
                    }
                }
                Some(Err(_)) | None => break,
                _ => {}
            },
        }
    }
    Ok(()) // _guard's Drop restores the terminal
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::server::{Pool, PoolConfig};
    use crate::types::Proto;
    use std::collections::BTreeSet;

    fn proxy(ip: &str, rt: f64) -> Proxy {
        let mut p = Proxy::new(ip.parse().unwrap(), 80, BTreeSet::new());
        p.add_type(Proto::Http, None);
        p.record_attempt(Some(rt), None); // a runtime so avg_resp_time reflects `rt`
        p
    }

    #[test]
    fn apply_snapshot_updates_rings_and_sorts() {
        let pool = Pool::from_proxies(
            vec![proxy("2.2.2.2", 0.9), proxy("1.1.1.1", 0.1)],
            PoolConfig::default(),
        );
        let mut st = DashboardState {
            sort: SortKey::RespTime,
            ..Default::default()
        };
        st.apply(&pool.proxies());
        assert_eq!(
            st.rows[0].addr, "1.1.1.1:80",
            "fastest first under RespTime"
        );
        st.apply(&pool.proxies());
        assert_eq!(
            st.history[&("1.1.1.1".parse().unwrap(), 80)].len(),
            2,
            "ring grew per apply"
        );
    }

    #[test]
    fn top_renders_sorted_pool_table() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let pool = Pool::from_proxies(
            vec![proxy("2.2.2.2", 0.9), proxy("1.1.1.1", 0.1)],
            PoolConfig::default(),
        );
        let mut st = DashboardState {
            sort: SortKey::RespTime,
            ..Default::default()
        };
        st.apply(&pool.proxies());

        let mut term = Terminal::new(TestBackend::new(90, 20)).unwrap();
        term.draw(|f| render(f, &st)).unwrap();
        let text: String = term
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            text.contains("1.1.1.1:80") && text.contains("2.2.2.2:80"),
            "both addrs rendered"
        );
        assert!(
            text.find("1.1.1.1").unwrap() < text.find("2.2.2.2").unwrap(),
            "sorted: fast first"
        );
    }

    #[test]
    fn sort_key_cycles() {
        use crossterm::event::KeyCode;

        // "9.9.9.9" is fastest (first under RespTime) but lexicographically last (last under
        // Addr) — a key that flips the row order proves `on_key` actually re-sorted.
        let pool = Pool::from_proxies(
            vec![proxy("9.9.9.9", 0.1), proxy("1.1.1.1", 0.9)],
            PoolConfig::default(),
        );
        let mut st = DashboardState::default(); // default sort: RespTime
        st.apply(&pool.proxies());
        assert_eq!(
            st.rows[0].addr, "9.9.9.9:80",
            "fastest first under RespTime"
        );

        assert!(st.on_key(KeyCode::Char('a')));
        assert_eq!(
            st.rows[0].addr, "1.1.1.1:80",
            "lexicographic first under Addr"
        );
    }

    #[test]
    fn quit_key_returns_false() {
        use crossterm::event::KeyCode;

        let mut st = DashboardState::default();
        assert!(!st.on_key(KeyCode::Char('q')), "q quits");
        assert!(!st.on_key(KeyCode::Esc), "Esc quits");
    }

    #[test]
    fn select_moves_within_bounds() {
        use crossterm::event::KeyCode;

        let pool = Pool::from_proxies(
            vec![
                proxy("1.1.1.1", 0.1),
                proxy("2.2.2.2", 0.2),
                proxy("3.3.3.3", 0.3),
            ],
            PoolConfig::default(),
        );
        let mut st = DashboardState::default();
        st.apply(&pool.proxies());
        assert_eq!(st.selected, 0);

        assert!(st.on_key(KeyCode::Up));
        assert_eq!(st.selected, 0, "up at 0 stays 0");

        for _ in 0..10 {
            st.on_key(KeyCode::Down);
        }
        assert_eq!(st.selected, 2, "down past the end stays clamped");

        assert!(st.on_key(KeyCode::Up));
        assert_eq!(st.selected, 1, "up moves back by one");
    }
}