1use 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
47pub trait ReadTransport: Send + Sync + 'static {
50 fn serves(&self, command: &str) -> bool;
53
54 fn read(&self, command: &str, args: &Json) -> Result<Json, String>;
60}
61
62#[derive(Clone, Debug, Default, PartialEq, Eq)]
64pub struct ReadPolicy {
65 pub fresh_for: Option<Duration>,
68 pub invalidated_by: Vec<String>,
71}
72
73impl ReadPolicy {
74 pub fn new() -> Self {
75 Self::default()
76 }
77
78 #[must_use]
80 pub fn fresh_for(mut self, d: Duration) -> Self {
81 self.fresh_for = Some(d);
82 self
83 }
84
85 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
96pub enum ReadState {
97 Pending,
99 Fresh,
102 Refreshing,
105 Failed,
107}
108
109#[derive(Clone, Debug, PartialEq)]
111pub struct Read {
112 pub state: ReadState,
113 pub value: Option<Json>,
115 pub error: Option<String>,
117}
118
119impl Read {
120 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 at: Option<Instant>,
137 stale: bool,
139 flight: Option<u64>,
141 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
173pub 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
191fn 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
201pub 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 pub fn policy(&self, command: &str, policy: ReadPolicy) {
220 lock(&self.inner).policies.insert(command.into(), policy);
221 }
222
223 pub fn serves(&self, command: &str) -> bool {
225 self.transport.serves(command)
226 }
227
228 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 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 if let Some(e) = lock(&self.inner).entries.get(&key) {
285 return e.read();
286 }
287 }
288 read
289 }
290
291 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 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 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 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 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 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 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
412fn 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 type Ask = (String, Sender<Result<Json, String>>);
440
441 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 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}