kovlet 0.1.0

Kovlet's portable sync client core: sign-in, sync, merge, outbox and files for Rust, Tauri, Swift and Kotlin apps
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! The file mirror (`space.files().mirror(dir, prefix)`): keeps a local folder
//! and the space's files under a path prefix in step.
//!
//! - A file in the space at `prefix + "a/b.png"` lives at `dir/a/b.png`.
//! - Files match by path and SHA-256: a file already in the space (or queued
//!   for upload) with the same path and bytes is never uploaded again, so
//!   mirroring a folder twice, or after re-linking, adds no file records.
//! - Every pass, download and upload runs on the core's runtime, never on the
//!   caller's thread. `notify_added` stages the new file's bytes on the
//!   caller's thread (like [`crate::Files::put_file`]) and returns.
//! - Not handled: deletes and moves in either direction (a file removed on
//!   one side stays on the other), and symlinks and dot-files in `dir`.

use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, UNIX_EPOCH};

use sha2::{Digest, Sha256};
use tokio::sync::{broadcast, watch};

use crate::engine::SyncState;
use crate::error::{Error, Result};
use crate::protocol::FileState;
use crate::space::Space;
use crate::store::Origin;

/// What a [`Mirror`] is doing.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct MirrorStatus {
    /// The first full pass (list, upload, download) has finished.
    pub ready: bool,
    /// A pass or a download is running.
    pub busy: bool,
    /// Files this mirror queued for upload.
    pub uploaded: u64,
    /// Files this mirror downloaded into the folder.
    pub downloaded: u64,
    /// The last error (a pass that failed is retried on reconnect and with backoff).
    pub error: Option<Error>,
}

/// The suffix of a download in progress (`files::download` writes there first).
const PARTIAL: &str = "kovlet-download";

/// A file the space has (or the outbox will commit) at a path.
#[derive(Debug, Clone)]
struct Known {
    id: String,
    sha256: String,
    wall_ms: u64,
}

impl Known {
    fn of(f: &FileState) -> Known {
        let wall_ms = f.hlc.as_deref().and_then(|h| crate::hlc::Hlc::parse(h).ok()).map_or(0, |h| h.wall_ms);
        Known { id: f.id.clone(), sha256: f.sha256.clone(), wall_ms }
    }
}

/// One per open space (on `SpaceShared`), shared by all its mirrors, so two
/// mirrors of the same files (started together, say) never both upload one.
#[derive(Default)]
pub(crate) struct SpaceIndex {
    /// Space path → the files the space has (or the outbox will commit) there.
    index: Mutex<HashMap<String, Vec<Known>>>,
    /// Serializes "decide and put" across passes, mirrors and `notify_added`.
    put_lock: Mutex<()>,
}

struct LocalFile {
    remote: String,
    abs: PathBuf,
    sha256: String,
    mtime_ms: u64,
}

struct Shared {
    space: Space,
    dir: PathBuf,
    prefix: String,
    /// The space's path index and put lock, shared by every mirror of the space.
    idx: Arc<SpaceIndex>,
    /// The index has been loaded once (from then on `notify_added` uploads).
    listed: std::sync::atomic::AtomicBool,
    /// (size, mtime) → SHA-256 of local files already hashed.
    hashes: Mutex<HashMap<PathBuf, (u64, u64, String)>>,
    status: watch::Sender<MirrorStatus>,
}

/// Aborts the mirror's task when the last [`Mirror`] clone is dropped.
struct Guard(tokio::task::JoinHandle<()>);

impl Drop for Guard {
    fn drop(&mut self) {
        self.0.abort();
    }
}

/// A running file mirror. Cheap to clone; stops when the last clone is dropped.
///
/// ```no_run
/// # fn f(space: &kovlet::Space, app_dir: &std::path::Path) -> Result<(), Box<dyn std::error::Error>> {
/// // Once, after opening the space:
/// let attachments = space.files().mirror(app_dir.join("attachments"), "attachments/")?;
/// // At each place the app writes a new file into the folder:
/// std::fs::write(app_dir.join("attachments/scan.png"), b"...")?;
/// attachments.notify_added("scan.png")?;
/// # Ok(()) }
/// ```
#[derive(Clone)]
pub struct Mirror {
    shared: Arc<Shared>,
    _guard: Arc<Guard>,
}

impl Mirror {
    pub(crate) fn start(space: Space, dir: PathBuf, prefix: &str) -> Result<Mirror> {
        let prefix = normalize_prefix(prefix)?;
        std::fs::create_dir_all(&dir).map_err(Error::storage)?;
        let (status, _) = watch::channel(MirrorStatus::default());
        let shared = Arc::new(Shared {
            space: space.clone(),
            dir,
            prefix,
            idx: space.sync.shared.mirror.clone(),
            listed: false.into(),
            hashes: Mutex::new(HashMap::new()),
            status,
        });
        // Subscribe before the first pass, so no change slips between its list and the loop.
        let files = space.sync.shared.files.subscribe();
        let state = space.watch_status();
        let task = space.ctx.handle.spawn(run(shared.clone(), files, state));
        Ok(Mirror { shared, _guard: Arc::new(Guard(task)) })
    }

    /// The local folder.
    pub fn dir(&self) -> &Path {
        &self.shared.dir
    }

    /// The space path prefix (`""`, or ending in `/`).
    pub fn prefix(&self) -> &str {
        &self.shared.prefix
    }

    pub fn status(&self) -> MirrorStatus {
        self.shared.status.borrow().clone()
    }

    pub fn watch_status(&self) -> watch::Receiver<MirrorStatus> {
        self.shared.status.subscribe()
    }

    /// Tells the mirror the app wrote a new (or changed) file into the folder.
    /// `path` is relative to the folder, or an absolute path inside it.
    ///
    /// Returns the queued file, or `None` when the space already has these
    /// bytes at this path, or the first pass hasn't finished (it picks the
    /// file up itself), or for dot-files, which are never uploaded. Reads the whole file on the caller's thread.
    pub fn notify_added(&self, path: impl AsRef<Path>) -> Result<Option<FileState>> {
        let s = &self.shared;
        let path = path.as_ref();
        let rel = if path.is_absolute() {
            path.strip_prefix(&s.dir).map_err(|_| {
                Error::config(format!("{} is outside the mirrored folder {}", path.display(), s.dir.display()))
            })?
        } else {
            path
        };
        let Some(remote) = local_to_remote(&s.prefix, rel) else {
            return Err(Error::config(format!("{} is not a plain path inside the mirrored folder", rel.display())));
        };
        if rel.components().any(|c| c.as_os_str().to_string_lossy().starts_with('.') && c != Component::CurDir) {
            return Ok(None); // dot-files are never uploaded (like the folder walk)
        }
        let abs = s.dir.join(rel);
        if !s.listed.load(std::sync::atomic::Ordering::SeqCst) {
            return Ok(None); // the first pass hasn't walked the folder yet: it will see the file
        }
        let (sha, mtime_ms) = s.hash(&abs)?;
        let local = LocalFile { remote, abs, sha256: sha, mtime_ms };
        let _g = s.idx.put_lock.lock().unwrap();
        s.upload_if_new(&local, true)
    }
}

impl Shared {
    fn set(&self, f: impl FnOnce(&mut MirrorStatus)) {
        self.status.send_modify(f);
    }

    /// SHA-256 and mtime of a local file, cached by (size, mtime).
    fn hash(&self, abs: &Path) -> Result<(String, u64)> {
        let meta = std::fs::metadata(abs).map_err(Error::storage)?;
        let mtime_ms =
            meta.modified().ok().and_then(|t| t.duration_since(UNIX_EPOCH).ok()).map_or(0, |d| d.as_millis() as u64);
        if let Some((size, mtime, sha)) = self.hashes.lock().unwrap().get(abs) {
            if *size == meta.len() && *mtime == mtime_ms {
                return Ok((sha.clone(), mtime_ms));
            }
        }
        let mut f = std::fs::File::open(abs).map_err(Error::storage)?;
        let mut h = Sha256::new();
        std::io::copy(&mut f, &mut h).map_err(Error::storage)?;
        let sha = hex::encode(h.finalize());
        self.hashes.lock().unwrap().insert(abs.to_path_buf(), (meta.len(), mtime_ms, sha.clone()));
        Ok((sha, mtime_ms))
    }

    /// File puts still in the outbox, by path.
    fn pending_puts(&self) -> HashMap<String, Known> {
        self.space
            .sync
            .target
            .outbox()
            .into_iter()
            .filter(|p| p.mutation.kind == "file" && p.mutation.op == "put")
            .filter_map(|p| {
                let f = p.mutation.file?;
                Some((f.path, Known { id: p.mutation.id, sha256: f.sha256, wall_ms: u64::MAX }))
            })
            .collect()
    }

    /// Records that the space has (or will have) this file at `path`. The
    /// index only grows (a remote delete removes an entry): a pass adds what
    /// the server lists, and never forgets a put it hasn't seen committed yet.
    fn remember(&self, path: &str, k: Known) {
        let mut index = self.idx.index.lock().unwrap();
        let entry = index.entry(path.to_string()).or_default();
        entry.retain(|e| e.id != k.id);
        entry.push(k);
    }

    /// Uploads a local file unless the space has these bytes at its path.
    /// With `overwrite`, different bytes at the path become a new version of
    /// that file (same id); otherwise the newer side wins. Call under `idx.put_lock`.
    fn upload_if_new(&self, local: &LocalFile, overwrite: bool) -> Result<Option<FileState>> {
        let pending = self.pending_puts();
        let newest = {
            let index = self.idx.index.lock().unwrap();
            let mut have: Vec<Known> = index.get(&local.remote).cloned().unwrap_or_default();
            have.extend(pending.get(&local.remote).cloned());
            if have.iter().any(|k| k.sha256 == local.sha256) {
                return Ok(None);
            }
            have.into_iter().max_by_key(|k| k.wall_ms)
        };
        if let Some(k) = &newest {
            if !overwrite && k.wall_ms >= local.mtime_ms {
                return Ok(None); // the space's copy is newer: the pass downloads it
            }
        }
        let state = self.space.files().put_file(
            &local.remote,
            &local.abs,
            mime_type(&local.remote),
            newest.as_ref().map(|k| k.id.as_str()),
        )?;
        self.remember(&local.remote, Known::of(&state));
        self.set(|s| s.uploaded += 1);
        Ok(Some(state))
    }

    /// Lists the space, uploads what it lacks, downloads what the folder lacks.
    async fn pass(self: &Arc<Self>) -> Result<()> {
        let ctx = self.space.ctx.clone();
        let prefix = (!self.prefix.is_empty()).then_some(self.prefix.as_str());
        // Puts queued now are either in the list or still queued after it:
        // remember them first, so one acked mid-list isn't uploaded again.
        for (path, k) in self.pending_puts() {
            self.remember(&path, k);
        }
        let remote = crate::files::list(&ctx, self.space.id(), prefix).await?;
        let mut by_path: HashMap<String, FileState> = HashMap::new();
        for f in remote {
            if f.deleted || !f.path.starts_with(&self.prefix) || remote_to_rel(&self.prefix, &f.path).is_none() {
                continue;
            }
            self.remember(&f.path, Known::of(&f));
            let newer = by_path.get(&f.path).is_none_or(|g| Known::of(&f).wall_ms >= Known::of(g).wall_ms);
            if newer {
                by_path.insert(f.path.clone(), f);
            }
        }
        self.listed.store(true, std::sync::atomic::Ordering::SeqCst);

        // Hash and upload on a blocking thread: both read whole files.
        let me = self.clone();
        let present = tokio::task::spawn_blocking(move || -> Result<Vec<(String, String)>> {
            let mut files = Vec::new();
            walk(&me.dir, &mut files).map_err(Error::storage)?;
            let mut present = Vec::new();
            for abs in files {
                let Some(remote) = abs.strip_prefix(&me.dir).ok().and_then(|r| local_to_remote(&me.prefix, r)) else {
                    continue;
                };
                let (sha, mtime_ms) = me.hash(&abs)?;
                let local = LocalFile { remote: remote.clone(), abs, sha256: sha.clone(), mtime_ms };
                let _g = me.idx.put_lock.lock().unwrap();
                me.upload_if_new(&local, false)?;
                present.push((remote, sha));
            }
            Ok(present)
        })
        .await
        .map_err(Error::storage)??;
        let present: HashMap<String, String> = present.into_iter().collect();

        let mut first_err = None;
        for (path, f) in by_path {
            if present.get(&path).is_some_and(|sha| *sha == f.sha256) {
                continue;
            }
            if let Err(e) = self.fetch(&f).await {
                first_err.get_or_insert(e);
            }
        }
        match first_err {
            Some(e) => Err(e),
            None => Ok(()),
        }
    }

    /// Downloads a file of the space into the folder, unless the folder has
    /// its bytes or a local put of that path is still pending.
    async fn fetch(&self, f: &FileState) -> Result<()> {
        let Some(rel) = remote_to_rel(&self.prefix, &f.path) else { return Ok(()) };
        if self.pending_puts().contains_key(&f.path) {
            return Ok(());
        }
        let to = self.dir.join(rel);
        if to.exists() {
            if let Ok((sha, _)) = self.hash(&to) {
                if sha == f.sha256 {
                    return Ok(());
                }
            }
        }
        if let Some(parent) = to.parent() {
            std::fs::create_dir_all(parent).map_err(Error::storage)?;
        }
        self.set(|s| s.busy = true);
        crate::files::download(&self.space.ctx, self.space.id(), &f.id, &to).await?;
        self.set(|s| s.downloaded += 1);
        Ok(())
    }

    /// A file change from the server (a broadcast, delta, snapshot or rollback).
    async fn remote_change(&self, f: &FileState) -> Result<()> {
        if !f.path.starts_with(&self.prefix) || remote_to_rel(&self.prefix, &f.path).is_none() {
            return Ok(());
        }
        // Only what is new to the mirror downloads: a snapshot or delta
        // replaying a version it already knows must not overwrite a local edit
        // (the pass settles those by modification time). Before the first
        // pass has listed the space, that pass does the downloading.
        let seen = self
            .idx
            .index
            .lock()
            .unwrap()
            .get(&f.path)
            .is_some_and(|e| e.iter().any(|k| k.id == f.id && k.sha256 == f.sha256));
        if f.deleted {
            if let Some(e) = self.idx.index.lock().unwrap().get_mut(&f.path) {
                e.retain(|k| k.id != f.id);
            }
        } else {
            self.remember(&f.path, Known::of(f));
        }
        if seen || !self.listed.load(std::sync::atomic::Ordering::SeqCst) {
            return Ok(());
        }
        // Moves leave a stale index entry at the old path; the next pass rebuilds it.
        if f.deleted || f.sha256.is_empty() {
            return Ok(());
        }
        self.fetch(f).await
    }
}

async fn run(
    s: Arc<Shared>,
    mut files: broadcast::Receiver<(Origin, Arc<Vec<FileState>>)>,
    mut state: watch::Receiver<crate::engine::SpaceStatus>,
) {
    let mut need_pass = true;
    let mut backoff = Duration::from_secs(1);
    let mut live = state.borrow().state == SyncState::Live;
    loop {
        if need_pass {
            s.set(|st| st.busy = true);
            match s.pass().await {
                Ok(()) => {
                    need_pass = false;
                    backoff = Duration::from_secs(1);
                    s.set(|st| {
                        st.ready = true;
                        st.error = None;
                    });
                }
                Err(e) => {
                    tracing::debug!(error = %e, "file mirror pass failed");
                    s.set(|st| st.error = Some(e));
                }
            }
            s.set(|st| st.busy = false);
        }
        let retry = tokio::time::sleep(if need_pass { backoff } else { Duration::from_secs(86_400) });
        tokio::select! {
            r = files.recv() => match r {
                Ok((Origin::Local, changed)) => {
                    // This app's own puts (also through `Files::put_file`): known, not downloaded.
                    for f in changed.iter().filter(|f| !f.deleted && f.path.starts_with(&s.prefix)) {
                        s.remember(&f.path, Known::of(f));
                    }
                }
                Ok((_, changed)) => {
                    for f in changed.iter() {
                        if let Err(e) = s.remote_change(f).await {
                            tracing::debug!(error = %e, path = %f.path, "file mirror download failed");
                            s.set(|st| st.error = Some(e));
                            need_pass = true;
                        }
                    }
                    s.set(|st| st.busy = false);
                }
                Err(broadcast::error::RecvError::Lagged(_)) => need_pass = true,
                Err(broadcast::error::RecvError::Closed) => break,
            },
            r = state.changed() => {
                if r.is_err() {
                    break;
                }
                let now = state.borrow().state == SyncState::Live;
                if now && !live {
                    need_pass = true; // reconnected: catch up on anything missed
                }
                live = now;
            }
            _ = retry => backoff = (backoff * 2).min(Duration::from_secs(60)),
        }
    }
}

/// `""` or `"a/b/"`.
fn normalize_prefix(prefix: &str) -> Result<String> {
    let p = prefix.trim_start_matches('/');
    if p.is_empty() {
        return Ok(String::new());
    }
    let p = if p.ends_with('/') { p.to_string() } else { format!("{p}/") };
    if p[..p.len() - 1].split('/').any(|seg| !safe_segment(seg)) {
        return Err(Error::config(format!("bad mirror prefix {prefix:?}")));
    }
    Ok(p)
}

fn safe_segment(seg: &str) -> bool {
    !seg.is_empty() && seg != "." && seg != ".." && !seg.contains(['\\', ':', '\0'])
}

/// The folder-relative path of a space path under `prefix`, if it is a plain
/// relative path (no `..`, no absolute or drive paths): a server can't write
/// outside the folder.
fn remote_to_rel(prefix: &str, path: &str) -> Option<PathBuf> {
    let rest = path.strip_prefix(prefix)?;
    if rest.is_empty() || !rest.split('/').all(safe_segment) {
        return None;
    }
    Some(rest.split('/').collect())
}

fn local_to_remote(prefix: &str, rel: &Path) -> Option<String> {
    let mut segs = Vec::new();
    for c in rel.components() {
        match c {
            Component::Normal(s) => {
                let s = s.to_str()?;
                if !safe_segment(s) {
                    return None;
                }
                segs.push(s);
            }
            Component::CurDir => {}
            _ => return None,
        }
    }
    (!segs.is_empty()).then(|| format!("{prefix}{}", segs.join("/")))
}

/// Regular files under `dir`, skipping dot-files, symlinks and partial downloads.
fn walk(dir: &Path, out: &mut Vec<PathBuf>) -> std::io::Result<()> {
    for e in std::fs::read_dir(dir)? {
        let e = e?;
        let name = e.file_name();
        let name = name.to_string_lossy();
        if name.starts_with('.') {
            continue;
        }
        let ty = e.file_type()?;
        let path = e.path();
        if ty.is_dir() {
            walk(&path, out)?;
        } else if ty.is_file() && path.extension().is_none_or(|x| x != PARTIAL) {
            out.push(path);
        }
    }
    Ok(())
}

/// A MIME type from the file extension.
pub(crate) fn mime_type(path: &str) -> &'static str {
    let ext = path.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default();
    match ext.as_str() {
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "gif" => "image/gif",
        "webp" => "image/webp",
        "svg" => "image/svg+xml",
        "heic" => "image/heic",
        "pdf" => "application/pdf",
        "txt" | "log" => "text/plain",
        "md" => "text/markdown",
        "csv" => "text/csv",
        "html" | "htm" => "text/html",
        "json" => "application/json",
        "zip" => "application/zip",
        "mp3" => "audio/mpeg",
        "m4a" => "audio/mp4",
        "mp4" => "video/mp4",
        "mov" => "video/quicktime",
        _ => "application/octet-stream",
    }
}

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

    #[test]
    fn paths_map_both_ways_and_never_escape_the_folder() {
        assert_eq!(normalize_prefix("attachments").unwrap(), "attachments/");
        assert_eq!(normalize_prefix("/a/b/").unwrap(), "a/b/");
        assert_eq!(normalize_prefix("").unwrap(), "");
        assert!(normalize_prefix("a/../b").is_err());
        assert_eq!(remote_to_rel("att/", "att/x/y.png"), Some(PathBuf::from("x").join("y.png")));
        for bad in ["att/../etc/passwd", "att/", "att//x", "att/./x", "other/x", "att/C:x", "att/a\\..\\b"] {
            assert_eq!(remote_to_rel("att/", bad), None, "{bad}");
        }
        assert_eq!(local_to_remote("att/", Path::new("x/y.png")).as_deref(), Some("att/x/y.png"));
        assert_eq!(local_to_remote("att/", Path::new("../y.png")), None);
        assert_eq!(mime_type("att/A.PNG"), "image/png");
    }
}