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