bee-tui 0.1.0

Production-grade k9s-style terminal cockpit for Ethereum Swarm Bee node operators.
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
//! S2 — Stamps screen (`docs/PLAN.md` § 8.S2).
//!
//! Renders one row per known postage batch with the volume +
//! duration framing operators actually reason about (bee#4992 is
//! retiring depth+amount). The "worst bucket" column tells the
//! truth that the API's `utilization` field is `MaxBucketCount`
//! — operators see exactly which batch is about to fail uploads
//! even though average usage is far from 100%.
//!
//! Behaviour is data-driven via [`Stamps::rows_for`] so insta
//! snapshot tests can stub the input and verify status / value /
//! `why` strings without launching a TUI.

use color_eyre::Result;
use ratatui::{
    Frame,
    layout::{Constraint, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph},
};
use tokio::sync::watch;

use super::Component;
use crate::action::Action;
use crate::watch::StampsSnapshot;

use bee::postage::PostageBatch;

/// Tri-state row outcome with `Pending` for chain-confirmation gating.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StampStatus {
    /// `usable=false` — chain hasn't confirmed the batch yet.
    Pending,
    /// `batch_ttl ≤ 0` — paid balance is exhausted, nothing to stamp.
    Expired,
    /// Worst bucket ≥ 95 % — the very next upload may fail
    /// (immutable batches return ErrBucketFull at the upper bound).
    Critical,
    /// Worst bucket ≥ 80 %. Above the safe-headroom line; warn early.
    Skewed,
    /// Everything green: usable, in budget, headroom present.
    Healthy,
}

impl StampStatus {
    fn color(self) -> Color {
        match self {
            Self::Pending => Color::Cyan,
            Self::Expired => Color::Red,
            Self::Critical => Color::Red,
            Self::Skewed => Color::Yellow,
            Self::Healthy => Color::Green,
        }
    }
    fn label(self) -> &'static str {
        match self {
            Self::Pending => "⏳ pending",
            Self::Expired => "✗ expired",
            Self::Critical => "✗ critical",
            Self::Skewed => "⚠ skewed",
            Self::Healthy => "",
        }
    }
}

/// One row of the stamps table.
#[derive(Debug, Clone)]
pub struct StampRow {
    pub label: String,
    pub batch_id_short: String,
    /// Theoretical volume = `2^depth × 4 KiB`, formatted to a
    /// human-readable string. Effective volume is bounded by the
    /// worst bucket — see `worst_bucket_pct`.
    pub volume: String,
    /// Worst-bucket fill percentage in `0..=100`. This *is* what the
    /// API calls `utilization`; operators don't always realise.
    pub worst_bucket_pct: u32,
    /// Raw `utilization` count plus `BucketUpperBound`.
    pub worst_bucket_raw: String,
    /// Pre-formatted `Xd Yh` countdown string. `"-"` if expired.
    pub ttl: String,
    /// `true` if `immutable` — flagged in the `value` line because
    /// mutable + full silently overwrites prior chunks (bee#5334).
    pub immutable: bool,
    pub status: StampStatus,
    /// Inline tooltip rendered on the continuation line.
    pub why: Option<String>,
}

pub struct Stamps {
    rx: watch::Receiver<StampsSnapshot>,
    snapshot: StampsSnapshot,
}

impl Stamps {
    pub fn new(rx: watch::Receiver<StampsSnapshot>) -> Self {
        let snapshot = rx.borrow().clone();
        Self { rx, snapshot }
    }

    fn pull_latest(&mut self) {
        self.snapshot = self.rx.borrow().clone();
    }

    /// Pure, snapshot-driven row computation. Exposed for snapshot
    /// tests.
    pub fn rows_for(snap: &StampsSnapshot) -> Vec<StampRow> {
        snap.batches.iter().map(row_from_batch).collect()
    }
}

fn row_from_batch(b: &PostageBatch) -> StampRow {
    let label = if b.label.is_empty() {
        "(unlabeled)".to_string()
    } else {
        b.label.clone()
    };
    let batch_hex = b.batch_id.to_hex();
    let batch_id_short = if batch_hex.len() > 8 {
        format!("{}", &batch_hex[..8])
    } else {
        batch_hex
    };
    let theoretical_bytes: u128 = (1u128 << b.depth) * 4096;
    let volume = format_bytes(theoretical_bytes);
    let worst_bucket_pct = worst_bucket_pct(b);
    let upper_bound = 1u32 << b.depth.saturating_sub(b.bucket_depth);
    let worst_bucket_raw = format!("{}/{}", b.utilization, upper_bound);
    let ttl = format_ttl_seconds(b.batch_ttl);

    let (status, why) = if !b.usable {
        (
            StampStatus::Pending,
            Some("waiting on chain confirmation (~10 blocks).".into()),
        )
    } else if b.batch_ttl <= 0 {
        (
            StampStatus::Expired,
            Some("paid balance exhausted; topup or stop using.".into()),
        )
    } else if worst_bucket_pct >= 95 {
        (
            StampStatus::Critical,
            Some(if b.immutable {
                "immutable batch will REJECT next upload at this bucket.".into()
            } else {
                "mutable batch will silently overwrite oldest chunks.".into()
            }),
        )
    } else if worst_bucket_pct >= 80 {
        (
            StampStatus::Skewed,
            Some(format!(
                "worst bucket {worst_bucket_pct}% > safe headroom — dilute or stop using."
            )),
        )
    } else {
        (StampStatus::Healthy, None)
    };

    StampRow {
        label,
        batch_id_short,
        volume,
        worst_bucket_pct,
        worst_bucket_raw,
        ttl,
        immutable: b.immutable,
        status,
        why,
    }
}

/// `MaxBucketCount` (Bee's `utilization`) as a 0..=100 percentage of
/// the per-bucket upper bound `2^(depth - bucket_depth)`.
fn worst_bucket_pct(b: &PostageBatch) -> u32 {
    let upper_bound: u32 = 1u32 << b.depth.saturating_sub(b.bucket_depth);
    if upper_bound == 0 {
        0
    } else {
        let pct = (u64::from(b.utilization) * 100) / u64::from(upper_bound);
        pct.min(100) as u32
    }
}

/// Bytes → IEC binary (KiB / MiB / GiB / TiB).
fn format_bytes(bytes: u128) -> String {
    const K: u128 = 1024;
    const M: u128 = K * 1024;
    const G: u128 = M * 1024;
    const T: u128 = G * 1024;
    if bytes >= T {
        format!("{:.1} TiB", bytes as f64 / T as f64)
    } else if bytes >= G {
        format!("{:.1} GiB", bytes as f64 / G as f64)
    } else if bytes >= M {
        format!("{:.1} MiB", bytes as f64 / M as f64)
    } else if bytes >= K {
        format!("{:.1} KiB", bytes as f64 / K as f64)
    } else {
        format!("{bytes} B")
    }
}

fn format_ttl_seconds(secs: i64) -> String {
    if secs <= 0 {
        return "expired".into();
    }
    let days = secs / 86_400;
    let hours = (secs % 86_400) / 3_600;
    if days >= 1 {
        format!("{days}d {hours:>2}h")
    } else {
        let minutes = (secs % 3_600) / 60;
        format!("{hours}h {minutes:>2}m")
    }
}

/// 8-character ASCII fill bar.
fn fill_bar(pct: u32, width: usize) -> String {
    let filled = ((pct as usize) * width) / 100;
    let mut bar = String::with_capacity(width);
    for _ in 0..filled.min(width) {
        bar.push('');
    }
    for _ in filled.min(width)..width {
        bar.push('');
    }
    bar
}

impl Component for Stamps {
    fn update(&mut self, action: Action) -> Result<Option<Action>> {
        if matches!(action, Action::Tick) {
            self.pull_latest();
        }
        Ok(None)
    }

    fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> {
        let chunks = Layout::vertical([
            Constraint::Length(3), // header
            Constraint::Min(0),    // table
            Constraint::Length(1), // footer
        ])
        .split(area);

        // Header
        let count = self.snapshot.batches.len();
        let header_l1 = Line::from(vec![
            Span::styled("STAMPS", Style::default().add_modifier(Modifier::BOLD)),
            Span::raw(format!("  {count} batch(es)")),
        ]);
        let mut header_l2 = Vec::new();
        if let Some(err) = &self.snapshot.last_error {
            header_l2.push(Span::styled(
                format!("error: {err}"),
                Style::default().fg(Color::Red),
            ));
        } else if !self.snapshot.is_loaded() {
            header_l2.push(Span::styled(
                "loading…",
                Style::default().fg(Color::DarkGray),
            ));
        }
        frame.render_widget(
            Paragraph::new(vec![header_l1, Line::from(header_l2)])
                .block(Block::default().borders(Borders::BOTTOM)),
            chunks[0],
        );

        // Table (rendered as a Paragraph of styled Lines for control)
        let mut lines: Vec<Line> = Vec::new();
        // Column header
        lines.push(Line::from(vec![Span::styled(
            "  LABEL                BATCH        VOLUME      WORST BUCKET                TTL         STATUS",
            Style::default()
                .fg(Color::DarkGray)
                .add_modifier(Modifier::BOLD),
        )]));
        if self.snapshot.batches.is_empty() {
            lines.push(Line::from(Span::styled(
                "  (no batches yet — buy one with swarm-cli or `bee stamps buy`)",
                Style::default()
                    .fg(Color::DarkGray)
                    .add_modifier(Modifier::ITALIC),
            )));
        } else {
            for r in Self::rows_for(&self.snapshot) {
                let bar = fill_bar(r.worst_bucket_pct, 8);
                let immut_glyph = if r.immutable { "I" } else { "M" };
                lines.push(Line::from(vec![
                    Span::raw("  "),
                    Span::styled(
                        format!("{:<20}", truncate(&r.label, 20)),
                        Style::default().add_modifier(Modifier::BOLD),
                    ),
                    Span::raw(format!("{:<13}", r.batch_id_short)),
                    Span::raw(format!("{:<12}", r.volume)),
                    Span::styled(
                        format!("{bar} {:>3}% ({})", r.worst_bucket_pct, r.worst_bucket_raw),
                        Style::default().fg(bucket_color(r.worst_bucket_pct)),
                    ),
                    Span::raw("    "),
                    Span::raw(format!("{:<10} ", r.ttl)),
                    Span::styled(immut_glyph, Style::default().fg(Color::DarkGray)),
                    Span::raw(" "),
                    Span::styled(
                        r.status.label(),
                        Style::default()
                            .fg(r.status.color())
                            .add_modifier(Modifier::BOLD),
                    ),
                ]));
                if let Some(why) = r.why {
                    lines.push(Line::from(vec![
                        Span::raw("       └─ "),
                        Span::styled(
                            why,
                            Style::default()
                                .fg(Color::DarkGray)
                                .add_modifier(Modifier::ITALIC),
                        ),
                    ]));
                }
            }
        }
        frame.render_widget(Paragraph::new(lines), chunks[1]);

        // Footer
        frame.render_widget(
            Paragraph::new(Line::from(vec![
                Span::styled(" Tab ", Style::default().fg(Color::Black).bg(Color::White)),
                Span::raw(" switch screen  "),
                Span::styled(" q ", Style::default().fg(Color::Black).bg(Color::White)),
                Span::raw(" quit  "),
                Span::styled(" I/M ", Style::default().fg(Color::DarkGray)),
                Span::raw(" immutable / mutable "),
            ])),
            chunks[2],
        );

        Ok(())
    }
}

fn truncate(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        s.to_string()
    } else {
        let mut out: String = s.chars().take(max.saturating_sub(1)).collect();
        out.push('');
        out
    }
}

fn bucket_color(pct: u32) -> Color {
    if pct >= 95 {
        Color::Red
    } else if pct >= 80 {
        Color::Yellow
    } else {
        Color::Green
    }
}

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

    #[test]
    fn fill_bar_clamps_to_width() {
        assert_eq!(fill_bar(0, 8), "░░░░░░░░");
        assert_eq!(fill_bar(50, 8), "▇▇▇▇░░░░");
        assert_eq!(fill_bar(100, 8), "▇▇▇▇▇▇▇▇");
        assert_eq!(fill_bar(150, 8), "▇▇▇▇▇▇▇▇"); // saturating
    }

    #[test]
    fn format_bytes_iec() {
        assert_eq!(format_bytes(0), "0 B");
        assert_eq!(format_bytes(1024), "1.0 KiB");
        assert_eq!(format_bytes(1024 * 1024), "1.0 MiB");
        assert_eq!(format_bytes(1024 * 1024 * 1024), "1.0 GiB");
        assert_eq!(format_bytes(16 * 1024 * 1024 * 1024), "16.0 GiB");
    }

    #[test]
    fn format_ttl_zero_is_expired() {
        assert_eq!(format_ttl_seconds(0), "expired");
        assert_eq!(format_ttl_seconds(-5), "expired");
    }

    #[test]
    fn format_ttl_days_and_hours() {
        // 47d 12h
        assert_eq!(format_ttl_seconds(47 * 86_400 + 12 * 3_600), "47d 12h");
    }

    #[test]
    fn format_ttl_under_a_day_uses_hours_minutes() {
        assert_eq!(format_ttl_seconds(2 * 3_600 + 30 * 60), "2h 30m");
    }
}