diff --git a/crates/daemon/src/dbus.rs b/crates/daemon/src/dbus.rs index 3c7c9e9..4971e48 100644 --- a/crates/daemon/src/dbus.rs +++ b/crates/daemon/src/dbus.rs @@ -18,6 +18,9 @@ pub struct OneDriveInterface { pub needs_auth: Arc, pub progress: ProgressText, pub quota: crate::quota::QuotaCache, + /// Edits waiting out their quiet period in the FUSE layer. `None` when not + /// running on-demand, where there is no such queue. + pub pending_uploads: Option>, } #[interface(name = "com.onedrive.linux1")] @@ -92,10 +95,19 @@ impl OneDriveInterface { Ok(self.progress.lock().clone()) } - /// How many uploads are queued for retry. Non-zero means edits exist that - /// have not reached OneDrive yet. + /// How many edits have not reached OneDrive yet. + /// + /// Both kinds count: uploads queued for retry after a failure, and edits + /// still waiting out their quiet period. With a debounce of any length the + /// second kind is the common one, and leaving it out would show "everything + /// synced" over work that is still only on this machine. async fn pending_uploads(&self) -> zbus::fdo::Result { - Ok(self.engine.pending_uploads().await as u32) + let queued = self.engine.pending_uploads().await as u32; + let waiting = match &self.pending_uploads { + Some(pending) => pending.count().await as u32, + None => 0, + }; + Ok(queued + waiting) } /// Bytes the on-demand cache is currently using. @@ -200,6 +212,7 @@ pub async fn export_dbus( recent: RecentBuffer, needs_auth: Arc, progress: ProgressText, + pending_uploads: Option>, ) -> anyhow::Result { // The interface reaches Graph only through this cache. let quota = crate::quota::QuotaCache::new(graph); @@ -213,6 +226,7 @@ pub async fn export_dbus( needs_auth, progress, quota, + pending_uploads, }, ) .await?; diff --git a/crates/daemon/src/main.rs b/crates/daemon/src/main.rs index e204ae7..0cb7c59 100644 --- a/crates/daemon/src/main.rs +++ b/crates/daemon/src/main.rs @@ -13,6 +13,10 @@ use sync_engine::{Config, Database, SyncEngine}; use tracing::{error, info}; use tracing_subscriber::EnvFilter; +/// How long shutdown waits for queued edits to reach OneDrive. Long enough for +/// a slow link to finish a reasonable file, short enough not to hang a reboot. +const FLUSH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60); + /// The release this binary was built from — see the same constant in odctl. const VERSION: &str = match option_env!("ONEDRIVE_RELEASE_VERSION") { Some(v) => v, @@ -129,6 +133,9 @@ async fn main() -> Result<()> { .context("start sync engine")?; // ── FUSE VFS ─────────────────────────────────────────────────────────────── + // Taken before the session consumes the filesystem, so shutdown can flush + // whatever is still waiting out its debounce. + let mut pending_uploads = None; let mount_handle = if config.on_demand { let mountpoint = config.sync_dir.clone(); vfs::prepare_mountpoint(&mountpoint).context("prepare mountpoint")?; @@ -139,9 +146,17 @@ async fn main() -> Result<()> { mountpoint.clone(), cache_dir(), config.excluded_patterns.clone(), + std::time::Duration::from_secs(config.upload_debounce_secs), ) .await .context("create FUSE filesystem")?; + pending_uploads = Some(fs.pending_uploads()); + if config.upload_debounce_secs > 0 { + info!( + "Edits upload after {}s of quiet — flushed on shutdown", + config.upload_debounce_secs + ); + } let mount_options = MountOptions::default(); let handle = Session::new(mount_options) @@ -216,6 +231,7 @@ async fn main() -> Result<()> { Arc::clone(&recent), Arc::clone(&needs_auth), Arc::clone(&progress), + pending_uploads.clone(), ) .await { @@ -247,6 +263,29 @@ async fn main() -> Result<()> { } // ── Graceful shutdown ────────────────────────────────────────────────────── + // Before anything else: an edit still waiting out its debounce exists only + // on this machine. Shutting down without sending it would make the wait a + // way to lose work rather than a way to avoid races. + if let Some(pending) = &pending_uploads { + let waiting = pending.count().await; + if waiting > 0 { + info!("Sending {waiting} edit(s) still waiting to upload…"); + pending.flush_now().await; + if pending.wait_idle(FLUSH_TIMEOUT).await { + info!("All edits uploaded"); + } else { + // Not lost: they are in the cache and the queue, and the next + // start picks them up. Worth saying out loud all the same. + error!( + "Gave up waiting after {}s with {} edit(s) unsent — they are \ + still cached and will upload on next start", + FLUSH_TIMEOUT.as_secs(), + pending.count().await + ); + } + } + } + if let Some(handle) = mount_handle { info!("Unmounting FUSE..."); if let Err(e) = handle.unmount().await { diff --git a/crates/sync-engine/src/config.rs b/crates/sync-engine/src/config.rs index aa03a9e..8999faf 100644 --- a/crates/sync-engine/src/config.rs +++ b/crates/sync-engine/src/config.rs @@ -52,6 +52,18 @@ fn default_max_cache_size_gb() -> f64 { 10.0 } +/// How long a file must go untouched before its edit is uploaded. +/// +/// Uploading the instant a file closes made the mount race itself: an atomic +/// save uploads a temp file it is about to rename away, a scratch file races +/// its own delete, and an editor saving repeatedly starts an upload per save. +/// Waiting for quiet removes all of that — at the cost of the edit living only +/// on this machine until the wait is up, which is why the daemon flushes the +/// queue before it shuts down. +fn default_upload_debounce_secs() -> u64 { + 900 +} + fn default_auth_method() -> String { "auto".into() } @@ -102,6 +114,12 @@ pub struct Config { #[serde(default = "default_max_cache_size_gb")] pub max_cache_size_gb: f64, + /// Seconds a file must go untouched before its edit is uploaded. `0` + /// uploads as soon as the file is closed, which is what the client used to + /// do — see [`default_upload_debounce_secs`] for why that was a problem. + #[serde(default = "default_upload_debounce_secs")] + pub upload_debounce_secs: u64, + /// How to sign in: "auto" (browser when a desktop session is present), /// "browser" (authorization code + PKCE — required when Conditional /// Access blocks the device code flow), or "device_code". @@ -159,6 +177,7 @@ impl Config { max_download_threads: 4, delta_poll_interval_secs: 30, max_cache_size_gb: default_max_cache_size_gb(), + upload_debounce_secs: default_upload_debounce_secs(), auth_method: default_auth_method(), }; cfg.save() diff --git a/crates/sync-engine/src/engine/delta.rs b/crates/sync-engine/src/engine/delta.rs index 52e31d0..90e9691 100644 --- a/crates/sync-engine/src/engine/delta.rs +++ b/crates/sync-engine/src/engine/delta.rs @@ -644,6 +644,7 @@ mod delta_tests { max_download_threads: 1, delta_poll_interval_secs: 30, max_cache_size_gb: 10.0, + upload_debounce_secs: 0, auth_method: "device_code".into(), }); let dir = tempfile::tempdir().unwrap(); diff --git a/crates/vfs/Cargo.toml b/crates/vfs/Cargo.toml index 8b50c12..d6986ae 100644 --- a/crates/vfs/Cargo.toml +++ b/crates/vfs/Cargo.toml @@ -18,6 +18,8 @@ bytes = "1" chrono.workspace = true [dev-dependencies] +# start_paused: the debounce tests must not actually wait 15 minutes. +tokio = { workspace = true, features = ["test-util"] } graph-client = { path = "../graph-client", features = ["test-util"] } wiremock = "0.6" tempfile = "3" diff --git a/crates/vfs/src/filesystem.rs b/crates/vfs/src/filesystem.rs index f360421..ed0c8a7 100644 --- a/crates/vfs/src/filesystem.rs +++ b/crates/vfs/src/filesystem.rs @@ -104,6 +104,10 @@ pub struct OneDriveFS { symlink_inodes: RwLock>, /// (parent_inode, name) → symlink inode for fast lookup symlink_lookup: RwLock>, + /// Edits waiting out their quiet period before upload. + pending: Arc, + /// How long a file must go untouched before its edit is uploaded. + upload_debounce: std::time::Duration, } impl OneDriveFS { @@ -113,6 +117,7 @@ impl OneDriveFS { sync_dir: std::path::PathBuf, cache_dir: std::path::PathBuf, excluded_patterns: Vec, + upload_debounce: std::time::Duration, ) -> anyhow::Result { std::fs::create_dir_all(&cache_dir) .map_err(|e| anyhow::anyhow!("create cache dir {:?}: {e}", cache_dir))?; @@ -137,9 +142,19 @@ impl OneDriveFS { root_drive_id: RwLock::new(root_drive_id), symlink_inodes: RwLock::new(BTreeMap::new()), symlink_lookup: RwLock::new(BTreeMap::new()), + pending: Arc::new(crate::pending::PendingUploads::new()), + upload_debounce, }) } + /// The queue of edits waiting to upload. + /// + /// Taken before the filesystem is handed to the FUSE session, which + /// consumes it — the daemon needs this to flush on shutdown. + pub fn pending_uploads(&self) -> Arc { + Arc::clone(&self.pending) + } + fn next_fh(&self) -> u64 { self.fh_counter.fetch_add(1, Ordering::SeqCst) } @@ -345,19 +360,29 @@ impl OneDriveFS { } /// Resolve current attributes for any inode: root, regular item, or symlink. + /// The row behind an inode. + /// + /// The inode lock is held across the query on purpose. An upload that + /// adopts the real OneDrive ID has to move the row from the temporary + /// `_local_*` ID to the real one, and `local_path` is unique, so the two + /// rows can never both exist — read the ID, then query, and a swap that + /// lands between the two makes a file the user just wrote look deleted. + /// + /// Adoption takes the same lock for writing across its own update, so a + /// reader sees either the whole "before" or the whole "after". + async fn resolve_item(&self, inode: u64) -> Option { + let map = self.inodes.read().await; + let item_id = map.get(&inode).map(|e| e.item_id.clone())?; + self.db.get_item_by_id(&item_id).await.ok().flatten() + } + async fn attr_for_inode(&self, inode: u64) -> Option { if inode == 1 { return Some(self.root_attr()); } - let item_id = { - let map = self.inodes.read().await; - map.get(&inode).map(|e| e.item_id.clone()) - }; - if let Some(id) = item_id { - if let Ok(Some(item)) = self.db.get_item_by_id(&id).await { - return Some(self.db_item_to_attr(&item, inode)); - } + if let Some(item) = self.resolve_item(inode).await { + return Some(self.db_item_to_attr(&item, inode)); } let map = self.symlink_inodes.read().await; @@ -753,18 +778,8 @@ impl Filesystem for OneDriveFS { async fn open(&self, _req: Request, inode: u64, flags: u32) -> FuseResult { debug!("open inode={inode} flags={flags:#o}"); - let item_id = { - let map = self.inodes.read().await; - map.get(&inode).map(|e| e.item_id.clone()) - }; - let item_id = item_id.ok_or(libc::ENOENT)?; - - let item = self - .db - .get_item_by_id(&item_id) - .await - .map_err(|_| libc::EIO)? - .ok_or(libc::ENOENT)?; + let item = self.resolve_item(inode).await.ok_or(libc::ENOENT)?; + let item_id = item.id.clone(); // Cache file lives OUTSIDE the FUSE mountpoint to avoid recursive FUSE calls. let cache_path = self.cache_dir.join(&item_id); @@ -932,10 +947,58 @@ impl Filesystem for OneDriveFS { let cache_dir = self.cache_dir.clone(); let inodes = Arc::clone(&self.inodes); let id_to_inode = Arc::clone(&self.id_to_inode); + let pending = Arc::clone(&self.pending); + + // Wait for the file to go quiet first. An atomic save closes + // a temp file it is about to rename away; a scratch file may + // be deleted seconds later; an editor may save ten times in + // a minute. Uploading on close made all three race their own + // upload. Waiting means the upload sees the settled result. + let waiter_id = id.clone(); + let scheduled = pending.schedule(&waiter_id, self.upload_debounce).await; + // release() is asynchronous with respect to close(), so an + // unlink of this file can land between the row check above + // and the schedule above. It would cancel an entry that did + // not exist yet, and this one would then sit out the whole + // window for a file that is gone — never uploading, since it + // re-reads the row first, but counting as unsent the whole + // time. Re-check now that the entry is in. + if self + .db + .get_item_by_id(&waiter_id) + .await + .ok() + .flatten() + .is_none() + { + pending.cancel(&waiter_id).await; + return Ok(()); + } + if !scheduled { + // Already waiting — that call just pushed its deadline + // out, and the existing waiter will upload the newer + // content from the same cache file. + return Ok(()); + } // Upload in background — release() must return immediately so // the kernel doesn't block the calling process (e.g. Dolphin). tokio::spawn(async move { + if !pending.wait_until_due(&waiter_id).await { + debug!("upload of {waiter_id} cancelled while waiting"); + return; + } + let _in_flight = pending.begin_upload(&waiter_id).await; + + // Re-read: the file has had the whole quiet period to be + // renamed, and the name is what the upload is addressed by. + let item = match db.get_item_by_id(&waiter_id).await { + Ok(Some(current)) => current, + _ => { + debug!("{waiter_id} no longer exists — nothing to upload"); + return; + } + }; if let Some(parent_id) = item.parent_id.clone() { // If-Match on the ETag we last synced. Without it an // upload is last-writer-wins: a file changed on @@ -1064,10 +1127,59 @@ impl Filesystem for OneDriveFS { // so one created file could stop sync dead. let old_id = std::mem::replace(&mut updated_item.id, updated.id.clone()); - if old_id != updated_item.id { + let adopted = old_id != updated_item.id; + if adopted { + // The row moves to the new ID *before* the + // cache file does. + // + // Renaming first left a window where the + // row still said `_local_*` and its cache + // file was already gone — which a read + // landing there treats as a file with no + // content anywhere, and drops the row for. + // A file could vanish moments after being + // written, purely because it happened to be + // uploading at the time. + // + // Moving the row first makes the window + // harmless: the ID is real, so a read + // inside it fetches from OneDrive, which + // now holds the content. + // Both halves of the swap under the + // inode lock, which resolve_item holds + // across its query — so no read can land + // between the row moving and the inode + // following it. + { + let mut entries = inodes.write().await; + // Re-read once more, inside the lock. + // The earlier read was before a network + // call; a rename landing since then + // would otherwise be overwritten by the + // name this upload started with, and + // the saved file would look missing + // until the next delta. + if let Ok(Some(latest)) = + db.get_item_by_id(&old_id).await + { + updated_item.name = latest.name; + updated_item.local_path = latest.local_path; + updated_item.parent_id = latest.parent_id; + } + if let Err(e) = db.upsert_item(&updated_item).await { + error!("Failed to adopt the real ID: {e}"); + } + let mut ids = id_to_inode.write().await; + if let Some(ino) = ids.remove(&old_id) { + ids.insert(updated_item.id.clone(), ino); + if let Some(entry) = entries.get_mut(&ino) { + entry.item_id = updated_item.id.clone(); + } + } + } // The cache file is named after the ID, so // it has to move with it or the next open() - // finds nothing and the file reads as EIO. + // re-fetches content we already have. let new_cache = cache_dir.join(&updated_item.id); if let Err(e) = std::fs::rename(&cache_path, &new_cache) { error!( @@ -1076,22 +1188,13 @@ impl Filesystem for OneDriveFS { old_id, updated_item.id ); } - // Repoint the inode the kernel already - // handed out; it must keep resolving. - let mut ids = id_to_inode.write().await; - if let Some(ino) = ids.remove(&old_id) { - ids.insert(updated_item.id.clone(), ino); - if let Some(entry) = inodes.write().await.get_mut(&ino) - { - entry.item_id = updated_item.id.clone(); - } - } } - // `upsert_item` evicts whatever else owns this - // path, which is how the old `_local_*` row goes. - if let Err(e) = db.upsert_item(&updated_item).await { - error!("Failed to upsert item after upload: {e}"); + // Already written above when adopting a new ID. + if !adopted { + if let Err(e) = db.upsert_item(&updated_item).await { + error!("Failed to upsert item after upload: {e}"); + } } info!( "upload complete: {} ({} bytes)", @@ -1271,6 +1374,13 @@ impl Filesystem for OneDriveFS { if let Err(e) = self.db.delete_item(&item.id).await { warn!("Failed to delete DB item {}: {e}", item.id); } + // Drop any edit still waiting to upload — otherwise the wait expires + // after the file is gone and puts it back. + // + // Deliberately after the row is deleted, so this and release()'s + // re-check cover each other: whichever of the two runs last finds + // the state the other left and cleans up. + self.pending.cancel(&item.id).await; // Remove the cache file if present. Do NOT touch item.local_path — it is // inside the FUSE mount and accessing it from the daemon causes a recursive // FUSE deadlock. The kernel removes the FUSE entry when we return Ok(()). diff --git a/crates/vfs/src/lib.rs b/crates/vfs/src/lib.rs index 3689186..f2f3288 100644 --- a/crates/vfs/src/lib.rs +++ b/crates/vfs/src/lib.rs @@ -1,5 +1,7 @@ pub mod filesystem; pub mod mount; +pub mod pending; pub use filesystem::OneDriveFS; pub use mount::{is_mounted, prepare_mountpoint, unmount}; +pub use pending::PendingUploads; diff --git a/crates/vfs/src/pending.rs b/crates/vfs/src/pending.rs new file mode 100644 index 0000000..95d1920 --- /dev/null +++ b/crates/vfs/src/pending.rs @@ -0,0 +1,284 @@ +//! Edits waiting out a quiet period before they are uploaded. +//! +//! Uploading the instant a file is closed is what made the mount fragile. An +//! atomic save — write a temp file, rename it over the target — closes the temp +//! file first, so the upload started under a name the file was about to stop +//! having. A file written and deleted seconds later raced its own upload. Rapid +//! saves of one file each started their own upload, and they collided with each +//! other on the way out. +//! +//! Waiting for a file to go quiet removes all of that at the source: by the +//! time the upload starts, the temp file has become the real one, the deleted +//! file is gone, and the ten saves have become one. +//! +//! What it costs is exactly as long as the wait: an edit lives only on this +//! machine until then. That is why [`PendingUploads::flush_now`] exists and why +//! the daemon calls it before shutting down — a restart must not take the wait +//! with it. + +use std::collections::{HashMap, HashSet}; +use std::time::Duration; +use tokio::sync::{Mutex, Notify}; +use tokio::time::Instant; + +#[derive(Default)] +struct State { + /// Item ID → when its upload becomes due. Rewriting a file pushes this out. + due: HashMap, + /// Item IDs whose upload has started, kept until it finishes so a flush can + /// wait for the bytes to actually land rather than merely to be sent. + in_flight: HashSet, +} + +#[derive(Default)] +pub struct PendingUploads { + state: Mutex, + /// Woken whenever a deadline moves, an entry is cancelled, or one finishes. + changed: Notify, +} + +impl PendingUploads { + pub fn new() -> Self { + Self::default() + } + + /// Note that `item_id` has an edit to upload once it has been quiet for + /// `delay`. + /// + /// Returns whether the caller should spawn a waiter. A second edit of a + /// file already waiting just pushes its deadline out — which is the whole + /// point, and is why an editor that saves continuously produces one upload + /// rather than one per save. + pub async fn schedule(&self, item_id: &str, delay: Duration) -> bool { + let mut state = self.state.lock().await; + let due_at = Instant::now() + delay; + let is_new = !state.due.contains_key(item_id); + state.due.insert(item_id.to_string(), due_at); + drop(state); + self.changed.notify_waiters(); + is_new + } + + /// Block until this item's edit is due to upload. + /// + /// Returns false if it was cancelled while waiting — the file was deleted, + /// and uploading it now would put it back. + pub async fn wait_until_due(&self, item_id: &str) -> bool { + loop { + // Registered before the deadline is read, so a deadline moved + // between the two is still seen. Missing that wakeup would leave + // the waiter asleep on a deadline nobody is going to honour. + let changed = self.changed.notified(); + + let due_at = match self.state.lock().await.due.get(item_id) { + Some(due_at) => *due_at, + None => return false, + }; + if due_at <= Instant::now() { + return true; + } + + tokio::select! { + _ = tokio::time::sleep_until(due_at) => {} + _ = changed => {} + } + } + } + + /// Move an item from waiting to uploading. The returned guard keeps it + /// counted until dropped. + pub async fn begin_upload(self: &std::sync::Arc, item_id: &str) -> UploadGuard { + let mut state = self.state.lock().await; + state.due.remove(item_id); + state.in_flight.insert(item_id.to_string()); + drop(state); + self.changed.notify_waiters(); + UploadGuard { + pending: std::sync::Arc::clone(self), + item_id: item_id.to_string(), + } + } + + /// Drop a waiting edit — the file it belongs to no longer exists. + pub async fn cancel(&self, item_id: &str) { + let removed = self.state.lock().await.due.remove(item_id).is_some(); + if removed { + self.changed.notify_waiters(); + } + } + + /// Bring every waiting edit due immediately. + /// + /// The wait is a convenience, never a promise to hold data back. Anything + /// that ends the session — shutting down, unmounting, the user asking — + /// calls this first, so the longest an edit can be stranded on this machine + /// is the debounce, not the time until the next launch. + pub async fn flush_now(&self) { + let mut state = self.state.lock().await; + let now = Instant::now(); + for due_at in state.due.values_mut() { + *due_at = now; + } + drop(state); + self.changed.notify_waiters(); + } + + /// Wait until nothing is queued or uploading, giving up after `timeout`. + /// Returns whether it drained. + pub async fn wait_idle(&self, timeout: Duration) -> bool { + let deadline = Instant::now() + timeout; + loop { + let changed = self.changed.notified(); + if self.count().await == 0 { + return true; + } + if Instant::now() >= deadline { + return false; + } + tokio::select! { + _ = tokio::time::sleep_until(deadline) => {} + _ = changed => {} + } + } + } + + /// Whether this item has an upload waiting or in flight. + /// + /// An upload rewrites the cache file it is uploading from — adopting the + /// real OneDrive ID renames it — so "the cache file is missing" does not + /// mean "the content is gone" while one is running. + pub async fn is_active(&self, item_id: &str) -> bool { + let state = self.state.lock().await; + state.due.contains_key(item_id) || state.in_flight.contains(item_id) + } + + /// Edits waiting or in flight — what the UI means by "not yet uploaded". + pub async fn count(&self) -> usize { + let state = self.state.lock().await; + state.due.len() + state.in_flight.len() + } +} + +/// Keeps an upload counted as in flight until it finishes, however it finishes. +pub struct UploadGuard { + pending: std::sync::Arc, + item_id: String, +} + +impl Drop for UploadGuard { + fn drop(&mut self) { + let pending = std::sync::Arc::clone(&self.pending); + let item_id = std::mem::take(&mut self.item_id); + // Drop is not async; the removal is trivial and must not be skipped, so + // it goes on the runtime rather than blocking here. + tokio::spawn(async move { + pending.state.lock().await.in_flight.remove(&item_id); + pending.changed.notify_waiters(); + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + #[tokio::test(start_paused = true)] + async fn an_edit_waits_for_its_delay() { + let pending = Arc::new(PendingUploads::new()); + assert!(pending.schedule("a", Duration::from_secs(900)).await); + + let p = Arc::clone(&pending); + let waiter = tokio::spawn(async move { p.wait_until_due("a").await }); + + tokio::time::advance(Duration::from_secs(899)).await; + assert!(!waiter.is_finished(), "uploaded before it went quiet"); + + tokio::time::advance(Duration::from_secs(2)).await; + assert!(waiter.await.unwrap(), "the edit should have come due"); + } + + #[tokio::test(start_paused = true)] + async fn rewriting_pushes_the_deadline_out() { + let pending = Arc::new(PendingUploads::new()); + assert!(pending.schedule("a", Duration::from_secs(900)).await); + let p = Arc::clone(&pending); + let waiter = tokio::spawn(async move { p.wait_until_due("a").await }); + + tokio::time::advance(Duration::from_secs(800)).await; + // A second save of the same file — one upload, not two. + assert!( + !pending.schedule("a", Duration::from_secs(900)).await, + "a file already waiting must not get a second waiter" + ); + + tokio::time::advance(Duration::from_secs(200)).await; + assert!( + !waiter.is_finished(), + "the deadline did not move — the upload would carry a half-written file" + ); + + tokio::time::advance(Duration::from_secs(800)).await; + assert!(waiter.await.unwrap()); + } + + #[tokio::test(start_paused = true)] + async fn deleting_the_file_cancels_the_upload() { + let pending = Arc::new(PendingUploads::new()); + pending.schedule("a", Duration::from_secs(900)).await; + let p = Arc::clone(&pending); + let waiter = tokio::spawn(async move { p.wait_until_due("a").await }); + + tokio::time::advance(Duration::from_secs(10)).await; + pending.cancel("a").await; + + assert!( + !waiter.await.unwrap(), + "a deleted file must not upload — that is what put it back before" + ); + } + + #[tokio::test(start_paused = true)] + async fn flush_brings_everything_due_at_once() { + let pending = Arc::new(PendingUploads::new()); + for id in ["a", "b", "c"] { + pending.schedule(id, Duration::from_secs(900)).await; + } + let waiters: Vec<_> = ["a", "b", "c"] + .into_iter() + .map(|id| { + let p = Arc::clone(&pending); + tokio::spawn(async move { p.wait_until_due(id).await }) + }) + .collect(); + + tokio::time::advance(Duration::from_secs(1)).await; + pending.flush_now().await; + + for waiter in waiters { + assert!( + waiter.await.unwrap(), + "a flush must release every waiting edit — this is what stops a \ + restart taking the whole debounce window's work with it" + ); + } + } + + #[tokio::test(start_paused = true)] + async fn count_covers_waiting_and_uploading() { + let pending = Arc::new(PendingUploads::new()); + pending.schedule("a", Duration::from_secs(900)).await; + assert_eq!(pending.count().await, 1); + + let guard = pending.begin_upload("a").await; + assert_eq!( + pending.count().await, + 1, + "an upload in flight is still not on OneDrive" + ); + + drop(guard); + tokio::task::yield_now().await; + assert_eq!(pending.count().await, 0); + } +} diff --git a/crates/vfs/tests/mount_roundtrip.rs b/crates/vfs/tests/mount_roundtrip.rs index 5073ea5..70f49b6 100644 --- a/crates/vfs/tests/mount_roundtrip.rs +++ b/crates/vfs/tests/mount_roundtrip.rs @@ -80,6 +80,7 @@ fn test_config(sync_dir: &Path) -> Config { max_download_threads: 1, delta_poll_interval_secs: 3600, max_cache_size_gb: 0.0, + upload_debounce_secs: 0, auth_method: "device_code".into(), } } @@ -161,6 +162,27 @@ async fn await_upload(server: &MockServer, within: Duration) -> wiremock::Reques } } +/// Whether the saved file ended up on OneDrive under its real name — either +/// because the upload addressed it correctly, or because a rename corrected it +/// afterwards. Both are right; only the destination matters. +async fn await_named_correctly(server: &MockServer, within: Duration) -> bool { + let deadline = Instant::now() + within; + loop { + let requests = server.received_requests().await.unwrap_or_default(); + let landed = requests.iter().any(|r| { + (r.method.as_str() == "PUT" && r.url.path().contains("notes.md:")) + || r.method.as_str() == "PATCH" + }); + if landed { + return true; + } + if Instant::now() >= deadline { + return false; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } +} + /// Whether a request with the given method reached the server in time. async fn await_request(server: &MockServer, verb: &str, within: Duration) -> bool { let deadline = Instant::now() + within; @@ -230,6 +252,9 @@ async fn edit_through_the_mount_reaches_onedrive() { mountpoint.clone(), cache_dir.clone(), config.excluded_patterns.clone(), + // No debounce: these tests assert on what reaches OneDrive, and the + // debounce is covered by its own tests in `pending`. + Duration::ZERO, ) .await .expect("build filesystem"); @@ -381,6 +406,9 @@ async fn a_file_created_through_the_mount_is_readable_and_adopts_its_real_id() { mountpoint.clone(), cache_dir.clone(), config.excluded_patterns.clone(), + // No debounce: these tests assert on what reaches OneDrive, and the + // debounce is covered by its own tests in `pending`. + Duration::ZERO, ) .await .expect("build filesystem"); @@ -563,6 +591,9 @@ async fn deleting_a_file_while_its_upload_is_in_flight_makes_the_delete_win() { mountpoint.clone(), cache_dir.clone(), config.excluded_patterns.clone(), + // No debounce: these tests assert on what reaches OneDrive, and the + // debounce is covered by its own tests in `pending`. + Duration::ZERO, ) .await .expect("build filesystem"); @@ -579,20 +610,34 @@ async fn deleting_a_file_while_its_upload_is_in_flight_makes_the_delete_win() { }; let mp = mountpoint.clone(); - let result = tokio::task::spawn_blocking(move || { + let written = tokio::task::spawn_blocking(move || { use std::io::Write; - let file = mp.join("churn.bin"); - let mut fh = std::fs::File::create(&file).expect("create"); + let mut fh = std::fs::File::create(mp.join("churn.bin")).expect("create"); fh.write_all(NEW_CONTENT).expect("write"); drop(fh); - // Immediately, inside the upload window — the case that failed. - std::fs::remove_file(&file).expect("delete right after writing"); + }) + .await; + + // Delete only once the upload is genuinely in flight. The mock holds the + // PUT open for 2s, so waiting for the request to arrive puts the unlink + // squarely inside the window — rather than relying on it losing a race it + // is now designed to win. + let started = await_request(&server, "PUT", Duration::from_secs(15)).await; + let mp = mountpoint.clone(); + let result = tokio::task::spawn_blocking(move || { + let file = mp.join("churn.bin"); + std::fs::remove_file(&file).expect("delete while the upload is in flight"); assert!( !file.exists(), "the file must be gone the moment unlink() returns" ); }) .await; + written.expect("write through the mount"); + assert!( + started, + "the upload never started, so there was no window to test" + ); // Outlast the upload, so the completion path has run. let outcome = if result.is_ok() { @@ -669,7 +714,22 @@ async fn an_atomic_save_leaves_the_file_under_its_real_name() { ) .mount(&server) .await; - // Correcting the remote name is a PATCH on the item. + // The upload re-reads the row after waiting, so it often addresses the final + // name directly — the case the debounce is for. + Mock::given(method("PUT")) + .and(path_regex(r"^/me/drive/items/root:/notes\.md:/content$")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "id": "saved-item", + "name": "notes.md", + "eTag": "etag-final", + "size": NEW_CONTENT.len(), + "lastModifiedDateTime": "2026-01-05T00:00:01Z", + "file": { "mimeType": "text/markdown" }, + "parentReference": { "id": "root" } + }))) + .mount(&server) + .await; + // And when it does go out under the temp name, a PATCH corrects it. Mock::given(method("PATCH")) .and(path("/me/drive/items/saved-item")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ @@ -711,6 +771,9 @@ async fn an_atomic_save_leaves_the_file_under_its_real_name() { mountpoint.clone(), cache_dir.clone(), config.excluded_patterns.clone(), + // No debounce: these tests assert on what reaches OneDrive, and the + // debounce is covered by its own tests in `pending`. + Duration::ZERO, ) .await .expect("build filesystem"); @@ -755,11 +818,12 @@ async fn an_atomic_save_leaves_the_file_under_its_real_name() { // Let the in-flight upload finish and correct itself. let outcome = if result.is_ok() { - let renamed_remotely = await_request(&server, "PATCH", Duration::from_secs(15)).await; + // Either route is correct; what matters is where the file ends up. + let landed = await_named_correctly(&server, Duration::from_secs(15)).await; tokio::time::sleep(Duration::from_millis(500)).await; let row = db.get_item_by_id("saved-item").await.unwrap(); Some(( - renamed_remotely, + landed, row, mountpoint.join("notes.md").exists(), mountpoint.join("notes.md.tmp.194149").exists(), @@ -770,12 +834,11 @@ async fn an_atomic_save_leaves_the_file_under_its_real_name() { let _ = mount_handle.unmount().await; result.expect("filesystem operations through the mount"); - let (renamed_remotely, row, target_there, temp_there) = outcome.unwrap(); + let (landed, row, target_there, temp_there) = outcome.unwrap(); assert!( - renamed_remotely, - "the upload started under the temp name and was never corrected, so \ - OneDrive holds the file as `notes.md.tmp.194149` — the next delta renames \ - the local file back to that and the saved file disappears" + landed, + "OneDrive ended up holding the file as `notes.md.tmp.194149` — the next \ + delta renames the local file back to that and the saved file disappears" ); let row = row.expect("the saved file must still have a row"); assert_eq!( @@ -791,3 +854,104 @@ async fn an_atomic_save_leaves_the_file_under_its_real_name() { "the temp name came back — this is what made an edit look like data loss" ); } + +/// The debounce's actual payoff: a file written and deleted inside the quiet +/// period never reaches OneDrive at all. +/// +/// Before, every close started an upload immediately, so a scratch file raced +/// its own delete — and the fixes for that race are recovery, not prevention: +/// the file is created remotely and then removed again. Waiting for quiet means +/// there is nothing to recover from, and no request is spent either. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_file_deleted_inside_the_quiet_period_never_uploads() { + if !fuse_available() { + skip("no /dev/fuse or fusermount3 available"); + return; + } + + let tmp = tempfile::tempdir().unwrap(); + let mountpoint = tmp.path().join("mount"); + let cache_dir = tmp.path().join("cache"); + std::fs::create_dir_all(&mountpoint).unwrap(); + std::fs::create_dir_all(&cache_dir).unwrap(); + + let server = mock_graph().await; + let graph = test_graph(&server.uri(), tmp.path()); + let db = Arc::new(Database::open(&tmp.path().join("items.db")).unwrap()); + let config = Arc::new(test_config(&mountpoint)); + + let token = TokenSet { + access_token: "test-token".into(), + refresh_token: Some("refresh".into()), + expires_at: chrono::Utc::now() + chrono::Duration::hours(1), + token_type: "Bearer".into(), + scope: "Files.ReadWrite.All".into(), + }; + let auth = Arc::new(AuthManager::for_tests(token, tmp.path().join("t2.json"))); + let (engine, _events) = SyncEngine::new( + Arc::clone(&config), + Arc::clone(&db), + Arc::clone(&graph), + auth, + Some(cache_dir.clone()), + ); + engine.sync_once().await.expect("delta pass"); + + let fs = vfs::OneDriveFS::new( + Arc::clone(&db), + Arc::clone(&graph), + mountpoint.clone(), + cache_dir.clone(), + config.excluded_patterns.clone(), + // Long enough that the delete lands well inside it, short enough that a + // failing test does not hang. + Duration::from_secs(30), + ) + .await + .expect("build filesystem"); + let pending = fs.pending_uploads(); + + let mount_handle = match fuse3::raw::Session::new(fuse3::MountOptions::default()) + .mount_with_unprivileged(fs, &mountpoint) + .await + { + Ok(handle) => handle, + Err(e) => { + skip(&format!("could not mount FUSE: {e}")); + return; + } + }; + + let mp = mountpoint.clone(); + let result = tokio::task::spawn_blocking(move || { + use std::io::Write; + let file = mp.join("scratch.bin"); + let mut fh = std::fs::File::create(&file).expect("create"); + fh.write_all(NEW_CONTENT).expect("write"); + drop(fh); + std::fs::remove_file(&file).expect("delete inside the quiet period"); + }) + .await; + + let outcome = if result.is_ok() { + // No upload should ever be attempted, so there is nothing to wait for + // except the absence of one. + let uploaded = await_request(&server, "PUT", Duration::from_secs(3)).await; + Some((uploaded, pending.count().await)) + } else { + None + }; + let _ = mount_handle.unmount().await; + result.expect("filesystem operations through the mount"); + + let (uploaded, still_queued) = outcome.unwrap(); + assert!( + !uploaded, + "a file created and deleted inside the quiet period was uploaded anyway — \ + the wait is not preventing the race, only papering over it" + ); + assert_eq!( + still_queued, 0, + "the deleted file is still queued, so it will upload later and come back" + ); +}