use alloc::boxed::Box;
use alloc::rc::Rc;
use core::cell::Cell;
use core::fmt;
use core::future::{Future, poll_fn};
use core::mem::DropGuard;
use core::pin::Pin;
use core::task::Poll;
use zwire_core::{Atom, Scope, Signal};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResourceState<T, E> {
Pending,
Refreshing(T),
Ready(T),
Error {
error: E,
previous: Option<T>,
},
Disposed,
}
impl<T, E> ResourceState<T, E> {
#[inline]
pub const fn is_pending(&self) -> bool {
matches!(self, Self::Pending | Self::Refreshing(_))
}
#[inline]
pub const fn is_ready(&self) -> bool {
matches!(self, Self::Ready(_))
}
#[inline]
pub const fn is_error(&self) -> bool {
matches!(self, Self::Error { .. })
}
#[inline]
pub const fn is_disposed(&self) -> bool {
matches!(self, Self::Disposed)
}
#[inline]
pub const fn latest(&self) -> Option<&T> {
match self {
Self::Ready(v)
| Self::Refreshing(v)
| Self::Error {
previous: Some(v), ..
} => Some(v),
Self::Pending | Self::Error { previous: None, .. } | Self::Disposed => None,
}
}
#[inline]
pub const fn error(&self) -> Option<&E> {
match self {
Self::Error { error, .. } => Some(error),
_ => None,
}
}
}
pub struct Resource<T: 'static, E: 'static, K: 'static = ()> {
scope: Scope,
source: Signal<K>,
state: Atom<ResourceState<T, E>>,
trigger: Atom<u64>,
generation: Rc<Cell<u64>>,
disposed: Rc<Cell<bool>>,
owns_source: bool,
}
impl<T: 'static, E: 'static, K: 'static> Clone for Resource<T, E, K> {
fn clone(&self) -> Self {
Self {
scope: self.scope.clone(),
source: self.source,
state: self.state,
trigger: self.trigger,
generation: Rc::clone(&self.generation),
disposed: Rc::clone(&self.disposed),
owns_source: self.owns_source,
}
}
}
impl<T: 'static, E: 'static, K: 'static> fmt::Debug for Resource<T, E, K> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Resource")
.field("source", &self.source)
.field("state", &self.state)
.field("generation", &self.generation.get())
.field("disposed", &self.disposed.get())
.finish_non_exhaustive()
}
}
impl<T: PartialEq + 'static, E: PartialEq + 'static> Resource<T, E, ()> {
pub fn stateless(scope: &Scope) -> Self {
let source = scope.atom(());
Self {
scope: scope.clone(),
source: source.as_signal(),
state: scope.atom(ResourceState::Pending),
trigger: scope.atom(0u64),
generation: Rc::new(Cell::new(0)),
disposed: Rc::new(Cell::new(false)),
owns_source: true,
}
}
}
impl<T: PartialEq + 'static, E: PartialEq + 'static, K: 'static> Resource<T, E, K> {
pub fn new(scope: &Scope, source: impl Into<Signal<K>>) -> Self {
Self {
scope: scope.clone(),
source: source.into(),
state: scope.atom(ResourceState::Pending),
trigger: scope.atom(0u64),
generation: Rc::new(Cell::new(0)),
disposed: Rc::new(Cell::new(false)),
owns_source: false,
}
}
pub fn with_initial(scope: &Scope, source: impl Into<Signal<K>>, initial: T) -> Self {
Self {
scope: scope.clone(),
source: source.into(),
state: scope.atom(ResourceState::Ready(initial)),
trigger: scope.atom(0u64),
generation: Rc::new(Cell::new(0)),
disposed: Rc::new(Cell::new(false)),
owns_source: false,
}
}
#[inline]
pub const fn state(&self) -> Atom<ResourceState<T, E>> {
self.state
}
#[inline]
pub fn generation(&self) -> u64 {
self.generation.get()
}
pub fn latest(&self) -> Option<T>
where
T: Clone,
{
self.scope
.try_with(self.state, |s| s.latest().cloned())
.ok()
.flatten()
}
pub fn is_pending(&self) -> bool {
self.scope
.try_with(self.state, ResourceState::is_pending)
.unwrap_or(false)
}
pub fn refetch(&self) {
if self.disposed.get() {
return;
}
self.scope.update(self.trigger, |rev| rev + 1);
}
pub fn mutate(&self, value: T) {
if self.disposed.get() {
return;
}
self.generation.set(self.generation.get() + 1);
self.scope.set(self.state, ResourceState::Ready(value));
}
pub fn dispose(&self) {
if self.disposed.replace(true) {
return;
}
self.generation.set(self.generation.get() + 1);
self.scope.set(self.state, ResourceState::Disposed);
let _ = self.scope.dispose(self.trigger);
if self.owns_source {
let _ = self.scope.dispose(self.source);
}
}
fn begin_request(&self) -> Option<u64>
where
T: Clone,
{
if self.disposed.get() {
return None;
}
let next_gen = self.generation.get() + 1;
self.generation.set(next_gen);
let prev = self.latest();
let next_state = match prev {
Some(v) => ResourceState::Refreshing(v),
None => ResourceState::Pending,
};
self.scope.set(self.state, next_state);
Some(next_gen)
}
fn finish_request(&self, request_gen: u64, result: Result<T, E>)
where
T: Clone,
{
if self.disposed.get() || self.generation.get() != request_gen {
return;
}
let next_state = match result {
Ok(value) => ResourceState::Ready(value),
Err(error) => ResourceState::Error {
error,
previous: self.latest(),
},
};
self.scope.set(self.state, next_state);
}
#[expect(
clippy::future_not_send,
reason = "local Scope and Rc state are confined to their executor thread"
)]
pub async fn load<F, Fut>(&self, loader: F)
where
T: Clone,
K: Clone,
F: FnOnce(K) -> Fut,
Fut: Future<Output = Result<T, E>>,
{
let Ok(key) = self.scope.try_get(self.source) else {
return;
};
let Some(request_gen) = self.begin_request() else {
return;
};
let result = loader(key).await;
self.finish_request(request_gen, result);
}
#[expect(
clippy::future_not_send,
reason = "local Scope and Rc state are confined to their executor thread"
)]
pub async fn drive<F, Fut>(&self, mut loader: F)
where
T: Clone,
K: Clone + PartialEq,
F: FnMut(K) -> Fut,
Fut: Future<Output = Result<T, E>>,
{
if self.disposed.get() {
return;
}
let source = self.source;
let trigger = self.trigger;
let request_key = self.scope.computed(move |cx| {
let rev = cx.try_get(trigger).ok()?;
let key = cx.try_get(source).ok()?;
Some((rev, key))
});
let scope_cleanup = self.scope.clone();
let _cleanup = DropGuard::new(request_key, move |comp| {
let _ = scope_cleanup.dispose(comp);
});
let mut changes = self.scope.changes(request_key);
let Ok(init_key) = self.scope.try_get(source) else {
return;
};
let mut in_flight: Option<(u64, Pin<Box<Fut>>)> = self
.begin_request()
.map(|request_gen| (request_gen, Box::pin(loader(init_key))));
poll_fn(|cx| {
loop {
if self.disposed.get() {
in_flight = None;
return Poll::Ready(());
}
match changes.poll_next(cx) {
Poll::Ready(Some(Ok(snapshot))) => {
let Some((_, next_key)) = snapshot.as_ref() else {
in_flight = None;
return Poll::Ready(());
};
let next_key = next_key.clone();
in_flight = self
.begin_request()
.map(|request_gen| (request_gen, Box::pin(loader(next_key))));
continue;
}
Poll::Ready(Some(Err(_)) | None) => {
in_flight = None;
return Poll::Ready(());
}
Poll::Pending => {}
}
if let Some((request_gen, fut)) = in_flight.as_mut() {
match fut.as_mut().poll(cx) {
Poll::Ready(result) => {
let finished_gen = *request_gen;
in_flight = None;
self.finish_request(finished_gen, result);
continue;
}
Poll::Pending => return Poll::Pending,
}
}
return Poll::Pending;
}
})
.await;
}
}