mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-28 20:12:14 +01:00
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5c6360e6e7 | ||
|
|
9b541899ef | ||
|
|
8a5f3f9ae0 | ||
|
|
d0697b7fcc | ||
|
|
f32e1b2765 | ||
|
|
b43f46e582 | ||
|
|
d3b70f1ee6 | ||
|
|
30b6d27c74 | ||
|
|
d10b28b14f | ||
|
|
c25e17fa9f | ||
|
|
6c21a58acf | ||
|
|
ea29a260b0 | ||
|
|
8e9816919d | ||
|
|
ef5f832b0f |
No files matched your search
@@ -278,6 +278,12 @@ pub struct AppConfig {
|
||||
/// the field.
|
||||
#[serde(default)]
|
||||
pub local_first: Option<bool>,
|
||||
/// Send a file small enough, with its thumbnails, to fit 128 KiB in one
|
||||
/// request instead of three or more. `None` means on. `false` uploads
|
||||
/// every file in blocks, the way all files went before. Defaulted for
|
||||
/// configs predating the field.
|
||||
#[serde(default)]
|
||||
pub small_uploads: Option<bool>,
|
||||
/// Ask GitHub once a day whether a newer release is out, and say so in the
|
||||
/// desktop app. Off by default: GitHub then sees the address and version
|
||||
/// asking. Never used where a package manager installs updates (see
|
||||
@@ -1077,6 +1083,7 @@ mod tests {
|
||||
language: Some("de".to_string()),
|
||||
online_map: true,
|
||||
local_first: Some(false),
|
||||
small_uploads: Some(false),
|
||||
update_check: true,
|
||||
update_last_checked: Some(1_760_000_000),
|
||||
update_latest: Some("3.6.0".to_string()),
|
||||
@@ -1096,6 +1103,7 @@ mod tests {
|
||||
assert_eq!(decoded.update_latest.as_deref(), Some("3.6.0"));
|
||||
assert_eq!(decoded.language.as_deref(), Some("de"));
|
||||
assert_eq!(decoded.upload_limit, Some(500_000));
|
||||
assert_eq!(decoded.small_uploads, Some(false));
|
||||
assert_eq!(decoded.download_limit, None);
|
||||
assert_eq!(decoded.files_view, config.files_view);
|
||||
assert_eq!(decoded.photos_view, config.photos_view);
|
||||
|
||||
@@ -363,6 +363,19 @@ pub enum Verdict {
|
||||
/// Compiled ignore rules for one synced folder.
|
||||
pub struct IgnoreRules {
|
||||
matcher: Option<Gitignore>,
|
||||
/// A hash of the patterns the rules were built from, so a caller can tell
|
||||
/// whether they changed.
|
||||
source: u64,
|
||||
}
|
||||
|
||||
/// A hash of `globals` and the folder's ignore file, `file` (its name and
|
||||
/// text), in the order [`IgnoreRules::load`] reads them.
|
||||
fn rules_source(globals: &[String], file: Option<(&str, &[u8])>) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
globals.hash(&mut hasher);
|
||||
file.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
impl IgnoreRules {
|
||||
@@ -382,6 +395,7 @@ impl IgnoreRules {
|
||||
}
|
||||
}
|
||||
|
||||
let mut file = None;
|
||||
for name in IGNORE_FILE_NAMES {
|
||||
let path = root.join(name);
|
||||
if !path.is_file() {
|
||||
@@ -390,15 +404,24 @@ impl IgnoreRules {
|
||||
// `add` returns the first parse error but still takes the lines it
|
||||
// could read, so a bad line costs that line and nothing more.
|
||||
let _ = builder.add(&path);
|
||||
file = Some((*name, std::fs::read(&path).unwrap_or_default()));
|
||||
any = true;
|
||||
break;
|
||||
}
|
||||
let source = rules_source(
|
||||
globals,
|
||||
file.as_ref().map(|(name, text)| (*name, text.as_slice())),
|
||||
);
|
||||
|
||||
if !any {
|
||||
return Self { matcher: None };
|
||||
return Self {
|
||||
matcher: None,
|
||||
source,
|
||||
};
|
||||
}
|
||||
Self {
|
||||
matcher: builder.build().ok(),
|
||||
source,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -415,17 +438,32 @@ impl IgnoreRules {
|
||||
for line in text.lines() {
|
||||
any |= builder.add_line(Some(file.clone()), line).is_ok();
|
||||
}
|
||||
let source = rules_source(globals, Some((IGNORE_FILE_NAMES[0], text.as_bytes())));
|
||||
if !any {
|
||||
return Self { matcher: None };
|
||||
return Self {
|
||||
matcher: None,
|
||||
source,
|
||||
};
|
||||
}
|
||||
Self {
|
||||
matcher: builder.build().ok(),
|
||||
source,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rules matching nothing, for callers with no folder context.
|
||||
pub fn empty() -> Self {
|
||||
Self { matcher: None }
|
||||
Self {
|
||||
matcher: None,
|
||||
source: rules_source(&[], None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Identifies the patterns these rules were built from: rules loaded
|
||||
/// again from the same globals and the same ignore file give the same
|
||||
/// value. Only for comparing within one run of the daemon.
|
||||
pub fn source(&self) -> u64 {
|
||||
self.source
|
||||
}
|
||||
|
||||
/// Whether any rule is loaded. When false, [`is_ignored`](Self::is_ignored)
|
||||
|
||||
@@ -241,6 +241,13 @@ pub fn mount_once(mountpoint: Option<PathBuf>) -> Result<pdfs_fuse::MountOutcome
|
||||
let (client, session) = rt
|
||||
.block_on(auth::resume_client())
|
||||
.context("resume session (run `pdfs login` first)")?;
|
||||
// On unless the config turns it off: the one-request upload for small
|
||||
// files is new, and this lets it be switched off without a new build.
|
||||
let small_uploads = config.small_uploads.unwrap_or(true);
|
||||
if !small_uploads {
|
||||
tracing::info!("small files are uploaded in blocks: small_uploads is off in the config");
|
||||
}
|
||||
let client = client.with_small_file_upload(small_uploads);
|
||||
|
||||
// Token updates are persisted automatically in real-time. The SDK session has
|
||||
// a token refresh callback registered during `resume_client` that writes updated
|
||||
|
||||
@@ -80,6 +80,13 @@ pub(crate) struct DrainState {
|
||||
/// The node an upload has just put on Drive, from when the drain lets go
|
||||
/// of its blob until the tree has the node (`docs/BUGS.md` B170).
|
||||
pub(crate) landed: Arc<Mutex<HashMap<NodeUid, Node>>>,
|
||||
/// A landed create's placeholder stamp, by the uid Drive gave it, with the
|
||||
/// revision the create sealed. A write released while the create landed
|
||||
/// can be based on the placeholder: a local mtime and no revision id. Its
|
||||
/// bytes are the ones the create sent, so the drain reads that base as the
|
||||
/// sealed revision ([`placeholder_base`]). Dropped once a later upload of
|
||||
/// the file lands.
|
||||
pub(crate) placeholders: Arc<Mutex<HashMap<NodeUid, Baseline>>>,
|
||||
/// How long this node's last upload actually took, in milliseconds, with
|
||||
/// the time it was measured for eviction. Feeds
|
||||
/// [`Core::revision_debounce`]: a file that takes 30 seconds to send needs
|
||||
@@ -110,6 +117,7 @@ impl DrainState {
|
||||
unadopted: Arc::new(Mutex::new(HashMap::new())),
|
||||
sealed_unread: Arc::new(Mutex::new(HashMap::new())),
|
||||
landed: Arc::new(Mutex::new(HashMap::new())),
|
||||
placeholders: Arc::new(Mutex::new(HashMap::new())),
|
||||
upload_times: Arc::new(Mutex::new(HashMap::new())),
|
||||
upload_cancel: Arc::new(Mutex::new(HashMap::new())),
|
||||
landing_uploads: Arc::new(AtomicU64::new(0)),
|
||||
@@ -874,6 +882,29 @@ fn revision_changed(base: &Baseline, node: &Node) -> Option<String> {
|
||||
})
|
||||
}
|
||||
|
||||
/// `base` as the revision it was made against, for [`revision_changed`].
|
||||
///
|
||||
/// A base with no revision id whose stamp is a landed create's placeholder
|
||||
/// (`placeholder`) was taken from that placeholder by a write released while
|
||||
/// the create landed: the release had taken its handle out of the tree, so the
|
||||
/// rebase onto the landed node missed it, and it queued after the queued writes
|
||||
/// were rebased. The placeholder's bytes are the ones the create sent, so the
|
||||
/// base is the revision the create sealed. Compared by its local mtime instead,
|
||||
/// the write was a conflict copy of the file's own create whenever the server
|
||||
/// stamped the create a second later than the placeholder.
|
||||
fn placeholder_base(base: &Baseline, placeholder: Option<&Baseline>) -> Baseline {
|
||||
match placeholder {
|
||||
Some(created)
|
||||
if base.revision_id.is_none()
|
||||
&& created.mtime == base.mtime
|
||||
&& created.size == base.size =>
|
||||
{
|
||||
created.clone()
|
||||
}
|
||||
_ => base.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a queued write that found the remote moved on ([`revision_changed`]
|
||||
/// fired) is nonetheless a single-writer self-supersede rather than a foreign
|
||||
/// conflict — the remote sits at a revision this daemon sealed itself, so
|
||||
@@ -1808,6 +1839,27 @@ mod tests {
|
||||
assert!(revision_changed(&base, &remote).is_some());
|
||||
}
|
||||
|
||||
/// A write released while its file's create landed keeps the
|
||||
/// placeholder's base: the local mtime, a second before the server's
|
||||
/// stamp, and no revision id.
|
||||
#[test]
|
||||
fn a_write_based_on_a_landed_create_placeholder_is_not_a_conflict() {
|
||||
let placeholder = baseline(1_795_799_834, 28, None);
|
||||
let created = baseline(1_795_799_834, 28, Some("rev-create"));
|
||||
let landed = file_node(1_795_799_835, 28, Some("rev-create"));
|
||||
assert!(revision_changed(&placeholder, &landed).is_some());
|
||||
let base = placeholder_base(&placeholder, Some(&created));
|
||||
assert_eq!(revision_changed(&base, &landed), None);
|
||||
// Another device writing over the create is still a conflict.
|
||||
let edited = file_node(1_795_799_835, 28, Some("theirs"));
|
||||
assert!(revision_changed(&base, &edited).is_some());
|
||||
// A base with a revision of its own, or another stamp, is left alone.
|
||||
let other = baseline(1_795_799_830, 28, None);
|
||||
assert_eq!(placeholder_base(&other, Some(&created)), other);
|
||||
let revised = baseline(1_795_799_834, 28, Some("older"));
|
||||
assert_eq!(placeholder_base(&revised, Some(&created)), revised);
|
||||
}
|
||||
|
||||
/// The reported shape (docs/BUGS.md B113): a downloader creates a file
|
||||
/// through the mount, and the file is moved before its write drains. The
|
||||
/// move re-stamps the node's mtime on the server (1790955809 -> 1790956593),
|
||||
|
||||
@@ -651,6 +651,9 @@ impl Core {
|
||||
// B123).
|
||||
let remote = node.clone();
|
||||
self.stamp_pending_sizes(std::slice::from_mut(&mut node));
|
||||
// The placeholder as the tree has it, before the landed node replaces
|
||||
// it: the base of a write that opened over it (`placeholder_base`).
|
||||
let mut placeholder = None;
|
||||
// The rows and queued ops already follow the node: `retire_create`
|
||||
// moved its row to the real uid, and ops find it by local id.
|
||||
|
||||
@@ -673,6 +676,11 @@ impl Core {
|
||||
node.parent_uid = e.node.parent_uid.clone();
|
||||
}
|
||||
st.write_through(node.clone());
|
||||
if let Some(e) = st.entries.get(&ino)
|
||||
&& node_revision_id(&e.node).is_none()
|
||||
{
|
||||
placeholder.get_or_insert((e.node.modification_time, node_size(&e.node)));
|
||||
}
|
||||
let mut landed = node.clone();
|
||||
st.keep_open_write_size(ino, &mut landed);
|
||||
if let Some(e) = st.entries.get_mut(&ino) {
|
||||
@@ -719,6 +727,25 @@ impl Core {
|
||||
{
|
||||
warn!(%real, error = %e, "persisting our sealed revision failed");
|
||||
}
|
||||
// A release that took its handle out of the tree before the rebase
|
||||
// below and queues after `rebaseline_pending` is caught by neither,
|
||||
// and an incomplete write does not chain onto our own revision. Its
|
||||
// base is the placeholder, whose bytes the create sent.
|
||||
if let Some((mtime, size)) = placeholder
|
||||
&& mtime != remote.modification_time
|
||||
&& size == node_size(&remote)
|
||||
&& let Some(rev) = node_revision_id(&remote)
|
||||
{
|
||||
self.drain.placeholders.lock().insert(
|
||||
real.clone(),
|
||||
Baseline {
|
||||
mtime,
|
||||
size,
|
||||
hash: None,
|
||||
revision_id: Some(rev),
|
||||
},
|
||||
);
|
||||
}
|
||||
self.rebase_open_writes(real, &remote);
|
||||
// A write carried over from the create was made against no revision at
|
||||
// all; the one just created is what it now replaces.
|
||||
|
||||
@@ -116,6 +116,8 @@ impl Core {
|
||||
if node.trashed {
|
||||
return Ok(Some("the file was trashed remotely".into()));
|
||||
}
|
||||
let placeholder = self.drain.placeholders.lock().get(uid).cloned();
|
||||
let base = &placeholder_base(base, placeholder.as_ref());
|
||||
let Some(reason) = revision_changed(base, &node) else {
|
||||
return Ok(None);
|
||||
};
|
||||
@@ -511,6 +513,8 @@ impl Core {
|
||||
if fetched.is_ok() {
|
||||
self.drain.sealed_unread.lock().remove(uid);
|
||||
}
|
||||
// This upload went after any write based on the create's placeholder.
|
||||
self.drain.placeholders.lock().remove(uid);
|
||||
let node = match fetched {
|
||||
Ok(Some(node)) => node,
|
||||
// Trashed or deleted under us: the tree will hear it from the event
|
||||
|
||||
@@ -61,6 +61,7 @@ impl Core {
|
||||
if let Err(e) = self.db.clear_own_sealed_rev(&uid.to_string()) {
|
||||
debug!(%uid, error = %e, "clearing the sealed-revision record failed");
|
||||
}
|
||||
self.drain.placeholders.lock().remove(&uid);
|
||||
self.invalidate_trash();
|
||||
self.log_activity(ActivityKind::Trash, &name, "trashed", true);
|
||||
info!(%uid, name, "pending trash landed");
|
||||
|
||||
@@ -1963,12 +1963,16 @@ mod tests {
|
||||
.map_or(0, |c| c.value)
|
||||
}
|
||||
|
||||
/// What the watcher reports covers every change a pass then finds on
|
||||
/// disk: an edit, a new folder with a file in it, a deletion, and a folder
|
||||
/// moved in from outside with a folder and a file in it (`local_dirty`).
|
||||
/// Once the watch has been live for a pass, a pass reads again only what
|
||||
/// the watcher reported, and that is enough to find every change: an
|
||||
/// edit, a new folder with a file in it, a deletion, and a folder moved in
|
||||
/// from outside with a folder and a file in it (`local_dirty`).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn the_local_dirty_set_covers_what_the_walk_finds() {
|
||||
fn a_trusted_local_dirty_set_stands_in_for_the_walk() {
|
||||
// The log is shared by every test in the process: drop what earlier
|
||||
// tests left in it, so only this daemon's lines are counted.
|
||||
take_logged();
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("local-dirty");
|
||||
let (daemon, folder, _client) =
|
||||
@@ -1978,6 +1982,7 @@ mod tests {
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
let settled = quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
assert_eq!(counted(&settled, "local dirty untrusted"), 0, "{settled}");
|
||||
assert!(counted(&settled, "local reused") > 0, "{settled}");
|
||||
|
||||
let local = dir.join("local");
|
||||
let outside = dir.join("outside");
|
||||
@@ -1995,6 +2000,9 @@ mod tests {
|
||||
}));
|
||||
let after = quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
assert_eq!(counted(&after, "local dirty untrusted"), 0, "{after}");
|
||||
// Still taken from the last pass's walk: none of the passes since
|
||||
// changed anything on disk, so each kept its walk for the next.
|
||||
assert!(counted(&after, "local reused") > 0, "{after}");
|
||||
let logged = take_logged();
|
||||
let missed: Vec<&String> = logged
|
||||
.iter()
|
||||
@@ -2015,6 +2023,190 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A sync root moved away and made again in its place is a new folder
|
||||
/// on disk, which the old watch does not see. The engine watches it again
|
||||
/// once it is back, and walks it once more after, so a file written in
|
||||
/// it as the watch was set up still reaches Drive without waiting for the
|
||||
/// poll (`root`).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_root_made_again_is_watched_again() {
|
||||
take_logged();
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("root-again");
|
||||
let (daemon, folder, _client) =
|
||||
start_mirror(&drive, &dir, &[("a.txt", b"one"), ("b.txt", b"two")]);
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
let local = dir.join("local");
|
||||
let away = dir.join("away");
|
||||
std::fs::rename(&local, &away).unwrap();
|
||||
let _ = daemon.request(&Request::SyncNow { id: Some(folder) });
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
take_logged()
|
||||
.iter()
|
||||
.any(|line| line.contains("to=suspended (RootMissing)"))
|
||||
}));
|
||||
// A new folder in the old one's place, with the same files.
|
||||
std::fs::create_dir(&local).unwrap();
|
||||
for name in ["a.txt", "b.txt"] {
|
||||
std::fs::copy(away.join(name), local.join(name)).unwrap();
|
||||
}
|
||||
let _ = daemon.request(&Request::SyncNow { id: Some(folder) });
|
||||
// The pass that finds it back walks it in full, and the watches are
|
||||
// set up again after it.
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
take_logged().iter().any(|line| {
|
||||
line.contains("from=suspended (RootMissing)") && line.contains("to=following")
|
||||
})
|
||||
}));
|
||||
// Written as that pass ends, which may be before the watch is set up
|
||||
// again: the event is then lost, and only the pass the new watch
|
||||
// brings about finds the file. Nothing else asks for one, and the
|
||||
// poll is two minutes off.
|
||||
std::fs::write(local.join("c.txt"), b"three").unwrap();
|
||||
assert!(
|
||||
wait_until(Duration::from_secs(60), || drive
|
||||
.lookup("mirrored/c.txt")
|
||||
.is_some()),
|
||||
"a file written in the root made again reaches Drive"
|
||||
);
|
||||
assert!(drive.lookup("mirrored/a.txt").is_some());
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A sync root replaced between two passes is never seen missing, and
|
||||
/// the watch stays on the folder moved away. The pass sees the root is
|
||||
/// another folder, and the engine watches the new one (`root`).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_root_replaced_between_passes_is_watched_again() {
|
||||
take_logged();
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("root-replaced");
|
||||
let (daemon, folder, _client) =
|
||||
start_mirror(&drive, &dir, &[("a.txt", b"one"), ("b.txt", b"two")]);
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
let local = dir.join("local");
|
||||
let away = dir.join("away");
|
||||
std::fs::rename(&local, &away).unwrap();
|
||||
std::fs::create_dir(&local).unwrap();
|
||||
for name in ["a.txt", "b.txt"] {
|
||||
std::fs::copy(away.join(name), local.join(name)).unwrap();
|
||||
}
|
||||
take_logged();
|
||||
let _ = daemon.request(&Request::SyncNow { id: Some(folder) });
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
take_logged()
|
||||
.iter()
|
||||
.any(|line| line.contains("the folder's root was replaced"))
|
||||
}));
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
std::fs::write(local.join("c.txt"), b"three").unwrap();
|
||||
// Only the watch can bring this pass about: the poll is two minutes
|
||||
// off.
|
||||
assert!(
|
||||
wait_until(Duration::from_secs(60), || drive
|
||||
.lookup("mirrored/c.txt")
|
||||
.is_some()),
|
||||
"a file written in the root put in place reaches Drive"
|
||||
);
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// An effect a daemon sent and never heard back from is `unsure` at the
|
||||
/// next start. One the folder still needs is sent again, and settles; one
|
||||
/// it no longer needs is settled by the first pass that looks (`effect`).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn an_effect_left_unsure_by_a_stop_is_sent_again_or_settled() {
|
||||
take_logged();
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("unsure-effect");
|
||||
let (daemon, folder, client) = start_mirror(&drive, &dir, &[("a.txt", b"one")]);
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
// What a daemon killed while it sent two uploads leaves: one landed
|
||||
// (a.txt is on Drive), the other never went out.
|
||||
let sent = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs() as i64
|
||||
- 10;
|
||||
let db = reopen(&dir);
|
||||
db.sync_intent_issue(folder, "a.txt", "upload", sent)
|
||||
.unwrap();
|
||||
db.sync_intent_issue(folder, "new.txt", "upload", sent)
|
||||
.unwrap();
|
||||
drop(db);
|
||||
std::fs::write(dir.join("local").join("new.txt"), b"new").unwrap();
|
||||
take_logged();
|
||||
let daemon = Daemon::start(&dir, client).unwrap();
|
||||
assert!(wait_until(Duration::from_secs(60), || drive
|
||||
.lookup("mirrored/new.txt")
|
||||
.is_some()));
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
let logged = take_logged();
|
||||
let has = |text: &str| logged.iter().any(|line| line.contains(text));
|
||||
assert!(
|
||||
has("effects=2") && has("did not hear back from"),
|
||||
"{logged:#?}"
|
||||
);
|
||||
assert!(
|
||||
has("sending again an effect a stopped daemon may have made"),
|
||||
"{logged:#?}"
|
||||
);
|
||||
assert!(
|
||||
has("an effect a stopped daemon may have made is no longer needed"),
|
||||
"{logged:#?}"
|
||||
);
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
assert!(
|
||||
reopen(&dir).sync_intents(Some(folder)).unwrap().is_empty(),
|
||||
"every intent settled"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A restart owes the disk a walk in full, since nothing watched it
|
||||
/// meanwhile, and owes Drive nothing: its event stream resumes from the
|
||||
/// cursor (`root`).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_restart_walks_the_disk_in_full_and_not_drive() {
|
||||
take_logged();
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("restart-owes");
|
||||
let (daemon, folder, _client) =
|
||||
start_mirror(&drive, &dir, &[("a.txt", b"one"), ("b.txt", b"two")]);
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
take_logged();
|
||||
let daemon = daemon.restart().unwrap();
|
||||
let quiet = quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
let logged = take_logged();
|
||||
let roots: Vec<&String> = logged
|
||||
.iter()
|
||||
.filter(|line| line.contains("sync: root state"))
|
||||
.collect();
|
||||
assert!(
|
||||
roots.len() == 1
|
||||
&& roots[0].contains("from=auditing (local: Restart)")
|
||||
&& roots[0].contains("to=following")
|
||||
&& roots[0].contains("Covered { local: true, remote: false }"),
|
||||
"{roots:?}"
|
||||
);
|
||||
assert!(
|
||||
!logged
|
||||
.iter()
|
||||
.any(|line| line.contains("the root state asks for a walk of all of Drive")),
|
||||
"a restart owes Drive nothing"
|
||||
);
|
||||
assert!(counted(&quiet, "reused") > 0, "{quiet}");
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_mirror_pass_reports_where_its_time_went() {
|
||||
|
||||
@@ -11,7 +11,7 @@ use super::Db;
|
||||
use pdfs_core::Result;
|
||||
|
||||
/// Current schema version. Bump on every forward migration added below.
|
||||
pub(super) const SCHEMA_VERSION: i64 = 50;
|
||||
pub(super) const SCHEMA_VERSION: i64 = 51;
|
||||
|
||||
impl Db {
|
||||
pub(super) fn migrate(&self) -> Result<()> {
|
||||
@@ -553,6 +553,16 @@ impl Db {
|
||||
tx.execute_batch(MIGRATION_V50)?;
|
||||
}
|
||||
}
|
||||
if current < 51 {
|
||||
let has_folders: bool = tx.query_row(
|
||||
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'sync_folder'",
|
||||
[],
|
||||
|row| row.get::<_, i64>(0).map(|n| n > 0),
|
||||
)?;
|
||||
if has_folders {
|
||||
tx.execute_batch(MIGRATION_V51)?;
|
||||
}
|
||||
}
|
||||
tx.execute(
|
||||
"INSERT INTO sync_state (key, value) VALUES ('schema_version', ?1)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||||
@@ -1585,6 +1595,38 @@ BEGIN
|
||||
END;
|
||||
";
|
||||
|
||||
/// Schema v51: an intent for each effect a mirror pass sends, written before
|
||||
/// it is sent and removed once its result is in (`docs/SYNC_ENGINE.md`).
|
||||
///
|
||||
/// One row a folder, path and kind of effect. A row left `issued` was sent by
|
||||
/// a daemon that stopped before it heard back: the effect may or may not have
|
||||
/// happened. A change to what the folder is, or its removal, drops its rows.
|
||||
const MIGRATION_V51: &str = "
|
||||
CREATE TABLE IF NOT EXISTS sync_intent (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
folder_id INTEGER NOT NULL,
|
||||
rel_path TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
state TEXT NOT NULL,
|
||||
attempts INTEGER NOT NULL,
|
||||
issued_at INTEGER NOT NULL,
|
||||
last_error TEXT,
|
||||
UNIQUE (folder_id, rel_path, kind)
|
||||
);
|
||||
DROP TRIGGER IF EXISTS sync_intent_drop_on_folder_update;
|
||||
DROP TRIGGER IF EXISTS sync_intent_drop_on_folder_delete;
|
||||
CREATE TRIGGER sync_intent_drop_on_folder_update
|
||||
AFTER UPDATE OF local_path, remote_uid, mode ON sync_folder
|
||||
BEGIN
|
||||
DELETE FROM sync_intent WHERE folder_id = OLD.id;
|
||||
END;
|
||||
CREATE TRIGGER sync_intent_drop_on_folder_delete
|
||||
AFTER DELETE ON sync_folder
|
||||
BEGIN
|
||||
DELETE FROM sync_intent WHERE folder_id = OLD.id;
|
||||
END;
|
||||
";
|
||||
|
||||
/// See [`MIGRATION_V49_COLUMNS`].
|
||||
const MIGRATION_V49: &str = "
|
||||
CREATE TABLE IF NOT EXISTS sync_remote_dirty (
|
||||
|
||||
@@ -66,7 +66,8 @@ pub use photos::{StoredPhoto, StoredPlace, THUMB_HAVE, THUMB_NONE, THUMB_UNKNOWN
|
||||
pub use pins::PinRow;
|
||||
pub use replace::ReplaceIntent;
|
||||
pub use sync::{
|
||||
DeleteWindow, SavedWalk, SavedWalkDir, SavedWalkItem, StoredSyncEntry, StoredSyncFolder,
|
||||
DeleteWindow, SavedWalk, SavedWalkDir, SavedWalkItem, StoredIntent, StoredSyncEntry,
|
||||
StoredSyncFolder,
|
||||
};
|
||||
pub use trash::StoredTrash;
|
||||
|
||||
|
||||
@@ -19,6 +19,23 @@ pub struct DeleteWindow {
|
||||
pub deleted: u64,
|
||||
}
|
||||
|
||||
/// An effect a mirror pass sent, or is about to send, and has not settled.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StoredIntent {
|
||||
pub id: i64,
|
||||
pub folder_id: i64,
|
||||
pub rel_path: String,
|
||||
/// What the effect does, such as `upload` or `download`.
|
||||
pub kind: String,
|
||||
/// Where it stands, as the effect reducer names it.
|
||||
pub state: String,
|
||||
/// How many times it was sent, this time included.
|
||||
pub attempts: u32,
|
||||
/// When it was last sent, in seconds since the epoch.
|
||||
pub issued_at: i64,
|
||||
pub last_error: Option<String>,
|
||||
}
|
||||
|
||||
/// What a mirror pass has walked of Drive, saved so a pass cut short
|
||||
/// resumes the walk instead of listing every folder again (B294), and so a
|
||||
/// finished walk serves as the next pass's picture of Drive.
|
||||
@@ -828,6 +845,116 @@ impl Db {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record that an effect is about to be sent: a new intent in state
|
||||
/// `issued`, or the one already there for the same folder, path and kind,
|
||||
/// sent once more. Returns the intent as it is now, and the state it was
|
||||
/// in before, if there was one.
|
||||
pub fn sync_intent_issue(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rel_path: &str,
|
||||
kind: &str,
|
||||
now: i64,
|
||||
) -> Result<(StoredIntent, Option<String>)> {
|
||||
let mut conn = self.conn.lock();
|
||||
let tx = conn.transaction()?;
|
||||
let before: Option<String> = tx
|
||||
.query_row(
|
||||
"SELECT state FROM sync_intent WHERE folder_id = ?1 AND rel_path = ?2 AND kind = ?3",
|
||||
params![folder_id, rel_path, kind],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
tx.execute(
|
||||
"INSERT INTO sync_intent (folder_id, rel_path, kind, state, attempts, issued_at)
|
||||
VALUES (?1, ?2, ?3, 'issued', 1, ?4)
|
||||
ON CONFLICT(folder_id, rel_path, kind) DO UPDATE SET state = 'issued',
|
||||
attempts = attempts + 1, issued_at = excluded.issued_at",
|
||||
params![folder_id, rel_path, kind, now],
|
||||
)?;
|
||||
let intent = tx.query_row(
|
||||
&format!(
|
||||
"SELECT {INTENT_COLUMNS} FROM sync_intent
|
||||
WHERE folder_id = ?1 AND rel_path = ?2 AND kind = ?3"
|
||||
),
|
||||
params![folder_id, rel_path, kind],
|
||||
intent_row,
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok((intent, before))
|
||||
}
|
||||
|
||||
/// Settle an intent whose effect is done: the row goes.
|
||||
pub fn sync_intent_settle(&self, id: i64) -> Result<()> {
|
||||
let conn = self.conn.lock();
|
||||
conn.execute("DELETE FROM sync_intent WHERE id = ?1", params![id])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Move an intent to `state`, with the error that put it there.
|
||||
pub fn sync_intent_set(&self, id: i64, state: &str, error: Option<&str>) -> Result<()> {
|
||||
let conn = self.conn.lock();
|
||||
conn.execute(
|
||||
"UPDATE sync_intent SET state = ?2, last_error = ?3 WHERE id = ?1",
|
||||
params![id, state, error],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every intent not settled, oldest first; only `folder_id`'s when given.
|
||||
pub fn sync_intents(&self, folder_id: Option<i64>) -> Result<Vec<StoredIntent>> {
|
||||
let conn = self.read()?;
|
||||
let mut stmt = conn.prepare(&format!(
|
||||
"SELECT {INTENT_COLUMNS} FROM sync_intent
|
||||
WHERE ?1 IS NULL OR folder_id = ?1 ORDER BY id"
|
||||
))?;
|
||||
let rows = stmt
|
||||
.query_map(params![folder_id], intent_row)?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// Move every intent in state `from` to `to`, across all folders.
|
||||
/// Returns how many moved.
|
||||
pub fn sync_intents_move(&self, from: &str, to: &str) -> Result<usize> {
|
||||
let conn = self.conn.lock();
|
||||
Ok(conn.execute(
|
||||
"UPDATE sync_intent SET state = ?2 WHERE state = ?1",
|
||||
params![from, to],
|
||||
)?)
|
||||
}
|
||||
|
||||
/// Settle the intents of `folder_id` in one of `states` that were last
|
||||
/// sent before `before`: a pass that started after them looked at their
|
||||
/// paths and did not send them again. Returns the intents settled.
|
||||
pub fn sync_intents_settle_before(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
states: &[&str],
|
||||
before: i64,
|
||||
) -> Result<Vec<StoredIntent>> {
|
||||
let mut conn = self.conn.lock();
|
||||
let tx = conn.transaction()?;
|
||||
let mut settled = Vec::new();
|
||||
{
|
||||
let mut stmt = tx.prepare(&format!(
|
||||
"SELECT {INTENT_COLUMNS} FROM sync_intent
|
||||
WHERE folder_id = ?1 AND issued_at < ?2 ORDER BY id"
|
||||
))?;
|
||||
for row in stmt.query_map(params![folder_id, before], intent_row)? {
|
||||
let row = row?;
|
||||
if states.contains(&row.state.as_str()) {
|
||||
settled.push(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
for intent in &settled {
|
||||
tx.execute("DELETE FROM sync_intent WHERE id = ?1", params![intent.id])?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(settled)
|
||||
}
|
||||
|
||||
/// Drop the entire baseline for a folder. Used when flipping ondemand→mirror:
|
||||
/// the local tree was evicted, so the old baseline is stale and would make the
|
||||
/// next reconcile mistake "locally deleted" for "must re-download". Clearing it
|
||||
@@ -842,6 +969,22 @@ impl Db {
|
||||
}
|
||||
}
|
||||
|
||||
const INTENT_COLUMNS: &str =
|
||||
"id, folder_id, rel_path, kind, state, attempts, issued_at, last_error";
|
||||
|
||||
fn intent_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoredIntent> {
|
||||
Ok(StoredIntent {
|
||||
id: row.get(0)?,
|
||||
folder_id: row.get(1)?,
|
||||
rel_path: row.get(2)?,
|
||||
kind: row.get(3)?,
|
||||
state: row.get(4)?,
|
||||
attempts: u32::try_from(row.get::<_, i64>(5)?).unwrap_or(u32::MAX),
|
||||
issued_at: row.get(6)?,
|
||||
last_error: row.get(7)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn clear_walk(tx: &rusqlite::Transaction<'_>, folder_id: i64) -> Result<()> {
|
||||
for table in [
|
||||
"sync_walk",
|
||||
|
||||
@@ -8452,3 +8452,51 @@ fn a_deletion_window_is_kept_per_folder_until_the_folder_changes() {
|
||||
db.sync_folder_remove(other).unwrap();
|
||||
assert_eq!(db.sync_delete_window(other).unwrap(), None);
|
||||
}
|
||||
|
||||
/// An intent is one row per folder, path and kind: sent again, it counts the
|
||||
/// attempt and says what state it was left in. It goes once settled, and with
|
||||
/// the folder.
|
||||
#[test]
|
||||
fn an_effect_intent_is_kept_until_it_is_settled_or_its_folder_changes() {
|
||||
let db = Db::open_in_memory().unwrap();
|
||||
let id = db.sync_folder_add("/home/me/Docs", "v~root", "s").unwrap();
|
||||
let other = db
|
||||
.sync_folder_add("/home/me/Other", "v~other", "s")
|
||||
.unwrap();
|
||||
let (first, before) = db.sync_intent_issue(id, "a.txt", "upload", 10).unwrap();
|
||||
assert_eq!(before, None);
|
||||
assert_eq!((first.state.as_str(), first.attempts), ("issued", 1));
|
||||
db.sync_intent_set(first.id, "retry", Some("timed out"))
|
||||
.unwrap();
|
||||
let (again, before) = db.sync_intent_issue(id, "a.txt", "upload", 20).unwrap();
|
||||
assert_eq!(before.as_deref(), Some("retry"));
|
||||
assert_eq!(again.id, first.id, "the same intent");
|
||||
assert_eq!((again.attempts, again.issued_at), (2, 20));
|
||||
assert_eq!(again.last_error.as_deref(), Some("timed out"));
|
||||
let (download, _) = db.sync_intent_issue(id, "a.txt", "download", 21).unwrap();
|
||||
db.sync_intent_issue(other, "b.txt", "upload", 5).unwrap();
|
||||
assert_eq!(db.sync_intents(Some(id)).unwrap().len(), 2);
|
||||
assert_eq!(db.sync_intents(None).unwrap().len(), 3);
|
||||
|
||||
db.sync_intent_settle(download.id).unwrap();
|
||||
assert_eq!(db.sync_intents(Some(id)).unwrap().len(), 1);
|
||||
|
||||
// A start finds what a stopped daemon left sent.
|
||||
assert_eq!(db.sync_intents_move("issued", "unsure").unwrap(), 2);
|
||||
assert_eq!(db.sync_intents_move("issued", "unsure").unwrap(), 0);
|
||||
// A pass that began after an intent was sent settles it.
|
||||
let settled = db
|
||||
.sync_intents_settle_before(other, &["unsure"], 6)
|
||||
.unwrap();
|
||||
assert_eq!(settled.len(), 1);
|
||||
assert!(db.sync_intents(Some(other)).unwrap().is_empty());
|
||||
assert!(
|
||||
db.sync_intents_settle_before(id, &["unsure"], 20)
|
||||
.unwrap()
|
||||
.is_empty(),
|
||||
"sent at 20, not before"
|
||||
);
|
||||
|
||||
db.sync_folder_set_mode(id, "ondemand").unwrap();
|
||||
assert!(db.sync_intents(Some(id)).unwrap().is_empty());
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
//! The effect reducer: where one effect a mirror pass sends stands, from the
|
||||
//! moment it is about to be sent until its result is in
|
||||
//! (`docs/SYNC_ENGINE.md`).
|
||||
//!
|
||||
//! An effect is an upload, a download, a folder made on Drive, and the other
|
||||
//! [`Pending`](crate::model::Pending) ops. Before one is sent, an intent for it
|
||||
//! is written to the database (`sync_intent`); when its result is in, the
|
||||
//! intent is settled or kept with the failure. An intent still `issued` when
|
||||
//! the daemon starts was sent by a daemon that stopped before it heard back,
|
||||
//! so the effect may or may not have happened: it is `unsure`.
|
||||
//!
|
||||
//! [`step`] is pure, as the root reducer is: the I/O results, the restart and
|
||||
//! the pass that looks again are inputs.
|
||||
//!
|
||||
//! For now the intents are kept in shadow: they record and log what happens,
|
||||
//! and nothing reads them to decide what to send. The apply step's own checks
|
||||
//! (a create that may have landed is looked up before it is sent again, B266;
|
||||
//! a download checks the disk before it replaces a file, B39) still do that.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// Failures in a row after which an effect is reported as blocked.
|
||||
pub const BLOCKED_AFTER: u32 = 5;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum EffectState {
|
||||
/// Sent, or about to be; no result yet.
|
||||
Issued,
|
||||
/// Found issued at a start: the daemon stopped before the result came,
|
||||
/// so the effect may or may not have happened.
|
||||
Unsure,
|
||||
/// It failed, and a later pass may send it again.
|
||||
Retry,
|
||||
/// It failed [`BLOCKED_AFTER`] times in a row.
|
||||
Blocked,
|
||||
/// Its result is in. The intent goes.
|
||||
Settled,
|
||||
}
|
||||
|
||||
impl EffectState {
|
||||
/// The name the database keeps.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
EffectState::Issued => "issued",
|
||||
EffectState::Unsure => "unsure",
|
||||
EffectState::Retry => "retry",
|
||||
EffectState::Blocked => "blocked",
|
||||
EffectState::Settled => "settled",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_name(name: &str) -> Option<EffectState> {
|
||||
Some(match name {
|
||||
"issued" => EffectState::Issued,
|
||||
"unsure" => EffectState::Unsure,
|
||||
"retry" => EffectState::Retry,
|
||||
"blocked" => EffectState::Blocked,
|
||||
"settled" => EffectState::Settled,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for EffectState {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(self.name())
|
||||
}
|
||||
}
|
||||
|
||||
/// Something that happened to an effect.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum EffectInput {
|
||||
/// It is sent (again); `attempts` counts this one.
|
||||
Issued { attempts: u32 },
|
||||
/// It did what it was sent to do.
|
||||
Succeeded,
|
||||
/// It failed.
|
||||
Failed,
|
||||
/// The daemon started.
|
||||
Restarted,
|
||||
/// A pass that began after it was sent looked at its path and did not
|
||||
/// send it again: what it was for has changed, or is done.
|
||||
Superseded,
|
||||
}
|
||||
|
||||
/// The state after `input`.
|
||||
pub fn step(state: EffectState, input: EffectInput) -> EffectState {
|
||||
use EffectState as S;
|
||||
match (state, input) {
|
||||
(S::Settled, _) => S::Settled,
|
||||
(_, EffectInput::Issued { .. }) => S::Issued,
|
||||
(_, EffectInput::Succeeded | EffectInput::Superseded) => S::Settled,
|
||||
(S::Issued, EffectInput::Restarted) => S::Unsure,
|
||||
(state, EffectInput::Restarted) => state,
|
||||
(_, EffectInput::Failed) => S::Retry,
|
||||
}
|
||||
}
|
||||
|
||||
/// The state after a failure on the `attempts`th send. Counts are kept
|
||||
/// outside [`step`], with the intent.
|
||||
pub fn failed(attempts: u32) -> EffectState {
|
||||
if attempts >= BLOCKED_AFTER {
|
||||
EffectState::Blocked
|
||||
} else {
|
||||
step(EffectState::Issued, EffectInput::Failed)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use EffectInput as I;
|
||||
use EffectState as S;
|
||||
|
||||
#[test]
|
||||
fn an_effect_settles_once_it_succeeds() {
|
||||
let sent = step(S::Retry, I::Issued { attempts: 2 });
|
||||
assert_eq!(sent, S::Issued);
|
||||
assert_eq!(step(sent, I::Succeeded), S::Settled);
|
||||
assert_eq!(step(S::Settled, I::Failed), S::Settled, "settled stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_effect_sent_before_a_stop_is_unsure_after_the_start() {
|
||||
assert_eq!(step(S::Issued, I::Restarted), S::Unsure);
|
||||
// Only one that was sent: a failure is known, and stays one.
|
||||
assert_eq!(step(S::Retry, I::Restarted), S::Retry);
|
||||
assert_eq!(step(S::Blocked, I::Restarted), S::Blocked);
|
||||
// Sent again, or found needless by a later pass.
|
||||
assert_eq!(step(S::Unsure, I::Issued { attempts: 2 }), S::Issued);
|
||||
assert_eq!(step(S::Unsure, I::Superseded), S::Settled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_effect_that_keeps_failing_is_blocked() {
|
||||
assert_eq!(failed(1), S::Retry);
|
||||
assert_eq!(failed(BLOCKED_AFTER - 1), S::Retry);
|
||||
assert_eq!(failed(BLOCKED_AFTER), S::Blocked);
|
||||
assert_eq!(step(S::Blocked, I::Superseded), S::Settled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_state_reads_back_by_its_name() {
|
||||
for state in [S::Issued, S::Unsure, S::Retry, S::Blocked, S::Settled] {
|
||||
assert_eq!(EffectState::from_name(state.name()), Some(state));
|
||||
}
|
||||
assert_eq!(EffectState::from_name("planned"), None);
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ use pdfs_store::db::{DeleteWindow, StoredSyncEntry};
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use proton_drive_rs::{Node, NodeKind};
|
||||
|
||||
pub mod effect;
|
||||
pub mod evidence;
|
||||
pub mod local_dirty;
|
||||
pub mod mirror;
|
||||
|
||||
@@ -11,14 +11,20 @@
|
||||
//! error, an overflowed queue or a restart breaks that, and the next pass has
|
||||
//! nothing to trust until a pass claims again with the watch live throughout.
|
||||
//!
|
||||
//! For now the set is checked, not used: a pass still walks the whole folder,
|
||||
//! and counts the changes it finds that a trusted claim did not cover. Once
|
||||
//! those stay at zero, a trusted claim can stand in for the walk.
|
||||
//! A trusted claim stands in for most of the local walk. The set keeps the
|
||||
//! last walk of each folder ([`LocalWalk`]), and a pass with a trusted claim
|
||||
//! reads again only what the claim covers and takes the rest from that walk.
|
||||
//! A walk is only kept after a pass that changed nothing on disk itself, and
|
||||
//! a full walk still runs now and then: it checks the set, counting the
|
||||
//! changes it finds that a trusted claim did not cover.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::time::Instant;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
|
||||
use crate::model::LocalItem;
|
||||
|
||||
/// The dirty marks of every mirror folder, by folder id.
|
||||
#[derive(Default)]
|
||||
pub struct LocalDirty {
|
||||
@@ -56,6 +62,36 @@ struct Marks {
|
||||
live_since: Option<u64>,
|
||||
/// The generation the last pass claimed through.
|
||||
claimed: Option<u64>,
|
||||
/// What the last pass found on disk, when it may stand in for a walk.
|
||||
walk: Option<LocalWalk>,
|
||||
/// The folder's root as it was when it was watched, as device and
|
||||
/// inode. A watch follows the folder it was set on, so a root moved away
|
||||
/// and made again is another folder the watch does not see.
|
||||
root: Option<RootId>,
|
||||
}
|
||||
|
||||
/// A folder on disk, as device and inode.
|
||||
pub type RootId = (u64, u64);
|
||||
|
||||
/// The identity of the folder at `path`, if there is one.
|
||||
pub fn root_id(path: &std::path::Path) -> Option<RootId> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
std::fs::metadata(path)
|
||||
.ok()
|
||||
.filter(|meta| meta.is_dir())
|
||||
.map(|meta| (meta.dev(), meta.ino()))
|
||||
}
|
||||
|
||||
/// What a pass found on disk, kept for the next pass to start from.
|
||||
pub struct LocalWalk {
|
||||
/// Every path the walk found, as a walk returns them.
|
||||
pub items: HashMap<String, LocalItem>,
|
||||
/// [`IgnoreRules::source`](pdfs_core::syncignore::IgnoreRules::source)
|
||||
/// of the rules it was walked with: other rules would have found other
|
||||
/// paths.
|
||||
pub rules: u64,
|
||||
/// When the folder was last walked in full.
|
||||
pub walked_at: Instant,
|
||||
}
|
||||
|
||||
/// The marks a pass claimed: what the watcher reported up to `through`.
|
||||
@@ -88,6 +124,16 @@ impl Claim {
|
||||
}
|
||||
}
|
||||
|
||||
/// The folders whose direct children changed.
|
||||
pub fn shallow(&self) -> impl Iterator<Item = &str> {
|
||||
self.shallow.iter().map(String::as_str)
|
||||
}
|
||||
|
||||
/// The paths that changed with whatever is below them.
|
||||
pub fn deep(&self) -> impl Iterator<Item = &str> {
|
||||
self.deep.iter().map(String::as_str)
|
||||
}
|
||||
|
||||
/// How many marks the claim holds.
|
||||
pub fn len(&self) -> usize {
|
||||
self.shallow.len() + self.deep.len()
|
||||
@@ -99,15 +145,21 @@ impl Claim {
|
||||
}
|
||||
|
||||
impl LocalDirty {
|
||||
/// The watch on `folder` is in place: every change from now on is
|
||||
/// reported.
|
||||
pub fn watched(&self, folder: i64) {
|
||||
/// The watch on `folder` is in place, set on the root `root`: every
|
||||
/// change from now on is reported.
|
||||
pub fn watched(&self, folder: i64, root: Option<RootId>) {
|
||||
let mut d = self.inner.lock();
|
||||
let now = d.tick();
|
||||
let marks = d.folders.entry(folder).or_default();
|
||||
if marks.live_since.is_none() {
|
||||
marks.live_since = Some(now);
|
||||
}
|
||||
marks.root = root;
|
||||
}
|
||||
|
||||
/// The root `folder`'s watch was last set on.
|
||||
pub fn watched_root(&self, folder: i64) -> Option<RootId> {
|
||||
self.inner.lock().folders.get(&folder)?.root
|
||||
}
|
||||
|
||||
/// The watch on `folder` is gone, or never came up.
|
||||
@@ -177,6 +229,22 @@ impl LocalDirty {
|
||||
marks.claimed = Some(claim.through);
|
||||
}
|
||||
|
||||
/// Take the walk the last pass kept for `folder`. Taken, not read: a pass
|
||||
/// that does not keep a walk again leaves the next one nothing to start
|
||||
/// from.
|
||||
pub fn take_walk(&self, folder: i64) -> Option<LocalWalk> {
|
||||
self.inner
|
||||
.lock()
|
||||
.folders
|
||||
.get_mut(&folder)
|
||||
.and_then(|marks| marks.walk.take())
|
||||
}
|
||||
|
||||
/// Keep what a pass found on disk for the next pass on `folder`.
|
||||
pub fn keep_walk(&self, folder: i64, walk: LocalWalk) {
|
||||
self.inner.lock().folders.entry(folder).or_default().walk = Some(walk);
|
||||
}
|
||||
|
||||
/// Forget a folder that is no longer synced.
|
||||
pub fn forget(&self, folder: i64) {
|
||||
self.inner.lock().folders.remove(&folder);
|
||||
@@ -218,7 +286,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_claim_is_trusted_only_with_the_watch_live_since_the_last_one() {
|
||||
let dirty = LocalDirty::default();
|
||||
dirty.watched(1);
|
||||
dirty.watched(1, None);
|
||||
// The first pass after the watch came up has nothing to measure from.
|
||||
let first = dirty.claim(1);
|
||||
assert!(!first.trusted);
|
||||
@@ -231,7 +299,7 @@ mod tests {
|
||||
let lost = dirty.claim(1);
|
||||
assert!(!lost.trusted);
|
||||
dirty.looked(1, &lost, true);
|
||||
dirty.watched(1);
|
||||
dirty.watched(1, None);
|
||||
dirty.mark(1, "a.txt");
|
||||
let back = dirty.claim(1);
|
||||
assert!(!back.trusted, "watched again after the last claim");
|
||||
@@ -263,7 +331,7 @@ mod tests {
|
||||
#[test]
|
||||
fn an_overflow_breaks_trust_until_a_pass_claims_again() {
|
||||
let dirty = LocalDirty::default();
|
||||
dirty.watched(1);
|
||||
dirty.watched(1, None);
|
||||
let first = dirty.claim(1);
|
||||
dirty.looked(1, &first, true);
|
||||
dirty.mark(1, "a.txt");
|
||||
|
||||
+282
-20
@@ -38,17 +38,20 @@ use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use sha1::{Digest as _, Sha1};
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use crate::effect::{self, EffectState};
|
||||
use crate::evidence::{Evidence, RemoteEvidence, Side};
|
||||
use crate::local_dirty::Claim;
|
||||
use crate::local_dirty::{Claim, LocalWalk, root_id};
|
||||
use crate::planner::HasKind;
|
||||
use crate::root::{RootInput, Suspension};
|
||||
use crate::root::{Doubt, Phase as RootPhase, RootInput, Suspension};
|
||||
use pdfs_core::batch;
|
||||
use pdfs_core::control::{ActivityKind, TransferDirection};
|
||||
use pdfs_core::syncignore::IgnoreRules;
|
||||
use pdfs_core::timestamp::now_secs;
|
||||
use pdfs_core::transfers::{CountingWriter, OwnedCountingReader};
|
||||
use pdfs_drive::parse_uid;
|
||||
use pdfs_store::db::{DeleteWindow, SavedWalk, SavedWalkItem, StoredSyncEntry, StoredSyncFolder};
|
||||
use pdfs_store::db::{
|
||||
DeleteWindow, SavedWalk, SavedWalkItem, StoredIntent, StoredSyncEntry, StoredSyncFolder,
|
||||
};
|
||||
|
||||
mod apply;
|
||||
mod engine;
|
||||
@@ -159,8 +162,39 @@ impl Syncer {
|
||||
.sync_folder_set_state(folder.id, "error", now_secs());
|
||||
self.roots
|
||||
.input(folder.id, RootInput::Suspended(Suspension::RootMissing));
|
||||
// A root removed takes its watch with it, and one made again in
|
||||
// its place is not watched until the watches are set up again.
|
||||
// Until then the disk is walked in full.
|
||||
self.local_dirty.unwatched(folder.id);
|
||||
self.roots
|
||||
.input(folder.id, RootInput::Doubted(Doubt::WatchLost));
|
||||
let _ = self.tx.send(SyncMsg::Rewatch);
|
||||
return;
|
||||
}
|
||||
// Back after it was missing: watch it again. This pass walks the disk
|
||||
// in full, as the root state owes it.
|
||||
if self
|
||||
.roots
|
||||
.state(folder.id)
|
||||
.is_some_and(|state| state.phase == RootPhase::Suspended(Suspension::RootMissing))
|
||||
{
|
||||
let _ = self.tx.send(SyncMsg::Rewatch);
|
||||
}
|
||||
// Moved away and made again between two passes, or before the engine
|
||||
// got to drop the old watch: the watch is on a folder that is no
|
||||
// longer the root, and reports nothing of this one.
|
||||
if let Some(watched) = self.local_dirty.watched_root(folder.id)
|
||||
&& root_id(&local_root).is_some_and(|now| now != watched)
|
||||
{
|
||||
info!(
|
||||
id = folder.id,
|
||||
"sync: the folder's root was replaced; watching it again"
|
||||
);
|
||||
self.local_dirty.unwatched(folder.id);
|
||||
self.roots
|
||||
.input(folder.id, RootInput::Doubted(Doubt::WatchLost));
|
||||
let _ = self.tx.send(SyncMsg::Rewatch);
|
||||
}
|
||||
self.roots.input(
|
||||
folder.id,
|
||||
if push_only {
|
||||
@@ -229,8 +263,12 @@ impl Syncer {
|
||||
let progress = self.progress.lock().get(&folder.id).cloned();
|
||||
self.progress_end(folder.id);
|
||||
self.log_trace(folder, &result, started.elapsed());
|
||||
if result.is_ok() && !push_only {
|
||||
self.roots.input(folder.id, RootInput::Covered);
|
||||
if let Ok(outcome) = &result
|
||||
&& !push_only
|
||||
{
|
||||
let (local, remote) = outcome.walked_in_full;
|
||||
self.roots
|
||||
.input(folder.id, RootInput::Covered { local, remote });
|
||||
}
|
||||
match result {
|
||||
Ok(outcome) => {
|
||||
@@ -497,6 +535,9 @@ impl Syncer {
|
||||
remote_root: &NodeUid,
|
||||
rules: &IgnoreRules,
|
||||
) -> Result<Outcome, PassAbort> {
|
||||
// Intents sent before this moment that the pass does not send again
|
||||
// are settled at its end (`effect`).
|
||||
let pass_began = now_secs();
|
||||
// Loaded before the walks: the remote one uses it to tell which files are
|
||||
// unchanged and so can skip decrypting their claimed size, and its size is
|
||||
// the only estimate available of how much this pass has to check — the walks
|
||||
@@ -512,26 +553,71 @@ impl Syncer {
|
||||
|
||||
let mut local: HashMap<String, LocalItem> = HashMap::new();
|
||||
let mut unscanned = Unscanned::default();
|
||||
// What the watcher reported since the last pass (`local_dirty`).
|
||||
// Claimed before the walk: a change made while it runs is newer than
|
||||
// the claim, and stays marked for the next pass.
|
||||
let claim = self.local_dirty.claim(folder_id);
|
||||
// What the root state says this pass must walk in full (`root`).
|
||||
let owed = self.roots.owed(folder_id);
|
||||
// The last pass's walk, when the claim can bring it up to date: the
|
||||
// watch was live since that pass claimed, the ignore rules are the
|
||||
// same, the folder was walked in full lately, and the root state owes
|
||||
// the disk nothing.
|
||||
let kept = self.local_dirty.take_walk(folder_id).filter(|kept| {
|
||||
claim.trusted
|
||||
&& kept.rules == rules.source()
|
||||
&& kept.walked_at.elapsed() < LOCAL_AUDIT_INTERVAL
|
||||
});
|
||||
let kept = match (kept, owed.local) {
|
||||
(Some(_), Some(doubt)) => {
|
||||
info!(
|
||||
id = folder_id,
|
||||
?doubt,
|
||||
"sync: the root state asks for a walk of the whole disk"
|
||||
);
|
||||
None
|
||||
}
|
||||
(kept, _) => kept,
|
||||
};
|
||||
let step = Instant::now();
|
||||
let writing = open_for_write_set(local_root);
|
||||
self.walk_local(
|
||||
folder_id,
|
||||
local_root,
|
||||
rules,
|
||||
&writing,
|
||||
&mut local,
|
||||
&mut unscanned,
|
||||
)?;
|
||||
let (walked_at, walked_in_full) = match kept {
|
||||
Some(kept) => {
|
||||
local = kept.items;
|
||||
self.trace_count(Count::LocalReused, local.len());
|
||||
// What is taken from the kept walk counts as scanned at once.
|
||||
self.progress_scanned_many(folder_id, local.len());
|
||||
rewalk_local_tree(
|
||||
local_root,
|
||||
rules,
|
||||
&writing,
|
||||
&claim,
|
||||
&mut local,
|
||||
&mut unscanned,
|
||||
&mut |rel| self.progress_scanned(folder_id, base_name(rel)),
|
||||
)?;
|
||||
(kept.walked_at, false)
|
||||
}
|
||||
None => {
|
||||
self.walk_local(
|
||||
folder_id,
|
||||
local_root,
|
||||
rules,
|
||||
&writing,
|
||||
&mut local,
|
||||
&mut unscanned,
|
||||
)?;
|
||||
(step, true)
|
||||
}
|
||||
};
|
||||
self.trace_phase(Phase::LocalWalk, step.elapsed());
|
||||
self.trace_count(Count::LocalEntries, local.len());
|
||||
// See `push_pass`: the guard must not count excluded paths as lost.
|
||||
guard_local_wipe(&tracked_baseline(&baseline, rules, &unscanned), &local)?;
|
||||
// What the watcher reported since the last pass, checked against what
|
||||
// the walk found (`local_dirty`).
|
||||
let claim = self.local_dirty.claim(folder_id);
|
||||
self.check_local_dirty(
|
||||
folder_id,
|
||||
&claim,
|
||||
walked_in_full,
|
||||
&tracked_baseline(&baseline, rules, &unscanned),
|
||||
&local,
|
||||
);
|
||||
@@ -550,11 +636,12 @@ impl Syncer {
|
||||
gaps: &mut gaps,
|
||||
},
|
||||
&baseline,
|
||||
owed.remote.is_none(),
|
||||
);
|
||||
// Timed even when cut short: a walk that never ends is the case the
|
||||
// trace exists for.
|
||||
self.trace_phase(Phase::RemoteWalk, step.elapsed());
|
||||
walked?;
|
||||
let remote_in_full = walked?;
|
||||
guard_remote_wipe(&tracked_baseline(&baseline, rules, &unscanned), &remote)?;
|
||||
|
||||
let mut order = classification_order(&local, &remote, &baseline, rules);
|
||||
@@ -580,6 +667,7 @@ impl Syncer {
|
||||
unscanned_report.extend(gaps.report());
|
||||
let mut outcome = Outcome {
|
||||
unscanned: unscanned_report,
|
||||
walked_in_full: (walked_in_full, remote_in_full),
|
||||
..Default::default()
|
||||
};
|
||||
// Folders to delete, collected here and removed deepest-first at the end
|
||||
@@ -672,6 +760,7 @@ impl Syncer {
|
||||
}
|
||||
(false, true) if !in_base => {
|
||||
// New remote folder → create locally (cheap, inline).
|
||||
outcome.local_changes += 1;
|
||||
if let Err(e) = std::fs::create_dir_all(local_root.join(rel_to_path(rel)))
|
||||
.map_err(|e| format!("mkdir {rel}: {e}"))
|
||||
.and_then(|()| self.baseline_dir(folder_id, rel, &remote[rel].uid))
|
||||
@@ -798,6 +887,7 @@ impl Syncer {
|
||||
outcome.deferred += 1;
|
||||
continue;
|
||||
}
|
||||
outcome.local_changes += 1;
|
||||
if let Err(e) = removed_locally(std::fs::remove_file(&path)) {
|
||||
warn!(rel, error = %e, "sync: remove local file failed");
|
||||
self.log_activity(
|
||||
@@ -877,6 +967,7 @@ impl Syncer {
|
||||
.sync_entries(folder_id)
|
||||
.map_err(|e| format!("reload baseline: {e:?}"))?;
|
||||
for removal in remove_local_dirs(local_root, delete_local_dirs, &mut current) {
|
||||
outcome.local_changes += 1;
|
||||
match removal {
|
||||
DirRemoval::Removed(rel) => {
|
||||
let _ = self.store.sync_entry_remove(folder_id, &rel);
|
||||
@@ -958,23 +1049,49 @@ impl Syncer {
|
||||
}
|
||||
self.trace_phase(Phase::Cleanup, cleanup.elapsed());
|
||||
self.settle_deletions(folder_id, window, outcome.deleted);
|
||||
// Every path was looked at and planned: what an earlier pass left
|
||||
// unsettled and this one did not send again is no longer owed.
|
||||
if outcome.unscanned.is_empty() && outcome.deferred == 0 {
|
||||
self.supersede_intents(folder_id, pass_began);
|
||||
}
|
||||
// A change the pass could not apply stays dirty for the next one.
|
||||
self.local_dirty.looked(
|
||||
folder_id,
|
||||
&claim,
|
||||
outcome.errors == 0 && outcome.deferred == 0,
|
||||
);
|
||||
// The walk is kept for the next pass only when the pass changed
|
||||
// nothing on disk itself and could read everything. A change of its
|
||||
// own is marked only once the watcher reports it, which may come
|
||||
// after the next pass claims, and a path left out has to be looked
|
||||
// at again anyway.
|
||||
if outcome.local_changes == 0
|
||||
&& outcome.errors == 0
|
||||
&& outcome.deferred == 0
|
||||
&& unscanned.is_empty()
|
||||
{
|
||||
self.local_dirty.keep_walk(
|
||||
folder_id,
|
||||
LocalWalk {
|
||||
items: local,
|
||||
rules: rules.source(),
|
||||
walked_at,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// Count the claimed marks of the local dirty set, and, when the claim is
|
||||
/// trusted, the local changes the walk found that it did not cover. Acts
|
||||
/// on nothing: the walk is still what the pass plans from.
|
||||
/// Count the claimed marks of the local dirty set, and, after a walk of
|
||||
/// the whole folder with a trusted claim, the local changes the walk
|
||||
/// found that the claim did not cover. Those are changes a pass that
|
||||
/// trusted the claim would have missed until the next full walk.
|
||||
fn check_local_dirty(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
claim: &Claim,
|
||||
walked_in_full: bool,
|
||||
tracked: &HashMap<String, &StoredSyncEntry>,
|
||||
local: &HashMap<String, LocalItem>,
|
||||
) {
|
||||
@@ -983,6 +1100,9 @@ impl Syncer {
|
||||
self.trace_count(Count::LocalUntrusted, 1);
|
||||
return;
|
||||
}
|
||||
if !walked_in_full {
|
||||
return;
|
||||
}
|
||||
let missed = missed_local(claim, tracked, local);
|
||||
if missed.is_empty() {
|
||||
return;
|
||||
@@ -1190,6 +1310,11 @@ fn dir_row(rel: &str, uid: &NodeUid) -> StoredSyncEntry {
|
||||
/// stream marked dirty; this full walk catches what the stream may have missed.
|
||||
const AUDIT_INTERVAL: Duration = Duration::from_secs(24 * 3600);
|
||||
|
||||
/// How long a pass may bring the last local walk up to date from the local
|
||||
/// dirty set before it walks the whole folder again. The full walk is what
|
||||
/// checks the set: it counts what the set missed.
|
||||
const LOCAL_AUDIT_INTERVAL: Duration = Duration::from_secs(3600);
|
||||
|
||||
/// How lately Drive's event stream must have been read for a pass to rely on
|
||||
/// it. A few polls' worth.
|
||||
const EVENTS_FRESH: Duration = Duration::from_secs(3 * crate::EVENT_POLL_INTERVAL.as_secs());
|
||||
@@ -2868,4 +2993,141 @@ mod tests {
|
||||
o.deferred = 1;
|
||||
assert!(!o.is_empty());
|
||||
}
|
||||
|
||||
/// What a walk found, comparable: kind, mtime and size by path.
|
||||
fn shape(items: &HashMap<String, LocalItem>) -> Vec<(String, bool, i64, i64)> {
|
||||
let mut shape: Vec<_> = items
|
||||
.iter()
|
||||
.map(|(rel, item)| (rel.clone(), item.is_dir, item.mtime, item.size))
|
||||
.collect();
|
||||
shape.sort();
|
||||
shape
|
||||
}
|
||||
|
||||
/// Bring `kept` up to date with what `dirty` marked for folder 1.
|
||||
fn rewalk(
|
||||
root: &Path,
|
||||
rules: &IgnoreRules,
|
||||
dirty: &crate::local_dirty::LocalDirty,
|
||||
kept: &mut HashMap<String, LocalItem>,
|
||||
) -> Unscanned {
|
||||
let mut unscanned = Unscanned::default();
|
||||
rewalk_local_tree(
|
||||
root,
|
||||
rules,
|
||||
&HashSet::new(),
|
||||
&dirty.claim(1),
|
||||
kept,
|
||||
&mut unscanned,
|
||||
&mut no_progress(),
|
||||
)
|
||||
.unwrap();
|
||||
unscanned
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rewalk_of_the_marked_paths_finds_what_a_full_walk_finds() {
|
||||
let root = sync_test_dir("rewalk");
|
||||
std::fs::create_dir_all(root.join("docs/old")).unwrap();
|
||||
std::fs::create_dir_all(root.join("quiet/deep")).unwrap();
|
||||
std::fs::write(root.join("docs/a.txt"), b"a").unwrap();
|
||||
std::fs::write(root.join("docs/b.txt"), b"b").unwrap();
|
||||
std::fs::write(root.join("docs/old/x.txt"), b"x").unwrap();
|
||||
std::fs::write(root.join("quiet/deep/q.txt"), b"q").unwrap();
|
||||
let (mut kept, _) = scan(&root).unwrap();
|
||||
|
||||
// Each kind of change, marked as the watcher reports it.
|
||||
let dirty = crate::local_dirty::LocalDirty::default();
|
||||
std::fs::write(root.join("docs/a.txt"), b"edited, and longer").unwrap();
|
||||
dirty.mark(1, "docs/a.txt");
|
||||
std::fs::remove_file(root.join("docs/b.txt")).unwrap();
|
||||
dirty.mark(1, "docs/b.txt");
|
||||
std::fs::write(root.join("docs/new.txt"), b"new").unwrap();
|
||||
dirty.mark(1, "docs/new.txt");
|
||||
std::fs::remove_dir_all(root.join("docs/old")).unwrap();
|
||||
dirty.mark(1, "docs/old");
|
||||
// A folder moved in: one event, for the folder only.
|
||||
let outside = sync_test_dir("rewalk-outside");
|
||||
std::fs::create_dir_all(outside.join("moved/sub")).unwrap();
|
||||
std::fs::write(outside.join("moved/sub/m.txt"), b"m").unwrap();
|
||||
std::fs::rename(outside.join("moved"), root.join("moved")).unwrap();
|
||||
dirty.mark(1, "moved");
|
||||
|
||||
let unscanned = rewalk(&root, &rules_for(&[]), &dirty, &mut kept);
|
||||
assert!(unscanned.is_empty());
|
||||
let (full, _) = scan(&root).unwrap();
|
||||
assert_eq!(shape(&kept), shape(&full));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let _ = std::fs::remove_dir_all(&outside);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rewalk_takes_what_nothing_marked_from_the_kept_walk() {
|
||||
let root = sync_test_dir("rewalk-kept");
|
||||
std::fs::create_dir_all(root.join("quiet")).unwrap();
|
||||
std::fs::write(root.join("quiet/q.txt"), b"q").unwrap();
|
||||
let (mut kept, _) = scan(&root).unwrap();
|
||||
// Changed with no mark: the rewalk does not look, which is why only
|
||||
// a trusted claim may stand in for the walk.
|
||||
std::fs::write(root.join("quiet/q.txt"), b"changed unseen").unwrap();
|
||||
let before = shape(&kept);
|
||||
rewalk(
|
||||
&root,
|
||||
&rules_for(&[]),
|
||||
&crate::local_dirty::LocalDirty::default(),
|
||||
&mut kept,
|
||||
);
|
||||
assert_eq!(shape(&kept), before);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rewalk_leaves_ignored_folders_out_and_walks_from_a_known_folder() {
|
||||
let root = sync_test_dir("rewalk-ignored");
|
||||
let rules = rules_for(&["build/"]);
|
||||
let (mut kept, _) = scan(&root).unwrap();
|
||||
let dirty = crate::local_dirty::LocalDirty::default();
|
||||
std::fs::create_dir_all(root.join("build/out")).unwrap();
|
||||
std::fs::write(root.join("build/out/o.bin"), b"o").unwrap();
|
||||
dirty.mark(1, "build/out/o.bin");
|
||||
// A file in a folder whose own mark never came.
|
||||
std::fs::create_dir_all(root.join("src/mod")).unwrap();
|
||||
std::fs::write(root.join("src/mod/s.rs"), b"s").unwrap();
|
||||
dirty.mark(1, "src/mod/s.rs");
|
||||
rewalk(&root, &rules, &dirty, &mut kept);
|
||||
let found: Vec<String> = shape(&kept).into_iter().map(|(rel, ..)| rel).collect();
|
||||
assert_eq!(found, ["src", "src/mod", "src/mod/s.rs"]);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rewalk_reads_again_a_file_that_was_open_for_writing() {
|
||||
let root = sync_test_dir("rewalk-open");
|
||||
std::fs::write(root.join("log.txt"), b"one").unwrap();
|
||||
let (mut kept, _) = scan(&root).unwrap();
|
||||
kept.get_mut("log.txt").unwrap().open_for_write = true;
|
||||
std::fs::write(root.join("log.txt"), b"one and two").unwrap();
|
||||
rewalk(
|
||||
&root,
|
||||
&rules_for(&[]),
|
||||
&crate::local_dirty::LocalDirty::default(),
|
||||
&mut kept,
|
||||
);
|
||||
let item = &kept["log.txt"];
|
||||
assert_eq!(item.size, 11);
|
||||
assert!(!item.open_for_write, "closed now");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mark_on_the_root_walks_everything() {
|
||||
let root = sync_test_dir("rewalk-root");
|
||||
let (mut kept, _) = scan(&root).unwrap();
|
||||
std::fs::write(root.join("top.txt"), b"t").unwrap();
|
||||
let dirty = crate::local_dirty::LocalDirty::default();
|
||||
dirty.mark(1, "");
|
||||
rewalk(&root, &rules_for(&[]), &dirty, &mut kept);
|
||||
assert!(kept.contains_key("top.txt"));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
@@ -134,6 +134,105 @@ impl Syncer {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write the intent of `op` before it is sent (`effect`). In shadow: a
|
||||
/// failure to write it is logged, and the op is sent anyway.
|
||||
fn issue_intent(&self, folder_id: i64, op: &Pending) -> Option<StoredIntent> {
|
||||
let (intent, before) = match self.store.sync_intent_issue(
|
||||
folder_id,
|
||||
op.rel(),
|
||||
op.intent(),
|
||||
now_secs(),
|
||||
) {
|
||||
Ok(issued) => issued,
|
||||
Err(e) => {
|
||||
debug!(id = folder_id, rel = op.rel(), error = ?e, "sync: cannot record an intent");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
match before.as_deref().and_then(EffectState::from_name) {
|
||||
// Sent by a daemon that stopped before it heard back. The apply
|
||||
// step's own checks tell whether it landed (B266, B39).
|
||||
Some(EffectState::Unsure) => {
|
||||
self.trace_count(Count::UnsureResent, 1);
|
||||
info!(
|
||||
id = folder_id,
|
||||
rel = op.rel(),
|
||||
kind = op.intent(),
|
||||
attempts = intent.attempts,
|
||||
"sync: sending again an effect a stopped daemon may have made"
|
||||
);
|
||||
}
|
||||
Some(EffectState::Retry | EffectState::Blocked) => {
|
||||
self.trace_count(Count::Retried, 1);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Some(intent)
|
||||
}
|
||||
|
||||
/// Settle or keep `intent` by how its op ended.
|
||||
fn settle_intent(&self, intent: &StoredIntent, op: &Pending, result: &Result<Applied, String>) {
|
||||
let written = match result {
|
||||
Ok(_) => self.store.sync_intent_settle(intent.id),
|
||||
Err(e) => {
|
||||
let state = effect::failed(intent.attempts);
|
||||
if state == EffectState::Blocked && intent.state != EffectState::Blocked.name() {
|
||||
warn!(
|
||||
id = intent.folder_id,
|
||||
rel = op.rel(),
|
||||
kind = op.intent(),
|
||||
attempts = intent.attempts,
|
||||
error = %e,
|
||||
"sync: an effect keeps failing"
|
||||
);
|
||||
}
|
||||
self.store.sync_intent_set(intent.id, state.name(), Some(e))
|
||||
}
|
||||
};
|
||||
if let Err(e) = written {
|
||||
debug!(id = intent.folder_id, rel = op.rel(), error = ?e, "sync: cannot settle an intent");
|
||||
}
|
||||
}
|
||||
|
||||
/// Settle the intents of `folder_id` that a pass begun at `began` did
|
||||
/// not send again, though it looked at every path: what they were for has
|
||||
/// changed, or is done.
|
||||
pub(super) fn supersede_intents(&self, folder_id: i64, began: i64) {
|
||||
let states = [
|
||||
EffectState::Unsure.name(),
|
||||
EffectState::Retry.name(),
|
||||
EffectState::Blocked.name(),
|
||||
];
|
||||
match self
|
||||
.store
|
||||
.sync_intents_settle_before(folder_id, &states, began)
|
||||
{
|
||||
Ok(settled) => {
|
||||
self.trace_count(Count::Superseded, settled.len());
|
||||
for intent in settled {
|
||||
let level_info = intent.state == EffectState::Unsure.name();
|
||||
if level_info {
|
||||
info!(
|
||||
id = folder_id,
|
||||
rel = %intent.rel_path,
|
||||
kind = %intent.kind,
|
||||
"sync: an effect a stopped daemon may have made is no longer needed"
|
||||
);
|
||||
} else {
|
||||
debug!(
|
||||
id = folder_id,
|
||||
rel = %intent.rel_path,
|
||||
kind = %intent.kind,
|
||||
state = %intent.state,
|
||||
"sync: an effect is no longer needed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => debug!(id = folder_id, error = ?e, "sync: cannot settle intents"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a removal of `folder_id` is waiting for its running pass.
|
||||
pub(super) fn pass_abandoned(&self, folder_id: i64) -> bool {
|
||||
self.abandon.lock().contains(&folder_id)
|
||||
@@ -150,9 +249,13 @@ impl Syncer {
|
||||
op: Pending,
|
||||
) -> Result<Applied, String> {
|
||||
self.progress_started(folder_id, base_name(op.rel()));
|
||||
let intent = self.issue_intent(folder_id, &op);
|
||||
let step = Instant::now();
|
||||
let result = self.apply_one(folder_id, local_root, &op).await;
|
||||
self.trace_call(op.call(), step.elapsed());
|
||||
if let Some(intent) = intent {
|
||||
self.settle_intent(&intent, &op, &result);
|
||||
}
|
||||
self.progress_finished(folder_id);
|
||||
let name = base_name(op.rel());
|
||||
match &result {
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::collections::BTreeMap;
|
||||
|
||||
use super::trace::PassTrace;
|
||||
use super::*;
|
||||
use crate::local_dirty::LocalDirty;
|
||||
use crate::local_dirty::{LocalDirty, root_id};
|
||||
use crate::root::{Doubt, RootInput};
|
||||
|
||||
/// How long the watcher must go quiet before a burst counts as finished.
|
||||
@@ -242,6 +242,19 @@ pub fn run(core: Syncer, rx: Receiver<SyncMsg>) {
|
||||
),
|
||||
Err(e) => warn!(error = ?e, "sync: cannot reset folders left syncing"),
|
||||
}
|
||||
// An effect still `issued` was sent by a daemon that stopped before it
|
||||
// heard back: it may or may not have happened (`effect`).
|
||||
match core.store.sync_intents_move(
|
||||
effect::EffectState::Issued.name(),
|
||||
effect::EffectState::Unsure.name(),
|
||||
) {
|
||||
Ok(0) => {}
|
||||
Ok(n) => info!(
|
||||
effects = n,
|
||||
"sync: effects the last run sent and did not hear back from"
|
||||
),
|
||||
Err(e) => warn!(error = ?e, "sync: cannot read the effects the last run sent"),
|
||||
}
|
||||
// Paths the watcher currently covers, mapped to their folder id, so an event
|
||||
// path can be resolved back to the folder it belongs to.
|
||||
let watched: Arc<Mutex<Vec<(PathBuf, i64)>>> = Arc::new(Mutex::new(Vec::new()));
|
||||
@@ -306,7 +319,7 @@ pub fn run(core: Syncer, rx: Receiver<SyncMsg>) {
|
||||
.ok();
|
||||
}
|
||||
|
||||
let mut unwatched = rewatch(&core, &mut watcher, &watched);
|
||||
let (mut unwatched, _) = rewatch(&core, &mut watcher, &watched);
|
||||
let mut last_rewatch = Instant::now();
|
||||
run_burst(&core, &HashSet::new(), true);
|
||||
|
||||
@@ -327,7 +340,14 @@ pub fn run(core: Syncer, rx: Receiver<SyncMsg>) {
|
||||
do_rewatch = true;
|
||||
}
|
||||
if do_rewatch {
|
||||
unwatched = rewatch(&core, &mut watcher, &watched);
|
||||
let newly;
|
||||
(unwatched, newly) = rewatch(&core, &mut watcher, &watched);
|
||||
// A change made before its folder was watched has no event. A
|
||||
// folder whose root came back was watched only after the pass
|
||||
// that found it walked it, so what was written in between waits
|
||||
// for this pass, which walks it in full: its claim is not trusted
|
||||
// yet.
|
||||
ids.extend(newly);
|
||||
last_rewatch = Instant::now();
|
||||
}
|
||||
run_burst(&core, &ids, all);
|
||||
@@ -540,18 +560,20 @@ pub(super) fn mark_dirty(dirty: &LocalDirty, watched: &[(PathBuf, i64)], paths:
|
||||
let Ok(rel) = path.strip_prefix(root) else {
|
||||
continue;
|
||||
};
|
||||
// The walk leaves out a name that is not UTF-8, so there is nothing
|
||||
// to mark for one.
|
||||
let parts: Option<Vec<&str>> = rel.components().map(|c| c.as_os_str().to_str()).collect();
|
||||
if let Some(parts) = parts {
|
||||
dirty.mark(*id, &parts.join("/"));
|
||||
}
|
||||
// A name that is not UTF-8 cannot be keyed: the folder that holds
|
||||
// it is marked instead, so the walk of it reports the name it leaves
|
||||
// out.
|
||||
let parts: Vec<&str> = rel
|
||||
.components()
|
||||
.map_while(|c| c.as_os_str().to_str())
|
||||
.collect();
|
||||
dirty.mark(*id, &parts.join("/"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Bring the filesystem watches in line with the current mirror-folder set:
|
||||
/// watch newly-added folders, drop removed ones. Returns whether a folder is
|
||||
/// left unwatched because its watch failed.
|
||||
/// left unwatched because its watch failed, and the folders watched anew.
|
||||
///
|
||||
/// The watch calls run on a copy, outside the lock: the watcher's event
|
||||
/// callback takes the same lock, and a backend that hands a watch request to
|
||||
@@ -560,7 +582,7 @@ fn rewatch(
|
||||
core: &Syncer,
|
||||
watcher: &mut notify::RecommendedWatcher,
|
||||
watched: &Mutex<Vec<(PathBuf, i64)>>,
|
||||
) -> bool {
|
||||
) -> (bool, Vec<i64>) {
|
||||
let want: Vec<(PathBuf, i64)> = match core.store.sync_folder_list() {
|
||||
Ok(f) => f
|
||||
.into_iter()
|
||||
@@ -569,7 +591,7 @@ fn rewatch(
|
||||
.collect(),
|
||||
Err(e) => {
|
||||
warn!(error = ?e, "sync: cannot list folders to watch");
|
||||
return false;
|
||||
return (false, Vec::new());
|
||||
}
|
||||
};
|
||||
let mut have = watched.lock().clone();
|
||||
@@ -582,8 +604,23 @@ fn rewatch(
|
||||
core.roots.forget(*id);
|
||||
}
|
||||
}
|
||||
// A root that is gone took its watch with it, and a root made again is
|
||||
// another folder than the one watched: drop the watch, so the root is
|
||||
// watched again below.
|
||||
have.retain(|(path, id)| {
|
||||
let same = core
|
||||
.local_dirty
|
||||
.watched_root(*id)
|
||||
.is_some_and(|root| root_id(path) == Some(root));
|
||||
if !same {
|
||||
let _ = watcher.unwatch(path);
|
||||
core.local_dirty.unwatched(*id);
|
||||
}
|
||||
same
|
||||
});
|
||||
// Add newly wanted watches.
|
||||
let mut failed = false;
|
||||
let mut newly = Vec::new();
|
||||
for (path, id) in &want {
|
||||
if have.iter().any(|(p, _)| p == path) {
|
||||
continue;
|
||||
@@ -591,7 +628,8 @@ fn rewatch(
|
||||
match watcher.watch(path, RecursiveMode::Recursive) {
|
||||
Ok(()) => {
|
||||
have.push((path.clone(), *id));
|
||||
core.local_dirty.watched(*id);
|
||||
core.local_dirty.watched(*id, root_id(path));
|
||||
newly.push(*id);
|
||||
}
|
||||
Err(e) => {
|
||||
core.local_dirty.unwatched(*id);
|
||||
@@ -610,7 +648,7 @@ fn rewatch(
|
||||
}
|
||||
}
|
||||
*watched.lock() = have;
|
||||
failed
|
||||
(failed, newly)
|
||||
}
|
||||
|
||||
/// Keep the watches in `have` that `want` still asks for, and return the paths
|
||||
|
||||
@@ -19,8 +19,9 @@ use tracing::{debug, warn};
|
||||
|
||||
use super::model::{LocalItem, LocalSig, system_mtime, system_mtime_ns};
|
||||
use super::planner::{
|
||||
Unscanned, conflict_path_with_suffix, filter_baseline, join_rel, rel_to_path,
|
||||
Unscanned, conflict_path_with_suffix, filter_baseline, join_rel, parent_rel, rel_to_path,
|
||||
};
|
||||
use crate::local_dirty::Claim;
|
||||
|
||||
/// A local file's identity and content SHA-1, both read from one descriptor,
|
||||
/// or `None` when it is gone. The identity is taken after the hash, so a file
|
||||
@@ -270,90 +271,271 @@ pub(super) fn walk_local_dir(
|
||||
let entries = std::fs::read_dir(dir).map_err(io(format!("read {}", dir.display())))?;
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(io(format!("read entry in {}", dir.display())))?;
|
||||
let path = entry.path();
|
||||
let stripped = path.strip_prefix(root).map_err(|e| {
|
||||
ScanError::Failed(format!(
|
||||
"local path {} escaped sync root {}: {e}",
|
||||
path.display(),
|
||||
root.display()
|
||||
))
|
||||
})?;
|
||||
let Some(rel) = stripped.to_str() else {
|
||||
// Nothing can be keyed by this name: not the baseline, which only
|
||||
// ever held paths this scan produced, and not Drive, whose names are
|
||||
// UTF-8. Leaving it out cannot read as a deletion of anything.
|
||||
warn!(path = %path.display(), "sync: name is not valid UTF-8; leaving it out of the pass");
|
||||
unscanned.unreadable(
|
||||
stripped.to_string_lossy().into_owned(),
|
||||
"name is not valid UTF-8",
|
||||
);
|
||||
continue;
|
||||
};
|
||||
// Ignore our own in-flight download temp files.
|
||||
if rel.contains(".pdfs-tmp-") {
|
||||
walk_local_entry(root, &entry.path(), rules, writing, out, unscanned, scanned)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Collect one entry of the local tree, at `path`, into `out`: a file, or a
|
||||
/// folder with everything under it. What cannot be read goes to `unscanned`,
|
||||
/// as in [`walk_local_tree`].
|
||||
pub(super) fn walk_local_entry(
|
||||
root: &Path,
|
||||
path: &Path,
|
||||
rules: &IgnoreRules,
|
||||
writing: &HashSet<PathBuf>,
|
||||
out: &mut HashMap<String, LocalItem>,
|
||||
unscanned: &mut Unscanned,
|
||||
scanned: &mut dyn FnMut(&str),
|
||||
) -> Result<(), ScanError> {
|
||||
let stripped = path.strip_prefix(root).map_err(|e| {
|
||||
ScanError::Failed(format!(
|
||||
"local path {} escaped sync root {}: {e}",
|
||||
path.display(),
|
||||
root.display()
|
||||
))
|
||||
})?;
|
||||
let Some(rel) = stripped.to_str() else {
|
||||
// Nothing can be keyed by this name: not the baseline, which only
|
||||
// ever held paths this scan produced, and not Drive, whose names are
|
||||
// UTF-8. Leaving it out cannot read as a deletion of anything.
|
||||
warn!(path = %path.display(), "sync: name is not valid UTF-8; leaving it out of the pass");
|
||||
unscanned.unreadable(
|
||||
stripped.to_string_lossy().into_owned(),
|
||||
"name is not valid UTF-8",
|
||||
);
|
||||
return Ok(());
|
||||
};
|
||||
// Ignore our own in-flight download temp files.
|
||||
if rel.contains(".pdfs-tmp-") {
|
||||
return Ok(());
|
||||
}
|
||||
let meta = match std::fs::symlink_metadata(path) {
|
||||
Ok(meta) => meta,
|
||||
// Gone since the listing, or in a folder that lists but does not
|
||||
// allow `stat`. Either way this pass cannot say what it is.
|
||||
Err(error) => {
|
||||
let what = format!("stat {}", path.display());
|
||||
return leave_out(rel, ScanError::Io { what, error }, unscanned);
|
||||
}
|
||||
};
|
||||
// Ignored paths are dropped here as well as from the classification
|
||||
// union — not for correctness (the union filter is what makes this
|
||||
// safe) but so an ignored `node_modules/` is never descended into or
|
||||
// counted against scan progress.
|
||||
if rules.is_ignored(rel, meta.is_dir()) {
|
||||
return Ok(());
|
||||
}
|
||||
if meta.is_dir() {
|
||||
out.insert(
|
||||
rel.to_string(),
|
||||
LocalItem {
|
||||
is_dir: true,
|
||||
mtime: 0,
|
||||
mtime_ns: None,
|
||||
size: 0,
|
||||
open_for_write: false,
|
||||
},
|
||||
);
|
||||
scanned(rel);
|
||||
if let Err(failure) = walk_local_dir(root, path, rules, writing, out, unscanned, scanned) {
|
||||
leave_out(rel, failure, unscanned)?;
|
||||
// What the folder did list before failing goes with it: a
|
||||
// half-read folder is as unknown as an unread one.
|
||||
let prefix = format!("{rel}/");
|
||||
out.retain(|k, _| k != rel && !k.starts_with(&prefix));
|
||||
}
|
||||
} else if meta.is_file() {
|
||||
// Check whether any process holds this file open for writing.
|
||||
// The canonical path is used because /proc/*/fd links resolve
|
||||
// to canonical targets.
|
||||
let ofw = std::fs::canonicalize(path)
|
||||
.map(|canon| writing.contains(&canon))
|
||||
.unwrap_or(false);
|
||||
out.insert(
|
||||
rel.to_string(),
|
||||
LocalItem {
|
||||
is_dir: false,
|
||||
mtime: system_mtime(&meta),
|
||||
mtime_ns: system_mtime_ns(&meta),
|
||||
size: meta.len() as i64,
|
||||
open_for_write: ofw,
|
||||
},
|
||||
);
|
||||
scanned(rel);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Bring `items`, a walk of `root` that an earlier pass kept, up to date with
|
||||
/// what `claim` reports changed since, instead of walking the whole tree:
|
||||
///
|
||||
/// - each folder whose direct children changed is listed again: a child gone
|
||||
/// from it goes with everything under it, a child that is new or no longer
|
||||
/// the same kind is walked, and a subfolder still there keeps what the
|
||||
/// earlier walk found under it;
|
||||
/// - each path that changed in full is walked again, with what is under it;
|
||||
/// - each file that was open for writing is read again, since closing it is
|
||||
/// not a change the watcher reports.
|
||||
///
|
||||
/// Everything else stands as the earlier walk found it. That is only sound
|
||||
/// for a claim that is trusted, of a walk taken before it, with the same
|
||||
/// ignore rules: see `local_dirty`.
|
||||
pub(super) fn rewalk_local_tree(
|
||||
root: &Path,
|
||||
rules: &IgnoreRules,
|
||||
writing: &HashSet<PathBuf>,
|
||||
claim: &Claim,
|
||||
items: &mut HashMap<String, LocalItem>,
|
||||
unscanned: &mut Unscanned,
|
||||
scanned: &mut dyn FnMut(&str),
|
||||
) -> Result<(), String> {
|
||||
let walked = |rel: &str, items: &HashMap<String, LocalItem>| {
|
||||
rel.is_empty() || items.get(rel).is_some_and(|item| item.is_dir)
|
||||
};
|
||||
// A path whose folder the earlier walk did not find (a mark that came
|
||||
// before its folder's, or one in an ignored folder) is walked from the
|
||||
// nearest folder it did find.
|
||||
let anchored = |mut rel: String, items: &HashMap<String, LocalItem>| {
|
||||
while !walked(parent_rel(&rel), items) {
|
||||
rel = parent_rel(&rel).to_string();
|
||||
}
|
||||
rel
|
||||
};
|
||||
// Paths walked again in full.
|
||||
let mut again: Vec<String> = claim
|
||||
.deep()
|
||||
.map(str::to_string)
|
||||
.chain(
|
||||
items
|
||||
.iter()
|
||||
.filter(|(_, item)| item.open_for_write)
|
||||
.map(|(rel, _)| rel.clone()),
|
||||
)
|
||||
.map(|rel| anchored(rel, items))
|
||||
.collect();
|
||||
if again.iter().any(String::is_empty) {
|
||||
items.clear();
|
||||
return walk_local_tree(root, rules, writing, items, unscanned, scanned);
|
||||
}
|
||||
let mut folders: Vec<&str> = claim.shallow().collect();
|
||||
folders.sort_by_key(|dir| (dir.matches('/').count(), *dir));
|
||||
let mut children: HashMap<&str, Vec<String>> =
|
||||
folders.iter().map(|dir| (*dir, Vec::new())).collect();
|
||||
for rel in items.keys() {
|
||||
if let Some(of) = children.get_mut(parent_rel(rel)) {
|
||||
of.push(rel.clone());
|
||||
}
|
||||
}
|
||||
// Subtrees to drop from the earlier walk before walking anything again.
|
||||
let mut dropped: HashSet<String> = again.iter().cloned().collect();
|
||||
for dir in folders {
|
||||
if !walked(dir, items) {
|
||||
// Not a folder the earlier walk found: new, ignored, or no
|
||||
// longer a folder. It is walked in full.
|
||||
let rel = anchored(dir.to_string(), items);
|
||||
dropped.insert(rel.clone());
|
||||
again.push(rel);
|
||||
continue;
|
||||
}
|
||||
let meta = match std::fs::symlink_metadata(&path) {
|
||||
Ok(meta) => meta,
|
||||
// Gone since the listing, or in a folder that lists but does not
|
||||
// allow `stat`. Either way this pass cannot say what it is.
|
||||
let path = root.join(rel_to_path(dir));
|
||||
let listing = std::fs::read_dir(&path).and_then(|entries| {
|
||||
entries
|
||||
.map(|entry| entry.map(|entry| entry.path()))
|
||||
.collect::<std::io::Result<Vec<PathBuf>>>()
|
||||
});
|
||||
let listing = match listing {
|
||||
Ok(listing) => listing,
|
||||
Err(error) if dir.is_empty() => {
|
||||
return Err(format!("read {}: {error}", path.display()));
|
||||
}
|
||||
Err(error) => {
|
||||
let what = format!("stat {}", path.display());
|
||||
leave_out(rel, ScanError::Io { what, error }, unscanned)?;
|
||||
dropped.insert(dir.to_string());
|
||||
if error.kind() != std::io::ErrorKind::NotFound {
|
||||
let what = format!("read {}", path.display());
|
||||
leave_out(dir, ScanError::Io { what, error }, unscanned)
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// Ignored paths are dropped here as well as from the classification
|
||||
// union — not for correctness (the union filter is what makes this
|
||||
// safe) but so an ignored `node_modules/` is never descended into or
|
||||
// counted against scan progress.
|
||||
if rules.is_ignored(rel, meta.is_dir()) {
|
||||
continue;
|
||||
let mut present: HashSet<String> = HashSet::with_capacity(listing.len());
|
||||
for child in listing {
|
||||
let Some(rel) = child
|
||||
.strip_prefix(root)
|
||||
.ok()
|
||||
.and_then(|rel| rel.to_str())
|
||||
.map(str::to_string)
|
||||
else {
|
||||
// Walked again, so a name that cannot be keyed is reported
|
||||
// as a full walk reports it.
|
||||
again.push(dir.to_string());
|
||||
dropped.insert(dir.to_string());
|
||||
break;
|
||||
};
|
||||
let still_a_folder = items.get(&rel).is_some_and(|item| item.is_dir)
|
||||
&& std::fs::symlink_metadata(&child).is_ok_and(|meta| meta.is_dir());
|
||||
if !still_a_folder {
|
||||
dropped.insert(rel.clone());
|
||||
again.push(rel.clone());
|
||||
}
|
||||
present.insert(rel);
|
||||
}
|
||||
if meta.is_dir() {
|
||||
out.insert(
|
||||
rel.to_string(),
|
||||
LocalItem {
|
||||
is_dir: true,
|
||||
mtime: 0,
|
||||
mtime_ns: None,
|
||||
size: 0,
|
||||
open_for_write: false,
|
||||
},
|
||||
);
|
||||
scanned(rel);
|
||||
if let Err(failure) =
|
||||
walk_local_dir(root, &path, rules, writing, out, unscanned, scanned)
|
||||
{
|
||||
leave_out(rel, failure, unscanned)?;
|
||||
// What the folder did list before failing goes with it: a
|
||||
// half-read folder is as unknown as an unread one.
|
||||
let prefix = format!("{rel}/");
|
||||
out.retain(|k, _| k != rel && !k.starts_with(&prefix));
|
||||
for rel in &children[dir] {
|
||||
if !present.contains(rel) {
|
||||
dropped.insert(rel.clone());
|
||||
}
|
||||
} else if meta.is_file() {
|
||||
// Check whether any process holds this file open for writing.
|
||||
// The canonical path is used because /proc/*/fd links resolve
|
||||
// to canonical targets.
|
||||
let ofw = std::fs::canonicalize(&path)
|
||||
.map(|canon| writing.contains(&canon))
|
||||
.unwrap_or(false);
|
||||
out.insert(
|
||||
rel.to_string(),
|
||||
LocalItem {
|
||||
is_dir: false,
|
||||
mtime: system_mtime(&meta),
|
||||
mtime_ns: system_mtime_ns(&meta),
|
||||
size: meta.len() as i64,
|
||||
open_for_write: ofw,
|
||||
},
|
||||
);
|
||||
scanned(rel);
|
||||
}
|
||||
}
|
||||
items.retain(|rel, _| !under_any(rel, &dropped));
|
||||
again.sort_by_key(|rel| (rel.matches('/').count(), rel.clone()));
|
||||
again.dedup();
|
||||
let mut walked_again: HashSet<String> = HashSet::new();
|
||||
for rel in again {
|
||||
if under_any(&rel, &walked_again) {
|
||||
continue;
|
||||
}
|
||||
let path = root.join(rel_to_path(&rel));
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Ok(_) => {
|
||||
walk_local_entry(root, &path, rules, writing, items, unscanned, scanned)
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
// Gone since it was marked, or its folder is no longer one:
|
||||
// nothing to find.
|
||||
Err(error)
|
||||
if matches!(
|
||||
error.kind(),
|
||||
std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
|
||||
) => {}
|
||||
Err(error) => {
|
||||
let what = format!("stat {}", path.display());
|
||||
leave_out(&rel, ScanError::Io { what, error }, unscanned)
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
walked_again.insert(rel);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether `rel` is one of `roots` or lies under one.
|
||||
fn under_any(rel: &str, roots: &HashSet<String>) -> bool {
|
||||
if roots.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let mut at = rel;
|
||||
loop {
|
||||
if roots.contains(at) {
|
||||
return true;
|
||||
}
|
||||
match at.rfind('/') {
|
||||
Some(i) => at = &at[..i],
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the mirror copy at `rel` holds something Proton Drive does not, or
|
||||
/// `None` when everything under it is on Drive exactly as it is on disk.
|
||||
///
|
||||
|
||||
@@ -79,18 +79,25 @@ impl Syncer {
|
||||
/// folder's baseline changes, so a resumed walk never meets a baseline
|
||||
/// newer than its listings; it is as old as a long walk's first listings
|
||||
/// would be, and the apply step checks each file again before it acts.
|
||||
///
|
||||
/// With `reuse` false, a complete saved walk is not used: the root state
|
||||
/// owes Drive a walk in full. Returns whether the walk covered all of
|
||||
/// Drive's side, rather than only the folders marked dirty.
|
||||
pub(super) fn walk_remote(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
root: &NodeUid,
|
||||
walk: &mut RemoteWalk<'_>,
|
||||
baseline: &HashMap<String, StoredSyncEntry>,
|
||||
) -> Result<(), PassAbort> {
|
||||
reuse: bool,
|
||||
) -> Result<bool, PassAbort> {
|
||||
let WalkStart {
|
||||
mut todo,
|
||||
mut children,
|
||||
dirty_upto,
|
||||
} = self.start_walk(folder_id, root, walk);
|
||||
} = self.start_walk(folder_id, root, walk, reuse);
|
||||
// Started from the saved picture, the walk lists only what changed.
|
||||
let in_full = children.is_none();
|
||||
// Folders to list again next pass: their listing failed or came back
|
||||
// short this time.
|
||||
let mut again: Vec<String> = Vec::new();
|
||||
@@ -221,7 +228,8 @@ impl Syncer {
|
||||
return Err(PassAbort::Stopped);
|
||||
}
|
||||
self.finish_walk(folder_id, dirty_upto, &again)
|
||||
.map_err(|e| PassAbort::from(format!("save the walk of Drive: {e:?}")))
|
||||
.map_err(|e| PassAbort::from(format!("save the walk of Drive: {e:?}")))?;
|
||||
Ok(in_full)
|
||||
}
|
||||
|
||||
/// Keep a walk that reached its end as the next pass's picture of Drive.
|
||||
@@ -264,6 +272,7 @@ impl Syncer {
|
||||
folder_id: i64,
|
||||
root: &NodeUid,
|
||||
walk: &mut RemoteWalk<'_>,
|
||||
reuse: bool,
|
||||
) -> WalkStart {
|
||||
let root_uid = root.to_string();
|
||||
let saved = match self.store.sync_walk_load(folder_id) {
|
||||
@@ -277,9 +286,17 @@ impl Syncer {
|
||||
&& saved.root_uid == root_uid
|
||||
{
|
||||
let age = now_secs().saturating_sub(saved.started);
|
||||
if saved.complete
|
||||
let fresh = saved.complete
|
||||
&& age < AUDIT_INTERVAL.as_secs() as i64
|
||||
&& self.events_trusted(root)
|
||||
&& self.events_trusted(root);
|
||||
if fresh && !reuse {
|
||||
info!(
|
||||
id = folder_id,
|
||||
"sync: the root state asks for a walk of all of Drive"
|
||||
);
|
||||
}
|
||||
if fresh
|
||||
&& reuse
|
||||
&& let Some(start) = self.walk_dirty(folder_id, &saved, walk)
|
||||
{
|
||||
return start;
|
||||
|
||||
@@ -146,6 +146,15 @@ pub struct Outcome {
|
||||
/// The first step that failed in this pass, so the line that ends a pass
|
||||
/// in `error` says why without a search back through the journal.
|
||||
pub first_error: Option<String>,
|
||||
/// Changes the pass made on disk itself: files downloaded, conflict
|
||||
/// copies kept, folders made, and files and folders removed. Not part of
|
||||
/// the summary, which counts them by kind; a pass that made any does not
|
||||
/// keep its walk for the next one (`local_dirty`).
|
||||
pub local_changes: usize,
|
||||
/// Which sides the pass walked in full, rather than bringing the last
|
||||
/// walk up to date from the dirty set: the disk, and Drive. The root
|
||||
/// state counts a side covered only after a walk in full (`root`).
|
||||
pub walked_in_full: (bool, bool),
|
||||
}
|
||||
|
||||
impl Outcome {
|
||||
@@ -162,8 +171,14 @@ impl Outcome {
|
||||
match applied {
|
||||
Applied::Dir(..) => self.created += 1,
|
||||
Applied::Uploaded => self.uploaded += 1,
|
||||
Applied::Downloaded => self.downloaded += 1,
|
||||
Applied::Conflict => self.conflicts += 1,
|
||||
Applied::Downloaded => {
|
||||
self.downloaded += 1;
|
||||
self.local_changes += 1;
|
||||
}
|
||||
Applied::Conflict => {
|
||||
self.conflicts += 1;
|
||||
self.local_changes += 1;
|
||||
}
|
||||
Applied::Vanished | Applied::Adopted => {}
|
||||
}
|
||||
}
|
||||
@@ -292,6 +307,19 @@ impl Pending {
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind of effect its intent records (`effect`).
|
||||
pub fn intent(&self) -> &'static str {
|
||||
match self {
|
||||
Pending::CreateDir { .. } => "create-folder",
|
||||
Pending::UploadNew { .. } => "upload",
|
||||
Pending::UploadRevision { .. } => "upload-revision",
|
||||
Pending::Download { .. } => "download",
|
||||
Pending::Adopt { .. } => "adopt",
|
||||
Pending::Conflict { .. } => "conflict",
|
||||
Pending::PushConflict { .. } => "push-conflict",
|
||||
}
|
||||
}
|
||||
|
||||
/// The activity line's detail, which distinguishes ops that share a kind.
|
||||
pub fn detail(&self) -> &'static str {
|
||||
match self {
|
||||
|
||||
@@ -126,6 +126,11 @@ impl Unscanned {
|
||||
.insert(rel, crate::evidence::Unknown::Unreadable);
|
||||
}
|
||||
|
||||
/// Whether nothing was left out.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.covered.is_empty()
|
||||
}
|
||||
|
||||
/// Whether `rel` is a left-out path or lies under one.
|
||||
pub fn covers(&self, rel: &str) -> bool {
|
||||
self.why(rel).is_some()
|
||||
|
||||
+302
-84
@@ -5,23 +5,29 @@
|
||||
//! state. Time, the watcher, the event stream and the passes stay outside, as
|
||||
//! inputs, so a sequence of inputs replays exactly.
|
||||
//!
|
||||
//! The states say how far the engine can trust what it has seen:
|
||||
//! The phases say how far the engine can trust what it has seen:
|
||||
//!
|
||||
//! - **Discovering**: no pass over the folder has finished yet.
|
||||
//! - **Following**: a pass covered the whole folder, and nothing since says a
|
||||
//! change could have gone unreported.
|
||||
//! - **Following**: passes covered the whole folder, and nothing since says a
|
||||
//! change could have gone unreported. A pass may work from the dirty sets.
|
||||
//! - **Auditing**: something did (a lost watch, an overflowed queue, a gap in
|
||||
//! Drive's event stream, a restart, a suspension). Only a pass over the
|
||||
//! whole folder brings it back to Following.
|
||||
//! Drive's event stream, a restart). Only a pass that walks the doubted
|
||||
//! side in full brings it back to Following.
|
||||
//! - **Suspended**: the folder cannot be synced for now: its local root is
|
||||
//! missing, or sync is paused.
|
||||
//! - **Draining**: a switch to on-demand is queued; passes only push.
|
||||
//! - **HandedOff**: the folder is on-demand.
|
||||
//!
|
||||
//! For now the reducer is run alongside the engine and acted on by nothing:
|
||||
//! every pass still covers the whole folder. Its transitions are logged, so
|
||||
//! they can be compared with what the engine did before anything relies on
|
||||
//! them.
|
||||
//! A doubt is about one side. The disk is followed by the watcher and Drive
|
||||
//! by its event stream, and each can fail on its own: a restart misses what
|
||||
//! happened on disk while the daemon was down, but the event stream resumes
|
||||
//! from its cursor. So the state keeps a doubt for each side ([`Owed`]), and
|
||||
//! a pass walks in full only the side that is owed.
|
||||
//!
|
||||
//! A pass asks [`Roots::owed`] before it walks. The checks a pass made
|
||||
//! before the reducer was acted on (a trusted watch, a fresh event stream,
|
||||
//! the audit intervals) still apply on top: the reducer can make a pass walk
|
||||
//! more, never less.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
@@ -29,19 +35,82 @@ use std::fmt;
|
||||
use parking_lot::Mutex;
|
||||
use tracing::info;
|
||||
|
||||
/// Why a folder's coverage is in doubt.
|
||||
/// Why a side of a folder is in doubt.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Doubt {
|
||||
/// The daemon started: nothing was watched while it was down.
|
||||
/// Nothing has walked this side yet.
|
||||
FirstSync,
|
||||
/// The daemon started: nothing watched the disk while it was down.
|
||||
Restart,
|
||||
/// The filesystem watcher reported an error.
|
||||
/// The filesystem watcher reported an error, or the folder's watch is
|
||||
/// gone.
|
||||
WatchLost,
|
||||
/// The watcher's event queue overflowed.
|
||||
Overflow,
|
||||
/// Drive's event stream lost changes.
|
||||
EventGap,
|
||||
/// The folder was suspended, and nothing was followed meanwhile.
|
||||
Suspension,
|
||||
/// The folder only pushed for a while, which drops its picture of Drive.
|
||||
Pushed,
|
||||
}
|
||||
|
||||
impl Doubt {
|
||||
/// Whether this doubt is about the disk, and whether about Drive.
|
||||
fn sides(self) -> (bool, bool) {
|
||||
match self {
|
||||
Doubt::FirstSync => (true, true),
|
||||
Doubt::Restart | Doubt::WatchLost | Doubt::Overflow => (true, false),
|
||||
Doubt::EventGap | Doubt::Pushed => (false, true),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a pass owes a folder: the sides it must walk in full, each with the
|
||||
/// first doubt that made it so.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Owed {
|
||||
pub local: Option<Doubt>,
|
||||
pub remote: Option<Doubt>,
|
||||
}
|
||||
|
||||
impl Owed {
|
||||
/// Both sides, for a folder nothing has walked.
|
||||
pub const ALL: Owed = Owed {
|
||||
local: Some(Doubt::FirstSync),
|
||||
remote: Some(Doubt::FirstSync),
|
||||
};
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.local.is_none() && self.remote.is_none()
|
||||
}
|
||||
|
||||
/// Add `doubt` to the sides it is about. The first doubt on a side
|
||||
/// stays: it is the one to report.
|
||||
fn doubt(self, doubt: Doubt) -> Owed {
|
||||
let (local, remote) = doubt.sides();
|
||||
Owed {
|
||||
local: self.local.or(local.then_some(doubt)),
|
||||
remote: self.remote.or(remote.then_some(doubt)),
|
||||
}
|
||||
}
|
||||
|
||||
/// What is left once a pass walked the sides given in full.
|
||||
fn cover(self, local: bool, remote: bool) -> Owed {
|
||||
Owed {
|
||||
local: self.local.filter(|_| !local),
|
||||
remote: self.remote.filter(|_| !remote),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Owed {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match (self.local, self.remote) {
|
||||
(None, None) => f.write_str("nothing"),
|
||||
(Some(l), None) => write!(f, "local: {l:?}"),
|
||||
(None, Some(r)) => write!(f, "remote: {r:?}"),
|
||||
(Some(l), Some(r)) => write!(f, "local: {l:?}, remote: {r:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a folder is not synced for now.
|
||||
@@ -52,26 +121,67 @@ pub enum Suspension {
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RootState {
|
||||
pub enum Phase {
|
||||
Discovering,
|
||||
Following,
|
||||
Auditing(Doubt),
|
||||
Auditing,
|
||||
Suspended(Suspension),
|
||||
Draining,
|
||||
HandedOff,
|
||||
}
|
||||
|
||||
/// A folder's state: its phase, and what a pass owes it. Following owes
|
||||
/// nothing and Auditing owes something; a suspended folder keeps what it is
|
||||
/// owed for when it comes back.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct RootState {
|
||||
pub phase: Phase,
|
||||
pub owed: Owed,
|
||||
}
|
||||
|
||||
impl RootState {
|
||||
/// A folder no pass has walked.
|
||||
pub const NEW: RootState = RootState {
|
||||
phase: Phase::Discovering,
|
||||
owed: Owed::ALL,
|
||||
};
|
||||
|
||||
/// A folder synced before the daemon started: what happened on disk
|
||||
/// meanwhile went unwatched. Drive's event stream resumes from its
|
||||
/// cursor, and reports a gap when it cannot.
|
||||
pub const RESTARTED: RootState = RootState {
|
||||
phase: Phase::Auditing,
|
||||
owed: Owed {
|
||||
local: Some(Doubt::Restart),
|
||||
remote: None,
|
||||
},
|
||||
};
|
||||
|
||||
/// Following once nothing is owed. Otherwise a folder still discovering
|
||||
/// stays so, and any other is audited.
|
||||
fn settled(phase: Phase, owed: Owed) -> RootState {
|
||||
let phase = match phase {
|
||||
_ if owed.is_empty() => Phase::Following,
|
||||
Phase::Discovering => Phase::Discovering,
|
||||
_ => Phase::Auditing,
|
||||
};
|
||||
RootState { phase, owed }
|
||||
}
|
||||
}
|
||||
|
||||
/// Something that happened to a folder, as the reducer takes it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RootInput {
|
||||
/// A pass over the whole folder finished.
|
||||
Covered,
|
||||
/// A pass finished. It walked the disk in full when `local`, and Drive
|
||||
/// when `remote`; otherwise it worked from that side's dirty set.
|
||||
Covered { local: bool, remote: bool },
|
||||
/// A change may have gone unreported.
|
||||
Doubted(Doubt),
|
||||
/// The folder cannot be synced for now.
|
||||
Suspended(Suspension),
|
||||
/// Sync is no longer paused. A missing root is only found again by a
|
||||
/// pass that covers it.
|
||||
/// Sync is no longer paused. The watcher and the event stream kept
|
||||
/// running meanwhile, so the folder owes what it owed before. A missing
|
||||
/// root is only found again by a pass that covers it.
|
||||
Resumed,
|
||||
/// A switch to on-demand is queued.
|
||||
HandoffQueued,
|
||||
@@ -83,42 +193,60 @@ pub enum RootInput {
|
||||
|
||||
/// The state after `input`.
|
||||
pub fn step(state: RootState, input: RootInput) -> RootState {
|
||||
use RootState as S;
|
||||
match (state, input) {
|
||||
use Phase as P;
|
||||
let RootState { phase, owed } = state;
|
||||
let with = |phase| RootState { phase, owed };
|
||||
match (phase, input) {
|
||||
// An on-demand folder is not synced: only going back to a mirror
|
||||
// changes it, and that is a first sync over again.
|
||||
(S::HandedOff, RootInput::Mirrored) => S::Discovering,
|
||||
(S::HandedOff, _) => S::HandedOff,
|
||||
(S::Draining, RootInput::HandedOff) => S::HandedOff,
|
||||
// A switch called off: a mirror again, which followed nothing while
|
||||
// it pushed.
|
||||
(S::Draining, RootInput::Mirrored) => S::Auditing(Doubt::Suspension),
|
||||
(S::Draining, _) => S::Draining,
|
||||
(_, RootInput::HandoffQueued) => S::Draining,
|
||||
(_, RootInput::HandedOff) => S::HandedOff,
|
||||
(S::Suspended(_), RootInput::Covered) => S::Following,
|
||||
(S::Suspended(Suspension::Paused), RootInput::Resumed) => S::Auditing(Doubt::Suspension),
|
||||
(S::Suspended(_), RootInput::Suspended(why)) => S::Suspended(why),
|
||||
(S::Suspended(why), _) => S::Suspended(why),
|
||||
(_, RootInput::Suspended(why)) => S::Suspended(why),
|
||||
(_, RootInput::Covered) => S::Following,
|
||||
(S::Following, RootInput::Doubted(why)) => S::Auditing(why),
|
||||
// A first sync and an audit cover everything anyway; the first doubt
|
||||
// is the one to report.
|
||||
(state, _) => state,
|
||||
(P::HandedOff, RootInput::Mirrored) => RootState::NEW,
|
||||
(P::HandedOff, _) => state,
|
||||
(P::Draining, RootInput::HandedOff) => with(P::HandedOff),
|
||||
// A switch called off: a mirror again. The push passes dropped the
|
||||
// picture of Drive; the disk stayed watched.
|
||||
(P::Draining, RootInput::Mirrored) => {
|
||||
RootState::settled(P::Auditing, owed.doubt(Doubt::Pushed))
|
||||
}
|
||||
(P::Draining, _) => state,
|
||||
(_, RootInput::HandoffQueued) => with(P::Draining),
|
||||
(_, RootInput::HandedOff) => with(P::HandedOff),
|
||||
// A suspended folder is still watched, and owes what went wrong
|
||||
// meanwhile when it comes back.
|
||||
(P::Suspended(_), RootInput::Doubted(why)) => RootState {
|
||||
phase,
|
||||
owed: owed.doubt(why),
|
||||
},
|
||||
(P::Suspended(_), RootInput::Covered { local, remote }) => {
|
||||
RootState::settled(P::Auditing, owed.cover(local, remote))
|
||||
}
|
||||
(P::Suspended(Suspension::Paused), RootInput::Resumed) => {
|
||||
RootState::settled(P::Auditing, owed)
|
||||
}
|
||||
(P::Suspended(_), RootInput::Suspended(why)) => with(P::Suspended(why)),
|
||||
(P::Suspended(_), _) => state,
|
||||
(_, RootInput::Suspended(why)) => with(P::Suspended(why)),
|
||||
(_, RootInput::Doubted(why)) => RootState::settled(phase, owed.doubt(why)),
|
||||
(_, RootInput::Covered { local, remote }) => {
|
||||
RootState::settled(phase, owed.cover(local, remote))
|
||||
}
|
||||
(_, RootInput::Resumed | RootInput::Mirrored) => state,
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RootState {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
RootState::Discovering => f.write_str("discovering"),
|
||||
RootState::Following => f.write_str("following"),
|
||||
RootState::Auditing(why) => write!(f, "auditing ({why:?})"),
|
||||
RootState::Suspended(why) => write!(f, "suspended ({why:?})"),
|
||||
RootState::Draining => f.write_str("draining"),
|
||||
RootState::HandedOff => f.write_str("handed off"),
|
||||
match self.phase {
|
||||
Phase::Discovering => f.write_str("discovering")?,
|
||||
Phase::Following => f.write_str("following")?,
|
||||
Phase::Auditing => f.write_str("auditing")?,
|
||||
Phase::Suspended(why) => write!(f, "suspended ({why:?})")?,
|
||||
Phase::Draining => f.write_str("draining")?,
|
||||
Phase::HandedOff => f.write_str("handed off")?,
|
||||
}
|
||||
if !self.owed.is_empty() && self.phase != Phase::Discovering {
|
||||
write!(f, " ({})", self.owed)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,16 +258,16 @@ pub struct Roots {
|
||||
|
||||
impl Roots {
|
||||
/// Start following `folder`, unless it already is: from discovery for a
|
||||
/// folder never synced, and otherwise from an audit, since nothing
|
||||
/// watched it while the daemon was down.
|
||||
/// folder never synced, and otherwise from an audit of the disk, since
|
||||
/// nothing watched it while the daemon was down.
|
||||
pub fn begin(&self, folder: i64, synced_before: bool) {
|
||||
self.states
|
||||
.lock()
|
||||
.entry(folder)
|
||||
.or_insert(if synced_before {
|
||||
RootState::Auditing(Doubt::Restart)
|
||||
RootState::RESTARTED
|
||||
} else {
|
||||
RootState::Discovering
|
||||
RootState::NEW
|
||||
});
|
||||
}
|
||||
|
||||
@@ -170,6 +298,12 @@ impl Roots {
|
||||
self.states.lock().get(&folder).copied()
|
||||
}
|
||||
|
||||
/// What a pass over `folder` must walk in full. A folder not begun is
|
||||
/// owed everything.
|
||||
pub fn owed(&self, folder: i64) -> Owed {
|
||||
self.state(folder).map_or(Owed::ALL, |state| state.owed)
|
||||
}
|
||||
|
||||
/// Forget a folder that is no longer synced.
|
||||
pub fn forget(&self, folder: i64) {
|
||||
self.states.lock().remove(&folder);
|
||||
@@ -179,77 +313,161 @@ impl Roots {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use Phase as P;
|
||||
use RootInput as I;
|
||||
use RootState as S;
|
||||
|
||||
fn run(from: RootState, inputs: &[RootInput]) -> RootState {
|
||||
inputs.iter().fold(from, |state, input| step(state, *input))
|
||||
}
|
||||
|
||||
const BOTH: RootInput = I::Covered {
|
||||
local: true,
|
||||
remote: true,
|
||||
};
|
||||
const NEITHER: RootInput = I::Covered {
|
||||
local: false,
|
||||
remote: false,
|
||||
};
|
||||
const LOCAL: RootInput = I::Covered {
|
||||
local: true,
|
||||
remote: false,
|
||||
};
|
||||
const REMOTE: RootInput = I::Covered {
|
||||
local: false,
|
||||
remote: true,
|
||||
};
|
||||
const FOLLOWING: RootState = RootState {
|
||||
phase: P::Following,
|
||||
owed: Owed {
|
||||
local: None,
|
||||
remote: None,
|
||||
},
|
||||
};
|
||||
|
||||
fn auditing(local: Option<Doubt>, remote: Option<Doubt>) -> RootState {
|
||||
RootState {
|
||||
phase: P::Auditing,
|
||||
owed: Owed { local, remote },
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_first_sync_follows_once_a_pass_covers_the_folder() {
|
||||
assert_eq!(run(S::Discovering, &[I::Covered]), S::Following);
|
||||
// A doubt during discovery changes nothing: the pass covers it all.
|
||||
fn a_first_sync_follows_once_a_pass_walks_both_sides() {
|
||||
assert_eq!(run(RootState::NEW, &[BOTH]), FOLLOWING);
|
||||
let half = run(RootState::NEW, &[LOCAL]);
|
||||
assert_eq!(half.phase, P::Discovering);
|
||||
assert_eq!(half.owed.remote, Some(Doubt::FirstSync));
|
||||
assert_eq!(step(half, REMOTE), FOLLOWING);
|
||||
// A doubt during discovery changes nothing: the pass walks it all.
|
||||
assert_eq!(
|
||||
run(S::Discovering, &[I::Doubted(Doubt::Overflow)]),
|
||||
S::Discovering
|
||||
run(RootState::NEW, &[I::Doubted(Doubt::Overflow)]),
|
||||
RootState::NEW
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_doubt_takes_a_followed_folder_to_an_audit_until_a_pass_covers_it() {
|
||||
fn a_pass_from_the_dirty_sets_keeps_a_followed_folder_following() {
|
||||
assert_eq!(run(FOLLOWING, &[NEITHER, NEITHER]), FOLLOWING);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_doubt_is_owed_on_its_side_until_a_pass_walks_that_side() {
|
||||
let audit = run(
|
||||
S::Following,
|
||||
&[I::Doubted(Doubt::WatchLost), I::Doubted(Doubt::EventGap)],
|
||||
FOLLOWING,
|
||||
&[
|
||||
I::Doubted(Doubt::WatchLost),
|
||||
I::Doubted(Doubt::Overflow),
|
||||
I::Doubted(Doubt::EventGap),
|
||||
],
|
||||
);
|
||||
assert_eq!(
|
||||
audit,
|
||||
S::Auditing(Doubt::WatchLost),
|
||||
"the first doubt stays"
|
||||
auditing(Some(Doubt::WatchLost), Some(Doubt::EventGap)),
|
||||
"the first doubt on each side stays"
|
||||
);
|
||||
assert_eq!(step(audit, I::Covered), S::Following);
|
||||
let local_done = step(audit, LOCAL);
|
||||
assert_eq!(local_done, auditing(None, Some(Doubt::EventGap)));
|
||||
assert_eq!(step(local_done, NEITHER), local_done);
|
||||
assert_eq!(step(local_done, REMOTE), FOLLOWING);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_suspension_ends_in_an_audit_or_a_pass() {
|
||||
let paused = run(S::Following, &[I::Suspended(Suspension::Paused)]);
|
||||
assert_eq!(paused, S::Suspended(Suspension::Paused));
|
||||
assert_eq!(step(paused, I::Doubted(Doubt::Overflow)), paused);
|
||||
assert_eq!(step(paused, I::Resumed), S::Auditing(Doubt::Suspension));
|
||||
let missing = run(S::Following, &[I::Suspended(Suspension::RootMissing)]);
|
||||
fn a_restart_owes_the_disk_and_not_drive() {
|
||||
assert_eq!(RootState::RESTARTED, auditing(Some(Doubt::Restart), None));
|
||||
assert_eq!(step(RootState::RESTARTED, LOCAL), FOLLOWING);
|
||||
assert_eq!(step(RootState::RESTARTED, REMOTE), RootState::RESTARTED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_suspension_keeps_what_is_owed_and_what_goes_wrong_meanwhile() {
|
||||
let paused = step(FOLLOWING, I::Suspended(Suspension::Paused));
|
||||
assert_eq!(paused.phase, P::Suspended(Suspension::Paused));
|
||||
assert_eq!(
|
||||
step(paused, I::Resumed),
|
||||
FOLLOWING,
|
||||
"nothing went unwatched"
|
||||
);
|
||||
let overflowed = step(paused, I::Doubted(Doubt::Overflow));
|
||||
assert_eq!(overflowed.phase, P::Suspended(Suspension::Paused));
|
||||
assert_eq!(
|
||||
step(overflowed, I::Resumed),
|
||||
auditing(Some(Doubt::Overflow), None)
|
||||
);
|
||||
let missing = step(FOLLOWING, I::Suspended(Suspension::RootMissing));
|
||||
assert_eq!(step(missing, I::Resumed), missing);
|
||||
assert_eq!(step(missing, I::Covered), S::Following);
|
||||
assert_eq!(step(missing, NEITHER), FOLLOWING);
|
||||
let lost = run(
|
||||
FOLLOWING,
|
||||
&[
|
||||
I::Suspended(Suspension::RootMissing),
|
||||
I::Doubted(Doubt::WatchLost),
|
||||
],
|
||||
);
|
||||
assert_eq!(step(lost, LOCAL), FOLLOWING);
|
||||
// Paused during discovery: still owed everything after.
|
||||
let paused_new = run(
|
||||
RootState::NEW,
|
||||
&[I::Suspended(Suspension::Paused), I::Resumed],
|
||||
);
|
||||
assert_eq!(paused_new.owed, Owed::ALL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_handoff_drains_then_stays_until_the_folder_is_a_mirror_again() {
|
||||
let draining = step(S::Following, I::HandoffQueued);
|
||||
assert_eq!(draining, S::Draining);
|
||||
assert_eq!(step(draining, I::Covered), S::Draining);
|
||||
let draining = step(FOLLOWING, I::HandoffQueued);
|
||||
assert_eq!(draining.phase, P::Draining);
|
||||
assert_eq!(step(draining, BOTH), draining);
|
||||
let off = step(draining, I::HandedOff);
|
||||
assert_eq!(off, S::HandedOff);
|
||||
assert_eq!(step(off, I::Covered), S::HandedOff);
|
||||
assert_eq!(step(off, I::Mirrored), S::Discovering);
|
||||
assert_eq!(off.phase, P::HandedOff);
|
||||
assert_eq!(step(off, BOTH), off);
|
||||
assert_eq!(step(off, I::Mirrored), RootState::NEW);
|
||||
assert_eq!(
|
||||
step(draining, I::Mirrored),
|
||||
S::Auditing(Doubt::Suspension),
|
||||
"a switch called off"
|
||||
auditing(None, Some(Doubt::Pushed)),
|
||||
"a switch called off walks Drive again"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roots_begin_once_and_feed_every_folder() {
|
||||
let roots = Roots::default();
|
||||
roots.input(1, I::Covered);
|
||||
roots.input(1, BOTH);
|
||||
assert_eq!(roots.state(1), None, "not begun");
|
||||
assert_eq!(roots.owed(1), Owed::ALL);
|
||||
roots.begin(1, false);
|
||||
roots.begin(2, true);
|
||||
assert_eq!(roots.state(2), Some(S::Auditing(Doubt::Restart)));
|
||||
roots.input_all(I::Covered);
|
||||
assert_eq!(roots.state(2), Some(RootState::RESTARTED));
|
||||
roots.input_all(BOTH);
|
||||
roots.begin(1, false);
|
||||
assert_eq!(roots.state(1), Some(S::Following), "begun only once");
|
||||
assert_eq!(roots.state(1), Some(FOLLOWING), "begun only once");
|
||||
roots.input_all(I::Doubted(Doubt::EventGap));
|
||||
assert_eq!(roots.state(2), Some(S::Auditing(Doubt::EventGap)));
|
||||
assert_eq!(
|
||||
roots.owed(2),
|
||||
Owed {
|
||||
local: None,
|
||||
remote: Some(Doubt::EventGap)
|
||||
}
|
||||
);
|
||||
roots.forget(2);
|
||||
assert_eq!(roots.state(2), None);
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ use std::collections::HashMap;
|
||||
|
||||
use pdfs_core::Result;
|
||||
use pdfs_store::db::{
|
||||
Db, DeleteWindow, SavedWalk, SavedWalkItem, StoredSyncEntry, StoredSyncFolder,
|
||||
Db, DeleteWindow, SavedWalk, SavedWalkItem, StoredIntent, StoredSyncEntry, StoredSyncFolder,
|
||||
};
|
||||
|
||||
/// The sync tables, as the mirror engine uses them.
|
||||
@@ -80,6 +80,34 @@ pub trait SyncStore: Send + Sync {
|
||||
fn sync_delete_window(&self, folder_id: i64) -> Result<Option<DeleteWindow>>;
|
||||
/// Record the folder's deletion window.
|
||||
fn sync_delete_window_set(&self, folder_id: i64, window: &DeleteWindow) -> Result<()>;
|
||||
|
||||
// The intent of each effect sent (`effect`).
|
||||
|
||||
/// Record that an effect is about to be sent; returns the intent and the
|
||||
/// state it was in before, if any.
|
||||
fn sync_intent_issue(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rel_path: &str,
|
||||
kind: &str,
|
||||
now: i64,
|
||||
) -> Result<(StoredIntent, Option<String>)>;
|
||||
/// Drop a settled intent.
|
||||
fn sync_intent_settle(&self, id: i64) -> Result<()>;
|
||||
/// Move an intent to `state`, with the error that put it there.
|
||||
fn sync_intent_set(&self, id: i64, state: &str, error: Option<&str>) -> Result<()>;
|
||||
/// Every intent not settled; only `folder_id`'s when given.
|
||||
fn sync_intents(&self, folder_id: Option<i64>) -> Result<Vec<StoredIntent>>;
|
||||
/// Move every intent in state `from` to `to`.
|
||||
fn sync_intents_move(&self, from: &str, to: &str) -> Result<usize>;
|
||||
/// Settle the intents of `folder_id` in one of `states` last sent before
|
||||
/// `before`.
|
||||
fn sync_intents_settle_before(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
states: &[&str],
|
||||
before: i64,
|
||||
) -> Result<Vec<StoredIntent>>;
|
||||
}
|
||||
|
||||
impl SyncStore for Db {
|
||||
@@ -154,6 +182,35 @@ impl SyncStore for Db {
|
||||
fn sync_delete_window_set(&self, folder_id: i64, window: &DeleteWindow) -> Result<()> {
|
||||
Db::sync_delete_window_set(self, folder_id, window)
|
||||
}
|
||||
fn sync_intent_issue(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rel_path: &str,
|
||||
kind: &str,
|
||||
now: i64,
|
||||
) -> Result<(StoredIntent, Option<String>)> {
|
||||
Db::sync_intent_issue(self, folder_id, rel_path, kind, now)
|
||||
}
|
||||
fn sync_intent_settle(&self, id: i64) -> Result<()> {
|
||||
Db::sync_intent_settle(self, id)
|
||||
}
|
||||
fn sync_intent_set(&self, id: i64, state: &str, error: Option<&str>) -> Result<()> {
|
||||
Db::sync_intent_set(self, id, state, error)
|
||||
}
|
||||
fn sync_intents(&self, folder_id: Option<i64>) -> Result<Vec<StoredIntent>> {
|
||||
Db::sync_intents(self, folder_id)
|
||||
}
|
||||
fn sync_intents_move(&self, from: &str, to: &str) -> Result<usize> {
|
||||
Db::sync_intents_move(self, from, to)
|
||||
}
|
||||
fn sync_intents_settle_before(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
states: &[&str],
|
||||
before: i64,
|
||||
) -> Result<Vec<StoredIntent>> {
|
||||
Db::sync_intents_settle_before(self, folder_id, states, before)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -216,5 +273,20 @@ mod tests {
|
||||
);
|
||||
store.sync_remote_dirty_consume(id, dirty[0].0).unwrap();
|
||||
assert!(store.sync_remote_dirty(id).unwrap().is_empty());
|
||||
|
||||
let (intent, _) = store.sync_intent_issue(id, "a.txt", "upload", 1).unwrap();
|
||||
store.sync_intent_set(intent.id, "retry", None).unwrap();
|
||||
assert_eq!(store.sync_intents(Some(id)).unwrap()[0].state, "retry");
|
||||
assert_eq!(store.sync_intents_move("retry", "blocked").unwrap(), 1);
|
||||
assert_eq!(
|
||||
store
|
||||
.sync_intents_settle_before(id, &["blocked"], 2)
|
||||
.unwrap()
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
let (intent, _) = store.sync_intent_issue(id, "a.txt", "upload", 3).unwrap();
|
||||
store.sync_intent_settle(intent.id).unwrap();
|
||||
assert!(store.sync_intents(None).unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -145,10 +145,21 @@ pub enum Count {
|
||||
/// Local changes the pass found that a trusted claim of the local dirty
|
||||
/// set did not cover. Should stay zero; see `local_dirty`.
|
||||
MissedLocal,
|
||||
/// Paths on disk taken from the last pass's walk, which a trusted claim
|
||||
/// of the local dirty set keeps up to date, instead of walked again.
|
||||
LocalReused,
|
||||
/// Effects sent again that a stopped daemon had sent and not heard back
|
||||
/// from: each may have happened already (`effect`).
|
||||
UnsureResent,
|
||||
/// Effects sent again after they failed.
|
||||
Retried,
|
||||
/// Unsettled effects of earlier passes that this pass looked at and no
|
||||
/// longer sent.
|
||||
Superseded,
|
||||
}
|
||||
|
||||
impl Count {
|
||||
const ALL: [Count; 13] = [
|
||||
const ALL: [Count; 17] = [
|
||||
Count::LocalEntries,
|
||||
Count::RemoteFolders,
|
||||
Count::Nodes,
|
||||
@@ -162,6 +173,10 @@ impl Count {
|
||||
Count::LocalDirty,
|
||||
Count::LocalUntrusted,
|
||||
Count::MissedLocal,
|
||||
Count::LocalReused,
|
||||
Count::UnsureResent,
|
||||
Count::Retried,
|
||||
Count::Superseded,
|
||||
];
|
||||
|
||||
fn name(self) -> &'static str {
|
||||
@@ -179,6 +194,10 @@ impl Count {
|
||||
Count::LocalDirty => "local dirty",
|
||||
Count::LocalUntrusted => "local dirty untrusted",
|
||||
Count::MissedLocal => "missed local changes",
|
||||
Count::LocalReused => "local reused",
|
||||
Count::UnsureResent => "unsure resent",
|
||||
Count::Retried => "retried",
|
||||
Count::Superseded => "superseded",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -919,6 +919,31 @@ follower whose leader failed lists the folder itself, so each caller still gets
|
||||
A shared folder's refresh stays out of the flight, since its generation check settles races of
|
||||
its own.
|
||||
|
||||
Step 4 has started, inside `pdfs-sync`:
|
||||
|
||||
- **Typed absence.** `evidence` says, for each path a walk touched, what the walk proved about it:
|
||||
present, absent, excluded by the ignore rules, or unknown, with the reason: a folder that could
|
||||
not be read, a path that vanished during the scan, or a Drive listing that failed or came back
|
||||
short. The mirror pass and the push pass both ask it, and a deletion without
|
||||
proof that the path is gone is not made: it is logged and counted, and the next pass plans it
|
||||
again.
|
||||
- **A delete guard over time.** Each mirror folder counts its deletions over the last day
|
||||
(`sync_delete_window`), on either side. A pass that would bring the count to nine in ten of
|
||||
what the folder held is refused, so a wipe spread over several passes is caught as one.
|
||||
- **The local dirty set.** `local_dirty::LocalDirty` holds where each folder changed on disk since
|
||||
a pass last looked, as the watcher reports it, and whether the watch was live throughout. A pass
|
||||
still walks the whole folder and counts the changes the set did not cover.
|
||||
- **The root reducer.** `root::Roots` holds one state machine per folder (discovering, following,
|
||||
auditing, suspended, draining, handed off) that says how far the engine can trust what it has
|
||||
seen. Its transitions are logged; nothing acts on them yet.
|
||||
|
||||
Where step 3 stopped: `Core` no longer holds raw state, only the handles of the parts that own it,
|
||||
and the areas that are services of their own build from those handles. Taking `Core` apart
|
||||
further would change how hundreds of call sites reach the tree without changing who owns what, so
|
||||
the mounted-files side stays in `Core` until step 5 moves it out. The inner crates still see the
|
||||
SDK's id and node types (`NodeUid`, `Node`), which come with the whole `proton-sdk` crate; a
|
||||
crate in the SDK with only those types is the way out, and comes with an SDK release.
|
||||
|
||||
Steps 0 to 3 are 4.0.0. Steps 4 to 6 follow in 4.x, one service at a time. Out of scope for
|
||||
now: an encrypted local vault (full-disk encryption covers a copied disk today), Windows and
|
||||
macOS adapters, and a separate repository for the sync engine.
|
||||
|
||||
@@ -108,6 +108,7 @@ a live account since.
|
||||
|
||||
| Entry | Title |
|
||||
|---|---|
|
||||
| [B304](#b304--a-write-released-while-its-files-create-lands-is-kept-as-a-conflict-copy) | A write released while its file's create lands is kept as a conflict copy |
|
||||
| [B303](#b303--a-file-made-where-a-withdrawn-create-was-listed-refuses-every-write) | A file made where a withdrawn create was listed refuses every write |
|
||||
| [B302](#b302--a-stop-during-a-replacing-rename-leaves-the-replaced-file-in-the-trash) | A stop during a replacing rename leaves the replaced file in the trash |
|
||||
| [B301](#b301--two-overlapping-fsyncs-can-leave-the-older-ones-record-on-disk) | Two overlapping fsyncs can leave the older one's record on disk |
|
||||
@@ -406,6 +407,36 @@ a live account since.
|
||||
|
||||
Newest first.
|
||||
|
||||
### B304 — A write released while its file's create lands is kept as a conflict copy
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
**Found:** 2026-11-27, from a CI failure of the `one_client_with_stale_hashes_and_reordered_echoes`
|
||||
simulation (seed 5): the queues did not drain in time, and Drive held a conflict copy of `e.md`.
|
||||
The daemon log said "the remote revision changed under the queued write (expected 28 bytes at
|
||||
mtime 1795799834, found 28 at 1795799835)".
|
||||
**Where:** `Core::adopt_real_uid` in `crates/pdfs-fuse/src/drain/create.rs` and
|
||||
`Core::revision_conflict` in `crates/pdfs-fuse/src/drain/revision.rs`
|
||||
|
||||
**Repro:** Make a file with some content, and let its create reach Drive in a later second than
|
||||
the file was made locally. As the create lands, write part of the file and close it. Rare: the
|
||||
close has to fall in a window of a few milliseconds.
|
||||
|
||||
**Cause.** The write opened over the create's placeholder, whose base is the local mtime and no
|
||||
revision id. Landing the create rebases the handles open on the file and the writes queued for
|
||||
it onto the node Drive made. A release takes its handle out of the tree before it queues the
|
||||
write, so a release that started before the rebase and queued after it was caught by neither.
|
||||
The drain then had no revision id to compare and fell back to the mtime, which Drive had stamped
|
||||
a second later. The write was not complete, so the check that chains a write onto a revision this
|
||||
daemon sealed did not apply either, and the write went up as a conflict copy of the file's own
|
||||
create.
|
||||
|
||||
**Fix.** Landing a create remembers the placeholder's mtime and size with the revision the create
|
||||
sealed. A base with no revision id and that stamp is read as that revision: its bytes are the ones
|
||||
the create sent. The record goes once a later upload of the file lands, or the file is trashed.
|
||||
|
||||
**Verified:** `a_write_based_on_a_landed_create_placeholder_is_not_a_conflict` checks the
|
||||
comparison. The race itself is not reproduced on demand; 40 local replays of the seed passed.
|
||||
|
||||
### B303 — A file made where a withdrawn create was listed refuses every write
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
|
||||
+12
-2
@@ -11,11 +11,15 @@ scratch (user data in `staging/` and `recovery/` is never touched by this).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
Schema: **50**. New tables save a mirror folder's walk of Proton Drive (48). A finished walk is
|
||||
Schema: **51**. New tables save a mirror folder's walk of Proton Drive (48). A finished walk is
|
||||
kept, with a list of the folders that changed on Proton Drive since (49). Each mirror folder
|
||||
counts the deletions it made in the last day (50).
|
||||
counts the deletions it made in the last day (50). Each upload, download or folder a mirror pass
|
||||
sends is recorded until its result is in (51).
|
||||
|
||||
### Added
|
||||
- **`small_uploads` in `config.json` turns off the one-request upload for small files.** It is
|
||||
on by default. Set it to `false` to send every file as a draft, its blocks and a commit, as
|
||||
before. The service reads it at start. See [Configuration](CONFIGURATION.md#small_uploads).
|
||||
- **`pdfs diagnostics` says which of the daemon's background services are running.** If one
|
||||
ends while the drive is mounted, for example the sync engine after a crash, the journal says
|
||||
so once, by name, instead of saying nothing until a restart. It also lists the jobs running
|
||||
@@ -45,6 +49,12 @@ counts the deletions it made in the last day (50).
|
||||
any more.
|
||||
|
||||
### Changed
|
||||
- **A sync pass over a quiet folder no longer reads the whole folder on disk.** While the
|
||||
filesystem watcher has been running without a break, a pass reads again only the folders and
|
||||
files it reported changed, and takes the rest from the pass before. The whole folder is still
|
||||
read at least once an hour, after a start, after a pass that downloaded or removed files, and
|
||||
whenever the watcher may have lost a change. `pdfs diagnostics` shows how many paths a pass
|
||||
took over as `local reused`.
|
||||
- **Deletions in a mirror folder add up across passes.** A sync pass already refuses to delete
|
||||
nearly every file of a folder at once. Now a folder lost a little at a time is stopped too:
|
||||
once nine in ten of its synced files would have been deleted within a day, on either side,
|
||||
|
||||
@@ -88,6 +88,7 @@ fix it.
|
||||
| `device_uid` | string | none | Computers → Continue This Backup Here… or Sync With This Computer… | The computer this machine syncs into. Unset means "match by hostname" |
|
||||
| `conflict_sweep` | `off` / `report` / `enforce` | `report` | Sync → Conflict Copies | See [`conflict_sweep`](#conflict_sweep) |
|
||||
| `local_first` | bool | `true` | — | See [`local_first`](#local_first) |
|
||||
| `small_uploads` | bool | `true` | — | See [`small_uploads`](#small_uploads) |
|
||||
| `language` | gettext code | system | General → Appearance | Language of the app, tray and prompt, such as `de` or `pt_BR` |
|
||||
| `proton_theme` | bool | follow system | General → Appearance | Proton's colours instead of the system theme |
|
||||
| `online_map` | bool | `false` | General → Appearance | Street map for Places from OpenFreeMap |
|
||||
@@ -145,6 +146,16 @@ call returns at once. The change goes to Drive from the queue, the same way it d
|
||||
Set it to `false` to have these calls wait for Drive again, as before 3.0.0. The switch is there
|
||||
for one release, in case the queued path misbehaves for you; please report it if it does.
|
||||
|
||||
### `small_uploads`
|
||||
|
||||
A file that fits in 128 KiB with its thumbnails goes to Proton Drive in one request. A larger one
|
||||
goes as a draft, its blocks, and a commit, which takes three requests or more. Most synced files
|
||||
are small, so this is what decides how fast a folder of many small files syncs.
|
||||
|
||||
Set it to `false` to upload every file in blocks again. The setting is read when the service
|
||||
starts. The journal says `small files are uploaded in blocks` while it is off. Please report it if
|
||||
you need to turn it off.
|
||||
|
||||
### `open_with`
|
||||
|
||||
Decides how files picked in the search launcher or the app are opened. Rules are tried in order;
|
||||
|
||||
+105
-20
@@ -200,28 +200,96 @@ that grows into hours: it is network-bound, while the local walk only reads the
|
||||
`a_pass_lists_only_the_folders_changed_on_drive` (sim: an edit, a new folder with a folder
|
||||
in it, and a deletion arrive, and a folder nothing changed in is never listed).
|
||||
|
||||
What a quiet pass still costs: loading the baseline and the picture from the database, and the
|
||||
local walk. The local dirty set removes the local walk.
|
||||
What a quiet pass still costs: loading the baseline and the picture from the database. The local
|
||||
dirty set takes the place of the local walk, as described below.
|
||||
|
||||
## Root reducer as built
|
||||
|
||||
The states above are first built as a check. `pdfs_sync::root` holds one reducer per mirror
|
||||
folder. `step(state, input)` is pure: the passes, the watcher, the event stream and pause are
|
||||
inputs, so a sequence of inputs replays exactly.
|
||||
`pdfs_sync::root` holds one reducer per mirror folder. `step(state, input)` is pure: the passes,
|
||||
the watcher, the event stream and pause are inputs, so a sequence of inputs replays exactly.
|
||||
|
||||
| State | Meaning |
|
||||
| Phase | Meaning |
|
||||
|---|---|
|
||||
| Discovering | No pass over the folder has finished yet. |
|
||||
| Following | A pass covered the whole folder, and nothing since says a change went unreported. |
|
||||
| Auditing | A doubt arrived: a watcher error, an overflowed queue, a gap in Drive's event stream, a restart or a suspension. Only a pass over the whole folder ends it. |
|
||||
| Following | Passes covered the whole folder, and nothing since says a change went unreported. |
|
||||
| Auditing | A doubt arrived, and the side it is about has not been walked in full since. |
|
||||
| Suspended | The local root is missing, or the folder is paused. |
|
||||
| Draining | A switch to on-demand is queued, and passes only push. |
|
||||
| HandedOff | The folder is on-demand. Going back to a mirror starts discovery again. |
|
||||
|
||||
Nothing acts on the state yet: every pass still covers the whole folder, so a finished pass
|
||||
always returns the folder to Following. The engine logs each transition as `sync: root state`,
|
||||
so the reducer can be compared with what the engine did. Once a Following folder plans from its
|
||||
dirty sets alone, the state decides which passes must walk everything.
|
||||
A doubt is about one side, since the disk and Drive are followed by different things that fail
|
||||
on their own. The state keeps, for each side, the first doubt not yet answered (`Owed`):
|
||||
|
||||
| Doubt | Side | Where it comes from |
|
||||
|---|---|---|
|
||||
| FirstSync | both | A folder no pass has walked, or one that is a mirror again. |
|
||||
| Restart | disk | The daemon started: nothing watched the disk while it was down. Drive's event stream resumes from its cursor. |
|
||||
| WatchLost | disk | A watcher error, or a root that went missing and took its watch with it. |
|
||||
| Overflow | disk | The watcher's queue overflowed. |
|
||||
| EventGap | Drive | The event stream reported `ContinuityLost`. |
|
||||
| Pushed | Drive | A switch to on-demand was called off; the push passes dropped the picture of Drive. |
|
||||
|
||||
A pause owes nothing by itself: the watcher and the event stream keep running for a paused
|
||||
folder. A doubt that arrives while a folder is suspended is kept for when it comes back.
|
||||
|
||||
**Acted on:** a pass asks the state what it owes before it walks. A side that is owed is walked
|
||||
in full: the disk without the kept walk, and Drive without the saved picture (a walk an earlier
|
||||
pass cut short still resumes). The pass reports which sides it walked in full
|
||||
(`Outcome::walked_in_full`), and only those answer a doubt. A pass from the dirty sets keeps a
|
||||
Following folder Following.
|
||||
|
||||
The checks a pass made before (a trusted claim, a fresh event stream, the audit intervals) still
|
||||
apply on top: the state can make a pass walk more, never less. Today each doubt also breaks one
|
||||
of those checks, so the state adds no full walks except after a missing root. When the state is
|
||||
what forces a walk, the journal says `the root state asks for a walk of the whole disk` or `of
|
||||
all of Drive`.
|
||||
|
||||
A watch follows the folder it was set on, so a root moved away and made again is another folder
|
||||
that the old watch does not see. The engine keeps the root's device and inode with each watch.
|
||||
A pass that finds the root missing, or finds a root with another inode, drops the folder's trust
|
||||
in its claims and asks for the watches to be set up again. Setting them up drops any watch whose
|
||||
root is gone or replaced and watches the new one. Then it runs a pass over each folder it watched
|
||||
anew, since a file written before the watch was in place has no event. Until a watch is back,
|
||||
the disk is walked in full.
|
||||
|
||||
**Tests:** the `root::tests` unit tests (a doubt per side, a restart, a suspension, a handoff),
|
||||
`a_restart_walks_the_disk_in_full_and_not_drive` (sim: the first pass after a restart walks the
|
||||
disk and reuses the picture of Drive), and `a_root_made_again_is_watched_again` and
|
||||
`a_root_replaced_between_passes_is_watched_again` (sims: a file written in a root moved away and
|
||||
made again reaches Drive within a minute; the second fails without the inode check).
|
||||
|
||||
## Effect intents as built
|
||||
|
||||
The second reducer, `pdfs_sync::effect`, follows one effect a mirror pass sends: a folder made on
|
||||
Drive, an upload, a new revision, a download, an adopted file or a conflict copy (the `Pending`
|
||||
ops). Before an op is sent, its intent is written to `sync_intent` (schema 51): one row per
|
||||
folder, path and kind, with the number of attempts and the time it was last sent. Its result
|
||||
decides what happens next:
|
||||
|
||||
| State | Meaning |
|
||||
|---|---|
|
||||
| issued | Sent, or about to be; no result yet. |
|
||||
| unsure | Found `issued` at a start: the daemon stopped before the result came, so the effect may or may not have happened. |
|
||||
| retry | It failed, and a later pass may send it again. |
|
||||
| blocked | It failed five times in a row. The journal says `sync: an effect keeps failing` once. |
|
||||
| settled | Its result is in. The row goes. |
|
||||
|
||||
- A start moves every `issued` row to `unsure`, and says how many in the journal.
|
||||
- An op sent again keeps its row and counts the attempt. When the row was `unsure`, the journal
|
||||
says `sync: sending again an effect a stopped daemon may have made`.
|
||||
- A pass that looked at every path (none unscanned or deferred) settles the rows from before it
|
||||
began that it did not send again: what they were for has changed, or is done. An `unsure` one
|
||||
is logged at info.
|
||||
- A change to what the folder is, or its removal, drops its rows.
|
||||
|
||||
The intents are kept in shadow for now: nothing reads them to decide what to send. The apply
|
||||
step's own checks still decide whether an effect that may have landed is sent again (B266 for a
|
||||
create, B39 for a download). Deletions on either side are not recorded yet. Trace counts:
|
||||
`unsure resent`, `retried`, `superseded`.
|
||||
|
||||
**Tests:** the `effect::tests` unit tests, `an_effect_intent_is_kept_until_it_is_settled_or_its_folder_changes`
|
||||
(DB), and `an_effect_left_unsure_by_a_stop_is_sent_again_or_settled` (sim: of two uploads a
|
||||
stopped daemon left unsure, the one still needed is sent again and the other is settled).
|
||||
|
||||
## Plan of work (separate PRs)
|
||||
|
||||
@@ -230,14 +298,31 @@ dirty sets alone, the state decides which passes must walk everything.
|
||||
- Left: per-subtree apply, once a round-level guard exists. A resumable local walk matters
|
||||
less now that the local walk is the only full walk left, and is cheap next to Drive.
|
||||
2. **Remote dirty set.** Done, described above.
|
||||
3. **Local dirty set.**
|
||||
- Done, as a check: the watcher marks each path an event names in `LocalDirty` (in memory).
|
||||
A pass claims the marks, and retires them once it applied everything it found. A claim is
|
||||
trusted when the watch was live since the last pass claimed; a watcher error, an overflow or
|
||||
a restart breaks that. Each pass still walks the whole folder, and counts the changes it
|
||||
found that a trusted claim did not cover (`missed local changes` in the trace).
|
||||
- Left: once that count stays at zero, a trusted claim stands in for the local walk, and
|
||||
only the marked folders are read.
|
||||
3. **Local dirty set.** Done:
|
||||
- The watcher marks each path an event names in `LocalDirty` (in memory): the path, with
|
||||
what is under it, and the folder it is in. A pass claims the marks before it looks at the
|
||||
disk, so a change made while it looks stays marked for the next pass, and retires them once
|
||||
it applied everything it found. A claim is trusted when the watch was live since the last
|
||||
pass claimed; a watcher error, an overflow or a restart breaks that.
|
||||
- A pass keeps what it found on disk (`LocalWalk`) for the next one, unless it changed the
|
||||
disk itself (a download, a conflict copy, a folder made or removed), failed a step, deferred
|
||||
a file or could not read a path. Its own changes are marked only once the watcher reports
|
||||
them, which may come after the next pass claims, so that pass walks in full instead.
|
||||
- The next pass with a trusted claim, the same ignore rules (`IgnoreRules::source`) and a
|
||||
full walk less than an hour old starts from the kept walk (`local reused` in the trace).
|
||||
It lists each marked folder again, walks each marked path again with what is under it, and
|
||||
reads again each file that was open for writing. Everything else is taken as it was.
|
||||
- A full walk with a trusted claim still counts the changes the claim did not cover
|
||||
(`missed local changes`). It runs at least once an hour, and after anything that breaks
|
||||
the trust.
|
||||
- A mark that was missed delays a change until the next full walk. It cannot lose one: a
|
||||
download and a local deletion check the file on disk against what the pass planned from
|
||||
before they act, and a path missing from the kept walk is one a walk found gone.
|
||||
- **Tests:** the `rewalk` unit tests in `mirror.rs` (each kind of change, ignored folders, a
|
||||
mark that came before its folder's, a file that was open for writing), and
|
||||
`a_trusted_local_dirty_set_stands_in_for_the_walk` (sim: an edit, a new folder, a deletion
|
||||
and a folder moved in reach Drive through reused walks; it fails with the watcher's marks
|
||||
switched off).
|
||||
4. **Step scheduler.** Replace `run_burst` and the per-pass lock with steps and priorities.
|
||||
5. **Drop the 120 s poll** for the daily audit, once 2 and 3 have run for a release with the
|
||||
poll still on, and traces show the dirty sets catch everything the poll finds.
|
||||
|
||||
+14
-2
@@ -318,8 +318,20 @@ What the parts mean:
|
||||
then: after a start, a watch that failed, or an overflowed event queue. **`missed local
|
||||
changes`** counts changes the pass found on disk that a trusted watch did not report. It
|
||||
should stay at zero; the journal then has a `sync: the local dirty set missed changes the walk
|
||||
found` line naming the first one. For now these only check the watcher: every pass still
|
||||
walks the whole folder.
|
||||
found` line naming the first one. **`local reused`** counts the paths on disk a pass took from
|
||||
the last pass's walk instead of walking the folder again: it then read only what the watcher
|
||||
reported. A pass with no `local reused` count walked the whole folder. That happens on the
|
||||
first pass, at least once an hour, after the pass before it changed files on disk itself,
|
||||
and after anything that breaks trust in the watch. Only those passes count `missed local
|
||||
changes`.
|
||||
A `sync: root state` line in the journal says when a folder's state changes, for example
|
||||
`from=following to=auditing (local: Overflow)`: the side named is walked in full by the next
|
||||
pass, which takes the folder back to `following`.
|
||||
**`unsure resent`** counts effects sent again that a daemon stopped before it heard back
|
||||
from; the apply step checks whether each already landed before it sends it. **`retried`**
|
||||
counts effects sent again after a failure, and **`superseded`** counts unsettled effects of
|
||||
earlier passes that were no longer needed. A `sync: an effect keeps failing` line names an
|
||||
upload, download or folder that failed five times in a row.
|
||||
|
||||
Please include these lines when you report a slow folder.
|
||||
|
||||
|
||||
Reference in new issue
Block a user