krab_core 0.6.0

Shared runtime for the Krab framework: config, HTTP, database, telemetry, resilience, signals, and protocol governance
Documentation
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Client-driven async reads with observable state.
//!
//! [`Action`](crate::action::Action) covers the write side of async; `Resource`
//! covers the read side: "this component needs data that comes from a future."
//! [`create_resource`] tracks a source, runs a fetcher when it changes, and
//! exposes the result as signals.
//!
//! ```ignore
//! let user = create_resource(
//!     move || user_id.get(),
//!     |id| async move { fetch_user(id).await },
//! );
//!
//! view! {
//!     <Show when={move || user.state().get().is_ready()}>
//!         <p>{ move || user.value().get().map(|u| u.name).unwrap_or_default() }</p>
//!     </Show>
//! }
//! ```
//!
//! # Server-side rendering
//!
//! Per [ADR 0009](https://github.com/ManirajKatuwal/krab-pub/blob/main/docs/adr/0009-resource-ssr-semantics.md),
//! a resource never polls its future on the server. Construction and every read
//! are pure signal operations: with an initial value it renders `Ready`,
//! without one it renders `Pending`, and the fetch happens in the browser after
//! hydration. Data needed for first paint belongs in the async route handler,
//! passed down as island props and into [`create_resource_with_initial`] — the
//! client then hydrates `Ready` and does **not** refetch on mount.
//!
//! # Suspense and streaming
//!
//! A resource created while building the children of a `<Suspense>` boundary
//! registers with it (see [`crate::suspense`]): the boundary shows its fallback
//! until the resource has produced a first value. Under
//! [`render_to_stream`](crate::render_stream) a resource can also declare a
//! **server loader** with [`Resource::with_server_loader`]; the streaming
//! renderer runs it after flushing the page shell and streams the boundary's
//! resolved content when it completes (ADR 0017). Outside a streaming render
//! the loader is never called, so the non-blocking contract above holds
//! unchanged.

use crate::action::{flatten_display_errors, run_guarded, GuardedFuture};
use crate::signal::{create_effect, create_signal, untrack, ReadSignal, WriteSignal};
use std::cell::Cell;
use std::future::Future;
use std::rc::Rc;

/// Where a [`Resource`] is in its load cycle.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResourceState {
    /// No completed fetch yet, or one is in flight.
    Pending,
    /// The most recent fetch succeeded; the value is in [`Resource::value`].
    Ready,
    /// The most recent fetch failed. The last good value, if any, is still in
    /// [`Resource::value`].
    Error(String),
}

impl ResourceState {
    /// The most recent fetch completed successfully.
    pub fn is_ready(&self) -> bool {
        matches!(self, ResourceState::Ready)
    }

    /// No fetch has completed yet, or a refetch is in flight.
    pub fn is_pending(&self) -> bool {
        matches!(self, ResourceState::Pending)
    }

    /// The most recent fetch failed.
    pub fn is_error(&self) -> bool {
        matches!(self, ResourceState::Error(_))
    }
}

/// An async read with `state` and `value` exposed as signals.
///
/// Created by [`create_resource`] or [`create_resource_with_initial`]. Cloning
/// is cheap and shares one fetcher and one set of signals.
///
/// The state carries no payload; the value lives in its own signal so that a
/// failed *refetch* moves `state` to `Error` while `value` keeps the last good
/// data — blanking rendered data because a refresh failed is worse than showing
/// it beside the error.
pub struct Resource<S, T: 'static> {
    state: ReadSignal<ResourceState>,
    set_state: WriteSignal<ResourceState>,
    value: ReadSignal<Option<T>>,
    set_value: WriteSignal<Option<T>>,
    source: Rc<dyn Fn() -> S>,
    fetcher: Rc<dyn Fn(S) -> GuardedFuture<T>>,
    /// Bumped on every fetch so a slow earlier request cannot overwrite a
    /// faster later one — the same discard-superseded-responses rule as
    /// [`Action`](crate::action::Action).
    generation: Rc<Cell<u64>>,
    /// The registration with the enclosing `<Suspense>` boundary, if the
    /// resource was created inside one. Kept so a server loader can tell the
    /// boundary it can be resolved by a streaming render.
    suspense: Option<crate::suspense::SourceHandle>,
}

impl<S, T: 'static> Clone for Resource<S, T> {
    fn clone(&self) -> Self {
        Self {
            state: self.state.clone(),
            set_state: self.set_state.clone(),
            value: self.value.clone(),
            set_value: self.set_value.clone(),
            source: self.source.clone(),
            fetcher: self.fetcher.clone(),
            generation: self.generation.clone(),
            suspense: self.suspense.clone(),
        }
    }
}

impl<S, T> Resource<S, T>
where
    S: 'static,
    T: Clone + 'static,
{
    /// Where the resource is in its load cycle.
    pub fn state(&self) -> ReadSignal<ResourceState> {
        self.state.clone()
    }

    /// The most recent successfully fetched value, if any.
    ///
    /// Survives a failed refetch: `state` reports the [`ResourceState::Error`]
    /// while this keeps the last good data.
    pub fn value(&self) -> ReadSignal<Option<T>> {
        self.value.clone()
    }

    /// Run the fetcher again with the current source value.
    ///
    /// Reads the source through [`untrack`], so calling this inside an effect
    /// does not subscribe that effect to the source. Inert on the server, like
    /// [`Action::dispatch`](crate::action::Action::dispatch): it returns before
    /// touching any signal.
    pub fn refetch(&self) {
        let input = untrack(|| (self.source)());
        self.fetch(input);
    }

    /// Start a fetch. Superseded responses are discarded, never applied.
    ///
    /// The executor check, generation bump, and stale-discard live in
    /// [`run_guarded`], shared with [`Action::dispatch`](crate::action::Action::dispatch):
    /// with no executor nothing polls the future, so this returns before
    /// touching any signal and SSR renders the same idle shape regardless of
    /// call count.
    fn fetch(&self, input: S) {
        let set_state = self.set_state.clone();
        let set_value = self.set_value.clone();

        run_guarded(
            &self.generation,
            // Pending during a refetch as well: consumers rendering a spinner
            // off `state` see the reload, while `value` keeps the data on
            // screen.
            || self.set_state.set(ResourceState::Pending),
            || (self.fetcher)(input),
            move |outcome| match outcome {
                Ok(value) => {
                    set_value.set(Some(value));
                    set_state.set(ResourceState::Ready);
                }
                Err(message) => set_state.set(ResourceState::Error(message)),
            },
        );
    }
}

impl<S, T> Resource<S, T>
where
    S: 'static,
    T: Clone + Send + 'static,
{
    /// Declare how the server loads this resource during a **streaming**
    /// render ([`render_to_stream`](crate::render_stream), ADR 0017).
    ///
    /// Inside a streaming render, `loader` is called once, on the render
    /// thread, and the future it returns is run on the Tokio runtime after the
    /// page shell has been flushed; its result is applied to this resource on
    /// the render thread, and the enclosing `<Suspense>` boundary's resolved
    /// content is streamed. The future must be `Send` and its value `Send`,
    /// because it runs off the render thread.
    ///
    /// Everywhere else — a non-streaming render, the browser, a resource that
    /// already holds an initial value — `loader` is **never called**. That is
    /// what keeps ADR 0009's guarantee: an ordinary server render never waits
    /// on data. On `wasm32` this is always a no-op; the browser keeps using
    /// the fetcher.
    ///
    /// Returns `self`, so it chains onto the constructor:
    ///
    /// ```ignore
    /// let user = create_resource(move || id, |id| async move { fetch_user(id).await })
    ///     .with_server_loader(move || async move { db_load_user(id).await });
    /// ```
    pub fn with_server_loader<L, Fut, E>(self, loader: L) -> Self
    where
        L: FnOnce() -> Fut,
        Fut: Future<Output = Result<T, E>> + Send + 'static,
        E: std::fmt::Display + 'static,
    {
        #[cfg(not(target_arch = "wasm32"))]
        {
            // `untrack`: the check must not subscribe whatever effect is
            // building this resource.
            let already_loaded = untrack(|| self.value.with(Option::is_some));
            if !already_loaded && crate::render_stream::stream_active() {
                let future = loader();
                let set_state = self.set_state.clone();
                let set_value = self.set_value.clone();
                let registered = crate::render_stream::register_server_loader(
                    async move { future.await.map_err(|error| error.to_string()) },
                    move |outcome: Result<T, String>| match outcome {
                        Ok(value) => {
                            set_value.set(Some(value));
                            set_state.set(ResourceState::Ready);
                        }
                        Err(message) => set_state.set(ResourceState::Error(message)),
                    },
                );
                if registered {
                    if let Some(handle) = &self.suspense {
                        handle.mark_streamable();
                    }
                }
            }
        }
        #[cfg(target_arch = "wasm32")]
        let _ = loader;
        self
    }
}

/// Create a [`Resource`] that fetches on creation and refetches when `source`
/// changes.
///
/// `source` is read inside an effect, so any signal it touches becomes a
/// dependency: when one changes, the fetcher runs again with the new source
/// value. On the server nothing fetches and the resource renders `Pending` —
/// see the module docs.
pub fn create_resource<S, T, Src, F, Fut, E>(source: Src, fetcher: F) -> Resource<S, T>
where
    S: 'static,
    T: Clone + 'static,
    Src: Fn() -> S + 'static,
    F: Fn(S) -> Fut + 'static,
    Fut: Future<Output = Result<T, E>> + 'static,
    E: std::fmt::Display + 'static,
{
    build(None, source, fetcher)
}

/// Create a [`Resource`] that starts `Ready` with a server-provided value and
/// does **not** fetch on creation.
///
/// `initial` typically arrives through island props, fetched by the async route
/// handler: the server renders `Ready`, the client hydrates `Ready` with the
/// same value, and no request is doubled on mount. Refetching-on-hydrate was
/// considered and rejected in ADR 0009 — staleness is handled by an explicit
/// [`Resource::refetch`] or a source change, not by replaying every load.
///
/// `None` behaves exactly like [`create_resource`], so a handler that may or
/// may not have the data can pass its `Option` straight through.
pub fn create_resource_with_initial<S, T, Src, F, Fut, E>(
    initial: Option<T>,
    source: Src,
    fetcher: F,
) -> Resource<S, T>
where
    S: 'static,
    T: Clone + 'static,
    Src: Fn() -> S + 'static,
    F: Fn(S) -> Fut + 'static,
    Fut: Future<Output = Result<T, E>> + 'static,
    E: std::fmt::Display + 'static,
{
    build(initial, source, fetcher)
}

fn build<S, T, Src, F, Fut, E>(initial: Option<T>, source: Src, fetcher: F) -> Resource<S, T>
where
    S: 'static,
    T: Clone + 'static,
    Src: Fn() -> S + 'static,
    F: Fn(S) -> Fut + 'static,
    Fut: Future<Output = Result<T, E>> + 'static,
    E: std::fmt::Display + 'static,
{
    let has_initial = initial.is_some();
    let (state, set_state) = create_signal(if has_initial {
        ResourceState::Ready
    } else {
        ResourceState::Pending
    });
    let (value, set_value) = create_signal(initial);

    // Registered with the nearest `<Suspense>`, if any. "Pending" for a
    // boundary means *no value yet*: a refetch over existing data, or a
    // failure, must not swap loaded content back out for the fallback.
    let suspense = crate::suspense::use_suspense().map(|boundary| {
        let state = state.clone();
        let value = value.clone();
        boundary.register(move || state.get().is_pending() && value.with(Option::is_none))
    });

    let resource = Resource {
        state,
        set_state,
        value,
        set_value,
        source: Rc::new(source),
        fetcher: flatten_display_errors(fetcher),
        generation: Rc::new(Cell::new(0)),
        suspense,
    };

    // The tracked read lives here: the effect subscribes to whatever `source`
    // touches, so a source change refetches. The first run is special-cased —
    // with an initial value the data is already on screen, and fetching anyway
    // would double every load the server just did.
    let tracked = resource.clone();
    let first_run = Cell::new(true);
    create_effect(move || {
        let input = (tracked.source)();
        if first_run.replace(false) && has_initial {
            return;
        }
        tracked.fetch(input);
    });

    resource
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The SSR contract from ADR 0009: construction never polls the future,
    /// and no signal is touched by a fetch that has nowhere to run — the same
    /// inertness `action::tests` pins for `dispatch`.
    #[test]
    fn a_resource_without_initial_renders_pending_on_the_server() {
        let (id, _set_id) = create_signal(1u32);
        let resource =
            create_resource(move || id.get(), |n: u32| async move { Ok::<_, String>(n) });

        assert!(resource.state().get().is_pending());
        assert_eq!(resource.value().get(), None);
    }

    #[test]
    fn a_resource_with_initial_renders_ready_on_the_server() {
        let (id, _set_id) = create_signal(1u32);
        let resource = create_resource_with_initial(
            Some(42u32),
            move || id.get(),
            |n: u32| async move { Ok::<_, String>(n) },
        );

        assert!(resource.state().get().is_ready());
        assert_eq!(resource.value().get(), Some(42));
    }

    /// A source change re-runs the tracking effect natively (effects are live
    /// under `cfg(test)`), but the fetch inside it must still be inert: state
    /// stays exactly as constructed, no matter how often the source moves.
    #[test]
    fn source_changes_and_refetch_are_inert_on_the_server() {
        let (id, set_id) = create_signal(1u32);
        let resource = create_resource_with_initial(
            Some(10u32),
            move || id.get(),
            |n: u32| async move { Ok::<_, String>(n) },
        );

        set_id.set(2);
        set_id.set(3);
        resource.refetch();

        assert!(
            resource.state().get().is_ready(),
            "no executor means no fetch: state must not move to Pending"
        );
        assert_eq!(resource.value().get(), Some(10));
    }

    #[test]
    fn clones_share_the_same_signals() {
        let (id, _set_id) = create_signal(1u32);
        let resource = create_resource_with_initial(
            Some(5u32),
            move || id.get(),
            |n: u32| async move { Ok::<_, String>(n) },
        );
        let observer = resource.clone();

        assert!(observer.state().get().is_ready());
        assert_eq!(observer.value().get(), Some(5));
    }

    #[test]
    fn a_none_initial_behaves_like_no_initial() {
        let (id, _set_id) = create_signal(1u32);
        let resource = create_resource_with_initial(
            None::<u32>,
            move || id.get(),
            |n: u32| async move { Ok::<_, String>(n) },
        );

        assert!(resource.state().get().is_pending());
        assert_eq!(resource.value().get(), None);
    }
}