Skip to main content

sk_tree/
log.rs

1//! A bounded in-process log ring so the devtools `logs` command can read back what the host printed.
2//! Off unless [`enable`] is called, so [`record`] is one relaxed atomic load. Output is teed here,
3//! not moved: the terminal keeps showing exactly what it did. The ring is thread-local because every
4//! recorder lives on the VM/gpui main thread.
5
6use std::cell::RefCell;
7use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
8
9const CAPACITY: usize = 500;
10
11static ENABLED: AtomicBool = AtomicBool::new(false);
12static SEQ: AtomicU64 = AtomicU64::new(0);
13
14#[derive(Clone, Debug)]
15pub struct Entry {
16    pub seq: u64,
17    pub at_ms: u64,
18    /// `log`, `warn`, `error`, `advisory`, `css`, `dev` or `js`: a coarse channel, not a severity.
19    pub kind: &'static str,
20    pub text: String,
21    /// `console.log("%cA%cB", …)` style runs as the JSON the console tee built
22    /// (`[{"at":0,"css":"…"}]`, `at` an index into [`Entry::text`]), kept as text because the inspector re-parses it.
23    pub styles: Option<String>,
24}
25
26thread_local! {
27    static RING: RefCell<std::collections::VecDeque<Entry>> =
28        RefCell::new(std::collections::VecDeque::new());
29    static START: std::cell::Cell<Option<std::time::Instant>> = const { std::cell::Cell::new(None) };
30    /// `__sk_set_status` is a one-line STATUS, not a log stream: the shell overwrites it, and the
31    /// hello app's prelude rewrites it twice a second.
32    static STATUS: RefCell<Option<String>> = const { RefCell::new(None) };
33}
34
35pub fn one_line(text: &str) -> String {
36    let mut out = String::with_capacity(text.len());
37    let mut space = false;
38    for ch in text.chars() {
39        if ch.is_whitespace() {
40            space = !out.is_empty();
41            continue;
42        }
43        if space {
44            out.push(' ');
45            space = false;
46        }
47        out.push(ch);
48    }
49    out
50}
51
52pub fn set_status(text: impl Into<String>) {
53    if !is_enabled() {
54        return;
55    }
56    STATUS.with(|s| *s.borrow_mut() = Some(text.into()));
57}
58
59pub fn status() -> Option<String> {
60    STATUS.with(|s| s.borrow().clone())
61}
62
63pub fn enable() {
64    ENABLED.store(true, Ordering::Relaxed);
65    START.with(|s| {
66        if s.get().is_none() {
67            s.set(Some(std::time::Instant::now()));
68        }
69    });
70}
71
72pub fn is_enabled() -> bool {
73    ENABLED.load(Ordering::Relaxed)
74}
75
76pub fn mem_stats() -> (usize, usize) {
77    RING.with(|r| {
78        let r = r.borrow();
79        let bytes = r
80            .iter()
81            .map(|e| {
82                std::mem::size_of::<Entry>()
83                    + e.text.capacity()
84                    + e.styles.as_ref().map_or(0, String::capacity)
85            })
86            .sum();
87        (r.len(), bytes)
88    })
89}
90
91pub fn record(kind: &'static str, text: impl Into<String>) {
92    record_styled(kind, text, None)
93}
94
95pub fn record_styled(kind: &'static str, text: impl Into<String>, styles: Option<String>) {
96    if !is_enabled() {
97        return;
98    }
99    let seq = SEQ.fetch_add(1, Ordering::Relaxed);
100    let at_ms = START
101        .with(|s| s.get())
102        .map(|t| t.elapsed().as_millis() as u64)
103        .unwrap_or(0);
104    let entry = Entry {
105        seq,
106        at_ms,
107        kind,
108        text: text.into(),
109        styles,
110    };
111    RING.with(|r| {
112        let mut r = r.borrow_mut();
113        if r.len() == CAPACITY {
114            r.pop_front();
115        }
116        r.push_back(entry);
117    });
118}
119
120/// Every entry with `seq >= since`, oldest first, plus how many were dropped from the front before
121/// `since` could be served.
122pub fn since(since: u64) -> (Vec<Entry>, u64) {
123    RING.with(|r| {
124        let r = r.borrow();
125        let oldest = r
126            .front()
127            .map(|e| e.seq)
128            .unwrap_or(SEQ.load(Ordering::Relaxed));
129        let missed = oldest.saturating_sub(since).min(u64::from(u32::MAX));
130        let out: Vec<Entry> = r.iter().filter(|e| e.seq >= since).cloned().collect();
131        (out, if since == 0 { 0 } else { missed })
132    })
133}
134
135pub fn next_seq() -> u64 {
136    SEQ.load(Ordering::Relaxed)
137}