1use core::any::{Any, TypeId};
4use core::cell::{Cell, Ref, RefCell};
5use core::fmt;
6use core::future::Future;
7use core::time::Duration;
8use std::rc::Rc;
9use std::sync::{Arc, Mutex};
10
11use egui::{AsId, Id};
12use web_time::Instant;
13
14use super::runtime::{self, Abort, BoxFuture, MaybeSend};
15use super::{CACHE_FOR, Entry, context, lock, with_registry};
16use crate::load::Invalidation;
17
18type Slot<T, E> = Arc<Mutex<Option<Result<T, E>>>>;
20
21struct Run<T, E> {
23 slot: Slot<T, E>,
24 _task: Abort,
25}
26
27struct State<T, E> {
29 value: Option<Rc<T>>,
30 error: Option<Rc<E>>,
32 version: u64,
33 fetched_at: Option<Instant>,
34 run: Option<Run<T, E>>,
35 stale: bool,
37 depends: Vec<String>,
38 read_at: Instant,
39 cache_for: Duration,
40}
41
42impl<T: 'static, E: 'static> Entry for RefCell<State<T, E>> {
43 fn invalidate(&self, invalidation: &Invalidation) {
44 let mut state = self.borrow_mut();
45 if invalidation.hits(&state.depends) {
46 state.stale = true;
47 state.run = None;
48 }
49 }
50
51 fn expired(&self, now: Instant) -> bool {
52 let state = self.borrow();
53 now.saturating_duration_since(state.read_at) >= state.cache_for
54 }
55
56 fn as_any(self: Rc<Self>) -> Rc<dyn Any> {
57 self
58 }
59}
60
61#[derive(Debug)]
63pub enum QueryState<T, E> {
64 Loading,
66 Ready(Rc<T>),
68 Failed(Rc<E>),
70}
71
72pub struct Query<T, E> {
94 state: Rc<RefCell<State<T, E>>>,
95 fetch: Rc<dyn Fn() -> BoxFuture<Result<T, E>>>,
96 refetch_every: Option<Duration>,
97 stale_after: Duration,
98 cache_for: Option<Duration>,
99 read: Cell<bool>,
101}
102
103pub fn query<T, E, F, Fut>(fetch: F) -> Query<T, E>
105where
106 T: MaybeSend + 'static,
107 E: MaybeSend + 'static,
108 F: Fn() -> Fut + 'static,
109 Fut: Future<Output = Result<T, E>> + MaybeSend + 'static,
110{
111 Query::new(fetch)
112}
113
114impl<T: MaybeSend + 'static, E: MaybeSend + 'static> Query<T, E> {
115 pub fn new<F, Fut>(fetch: F) -> Self
117 where
118 F: Fn() -> Fut + 'static,
119 Fut: Future<Output = Result<T, E>> + MaybeSend + 'static,
120 {
121 let state = Rc::new(RefCell::new(State {
122 value: None,
123 error: None,
124 version: 0,
125 fetched_at: None,
126 run: None,
127 stale: false,
128 depends: Vec::new(),
129 read_at: Instant::now(),
130 cache_for: CACHE_FOR,
131 }));
132 let entry: Rc<dyn Entry> = Rc::clone(&state) as _;
133 with_registry(|registry| registry.entries.push(Rc::downgrade(&entry)));
134 Self {
135 state,
136 fetch: Rc::new(move || Box::pin(fetch())),
137 refetch_every: None,
138 stale_after: Duration::ZERO,
139 cache_for: None,
140 read: Cell::new(false),
141 }
142 }
143
144 #[must_use]
151 pub fn key(mut self, key: impl AsId) -> Self {
152 let id = (TypeId::of::<(T, E)>(), Id::new(key));
153 let shared = with_registry(|registry| {
154 if let Some(entry) = registry.cache.get(&id) {
155 return Rc::clone(entry).as_any().downcast().ok();
156 }
157 registry
158 .cache
159 .insert(id, Rc::clone(&self.state) as Rc<dyn Entry>);
160 None
161 });
162 if let Some(shared) = shared {
163 let depends = core::mem::take(&mut self.state.borrow_mut().depends);
164 self.state = shared;
165 for key in depends {
166 self = self.depends(key);
167 }
168 }
169 self.apply_cache_for();
170 self
171 }
172
173 #[must_use]
181 pub fn depends(self, key: impl Into<String>) -> Self {
182 let key = key.into();
183 let mut state = self.state.borrow_mut();
184 if !state.depends.contains(&key) {
185 state.depends.push(key);
186 }
187 drop(state);
188 self
189 }
190
191 #[must_use]
194 pub fn refetch_every(mut self, every: Duration) -> Self {
195 self.refetch_every = Some(every);
196 self
197 }
198
199 #[must_use]
203 pub fn stale_after(mut self, duration: Duration) -> Self {
204 self.stale_after = duration;
205 self
206 }
207
208 #[must_use]
210 pub fn cache_for(mut self, duration: Duration) -> Self {
211 self.cache_for = Some(duration);
212 self.apply_cache_for();
213 self
214 }
215
216 fn apply_cache_for(&self) {
217 if let Some(duration) = self.cache_for {
218 self.state.borrow_mut().cache_for = duration;
219 }
220 }
221
222 pub fn state(&self) -> QueryState<T, E> {
224 let state = self.read();
225 if let Some(error) = &state.error {
226 QueryState::Failed(Rc::clone(error))
227 } else if let Some(value) = &state.value {
228 QueryState::Ready(Rc::clone(value))
229 } else {
230 QueryState::Loading
231 }
232 }
233
234 pub fn data(&self) -> Option<Rc<T>> {
236 self.read().value.clone()
237 }
238
239 pub fn error(&self) -> Option<Rc<E>> {
241 self.read().error.clone()
242 }
243
244 pub fn is_loading(&self) -> bool {
246 let state = self.read();
247 state.value.is_none() && state.run.is_some()
248 }
249
250 pub fn is_fetching(&self) -> bool {
252 self.read().run.is_some()
253 }
254
255 pub fn version(&self) -> u64 {
258 self.read().version
259 }
260
261 pub fn refresh(&self) {
263 let mut state = self.state.borrow_mut();
264 state.stale = true;
265 state.run = None;
266 drop(state);
267 if let Some(ctx) = context() {
268 ctx.request_repaint();
269 }
270 }
271
272 pub fn set_data(&self, value: T) {
275 let mut state = self.state.borrow_mut();
276 state.value = Some(Rc::new(value));
277 state.error = None;
278 state.version += 1;
279 }
280
281 fn read(&self) -> Ref<'_, State<T, E>> {
283 let now = Instant::now();
284 let mut state = self.state.borrow_mut();
285 state.read_at = now;
286 if let Some(result) = state.run.as_ref().and_then(|run| lock(&run.slot).take()) {
287 state.run = None;
288 state.fetched_at = Some(now);
289 match result {
290 Ok(value) => {
291 state.value = Some(Rc::new(value));
292 state.error = None;
293 state.version += 1;
294 }
295 Err(error) => state.error = Some(Rc::new(error)),
296 }
297 }
298 if state.run.is_none() && self.due(&state, now) {
299 state.stale = false;
300 state.run = Some(self.start());
301 }
302 drop(state);
303 self.read.set(true);
304 self.state.borrow()
305 }
306
307 fn due(&self, state: &State<T, E>, now: Instant) -> bool {
308 let Some(fetched_at) = state.fetched_at else {
309 return true;
310 };
311 let age = now.saturating_duration_since(fetched_at);
312 if state.stale || (!self.read.get() && age >= self.stale_after) {
313 return true;
314 }
315 match self.refetch_every {
316 Some(every) if age >= every => true,
317 Some(every) => {
318 if let Some(ctx) = context() {
319 ctx.request_repaint_after(every.saturating_sub(age));
320 }
321 false
322 }
323 None => false,
324 }
325 }
326
327 fn start(&self) -> Run<T, E> {
328 let slot: Slot<T, E> = Arc::default();
329 let future = (self.fetch)();
330 let ctx = context();
331 let task = runtime::spawn({
332 let slot = Arc::clone(&slot);
333 async move {
334 let result = future.await;
335 *lock(&slot) = Some(result);
336 if let Some(ctx) = ctx {
337 ctx.request_repaint();
338 }
339 }
340 });
341 Run { slot, _task: task }
342 }
343}
344
345impl<T, E> Clone for Query<T, E> {
346 fn clone(&self) -> Self {
347 Self {
348 state: Rc::clone(&self.state),
349 fetch: Rc::clone(&self.fetch),
350 refetch_every: self.refetch_every,
351 stale_after: self.stale_after,
352 cache_for: self.cache_for,
353 read: self.read.clone(),
354 }
355 }
356}
357
358impl<T: fmt::Debug, E: fmt::Debug> fmt::Debug for Query<T, E> {
359 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
360 let state = self.state.borrow();
361 f.debug_struct("Query")
362 .field("value", &state.value)
363 .field("error", &state.error)
364 .field("version", &state.version)
365 .field("fetching", &state.run.is_some())
366 .finish_non_exhaustive()
367 }
368}