Skip to main content

oomtop_core/
provider.rs

1//! Frontend-facing traits. Frontends (`tui`, `mcp`, `serve`) never touch OS APIs: they receive a
2//! [`SnapshotProvider`] (and optionally an [`crate::actions::Actuator`]) built by `oomtop-cli`.
3
4use crate::headroom::HeadroomConfig;
5use crate::history::History;
6use crate::model::Snapshot;
7
8/// Produces enriched snapshots (sampled, attributed, adapters probed, idle/orphan/forecast applied).
9pub trait SnapshotProvider: Send {
10    /// Takes a fresh sample (the TUI/serve call this on their refresh cadence; MCP per call).
11    fn snapshot(&mut self) -> Snapshot;
12
13    /// Like [`Self::snapshot`] but samples every source now, ignoring the cadence (the TUI's second
14    /// sample 500 ms after start, so CPU % appears within a second; a refresh right after an action).
15    fn snapshot_now(&mut self) -> Snapshot {
16        self.snapshot()
17    }
18
19    /// History ring buffer of samples taken so far (may be empty for one-shot providers).
20    fn history(&self) -> &History;
21
22    /// Headroom tunables from config.
23    fn headroom_config(&self) -> HeadroomConfig {
24        HeadroomConfig::default()
25    }
26}
27
28/// A provider that always returns the same snapshot (tests, fixtures, `--replay`).
29#[derive(Debug, Clone, Default)]
30pub struct StaticProvider {
31    pub snapshot: Snapshot,
32    pub history: History,
33    pub headroom: HeadroomConfig,
34}
35
36impl StaticProvider {
37    pub fn new(snapshot: Snapshot) -> Self {
38        let mut history = History::default();
39        history.push_snapshot(&snapshot);
40        StaticProvider {
41            snapshot,
42            history,
43            headroom: HeadroomConfig::default(),
44        }
45    }
46}
47
48impl SnapshotProvider for StaticProvider {
49    fn snapshot(&mut self) -> Snapshot {
50        self.snapshot.clone()
51    }
52    fn history(&self) -> &History {
53        &self.history
54    }
55    fn headroom_config(&self) -> HeadroomConfig {
56        self.headroom.clone()
57    }
58}
59
60/// A provider replaying a sequence of snapshots, then repeating the last one.
61#[derive(Debug, Clone, Default)]
62pub struct SequenceProvider {
63    snapshots: Vec<Snapshot>,
64    next: usize,
65    history: History,
66}
67
68impl SequenceProvider {
69    pub fn new(snapshots: Vec<Snapshot>) -> Self {
70        SequenceProvider {
71            snapshots,
72            next: 0,
73            history: History::default(),
74        }
75    }
76}
77
78impl SnapshotProvider for SequenceProvider {
79    fn snapshot(&mut self) -> Snapshot {
80        let s = match self.snapshots.get(self.next) {
81            Some(s) => {
82                self.next += 1;
83                s.clone()
84            }
85            None => self.snapshots.last().cloned().unwrap_or_default(),
86        };
87        self.history.push_snapshot(&s);
88        s
89    }
90    fn history(&self) -> &History {
91        &self.history
92    }
93}