1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
//! Async resources: a value loaded off the main thread from the signals it
//! reads, with loading and error states.
use std::cell::Cell;
use std::fmt;
use std::future::Future;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use crate::signal::{Effect, Signal, keep_with_owner, untrack};
/// Tells a load whether its result is still wanted. A load is cancelled when
/// a newer one starts (its inputs changed, or [`Resource::refetch`]) or the
/// resource's owner goes; long work can check and stop early.
#[derive(Clone, Default)]
pub struct Cancel(Arc<AtomicBool>);
impl Cancel {
/// Whether a newer load replaced this one (its result will be dropped).
pub fn is_cancelled(&self) -> bool {
self.0.load(Ordering::Relaxed)
}
fn cancel(&self) {
self.0.store(true, Ordering::Relaxed);
}
}
impl fmt::Debug for Cancel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Cancel").field(&self.is_cancelled()).finish()
}
}
/// A resource's state, from [`Resource::state`].
#[derive(Clone, Debug, PartialEq)]
pub enum Load<T> {
/// The first load hasn't finished.
Loading,
/// The latest finished load succeeded (a newer one may be running: see
/// [`Resource::loading`]).
Ready(T),
/// The latest finished load failed, with its error's text.
Failed(String),
}
/// A value loaded on a background thread from inputs read on the main
/// thread. When the signals `source` reads change, a new load starts and the
/// one running is cancelled: only the newest result is ever shown, so
/// search-as-you-type can't show an older query's rows. The last value stays
/// readable while a new one loads.
///
/// A `Copy` handle, owned like a [`Signal`]: when its owner goes, the
/// running load is cancelled and its result dropped.
pub struct Resource<T> {
value: Signal<Option<T>>,
error: Signal<Option<String>>,
loading: Signal<bool>,
reload: Signal<u64>,
}
impl<T> Clone for Resource<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for Resource<T> {}
/// Cancels the running load when the resource's effect goes.
struct CancelOnDrop(Rc<Cell<Option<Cancel>>>);
impl Drop for CancelOnDrop {
fn drop(&mut self) {
if let Some(c) = self.0.take() {
c.cancel();
}
}
}
impl<T: Clone + Send + 'static> Resource<T> {
/// Loads with `fetch(source())` on a background thread, again whenever
/// the signals `source` reads change. Call from the main thread.
///
/// ```no_run
/// use ferrokit::*;
///
/// let query = Signal::new(String::new());
/// let matches = Resource::new(move || query.get(), |q: String, cancel: &Cancel| {
/// let words = std::fs::read_to_string("/usr/share/dict/words").map_err(|e| e.to_string())?;
/// let mut found = Vec::new();
/// for w in words.lines().filter(|w| w.starts_with(&q)) {
/// if cancel.is_cancelled() {
/// break; // a newer query started; this result won't be shown
/// }
/// found.push(w.to_string());
/// }
/// Ok::<_, String>(found)
/// });
/// let status = text(move || match matches.state() {
/// Load::Loading => "Searching…".into(),
/// Load::Ready(words) => format!("{} words", words.len()),
/// Load::Failed(e) => format!("Couldn't search: {e}"),
/// });
/// # let _ = status;
/// ```
pub fn new<S, E>(source: impl Fn() -> S + 'static, fetch: impl Fn(S, &Cancel) -> Result<T, E> + Send + Sync + 'static) -> Self
where
S: Send + 'static,
E: fmt::Display,
{
let resource = Resource { value: Signal::new(None), error: Signal::new(None), loading: Signal::new(true), reload: Signal::new(0) };
let Resource { value, error, loading, reload } = resource;
let fetch = Arc::new(fetch);
let running: Rc<Cell<Option<Cancel>>> = Rc::default();
let guard = CancelOnDrop(running.clone());
let effect = Effect::new(move || {
let _ = &guard;
reload.get();
let input = source();
untrack(|| {
let cancel = Cancel::default();
if let Some(old) = running.replace(Some(cancel.clone())) {
old.cancel();
}
loading.set_if_changed(true);
let (fetch, theirs) = (fetch.clone(), cancel.clone());
crate::spawn_outcome(
move || fetch(input, &theirs).map_err(|e| e.to_string()),
move |outcome| {
// A fetch that panicked is a failed load.
let result = outcome.unwrap_or_else(|panic| Err(format!("the load panicked: {panic}")));
if cancel.is_cancelled() {
return; // a newer load is running (or the owner went)
}
match result {
Ok(v) => {
value.set(Some(v));
error.set_if_changed(None);
}
Err(e) => error.set(Some(e)),
}
loading.set_if_changed(false);
},
);
});
});
keep_with_owner(effect);
resource
}
}
impl<T: Clone + 'static> Resource<T> {
/// [`Resource::new`] with an async load: `fetch(source())` returns a
/// future, run on the main thread as a [`spawn_local`](crate::spawn_local)
/// task (so neither it nor its result needs to be `Send`). Await
/// [`background`](crate::background) for blocking work, and your
/// runtime for I/O (`on_runtime`, with the `tokio`
/// feature). Call from the main thread.
///
/// When the inputs change, the running load's future is dropped: it
/// stops at the `.await` it's waiting at, so there's no [`Cancel`] to
/// check. A panic in the load is reported (see
/// [`App::on_error`](crate::App::on_error)) and makes it a failed load.
///
/// ```no_run
/// use ferrokit::*;
/// use std::time::Duration;
///
/// let query = Signal::new(String::new());
/// let matches = Resource::new_async(move || query.get(), |q: String| async move {
/// sleep(Duration::from_millis(200)).await; // debounce: a newer query drops this one here
/// let words = background(|| std::fs::read_to_string("/usr/share/dict/words")).await.map_err(|e| e.to_string())?;
/// Ok::<_, String>(words.lines().filter(|w| w.starts_with(&q)).count())
/// });
/// let status = text(move || match matches.state() {
/// Load::Loading => "Searching…".into(),
/// Load::Ready(n) => format!("{n} words"),
/// Load::Failed(e) => format!("Couldn't search: {e}"),
/// });
/// # let _ = status;
/// ```
pub fn new_async<S, F, E>(source: impl Fn() -> S + 'static, fetch: impl Fn(S) -> F + 'static) -> Self
where
S: 'static,
F: Future<Output = Result<T, E>> + 'static,
E: fmt::Display,
{
let resource = Resource { value: Signal::new(None), error: Signal::new(None), loading: Signal::new(true), reload: Signal::new(0) };
let Resource { value, error, loading, reload } = resource;
let running: Rc<Cell<Option<crate::Task>>> = Rc::default();
let guard = CancelTaskOnDrop(running.clone());
let effect = Effect::new(move || {
let _ = &guard;
reload.get();
let input = source();
untrack(|| {
if let Some(old) = running.take() {
old.cancel();
}
loading.set_if_changed(true);
let load = Caught { inner: Box::pin(fetch(input)) };
let task = crate::spawn_local(async move {
// Only the newest load gets here: older ones are dropped
// at an `.await` when a newer one starts.
match load.await {
Ok(v) => {
value.set(Some(v));
error.set_if_changed(None);
}
Err(e) => error.set(Some(e)),
}
loading.set_if_changed(false);
});
// The resource, not the owner current now, decides when it stops.
task.detach();
running.set(Some(task));
});
});
keep_with_owner(effect);
resource
}
}
/// Cancels the running async load when the resource's effect goes.
struct CancelTaskOnDrop(Rc<Cell<Option<crate::Task>>>);
impl Drop for CancelTaskOnDrop {
fn drop(&mut self) {
if let Some(t) = self.0.take() {
t.cancel();
}
}
}
/// An async load whose panic is reported and becomes its error.
struct Caught<F> {
inner: std::pin::Pin<Box<F>>,
}
impl<T, E: fmt::Display, F: Future<Output = Result<T, E>>> Future for Caught<F> {
type Output = Result<T, String>;
fn poll(mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Self::Output> {
let inner = self.inner.as_mut();
crate::failure::guard("an async resource's load", None, || Some(inner.poll(cx)))
.map(|p| p.map(|r| r.map_err(|e| e.to_string())))
.unwrap_or_else(|| {
let message = crate::failure::caught().last().map(|f| f.message.clone()).unwrap_or_default();
std::task::Poll::Ready(Err(format!("the load panicked: {message}")))
})
}
}
impl<T: Clone + 'static> Resource<T> {
/// The latest loaded value (kept while a newer load runs), subscribing
/// the running effect. `None` until the first load succeeds.
pub fn get(&self) -> Option<T> {
self.value.get()
}
/// The latest value, without subscribing (for event handlers).
pub fn get_untracked(&self) -> Option<T> {
self.value.get_untracked()
}
/// Reads the latest value through `f` without copying it.
pub fn with<R>(&self, f: impl FnOnce(Option<&T>) -> R) -> R {
self.value.with(|v| f(v.as_ref()))
}
/// Whether a load is running.
pub fn loading(&self) -> bool {
self.loading.get()
}
/// The error of the latest finished load, if it failed.
pub fn error(&self) -> Option<String> {
self.error.get()
}
/// Loading, the latest value, or the latest error: whichever the most
/// recent finished load produced (`Loading` only before the first).
pub fn state(&self) -> Load<T> {
match (self.error.get(), self.value.get()) {
(Some(e), _) => Load::Failed(e),
(None, Some(v)) => Load::Ready(v),
(None, None) => Load::Loading,
}
}
/// Loads again with the same inputs (the running load is cancelled).
pub fn refetch(&self) {
self.reload.update(|n| *n += 1);
}
}