tauri_plugin_update_gate/
source.rs1use std::io::Read;
7use std::sync::{Arc, Mutex};
8use std::time::{Duration, Instant};
9
10use async_trait::async_trait;
11use log::warn;
12
13use crate::decide::{decide, Document, Gate};
14
15const MAX_BODY: u64 = 64 * 1024;
19
20pub struct Config {
23 url: String,
24 ttl: Duration,
25 timeout: Duration,
26}
27
28impl Config {
29 pub fn url(u: impl Into<String>) -> Self {
32 Self {
33 url: u.into(),
34 ttl: Duration::from_secs(6 * 60 * 60),
35 timeout: Duration::from_secs(5),
36 }
37 }
38
39 #[must_use]
42 pub fn ttl(mut self, d: Duration) -> Self {
43 self.ttl = d;
44 self
45 }
46
47 #[must_use]
49 pub fn timeout(mut self, d: Duration) -> Self {
50 self.timeout = d;
51 self
52 }
53}
54
55#[async_trait]
59pub trait Fetch: Send + Sync {
60 async fn get(&self, url: &str) -> Result<String, String>;
61}
62
63struct UreqFetch(ureq::Agent);
68
69impl UreqFetch {
70 fn new(timeout: Duration) -> Self {
74 let agent = ureq::Agent::config_builder()
75 .timeout_global(Some(timeout))
76 .build()
77 .into();
78 Self(agent)
79 }
80}
81
82#[async_trait]
83impl Fetch for UreqFetch {
84 async fn get(&self, url: &str) -> Result<String, String> {
85 let agent = self.0.clone();
87 let url = url.to_owned();
88 tauri::async_runtime::spawn_blocking(move || {
89 let mut response = agent.get(&url).call().map_err(|e| e.to_string())?;
90 let declared = response.body().content_length();
91 read_capped(declared, response.body_mut().as_reader(), MAX_BODY)
92 })
93 .await
94 .map_err(|e| e.to_string())?
95 }
96}
97
98fn read_capped(declared: Option<u64>, body: impl Read, cap: u64) -> Result<String, String> {
103 if let Some(n) = declared.filter(|&n| n > cap) {
104 return Err(format!(
105 "document declares {n} bytes, over the {cap}-byte cap"
106 ));
107 }
108 let mut bytes = Vec::new();
109 body.take(cap + 1)
110 .read_to_end(&mut bytes)
111 .map_err(|e| e.to_string())?;
112 if bytes.len() as u64 > cap {
113 return Err(format!("document runs past the {cap}-byte cap"));
114 }
115 String::from_utf8(bytes).map_err(|e| e.to_string())
116}
117
118pub struct Source {
122 config: Config,
123 fetcher: Arc<dyn Fetch>,
124 cache: Mutex<Option<(Instant, Document)>>,
125}
126
127impl Source {
128 #[must_use]
131 pub fn new(config: Config) -> Self {
132 let fetcher = UreqFetch::new(config.timeout);
133 Self::with(config, fetcher)
134 }
135
136 pub fn with(config: Config, fetcher: impl Fetch + 'static) -> Self {
139 Self {
140 config,
141 fetcher: Arc::new(fetcher),
142 cache: Mutex::new(None),
143 }
144 }
145
146 pub async fn gate(&self, running: &str, lang: &str, platform: &str) -> Gate {
152 if let Some(doc) = self.cached() {
153 return decide(&doc, running, lang, platform);
154 }
155
156 match self.fetch_and_cache().await {
157 Ok(doc) => decide(&doc, running, lang, platform),
158 Err(e) => {
159 warn!("update-gate: {e}");
160 decide(&Document::default(), running, lang, platform)
161 }
162 }
163 }
164
165 fn cached(&self) -> Option<Document> {
167 let cache = self
168 .cache
169 .lock()
170 .unwrap_or_else(std::sync::PoisonError::into_inner);
171 cache.as_ref().and_then(|(at, doc)| {
172 (Instant::now().saturating_duration_since(*at) < self.config.ttl).then(|| doc.clone())
173 })
174 }
175
176 async fn fetch_and_cache(&self) -> Result<Document, String> {
181 let fetcher = Arc::clone(&self.fetcher);
182 let url = self.config.url.clone();
183 let body = tauri::async_runtime::spawn(async move { fetcher.get(&url).await })
184 .await
185 .map_err(|e| format!("fetch did not finish: {e}"))??;
186 let doc: Document = serde_json::from_str(&body).map_err(|e| e.to_string())?;
187 *self
188 .cache
189 .lock()
190 .unwrap_or_else(std::sync::PoisonError::into_inner) =
191 Some((Instant::now(), doc.clone()));
192 Ok(doc)
193 }
194}
195
196#[cfg(test)]
197mod tests {
198 use std::sync::atomic::{AtomicUsize, Ordering};
199 use std::sync::Arc;
200
201 use super::{read_capped, Config, Fetch, Source};
202 use crate::decide::State;
203
204 struct Canned(Result<String, String>, Arc<AtomicUsize>);
205
206 #[async_trait::async_trait]
207 impl Fetch for Canned {
208 async fn get(&self, _url: &str) -> Result<String, String> {
209 self.1.fetch_add(1, Ordering::SeqCst);
210 self.0.clone()
211 }
212 }
213
214 struct Panics;
215
216 #[async_trait::async_trait]
217 impl Fetch for Panics {
218 async fn get(&self, _url: &str) -> Result<String, String> {
219 panic!("the network stack fell over");
220 }
221 }
222
223 fn n() -> Arc<AtomicUsize> {
224 Arc::new(AtomicUsize::new(0))
225 }
226
227 #[tokio::test]
228 async fn a_network_error_opens_the_gate() {
229 let s = Source::with(Config::url("http://x"), Canned(Err("offline".into()), n()));
230 assert!(matches!(
231 s.gate("1.0.0", "vi", "ios").await.state,
232 State::Ok
233 ));
234 }
235
236 #[tokio::test]
237 async fn a_fetch_that_panics_still_opens_the_gate() {
238 let s = Source::with(Config::url("http://x"), Panics);
239 assert!(matches!(
240 s.gate("1.0.0", "vi", "ios").await.state,
241 State::Ok
242 ));
243 }
244
245 #[tokio::test]
246 async fn malformed_json_opens_the_gate() {
247 let s = Source::with(
248 Config::url("http://x"),
249 Canned(Ok("<html>404</html>".into()), n()),
250 );
251 assert!(matches!(
252 s.gate("1.0.0", "vi", "ios").await.state,
253 State::Ok
254 ));
255 }
256
257 #[tokio::test]
258 async fn it_fetches_once_inside_the_ttl() {
259 let calls = n();
260 let s = Source::with(
261 Config::url("http://x"),
262 Canned(Ok(r#"{"minVersion":"2.0.0"}"#.into()), calls.clone()),
263 );
264 assert!(matches!(
265 s.gate("1.0.0", "vi", "ios").await.state,
266 State::Forced
267 ));
268 assert!(matches!(
269 s.gate("1.0.0", "vi", "ios").await.state,
270 State::Forced
271 ));
272 assert_eq!(calls.load(Ordering::SeqCst), 1);
273 }
274
275 #[tokio::test]
276 async fn it_fetches_again_once_the_ttl_has_passed() {
277 let calls = n();
278 let s = Source::with(
279 Config::url("http://x").ttl(std::time::Duration::ZERO),
280 Canned(Ok(r#"{"minVersion":"2.0.0"}"#.into()), calls.clone()),
281 );
282 s.gate("1.0.0", "vi", "ios").await;
283 s.gate("1.0.0", "vi", "ios").await;
284 assert_eq!(calls.load(Ordering::SeqCst), 2);
285 }
286
287 #[test]
288 fn a_body_within_the_cap_is_read_whole() {
289 let body = r#"{"minVersion":"2.0.0"}"#;
290 assert_eq!(read_capped(None, body.as_bytes(), 64).unwrap(), body);
291 assert_eq!(read_capped(Some(4), &b"abcd"[..], 4).unwrap(), "abcd");
292 }
293
294 #[test]
295 fn a_declared_length_over_the_cap_is_refused_before_reading() {
296 struct Unread;
297 impl std::io::Read for Unread {
298 fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
299 panic!("read a body its header already ruled out");
300 }
301 }
302 assert!(read_capped(Some(5), Unread, 4).is_err());
303 }
304
305 #[test]
306 fn a_body_that_outgrows_the_cap_is_refused() {
307 assert!(read_capped(None, &b"abcde"[..], 4).is_err());
309 assert!(read_capped(Some(1), &b"abcde"[..], 4).is_err());
310 }
311
312 #[test]
313 fn a_body_that_is_not_utf8_is_refused() {
314 assert!(read_capped(None, &[0xff, 0xfe][..], 4).is_err());
315 }
316}