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
use std::fmt::Debug;
use std::rc::Rc;

use crate::{
    computed::{context::Context, Value},
    get_driver,
    struct_mut::ValueMut,
    transaction, Computed, DomNode, Instant, Resource, ToComputed,
};

use super::request_builder::{RequestBody, RequestBuilder};

type MapResponse<T> = Option<Result<T, String>>;

fn get_unique_id() -> u64 {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(1);
    COUNTER.fetch_add(1, Ordering::Relaxed)
}

enum ApiResponse<T> {
    Uninitialized,
    Data {
        value: Resource<Rc<T>>,
        expiry: Option<Instant>,
    },
}

impl<T> ApiResponse<T> {
    pub fn new(value: Resource<Rc<T>>, expiry: Option<Instant>) -> Self {
        Self::Data { value, expiry }
    }

    pub fn new_loading() -> Self {
        ApiResponse::Data {
            value: Resource::Loading,
            expiry: None,
        }
    }

    pub fn get_value(&self) -> Resource<Rc<T>> {
        match self {
            Self::Uninitialized => Resource::Loading,
            Self::Data { value, expiry: _ } => value.clone(),
        }
    }

    pub fn needs_update(&self) -> bool {
        match self {
            ApiResponse::Uninitialized => true,
            ApiResponse::Data { value: _, expiry } => {
                let Some(expiry) = expiry else {
                    return false;
                };

                expiry.is_expire()
            }
        }
    }
}

impl<T> Clone for ApiResponse<T> {
    fn clone(&self) -> Self {
        match self {
            ApiResponse::Uninitialized => ApiResponse::Uninitialized,
            ApiResponse::Data { value, expiry } => ApiResponse::Data {
                value: value.clone(),
                expiry: expiry.clone(),
            },
        }
    }
}

/// A structure similar to [Value] but supports Loading/Error states and automatic refresh
/// after defined amount of time.
///
/// ```rust
/// use vertigo::{Computed, LazyCache, RequestBuilder, AutoJsJson, Resource};
///
/// #[derive(AutoJsJson, PartialEq, Clone)]
/// pub struct Model {
///     id: i32,
///     name: String,
/// }
///
/// pub struct TodoState {
///     posts: LazyCache<Vec<Model>>,
/// }
///
/// impl TodoState {
///     pub fn new() -> Self {
///         let posts = RequestBuilder::get("https://some.api/posts")
///             .ttl_seconds(300)
///             .lazy_cache(|status, body| {
///                 if status == 200 {
///                     Some(body.into::<Vec<Model>>())
///                 } else {
///                     None
///                 }
///             });
///
///         TodoState {
///             posts
///         }
///     }
/// }
/// ```
///
/// See ["todo" example](../src/vertigo_demo/app/todo/state.rs.html) in vertigo-demo package for more.
pub struct LazyCache<T: 'static> {
    id: u64,
    value: Value<ApiResponse<T>>,
    queued: Rc<ValueMut<bool>>,
    request: Rc<RequestBuilder>,
    map_response: Rc<dyn Fn(u32, RequestBody) -> MapResponse<T>>,
}

impl<T: 'static> Debug for LazyCache<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LazyCache")
            .field("queued", &self.queued)
            .finish()
    }
}

impl<T> Clone for LazyCache<T> {
    fn clone(&self) -> Self {
        LazyCache {
            id: self.id,
            value: self.value.clone(),
            queued: self.queued.clone(),
            request: self.request.clone(),
            map_response: self.map_response.clone(),
        }
    }
}

impl<T> LazyCache<T> {
    pub fn new(
        request: RequestBuilder,
        map_response: impl Fn(u32, RequestBody) -> MapResponse<T> + 'static,
    ) -> Self {
        Self {
            id: get_unique_id(),
            value: Value::new(ApiResponse::Uninitialized),
            queued: Rc::new(ValueMut::new(false)),
            request: Rc::new(request),
            map_response: Rc::new(map_response),
        }
    }

    /// Get value (update if needed)
    pub fn get(&self, context: &Context) -> Resource<Rc<T>> {
        let api_response = self.value.get(context);

        if !self.queued.get() && api_response.needs_update() {
            self.update(false, false);
        }

        api_response.get_value()
    }

    /// Delete value so it will refresh on next access
    pub fn forget(&self) {
        self.value.set(ApiResponse::Uninitialized);
    }

    /// Force refresh the value now
    pub fn force_update(&self, with_loading: bool) {
        self.update(with_loading, true)
    }

    /// Update the value if expired
    pub fn update(&self, with_loading: bool, force: bool) {
        if self.queued.get() {
            return;
        }

        self.queued.set(true); //set lock
        get_driver().inner.api.on_fetch_start.trigger(());

        let self_clone = self.clone();

        get_driver().spawn(async move {
            if !self_clone.queued.get() {
                log::error!("force_update_spawn: queued.get() in spawn -> expected false");
                return;
            }

            let api_response = transaction(|context| self_clone.value.get(context));

            if force || api_response.needs_update() {
                if with_loading {
                    self_clone.value.set(ApiResponse::new_loading());
                }

                let new_value = self_clone
                    .request
                    .call()
                    .await
                    .into(self_clone.map_response.as_ref());

                let new_value = match new_value {
                    Ok(value) => Resource::Ready(Rc::new(value)),
                    Err(message) => Resource::Error(message),
                };

                let expiry = self_clone
                    .request
                    .get_ttl()
                    .map(|ttl| get_driver().now().add_duration(ttl));

                self_clone.value.set(ApiResponse::new(new_value, expiry));
            }

            self_clone.queued.set(false);
            get_driver().inner.api.on_fetch_stop.trigger(());
        });
    }

    pub fn to_computed(&self) -> Computed<Resource<Rc<T>>> {
        Computed::from({
            let state = self.clone();
            move |context| state.get(context)
        })
    }
}

impl<T: Clone> ToComputed<Resource<Rc<T>>> for LazyCache<T> {
    fn to_computed(&self) -> Computed<Resource<Rc<T>>> {
        self.to_computed()
    }
}

impl<T> PartialEq for LazyCache<T> {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl<T: PartialEq + Clone> LazyCache<T> {
    pub fn render(&self, render: impl Fn(Rc<T>) -> DomNode + 'static) -> DomNode {
        self.to_computed().render_value(move |value| match value {
            Resource::Ready(value) => render(value),
            Resource::Loading => {
                use crate as vertigo;

                vertigo::dom! {
                    <vertigo-suspense />
                }
            }
            Resource::Error(error) => {
                use crate as vertigo;

                vertigo::dom! {
                    <div>
                        "error = "
                        {error}
                    </div>
                }
            }
        })
    }
}