tauri_store/store/
save.rs

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
use crate::error::Result;
use crate::manager::ManagerExt;
use futures::future::{BoxFuture, FutureExt};
use serde::ser::SerializeTuple;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value as Json;
use std::fmt;
use std::result::Result as StdResult;
use std::sync::Arc;
use std::time::Duration;
use tauri::async_runtime::spawn_blocking;
use tauri::{AppHandle, Runtime};
use tauri_store_utils::{Debounce, RemoteCallable, Throttle};

type RemoteSaveHandle<R> = Box<dyn RemoteCallable<AppHandle<R>> + Send + Sync>;
type SaveHandleFn<R> = Box<dyn Fn(AppHandle<R>) -> BoxFuture<'static, ()> + Send + Sync + 'static>;

pub(super) struct SaveHandle<R: Runtime>(RemoteSaveHandle<R>);

impl<R: Runtime> SaveHandle<R> {
  pub fn call(&self, app: &AppHandle<R>) {
    self.0.call(app);
  }

  pub fn abort(&self) {
    self.0.abort();
  }
}

pub(super) fn debounce<R: Runtime>(duration: Duration, id: Arc<str>) -> SaveHandle<R> {
  SaveHandle(Box::new(Debounce::new(duration, save_handle(id))))
}

pub(super) fn throttle<R: Runtime>(duration: Duration, id: Arc<str>) -> SaveHandle<R> {
  SaveHandle(Box::new(Throttle::new(duration, save_handle(id))))
}

fn save_handle<R: Runtime>(id: Arc<str>) -> SaveHandleFn<R> {
  Box::new(move |app| {
    let id = Arc::clone(&id);
    Box::pin(async move {
      let task = spawn_blocking(move || {
        app
          .store_collection()
          .get_resource(&id)?
          .locked(|store| store.save_now())
      });

      task.map(drop).await;
    })
  })
}

/// The strategy to use when saving a store.
///
/// For a detailed explanation of the differences between debouncing and throttling,
/// take a look at [this article](https://kettanaito.com/blog/debounce-vs-throttle).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default)]
pub enum SaveStrategy {
  #[default]
  Immediate,
  Debounce(Duration),
  Throttle(Duration),
}

impl SaveStrategy {
  const IMMEDIATE: &'static str = "immediate";
  const DEBOUNCE: &'static str = "debounce";
  const THROTTLE: &'static str = "throttle";

  /// Returns [`Debounce`](SaveStrategy::Debounce) with the given duration, in milliseconds.
  pub const fn debounce_millis(millis: u64) -> Self {
    Self::Debounce(Duration::from_millis(millis))
  }

  /// Returns [`Debounce`](SaveStrategy::Debounce) with the given duration, in seconds.
  pub const fn debounce_secs(secs: u64) -> Self {
    Self::Debounce(Duration::from_secs(secs))
  }

  /// Returns [`Throttle`](SaveStrategy::Throttle) with the given duration, in milliseconds.
  pub const fn throttle_millis(millis: u64) -> Self {
    Self::Throttle(Duration::from_millis(millis))
  }

  /// Returns [`Throttle`](SaveStrategy::Throttle) with the given duration, in seconds.
  pub const fn throttle_secs(secs: u64) -> Self {
    Self::Throttle(Duration::from_secs(secs))
  }

  /// Whether the strategy is [`Debounce`](SaveStrategy::Debounce).
  pub const fn is_debounce(&self) -> bool {
    matches!(self, Self::Debounce(_))
  }

  /// Whether the strategy is [`Throttle`](SaveStrategy::Throttle).
  pub const fn is_throttle(&self) -> bool {
    matches!(self, Self::Throttle(_))
  }
}

impl fmt::Display for SaveStrategy {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::Immediate => write!(f, "{}", Self::IMMEDIATE),
      Self::Debounce(_) => write!(f, "{}", Self::DEBOUNCE),
      Self::Throttle(_) => write!(f, "{}", Self::THROTTLE),
    }
  }
}

impl Serialize for SaveStrategy {
  fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>
  where
    S: Serializer,
  {
    let interval = match self {
      Self::Immediate => 0,
      Self::Debounce(duration) | Self::Throttle(duration) => duration.as_millis(),
    };

    let mut tuple = serializer.serialize_tuple(2)?;
    tuple.serialize_element(&self.to_string())?;
    tuple.serialize_element(&interval.to_string())?;
    tuple.end()
  }
}

impl<'de> Deserialize<'de> for SaveStrategy {
  fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error>
  where
    D: Deserializer<'de>,
  {
    let err = || {
      use serde::de::Error;
      D::Error::custom("invalid save strategy")
    };

    let value = Json::deserialize(deserializer)?;
    if let Json::Array(mut array) = value {
      if array.len() != 2 {
        return Err(err());
      }

      let strategy = array
        .remove(0)
        .as_str()
        .map(ToOwned::to_owned)
        .ok_or_else(err)?;

      let duration = array
        .remove(0)
        .as_str()
        .map(str::parse)
        .ok_or_else(err)?
        .map(Duration::from_millis)
        .map_err(|_| err())?;

      if duration.is_zero() {
        return Ok(Self::Immediate);
      }

      match strategy.as_str() {
        Self::DEBOUNCE => Ok(Self::Debounce(duration)),
        Self::THROTTLE => Ok(Self::Throttle(duration)),
        Self::IMMEDIATE => Ok(Self::Immediate),
        _ => Err(err()),
      }
    } else {
      Err(err())
    }
  }
}

pub(super) fn to_bytes<T>(value: &T, pretty: bool) -> Result<Vec<u8>>
where
  T: ?Sized + Serialize,
{
  if pretty {
    Ok(serde_json::to_vec_pretty(value)?)
  } else {
    Ok(serde_json::to_vec(value)?)
  }
}