1use 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
40pub type Sink = Arc<dyn Fn(&str) + Send + Sync>;
43
44pub const BUILD_NOTICE_AFTER: Duration = Duration::from_secs(1);
46
47#[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
61pub(crate) fn with_notice_slot(config: SessionConfig) -> SessionConfig {
63 config.with_extension(Arc::new(NoticeSlot::default()))
64}
65
66pub 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#[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 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 pub fn silent() -> Self {
105 Self::default()
106 }
107
108 pub fn new(sink: Sink, level: NoticeLevel) -> Self {
111 Self {
112 sink: Some(sink),
113 level,
114 }
115 }
116
117 pub fn level(&self) -> NoticeLevel {
119 if self.sink.is_some() {
120 self.level
121 } else {
122 NoticeLevel::Off
123 }
124 }
125
126 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 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 #[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 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#[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 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
220pub 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
235pub 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
245pub 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}