use std::{
collections::VecDeque,
fmt,
future::Future,
rc::Rc,
sync::Arc,
time::{Duration, Instant},
};
use gpui::{App, Entity, Global, Task};
use super::{
cache::{cache, AnyData},
invalidate,
options::BoxFuture,
services::task_cx,
QueryKey, TaskCx,
};
use crate::Cx;
type Runner<I, O, E> = Arc<dyn Fn(TaskCx, I) -> BoxFuture<Result<O, E>> + Send + Sync>;
type SuccessHandler<I, O> = Rc<dyn Fn(&O, &I, &mut App)>;
type ErrorHandler<I, E> = Rc<dyn Fn(&E, &I, &mut App)>;
type OptimisticUpdate<I> = Rc<dyn Fn(&I, &mut Optimistic<'_>)>;
pub struct MutationOptions<I, O, E> {
run: Runner<I, O, E>,
key: Option<QueryKey>,
invalidates: Vec<QueryKey>,
on_success: Vec<SuccessHandler<I, O>>,
on_error: Vec<ErrorHandler<I, E>>,
optimistic: Option<OptimisticUpdate<I>>,
}
impl<I, O, E> MutationOptions<I, O, E>
where
I: Send + 'static,
O: Send + 'static,
E: Send + 'static,
{
pub fn new<F, Fut>(run: F) -> Self
where
F: Fn(TaskCx, I) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<O, E>> + Send + 'static,
{
Self {
run: Arc::new(move |cx, input| Box::pin(run(cx, input))),
key: None,
invalidates: Vec::new(),
on_success: Vec::new(),
on_error: Vec::new(),
optimistic: None,
}
}
}
impl<I, O, E> MutationOptions<I, O, E> {
#[must_use]
pub fn key(mut self, key: QueryKey) -> Self {
self.key = Some(key);
self
}
#[must_use]
pub fn invalidates(mut self, prefix: QueryKey) -> Self {
self.invalidates.push(prefix);
self
}
#[must_use]
pub fn on_success(mut self, handler: impl Fn(&O, &I, &mut App) + 'static) -> Self {
self.on_success.push(Rc::new(handler));
self
}
#[must_use]
pub fn on_error(mut self, handler: impl Fn(&E, &I, &mut App) + 'static) -> Self {
self.on_error.push(Rc::new(handler));
self
}
#[must_use]
pub fn optimistic(mut self, update: impl Fn(&I, &mut Optimistic<'_>) + 'static) -> Self {
self.optimistic = Some(Rc::new(update));
self
}
}
impl<I, O, E> Clone for MutationOptions<I, O, E> {
fn clone(&self) -> Self {
Self {
run: self.run.clone(),
key: self.key.clone(),
invalidates: self.invalidates.clone(),
on_success: self.on_success.clone(),
on_error: self.on_error.clone(),
optimistic: self.optimistic.clone(),
}
}
}
pub struct Optimistic<'a> {
cx: &'a mut App,
snapshots: Vec<Snapshot>,
}
struct Snapshot {
key: QueryKey,
data: Option<AnyData>,
}
impl Optimistic<'_> {
pub fn update<T: Clone + 'static>(&mut self, key: &QueryKey, update: impl FnOnce(&mut T)) {
self.record(key);
super::update_query_data(self.cx, key, update);
}
pub fn set<T: 'static>(&mut self, key: &QueryKey, data: T) {
self.record(key);
super::set_query_data(self.cx, key, data);
}
fn record(&mut self, key: &QueryKey) {
if self.snapshots.iter().any(|snapshot| &snapshot.key == key) {
return;
}
let data = cache(self.cx)
.entries
.get(key)
.and_then(|entry| entry.data.clone());
self.snapshots.push(Snapshot {
key: key.clone(),
data,
});
}
}
fn roll_back(cx: &mut App, snapshots: Vec<Snapshot>) {
let entries = &mut cache(cx).entries;
for snapshot in snapshots {
match snapshot.data {
Some(data) => {
if let Some(entry) = entries.get_mut(&snapshot.key) {
entry.set_data(data);
}
}
None => {
entries.remove(&snapshot.key);
}
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MutationStatus {
Idle,
Pending,
Success,
Error,
}
struct MutationState<O, E> {
status: MutationStatus,
data: Option<Rc<O>>,
error: Option<Rc<E>>,
run: u64,
submitted_at: Option<Instant>,
task: Option<Task<()>>,
logged: Option<u64>,
}
impl<O, E> Default for MutationState<O, E> {
fn default() -> Self {
Self {
status: MutationStatus::Idle,
data: None,
error: None,
run: 0,
submitted_at: None,
task: None,
logged: None,
}
}
}
pub struct Mutation<I, O, E> {
state: Entity<MutationState<O, E>>,
options: MutationOptions<I, O, E>,
status: MutationStatus,
data: Option<Rc<O>>,
error: Option<Rc<E>>,
}
impl<I, O, E> Clone for Mutation<I, O, E> {
fn clone(&self) -> Self {
Self {
state: self.state.clone(),
options: self.options.clone(),
status: self.status,
data: self.data.clone(),
error: self.error.clone(),
}
}
}
impl<I, O, E> fmt::Debug for Mutation<I, O, E> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Mutation")
.field("status", &self.status)
.finish_non_exhaustive()
}
}
impl<I, O, E> Mutation<I, O, E>
where
I: Clone + Send + 'static,
O: Send + 'static,
E: Send + 'static,
{
pub fn mutate(&self, cx: &mut App, input: I) {
let options = self.options.clone();
let snapshots = match &options.optimistic {
Some(update) => {
let mut optimistic = Optimistic {
cx,
snapshots: Vec::new(),
};
update(&input, &mut optimistic);
optimistic.snapshots
}
None => Vec::new(),
};
let logged = log_start(cx, options.key.clone());
let (run_id, superseded) = self.state.update(cx, |state, _| {
state.run += 1;
state.status = MutationStatus::Pending;
state.submitted_at = Some(Instant::now());
(state.run, state.logged.replace(logged))
});
if let Some(superseded) = superseded {
log_finish(cx, superseded, MutationStatus::Idle);
}
let services = task_cx(cx);
let run = options.run.clone();
let sent_input = input.clone();
let running = crate::runtime::spawn(async move { run(services, sent_input).await });
let state = self.state.clone();
let task = cx.spawn(async move |cx| {
let outcome = running.await;
cx.update(|cx| {
if state.read(cx).run != run_id {
return;
}
let status = match &outcome {
Ok(Ok(_)) => MutationStatus::Success,
Ok(Err(_)) => MutationStatus::Error,
Err(_) => MutationStatus::Idle,
};
log_finish(cx, logged, status);
match outcome {
Ok(Ok(data)) => {
let data = Rc::new(data);
state.update(cx, |state, _| {
state.status = MutationStatus::Success;
state.data = Some(data.clone());
state.error = None;
state.task = None;
});
for handler in &options.on_success {
handler(&data, &input, cx);
}
for prefix in &options.invalidates {
invalidate(cx, prefix);
}
}
Ok(Err(error)) => {
roll_back(cx, snapshots);
let error = Rc::new(error);
state.update(cx, |state, _| {
state.status = MutationStatus::Error;
state.error = Some(error.clone());
state.task = None;
});
for handler in &options.on_error {
handler(&error, &input, cx);
}
}
Err(_) => {
roll_back(cx, snapshots);
state.update(cx, |state, _| {
state.status = MutationStatus::Idle;
state.task = None;
});
}
}
cx.refresh_windows();
})
.ok();
});
self.state.update(cx, |state, _| state.task = Some(task));
cx.refresh_windows();
}
pub fn mutate_handler<Event>(
&self,
input: I,
) -> impl Fn(&Event, &mut gpui::Window, &mut App) + 'static {
let mutation = self.clone();
move |_, _, cx| mutation.mutate(cx, input.clone())
}
}
impl<I, O: 'static, E: 'static> Mutation<I, O, E> {
#[must_use]
pub fn on_success(mut self, handler: impl Fn(&O, &I, &mut App) + 'static) -> Self {
self.options.on_success.push(Rc::new(handler));
self
}
#[must_use]
pub fn on_error(mut self, handler: impl Fn(&E, &I, &mut App) + 'static) -> Self {
self.options.on_error.push(Rc::new(handler));
self
}
#[must_use]
pub fn optimistic(mut self, update: impl Fn(&I, &mut Optimistic<'_>) + 'static) -> Self {
self.options.optimistic = Some(Rc::new(update));
self
}
#[must_use]
pub fn status(&self) -> MutationStatus {
self.status
}
#[must_use]
pub fn is_pending(&self) -> bool {
self.status == MutationStatus::Pending
}
#[must_use]
pub fn is_idle(&self) -> bool {
self.status == MutationStatus::Idle
}
#[must_use]
pub fn is_success(&self) -> bool {
self.status == MutationStatus::Success
}
#[must_use]
pub fn is_error(&self) -> bool {
self.status == MutationStatus::Error
}
#[must_use]
pub fn data(&self) -> Option<&O> {
self.data.as_deref()
}
#[must_use]
pub fn error(&self) -> Option<&E> {
self.error.as_deref()
}
pub fn reset(&self, cx: &mut App) {
let logged = self.state.update(cx, |state, _| {
let logged = state.logged;
*state = MutationState {
run: state.run + 1,
..MutationState::default()
};
logged
});
if let Some(logged) = logged {
log_finish(cx, logged, MutationStatus::Idle);
}
cx.refresh_windows();
}
}
#[track_caller]
pub fn use_mutation<I, O, E>(cx: &mut Cx, options: MutationOptions<I, O, E>) -> Mutation<I, O, E>
where
O: 'static,
E: 'static,
{
let state = cx
.window
.use_state(cx.app, |_, _| MutationState::<O, E>::default());
let (status, data, error) = {
let current = state.read(cx.app);
(current.status, current.data.clone(), current.error.clone())
};
Mutation {
state,
options,
status,
data,
error,
}
}
const LOG_LIMIT: usize = 50;
#[derive(Default)]
struct MutationLog {
next: u64,
entries: VecDeque<MutationInfo>,
}
impl Global for MutationLog {}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MutationInfo {
pub key: Option<QueryKey>,
pub status: MutationStatus,
pub submitted_at: Instant,
pub duration: Option<Duration>,
id: u64,
}
fn log_start(cx: &mut App, key: Option<QueryKey>) -> u64 {
let log = cx.default_global::<MutationLog>();
log.next += 1;
log.entries.push_back(MutationInfo {
key,
status: MutationStatus::Pending,
submitted_at: Instant::now(),
duration: None,
id: log.next,
});
while log.entries.len() > LOG_LIMIT {
let Some(finished) = log
.entries
.iter()
.position(|entry| entry.status != MutationStatus::Pending)
else {
break;
};
log.entries.remove(finished);
}
log.next
}
fn log_finish(cx: &mut App, id: u64, status: MutationStatus) {
let log = cx.default_global::<MutationLog>();
if let Some(entry) = log.entries.iter_mut().find(|entry| entry.id == id) {
if entry.status == MutationStatus::Pending {
entry.status = status;
entry.duration = Some(entry.submitted_at.elapsed());
}
}
}
#[must_use]
pub fn mutations(cx: &App) -> Vec<MutationInfo> {
cx.try_global::<MutationLog>()
.map(|log| log.entries.iter().rev().cloned().collect())
.unwrap_or_default()
}