Skip to main content

ursa_engine/
notices.rs

1//! Notices: one-line messages about work the engine does on its own, such as
2//! building a graph index or deciding what a database keeps on disk (#327).
3//!
4//! A notice is never part of a result. The engine hands each one to the
5//! session's sink, which the host installs ([`set_sink`]); with no sink,
6//! nothing is said. The CLI's sink writes `ursa: <notice>` to stderr, so
7//! stdout carries only results whoever reads it.
8//!
9//! Which notices are said is `ursa.notices` ([`NoticeLevel`]):
10//!
11//! - `on` (the default): a build that has run for a second announces itself
12//!   (`building the index for g (95.7M edges)…`) and says when it is done and
13//!   what became of it (`built the index for g in 30.7 s; stored in club.ursa
14//!   (768.0 MiB; about 1.5 GiB once an algorithm adds the reverse
15//!   adjacency)`); and every stored-index decision that loses work is said,
16//!   however quick: an index not stored (too large for
17//!   `ursa.index_storage_limit`, the stored indexes already over it, or no
18//!   room beside the indexes in use), an index evicted to make room, a write
19//!   that failed, and stored indexes dropped because another version of Ursa
20//!   wrote them. A quick build that is stored, or is in memory only, says
21//!   nothing. So are a `SET` of the limit below what is already stored
22//!   (#353), and a limit Ursa 0.8 or 0.9 saved in the database, which is no
23//!   longer applied.
24//! - `all`: also every build, load and store, however quick.
25//! - `off`: nothing.
26//!
27//! A notice decided on a background thread (a failed write, a chunk appended
28//! when the database closes) goes to the sink of the session that started the
29//! work, at the level it had then ([`Notifier`]).
30
31use std::fmt;
32use std::sync::{Arc, Mutex};
33use std::time::Duration;
34
35use datafusion::execution::context::SessionState;
36use datafusion::prelude::SessionConfig;
37
38pub use crate::options::NoticeLevel;
39
40/// Where a session's notices go: called with each notice, one line, without
41/// a trailing newline.
42pub type Sink = Arc<dyn Fn(&str) + Send + Sync>;
43
44/// How long a build runs before it announces itself, at `ursa.notices = on`.
45pub const BUILD_NOTICE_AFTER: Duration = Duration::from_secs(1);
46
47/// The session's sink, set by the host (a session config extension, installed
48/// by `new_session`).
49#[derive(Default)]
50pub struct NoticeSlot {
51    sink: Mutex<Option<Sink>>,
52}
53
54impl fmt::Debug for NoticeSlot {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        let set = self.sink.lock().map(|s| s.is_some()).unwrap_or(false);
57        write!(f, "NoticeSlot(sink: {set})")
58    }
59}
60
61/// Install an empty notice slot on `config` (done by `new_session`).
62pub(crate) fn with_notice_slot(config: SessionConfig) -> SessionConfig {
63    config.with_extension(Arc::new(NoticeSlot::default()))
64}
65
66/// Send the session's notices to `sink` (`None`: say nothing).
67pub fn set_sink(state: &SessionState, sink: Option<Sink>) {
68    if let Some(slot) = state.config().get_extension::<NoticeSlot>() {
69        *slot.sink.lock().unwrap_or_else(|e| e.into_inner()) = sink;
70    }
71}
72
73/// A session's sink and notice level, as they were when it was taken: what
74/// background work says its notices with.
75#[derive(Clone, Default)]
76pub struct Notifier {
77    sink: Option<Sink>,
78    level: NoticeLevel,
79}
80
81impl fmt::Debug for Notifier {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        write!(f, "Notifier({}, sink: {})", self.level, self.sink.is_some())
84    }
85}
86
87impl Notifier {
88    /// The notifier of the session `config` belongs to.
89    pub fn of(config: &SessionConfig) -> Self {
90        let sink = config
91            .get_extension::<NoticeSlot>()
92            .and_then(|slot| slot.sink.lock().unwrap_or_else(|e| e.into_inner()).clone());
93        Self {
94            level: if sink.is_some() {
95                crate::options::notice_level(config)
96            } else {
97                NoticeLevel::Off
98            },
99            sink,
100        }
101    }
102
103    /// A notifier that says nothing.
104    pub fn silent() -> Self {
105        Self::default()
106    }
107
108    /// One that says notices at `level` to `sink` (for tests and hosts
109    /// without a session).
110    pub fn new(sink: Sink, level: NoticeLevel) -> Self {
111        Self {
112            sink: Some(sink),
113            level,
114        }
115    }
116
117    /// The level notices are said at: `Off` without a sink.
118    pub fn level(&self) -> NoticeLevel {
119        if self.sink.is_some() {
120            self.level
121        } else {
122            NoticeLevel::Off
123        }
124    }
125
126    /// Say `text` if the level is at least `level`.
127    pub fn say(&self, level: NoticeLevel, text: impl FnOnce() -> String) {
128        if level == NoticeLevel::Off || self.level() < level {
129            return;
130        }
131        if let Some(sink) = &self.sink {
132            sink(&text());
133        }
134    }
135
136    /// Announce `text` once `after` has passed, unless [`Announcement::finish`]
137    /// is called first; at once if `after` is zero.
138    pub fn announce_after(&self, after: Duration, text: String) -> Announcement {
139        let state = Arc::new(AnnounceState::default());
140        let Some(sink) = self
141            .sink
142            .clone()
143            .filter(|_| self.level() >= NoticeLevel::On)
144        else {
145            return Announcement { state };
146        };
147        if after.is_zero() {
148            sink(&text);
149            state.lock().said = true;
150            return Announcement { state };
151        }
152        // Native only: the browser has one thread, and no sink.
153        #[cfg(not(target_arch = "wasm32"))]
154        {
155            let waiting = Arc::clone(&state);
156            let _ = std::thread::Builder::new()
157                .name("ursa-notice".into())
158                .spawn(move || {
159                    let guard = waiting.lock();
160                    let (mut guard, _) = waiting
161                        .done
162                        .wait_timeout_while(guard, after, |s| !s.finished)
163                        .unwrap_or_else(|e| e.into_inner());
164                    if !guard.finished {
165                        // Said under the lock, so it comes before what
166                        // `finish`'s caller says next.
167                        sink(&text);
168                        guard.said = true;
169                    }
170                });
171        }
172        #[cfg(target_arch = "wasm32")]
173        let _ = (sink, text);
174        Announcement { state }
175    }
176}
177
178/// A notice that is said if the work it announces is still running when its
179/// time comes (see [`Notifier::announce_after`]).
180#[derive(Debug)]
181pub struct Announcement {
182    state: Arc<AnnounceState>,
183}
184
185#[derive(Debug, Default)]
186struct AnnounceState {
187    flags: Mutex<Flags>,
188    done: std::sync::Condvar,
189}
190
191#[derive(Debug, Default)]
192struct Flags {
193    finished: bool,
194    said: bool,
195}
196
197impl AnnounceState {
198    fn lock(&self) -> std::sync::MutexGuard<'_, Flags> {
199        self.flags.lock().unwrap_or_else(|e| e.into_inner())
200    }
201}
202
203impl Announcement {
204    /// The work is done: the notice is not said now if it has not been.
205    /// Returns whether it was said.
206    pub fn finish(&self) -> bool {
207        let mut flags = self.state.lock();
208        flags.finished = true;
209        self.state.done.notify_all();
210        flags.said
211    }
212}
213
214impl Drop for Announcement {
215    fn drop(&mut self) {
216        self.finish();
217    }
218}
219
220/// `bytes` for people, in binary units with one decimal: `1.4 GiB`, `512 B`.
221pub fn size(bytes: u64) -> String {
222    const UNITS: [&str; 5] = ["KiB", "MiB", "GiB", "TiB", "PiB"];
223    if bytes < 1024 {
224        return format!("{bytes} B");
225    }
226    let mut value = bytes as f64 / 1024.0;
227    let mut unit = 0;
228    while value >= 1024.0 && unit + 1 < UNITS.len() {
229        value /= 1024.0;
230        unit += 1;
231    }
232    format!("{value:.1} {}", UNITS[unit])
233}
234
235/// `n` for people: `950`, `12.3K`, `95.7M`, `1.2B`.
236pub fn count(n: u64) -> String {
237    match n {
238        0..1_000 => n.to_string(),
239        1_000..1_000_000 => format!("{:.1}K", n as f64 / 1e3),
240        1_000_000..1_000_000_000 => format!("{:.1}M", n as f64 / 1e6),
241        _ => format!("{:.1}B", n as f64 / 1e9),
242    }
243}
244
245/// `duration` for people: `0.4 s`, `30.7 s`, `4 min 5 s`.
246pub fn duration(duration: Duration) -> String {
247    let seconds = duration.as_secs_f64();
248    if seconds < 120.0 {
249        format!("{seconds:.1} s")
250    } else {
251        let whole = duration.as_secs();
252        format!("{} min {} s", whole / 60, whole % 60)
253    }
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259
260    fn collecting(level: NoticeLevel) -> (Notifier, Arc<Mutex<Vec<String>>>) {
261        let said = Arc::new(Mutex::new(Vec::new()));
262        let sink = {
263            let said = Arc::clone(&said);
264            Arc::new(move |line: &str| said.lock().unwrap().push(line.to_string())) as Sink
265        };
266        (Notifier::new(sink, level), said)
267    }
268
269    #[test]
270    fn levels_filter_what_is_said() {
271        let (on, said) = collecting(NoticeLevel::On);
272        on.say(NoticeLevel::On, || "kept".into());
273        on.say(NoticeLevel::All, || "detail".into());
274        assert_eq!(*said.lock().unwrap(), ["kept"]);
275        let (all, said) = collecting(NoticeLevel::All);
276        all.say(NoticeLevel::On, || "kept".into());
277        all.say(NoticeLevel::All, || "detail".into());
278        assert_eq!(*said.lock().unwrap(), ["kept", "detail"]);
279        let (off, said) = collecting(NoticeLevel::Off);
280        off.say(NoticeLevel::On, || "kept".into());
281        assert!(said.lock().unwrap().is_empty());
282        assert_eq!(Notifier::silent().level(), NoticeLevel::Off);
283    }
284
285    #[test]
286    fn an_announcement_is_said_only_if_the_work_outlasts_its_delay() {
287        let (on, said) = collecting(NoticeLevel::On);
288        let quick = on.announce_after(Duration::from_secs(60), "quick".into());
289        assert!(!quick.finish());
290        let slow = on.announce_after(Duration::from_millis(1), "slow".into());
291        let started = std::time::Instant::now();
292        while said.lock().unwrap().is_empty() && started.elapsed() < Duration::from_secs(10) {
293            std::thread::sleep(Duration::from_millis(5));
294        }
295        assert!(slow.finish());
296        assert!(on.announce_after(Duration::ZERO, "now".into()).finish());
297        assert_eq!(*said.lock().unwrap(), ["slow", "now"]);
298        let (off, said) = collecting(NoticeLevel::Off);
299        assert!(!off.announce_after(Duration::ZERO, "no".into()).finish());
300        assert!(said.lock().unwrap().is_empty());
301    }
302
303    #[test]
304    fn sizes_counts_and_durations_read_well() {
305        assert_eq!(size(512), "512 B");
306        assert_eq!(size(1536), "1.5 KiB");
307        assert_eq!(size(1_503_238_554), "1.4 GiB");
308        assert_eq!(count(78), "78");
309        assert_eq!(count(95_700_000), "95.7M");
310        assert_eq!(count(12_345), "12.3K");
311        assert_eq!(duration(Duration::from_millis(30_700)), "30.7 s");
312        assert_eq!(duration(Duration::from_secs(245)), "4 min 5 s");
313    }
314}