Skip to main content

egui_pop_api/
reads.rs

1//! The read kernel: what a page reads from the host (a status's value, a
2//! list's rows), kept in one place and read away from the UI thread.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! - **Keyed**: a read is a command and its arguments. Two pages asking
8//!   the same thing share one entry, and one request while it is in
9//!   flight.
10//! - **At once**: [`ReadKernel::read`] never waits. It answers what it
11//!   holds now with a [`ReadState`]: `Pending` (nothing yet), `Fresh`,
12//!   `Refreshing` (the last value, known to be out of date, while a new
13//!   one is read) or `Failed` (the last read failed; the value before it,
14//!   if any, is kept).
15//! - **Stale while revalidating**: a value is never dropped for being
16//!   old. Out of date, it is shown until the new one comes.
17//! - **Policies**: the host says, per command, how long a value stays
18//!   fresh ([`ReadPolicy::fresh_for`]) and which events make it out of
19//!   date ([`ReadPolicy::invalidated_by`], `name` or `prefix.*`). A
20//!   value past its freshness is read again in the background while it
21//!   is shown, and keeps the state `Fresh` meanwhile; one an event made
22//!   out of date is `Refreshing`. Without a freshness, a value stays
23//!   fresh until an event or [`ReadKernel::invalidate_all`].
24//! - **The host contract**: the host gives a [`ReadTransport`], called
25//!   on a thread of the kernel's (at once on the web, or when no thread
26//!   starts). The kernel asks the window to repaint when an answer comes,
27//!   and when a value shown will be past its freshness.
28//!
29//! The Settings app reads through it the commands its transport serves
30//! ([`crate::admin::Admin::attach_reads`]); other commands keep being run
31//! on the command bus.
32//!
33//! The cache is a map under a lock, not a cache crate: the entries are a
34//! page's reads (tens, not millions), they are never evicted (a stale
35//! value is what is shown while revalidating), and in-flight sharing
36//! must not block the caller, which the caches surveyed (`moka`,
37//! `quick_cache`) do by waiting on the first loader.
38
39use std::collections::BTreeMap;
40use std::sync::{Arc, Mutex};
41use std::time::Duration;
42
43use egui_pop_core::lock;
44use serde_json::{Value as Json, json};
45use web_time::Instant;
46
47/// What the host reads for the kernel: its node, its database, a
48/// service. Called away from the UI thread; may take its time.
49pub trait ReadTransport: Send + Sync + 'static {
50    /// Whether this transport reads `command`; the others are not the
51    /// kernel's.
52    fn serves(&self, command: &str) -> bool;
53
54    /// Reads `command` with `args` (an object, `{}` without arguments).
55    ///
56    /// # Errors
57    /// The read failed: the text is shown in place of the value, or
58    /// beside the value kept from before.
59    fn read(&self, command: &str, args: &Json) -> Result<Json, String>;
60}
61
62/// How a command's reads are kept.
63#[derive(Clone, Debug, Default, PartialEq, Eq)]
64pub struct ReadPolicy {
65    /// How long a value stays fresh; `None`: until an event says it
66    /// changed.
67    pub fresh_for: Option<Duration>,
68    /// The events that make its values out of date: `name` or
69    /// `prefix.*`.
70    pub invalidated_by: Vec<String>,
71}
72
73impl ReadPolicy {
74    pub fn new() -> Self {
75        Self::default()
76    }
77
78    /// Fresh for `d`, then read again in the background while shown.
79    #[must_use]
80    pub fn fresh_for(mut self, d: Duration) -> Self {
81        self.fresh_for = Some(d);
82        self
83    }
84
85    /// Out of date after any of these events (`name` or `prefix.*`).
86    #[must_use]
87    pub fn invalidated_by(mut self, patterns: &[&str]) -> Self {
88        self.invalidated_by
89            .extend(patterns.iter().map(|p| (*p).to_string()));
90        self
91    }
92}
93
94/// Where a read stands.
95#[derive(Clone, Copy, Debug, PartialEq, Eq)]
96pub enum ReadState {
97    /// Nothing read yet: being read.
98    Pending,
99    /// The value is fresh (or read again in the background past its
100    /// freshness, as nothing said it changed).
101    Fresh,
102    /// The value shown is out of date (an event said so) while a new one
103    /// is read.
104    Refreshing,
105    /// The last read failed; the value read before it, if any, is kept.
106    Failed,
107}
108
109/// A read's answer now.
110#[derive(Clone, Debug, PartialEq)]
111pub struct Read {
112    pub state: ReadState,
113    /// The last value read, if any.
114    pub value: Option<Json>,
115    /// The last read's error, when it failed.
116    pub error: Option<String>,
117}
118
119impl Read {
120    /// What a page shows: the value, else the error, else nothing yet.
121    pub fn answer(&self) -> Option<Result<Json, String>> {
122        match (&self.value, &self.error) {
123            (Some(v), _) => Some(Ok(v.clone())),
124            (None, Some(e)) => Some(Err(e.clone())),
125            (None, None) => None,
126        }
127    }
128}
129
130#[derive(Debug, Default)]
131struct Entry {
132    command: String,
133    value: Option<Json>,
134    error: Option<String>,
135    /// When the last answer came.
136    at: Option<Instant>,
137    /// An event made it out of date.
138    stale: bool,
139    /// The read in flight, by its number.
140    flight: Option<u64>,
141    /// An event came while a read was in flight: its answer may predate
142    /// the change, so it is out of date as it lands.
143    again: bool,
144}
145
146impl Entry {
147    fn read(&self) -> Read {
148        let state = if self.error.is_some() && self.flight.is_none() {
149            ReadState::Failed
150        } else if self.value.is_none() && self.error.is_none() {
151            ReadState::Pending
152        } else if self.stale {
153            ReadState::Refreshing
154        } else {
155            ReadState::Fresh
156        };
157        Read {
158            state,
159            value: self.value.clone(),
160            error: self.error.clone(),
161        }
162    }
163}
164
165#[derive(Default)]
166struct Inner {
167    entries: BTreeMap<String, Entry>,
168    policies: BTreeMap<String, ReadPolicy>,
169    next: u64,
170    fetches: u64,
171}
172
173/// The kernel: the host's [`ReadTransport`], the policies and the
174/// values read. Shared ([`Arc`]); every method takes `&self`.
175pub struct ReadKernel {
176    transport: Arc<dyn ReadTransport>,
177    inner: Arc<Mutex<Inner>>,
178    repaint: Arc<Mutex<Option<egui::Context>>>,
179}
180
181impl std::fmt::Debug for ReadKernel {
182    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183        let i = lock(&self.inner);
184        f.debug_struct("ReadKernel")
185            .field("entries", &i.entries.len())
186            .field("policies", &i.policies)
187            .finish_non_exhaustive()
188    }
189}
190
191/// A read's key: its command and arguments (`{}` for none).
192fn key_of(command: &str, args: &Json) -> (String, Json) {
193    let args = if args.is_null() {
194        json!({})
195    } else {
196        args.clone()
197    };
198    (format!("{command} {args}"), args)
199}
200
201/// Whether `name` matches `pattern` (`name`, or `prefix.*`).
202pub fn matches(pattern: &str, name: &str) -> bool {
203    match pattern.strip_suffix('*') {
204        Some(prefix) => name.starts_with(prefix),
205        None => name == pattern,
206    }
207}
208
209impl ReadKernel {
210    pub fn new(transport: Arc<dyn ReadTransport>) -> Self {
211        Self {
212            transport,
213            inner: Arc::default(),
214            repaint: Arc::default(),
215        }
216    }
217
218    /// Sets `command`'s policy (a later one replaces it).
219    pub fn policy(&self, command: &str, policy: ReadPolicy) {
220        lock(&self.inner).policies.insert(command.into(), policy);
221    }
222
223    /// Whether the kernel reads `command` (its transport serves it).
224    pub fn serves(&self, command: &str) -> bool {
225        self.transport.serves(command)
226    }
227
228    /// The context repainted when an answer comes.
229    pub fn set_context(&self, ctx: &egui::Context) {
230        let mut r = lock(&self.repaint);
231        if r.is_none() {
232            *r = Some(ctx.clone());
233        }
234    }
235
236    /// What `command` with `args` answers now, never waiting: a read
237    /// starts when there is nothing yet, when the value is out of date
238    /// or past its freshness, and none is in flight.
239    pub fn read(&self, command: &str, args: &Json) -> Read {
240        let (key, args) = key_of(command, args);
241        let now = Instant::now();
242        let (read, start, wake_in) = {
243            let mut i = lock(&self.inner);
244            let fresh_for = i.policies.get(command).and_then(|p| p.fresh_for);
245            let e = i.entries.entry(key.clone()).or_insert_with(|| Entry {
246                command: command.into(),
247                ..Entry::default()
248            });
249            let expired = |at: Instant| fresh_for.is_some_and(|f| now.duration_since(at) >= f);
250            let due = match e.at {
251                None => true,
252                Some(at) => e.stale || expired(at),
253            };
254            let mut start = None;
255            if due && e.flight.is_none() {
256                start = Some(());
257            }
258            let wake_in = match (e.at, fresh_for) {
259                (Some(at), Some(f)) if !due => Some(f.saturating_sub(now.duration_since(at))),
260                _ => None,
261            };
262            let start = start.map(|()| {
263                i.next += 1;
264                i.fetches += 1;
265                let n = i.next;
266                if let Some(e) = i.entries.get_mut(&key) {
267                    e.flight = Some(n);
268                }
269                n
270            });
271            let read = i.entries.get(&key).map(Entry::read).unwrap_or(Read {
272                state: ReadState::Pending,
273                value: None,
274                error: None,
275            });
276            (read, start, wake_in)
277        };
278        if let (Some(d), Some(ctx)) = (wake_in, lock(&self.repaint).as_ref()) {
279            ctx.request_repaint_after(d);
280        }
281        if let Some(n) = start {
282            self.fetch(key.clone(), command.to_string(), args, n);
283            // A read run at once (on the web) answers this frame.
284            if let Some(e) = lock(&self.inner).entries.get(&key) {
285                return e.read();
286            }
287        }
288        read
289    }
290
291    /// What `command` with `args` answers now, starting nothing.
292    pub fn peek(&self, command: &str, args: &Json) -> Read {
293        let (key, _) = key_of(command, args);
294        lock(&self.inner).entries.get(&key).map_or(
295            Read {
296                state: ReadState::Pending,
297                value: None,
298                error: None,
299            },
300            Entry::read,
301        )
302    }
303
304    /// An event happened: the values of the commands whose policy names
305    /// it are out of date. How many were.
306    pub fn event(&self, name: &str) -> usize {
307        let mut i = lock(&self.inner);
308        let hit: Vec<String> = i
309            .policies
310            .iter()
311            .filter(|(_, p)| p.invalidated_by.iter().any(|pat| matches(pat, name)))
312            .map(|(c, _)| c.clone())
313            .collect();
314        let mut n = 0;
315        for e in i.entries.values_mut() {
316            if hit.contains(&e.command) {
317                Self::stale(e);
318                n += 1;
319            }
320        }
321        drop(i);
322        if n > 0 {
323            self.wake();
324        }
325        n
326    }
327
328    /// Every value of `command` is out of date.
329    pub fn invalidate(&self, command: &str) {
330        for e in lock(&self.inner).entries.values_mut() {
331            if e.command == command {
332                Self::stale(e);
333            }
334        }
335        self.wake();
336    }
337
338    /// Every value is out of date (something changed, nobody says what).
339    pub fn invalidate_all(&self) {
340        for e in lock(&self.inner).entries.values_mut() {
341            Self::stale(e);
342        }
343        self.wake();
344    }
345
346    /// Reads in flight now.
347    pub fn in_flight(&self) -> usize {
348        lock(&self.inner)
349            .entries
350            .values()
351            .filter(|e| e.flight.is_some())
352            .count()
353    }
354
355    /// How many reads the transport was asked for since the start.
356    pub fn fetches(&self) -> u64 {
357        lock(&self.inner).fetches
358    }
359
360    fn stale(e: &mut Entry) {
361        if e.flight.is_some() {
362            e.again = true;
363        }
364        if e.at.is_some() {
365            e.stale = true;
366        }
367    }
368
369    fn wake(&self) {
370        if let Some(ctx) = lock(&self.repaint).as_ref() {
371            ctx.request_repaint();
372        }
373    }
374
375    /// Reads on a thread of its own, at once where none starts.
376    fn fetch(&self, key: String, command: String, args: Json, n: u64) {
377        let (transport, inner, repaint) = (
378            self.transport.clone(),
379            self.inner.clone(),
380            self.repaint.clone(),
381        );
382        let job = move || {
383            let answer = transport.read(&command, &args);
384            land(&inner, &key, n, answer);
385            if let Some(ctx) = lock(&repaint).as_ref() {
386                ctx.request_repaint();
387            }
388        };
389        #[cfg(not(target_arch = "wasm32"))]
390        {
391            let job = Arc::new(Mutex::new(Some(job)));
392            let j = job.clone();
393            let spawned = std::thread::Builder::new()
394                .name("egui-pop-read".into())
395                .spawn(move || {
396                    if let Some(job) = lock(&j).take() {
397                        job();
398                    }
399                });
400            if let Err(e) = spawned {
401                log::warn!(target: "egui_pop", "reads: no thread to read on: {e}");
402                if let Some(job) = lock(&job).take() {
403                    job();
404                }
405            }
406        }
407        #[cfg(target_arch = "wasm32")]
408        job();
409    }
410}
411
412/// An answer lands on its entry, if it is still the read in flight.
413fn land(inner: &Mutex<Inner>, key: &str, n: u64, answer: Result<Json, String>) {
414    let mut i = lock(inner);
415    let Some(e) = i.entries.get_mut(key) else {
416        return;
417    };
418    if e.flight != Some(n) {
419        return;
420    }
421    e.flight = None;
422    match answer {
423        Ok(v) => {
424            e.value = Some(v);
425            e.error = None;
426        }
427        Err(err) => e.error = Some(err),
428    }
429    e.at = Some(Instant::now());
430    e.stale = std::mem::take(&mut e.again);
431}
432
433#[cfg(test)]
434mod tests {
435    use super::*;
436    use std::sync::mpsc::{Receiver, Sender, channel};
437
438    /// A read asked: its command, and where its answer goes.
439    type Ask = (String, Sender<Result<Json, String>>);
440
441    /// A transport whose reads wait for the test to answer them.
442    struct Gated {
443        asked: Mutex<Sender<Ask>>,
444    }
445
446    impl ReadTransport for Gated {
447        fn serves(&self, command: &str) -> bool {
448            command.starts_with("t.")
449        }
450        fn read(&self, command: &str, _: &Json) -> Result<Json, String> {
451            let (tx, rx) = channel();
452            lock(&self.asked).send((command.into(), tx)).unwrap();
453            rx.recv_timeout(Duration::from_secs(10))
454                .unwrap_or_else(|_| Err("no answer".into()))
455        }
456    }
457
458    fn kernel() -> (ReadKernel, Receiver<Ask>) {
459        let (tx, rx) = channel();
460        let k = ReadKernel::new(Arc::new(Gated {
461            asked: Mutex::new(tx),
462        }));
463        (k, rx)
464    }
465
466    fn settle(k: &ReadKernel) {
467        let until = Instant::now() + Duration::from_secs(10);
468        while k.in_flight() > 0 {
469            assert!(Instant::now() < until, "a read never landed");
470            std::thread::sleep(Duration::from_millis(2));
471        }
472    }
473
474    fn next(rx: &Receiver<Ask>) -> Ask {
475        rx.recv_timeout(Duration::from_secs(10))
476            .expect("a read asked")
477    }
478
479    #[test]
480    fn a_read_answers_at_once_and_shares_its_flight() {
481        let (k, rx) = kernel();
482        assert_eq!(k.read("t.a", &Json::Null).state, ReadState::Pending);
483        assert_eq!(k.read("t.a", &json!({})).state, ReadState::Pending);
484        let (cmd, answer) = next(&rx);
485        assert_eq!(cmd, "t.a");
486        assert_eq!(k.fetches(), 1, "two asks, one read");
487        answer.send(Ok(json!(1))).unwrap();
488        settle(&k);
489        let r = k.read("t.a", &Json::Null);
490        assert_eq!((r.state, r.value), (ReadState::Fresh, Some(json!(1))));
491        assert_eq!(k.fetches(), 1, "a fresh value is not read again");
492    }
493
494    #[test]
495    fn an_event_keeps_the_value_while_it_is_read_again() {
496        let (k, rx) = kernel();
497        k.policy("t.v", ReadPolicy::new().invalidated_by(&["storage.*"]));
498        k.read("t.v", &Json::Null);
499        next(&rx).1.send(Ok(json!("old"))).unwrap();
500        settle(&k);
501        assert_eq!(k.event("import.done"), 0);
502        assert_eq!(k.event("storage.volume.changed"), 1);
503        let r = k.read("t.v", &Json::Null);
504        assert_eq!(r.state, ReadState::Refreshing);
505        assert_eq!(r.value, Some(json!("old")), "a refresh never blanks");
506        next(&rx).1.send(Ok(json!("new"))).unwrap();
507        settle(&k);
508        let r = k.read("t.v", &Json::Null);
509        assert_eq!((r.state, r.value), (ReadState::Fresh, Some(json!("new"))));
510    }
511
512    #[test]
513    fn an_event_during_a_read_reads_again() {
514        let (k, rx) = kernel();
515        k.policy("t.v", ReadPolicy::new().invalidated_by(&["storage.*"]));
516        k.read("t.v", &Json::Null);
517        next(&rx).1.send(Ok(json!(1))).unwrap();
518        settle(&k);
519        k.invalidate_all();
520        k.read("t.v", &Json::Null);
521        let (_, first) = next(&rx);
522        k.event("storage.x");
523        first.send(Ok(json!(2))).unwrap();
524        settle(&k);
525        let r = k.read("t.v", &Json::Null);
526        assert_eq!(r.value, Some(json!(2)));
527        assert_eq!(
528            r.state,
529            ReadState::Refreshing,
530            "its answer may predate the event"
531        );
532        next(&rx).1.send(Ok(json!(3))).unwrap();
533        settle(&k);
534        assert_eq!(k.read("t.v", &Json::Null).value, Some(json!(3)));
535    }
536
537    #[test]
538    fn a_failure_keeps_the_last_value_and_a_freshness_reads_again() {
539        let (k, rx) = kernel();
540        k.policy("t.f", ReadPolicy::new().fresh_for(Duration::ZERO));
541        k.read("t.f", &Json::Null);
542        next(&rx).1.send(Ok(json!(1))).unwrap();
543        settle(&k);
544        // Past its freshness: read again, shown meanwhile, still fresh.
545        let r = k.read("t.f", &Json::Null);
546        assert_eq!((r.state, r.value), (ReadState::Fresh, Some(json!(1))));
547        next(&rx).1.send(Err("node gone".into())).unwrap();
548        settle(&k);
549        let r = k.peek("t.f", &Json::Null);
550        assert_eq!(r.state, ReadState::Failed);
551        assert_eq!(r.value, Some(json!(1)));
552        assert_eq!(r.answer(), Some(Ok(json!(1))));
553    }
554}