mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-28 12:02:14 +01:00
Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7af8ae6c2 | ||
|
|
7adcdd250f | ||
|
|
006b6f6926 | ||
|
|
251655548a | ||
|
|
59c6740137 | ||
|
|
ae633c2899 | ||
|
|
d14ed56b86 | ||
|
|
a13ca95a83 | ||
|
|
7978a40224 | ||
|
|
275f40b24b | ||
|
|
695a810cea | ||
|
|
9dbb4c9950 | ||
|
|
c5884ba638 | ||
|
|
860593b655 | ||
|
|
4dcc2aa04e | ||
|
|
d891e24e96 | ||
|
|
957a7ff391 | ||
|
|
d9881810b7 | ||
|
|
89b3fce38d |
No files matched your search
Generated
+14
@@ -3729,6 +3729,7 @@ dependencies = [
|
||||
"pdfs-drive",
|
||||
"pdfs-store",
|
||||
"pdfs-sync",
|
||||
"pdfs-vfs",
|
||||
"proton-drive-rs",
|
||||
"proton-gallery-app-rs",
|
||||
"proton-gallery-rs",
|
||||
@@ -3800,6 +3801,19 @@ dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pdfs-vfs"
|
||||
version = "3.10.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"parking_lot 0.13.0",
|
||||
"pdfs-core",
|
||||
"pdfs-drive",
|
||||
"pdfs-store",
|
||||
"proton-drive-rs",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pem-rfc7468"
|
||||
version = "0.7.0"
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["crates/pdfs-core", "crates/pdfs-store", "crates/pdfs-drive", "crates/pdfs-sync", "crates/pdfs-fuse", "crates/pdfs-daemon", "crates/pdfs-cli", "crates/pdfs-gui"]
|
||||
members = ["crates/pdfs-core", "crates/pdfs-store", "crates/pdfs-drive", "crates/pdfs-sync", "crates/pdfs-vfs", "crates/pdfs-fuse", "crates/pdfs-daemon", "crates/pdfs-cli", "crates/pdfs-gui"]
|
||||
|
||||
[workspace.package]
|
||||
version = "3.10.0"
|
||||
@@ -27,6 +27,7 @@ pdfs-core = { path = "crates/pdfs-core" }
|
||||
pdfs-store = { path = "crates/pdfs-store" }
|
||||
pdfs-drive = { path = "crates/pdfs-drive" }
|
||||
pdfs-sync = { path = "crates/pdfs-sync" }
|
||||
pdfs-vfs = { path = "crates/pdfs-vfs" }
|
||||
pdfs-fuse = { path = "crates/pdfs-fuse" }
|
||||
pdfs-daemon = { path = "crates/pdfs-daemon" }
|
||||
|
||||
|
||||
@@ -599,6 +599,19 @@ pub fn is_network_error(e: &ProtonError) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// A node's plaintext size as far as its listing knows: the claimed size when
|
||||
/// the revision carries one, else the size on storage. Zero for a folder.
|
||||
pub fn node_size(node: &Node) -> u64 {
|
||||
match &node.kind {
|
||||
NodeKind::Folder => 0,
|
||||
NodeKind::File {
|
||||
claimed_size,
|
||||
total_size_on_storage,
|
||||
..
|
||||
} => claimed_size.unwrap_or(*total_size_on_storage).max(0) as u64,
|
||||
}
|
||||
}
|
||||
|
||||
/// The server revision id of a node's active revision, if it is a file that has
|
||||
/// one. The stable identity the drain conflict-checks against (see `Baseline` in pdfs-store).
|
||||
pub fn node_revision_id(node: &Node) -> Option<String> {
|
||||
|
||||
@@ -13,6 +13,7 @@ description = "FUSE on-demand filesystem for Proton Drive"
|
||||
pdfs-core.workspace = true
|
||||
pdfs-drive.workspace = true
|
||||
pdfs-sync.workspace = true
|
||||
pdfs-vfs.workspace = true
|
||||
pdfs-store.workspace = true
|
||||
zip.workspace = true
|
||||
sha1.workspace = true
|
||||
@@ -41,6 +42,7 @@ notify = "8"
|
||||
parking_lot.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
pdfs-vfs = { workspace = true, features = ["test-support"] }
|
||||
pdfs-drive = { workspace = true, features = ["sim"] }
|
||||
tracing-subscriber.workspace = true
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
@@ -42,7 +42,6 @@ use tracing::{debug, error, info, warn};
|
||||
|
||||
use super::link::{self, is_network_error};
|
||||
use super::photos::sha1_of;
|
||||
use super::state::{Intervals, PendingRevision};
|
||||
use super::transfers::CountingReader;
|
||||
use super::{
|
||||
Core, DRAIN_BACKOFF_MAX, DRAIN_BACKOFF_MIN, DRAIN_IDLE_POLL, DRAIN_REVISION_DEBOUNCE,
|
||||
@@ -50,6 +49,7 @@ use super::{
|
||||
is_already_exists, is_gone, is_local_uid_str, media_type_for, node_revision_id, node_size,
|
||||
now_millis, now_secs, parse_node_uid,
|
||||
};
|
||||
use pdfs_vfs::open::{Intervals, PendingRevision};
|
||||
use proton_drive_rs::proton_sdk::api::ResponseCode;
|
||||
use proton_drive_rs::proton_sdk::error::ProtonError;
|
||||
|
||||
@@ -421,6 +421,10 @@ impl Core {
|
||||
// Cheap and a no-op when empty.
|
||||
self.cache.flush_touches();
|
||||
self.recovery().recover_fsynced_writes();
|
||||
// One a stop cut off that waited for Drive.
|
||||
if online {
|
||||
self.recovery().settle_replaces();
|
||||
}
|
||||
// Parked rows are invisible to `claim_next_due_op`, so
|
||||
// an idle queue is exactly when a park that has outlived
|
||||
// its writer has to be noticed.
|
||||
@@ -1135,9 +1139,9 @@ fn placed_in(st: &crate::state::State, uid: &NodeUid) -> Option<(String, Option<
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::state::WriteHandle;
|
||||
use pdfs_core::Access;
|
||||
use pdfs_store::db::Db;
|
||||
use pdfs_vfs::open::WriteHandle;
|
||||
use proton_drive_rs::NodeKind;
|
||||
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
|
||||
use std::cell::Cell;
|
||||
|
||||
@@ -564,7 +564,7 @@ impl Core {
|
||||
}
|
||||
}
|
||||
}
|
||||
for aw in st.active_writes.values_mut() {
|
||||
for aw in st.open.writers_mut() {
|
||||
if aw.uid == *local {
|
||||
aw.uid = real.clone();
|
||||
}
|
||||
|
||||
@@ -647,7 +647,7 @@ impl Core {
|
||||
/// daemon has just put there itself (`WriteHandle::rebase_onto`).
|
||||
pub(crate) fn rebase_open_writes(&self, uid: &NodeUid, node: &Node) {
|
||||
self.for_each_state(|st| {
|
||||
for aw in st.active_writes.values_mut() {
|
||||
for aw in st.open.writers_mut() {
|
||||
if aw.uid == *uid {
|
||||
aw.rebase_onto(node);
|
||||
debug!(%uid, mtime = aw.base_mtime, size = aw.base_size,
|
||||
|
||||
@@ -19,59 +19,3 @@ impl Core {
|
||||
self.writes.take_echo(uid, now_millis())
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a change this daemon made stays recognisable as its own. Generous
|
||||
/// against a feed that can lag, but finite: past it, an event for the node is
|
||||
/// applied like any other. See [`writes::WriteState`].
|
||||
pub(super) const SELF_CHANGE_TTL_MS: i64 = 120_000;
|
||||
|
||||
/// A remote change this daemon made, awaiting its echo from the event feed.
|
||||
pub(super) struct SelfChange {
|
||||
/// When we made it, in the same epoch millis as [`now_millis`].
|
||||
at_ms: i64,
|
||||
/// Echoes not yet seen. More than one because a single file can be created
|
||||
/// and then have a revision uploaded, and the feed reports both.
|
||||
echoes: u32,
|
||||
}
|
||||
|
||||
/// Record one remote change this daemon made. Split from [`Core`] so the
|
||||
/// expiry and echo-counting rules can be tested against a clock the test owns.
|
||||
pub(super) fn note_self_change(
|
||||
changes: &mut HashMap<NodeUid, SelfChange>,
|
||||
uid: &NodeUid,
|
||||
now_ms: i64,
|
||||
) {
|
||||
// Echoes that never arrived — a node trashed before its event came round, a
|
||||
// feed that skipped it — would otherwise accumulate for the life of the
|
||||
// daemon. Pruning on write keeps the map the size of the recent queue.
|
||||
changes.retain(|_, c| now_ms - c.at_ms < SELF_CHANGE_TTL_MS);
|
||||
let change = changes.entry(uid.clone()).or_insert(SelfChange {
|
||||
at_ms: now_ms,
|
||||
echoes: 0,
|
||||
});
|
||||
change.at_ms = now_ms;
|
||||
change.echoes += 1;
|
||||
}
|
||||
|
||||
/// Claim one echo, per [`Core::take_self_change`].
|
||||
pub(super) fn take_self_change(
|
||||
changes: &mut HashMap<NodeUid, SelfChange>,
|
||||
uid: &NodeUid,
|
||||
now_ms: i64,
|
||||
) -> bool {
|
||||
let Some(change) = changes.get_mut(uid) else {
|
||||
return false;
|
||||
};
|
||||
// Too old to attribute: the feed is far enough behind that this is as likely
|
||||
// to be someone else's change as ours, and guessing wrong here costs the user
|
||||
// a stale file.
|
||||
if now_ms - change.at_ms >= SELF_CHANGE_TTL_MS {
|
||||
changes.remove(uid);
|
||||
return false;
|
||||
}
|
||||
change.echoes -= 1;
|
||||
if change.echoes == 0 {
|
||||
changes.remove(uid);
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -15,12 +15,12 @@ impl Core {
|
||||
pub(crate) fn queue_unreleased_writes(&self) {
|
||||
let handles: Vec<(WriteHandle, bool)> = {
|
||||
let mut st = self.state();
|
||||
st.handles.clear();
|
||||
let inos: Vec<u64> = st.active_writes.keys().copied().collect();
|
||||
inos.into_iter()
|
||||
.filter_map(|ino| {
|
||||
let unlinked = st.entries.get(&ino).is_some_and(|e| e.unlinked);
|
||||
st.active_writes.remove(&ino).map(|h| (h, unlinked))
|
||||
let writers = st.open.take_all();
|
||||
writers
|
||||
.into_iter()
|
||||
.map(|h| {
|
||||
let unlinked = st.entries.get(&h.ino).is_some_and(|e| e.unlinked);
|
||||
(h, unlinked)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
@@ -201,18 +201,8 @@ impl Core {
|
||||
base_size: u64,
|
||||
base_revision_id: Option<String>,
|
||||
) -> Option<Baseline> {
|
||||
if is_local_uid(uid) {
|
||||
return None;
|
||||
}
|
||||
match self.writes.pending.lock().get(uid) {
|
||||
Some(p) => p.meta.based_on.clone(),
|
||||
None => Some(Baseline {
|
||||
mtime: base_mtime,
|
||||
size: base_size,
|
||||
hash: None,
|
||||
revision_id: base_revision_id,
|
||||
}),
|
||||
}
|
||||
self.writes
|
||||
.baseline(uid, base_mtime, base_size, base_revision_id)
|
||||
}
|
||||
|
||||
/// Move a file holding a node's intended new content into staging and queue
|
||||
|
||||
+117
-1019
File diff suppressed because it is too large.
Load diff
+288
-734
File diff suppressed because it is too large.
Load diff
@@ -582,6 +582,9 @@ pub(crate) fn mount_with(
|
||||
// Writes queued by a previous run (or left behind by a crash) are still owed
|
||||
// an upload, and reads must be served from their staged blobs until they land.
|
||||
core.recovery().hydrate_pending();
|
||||
// A replacing rename a stop cut off: its victim comes back, or its end
|
||||
// state stands. After `hydrate_pending`, which hides queued trashes.
|
||||
core.recovery().settle_replaces();
|
||||
// Then the writes that were fsynced but never closed, which the cache moved
|
||||
// aside at open. After `hydrate_pending`, so a recovered partial write can
|
||||
// see an already-queued write to the same node.
|
||||
|
||||
+20
-103
@@ -1,6 +1,7 @@
|
||||
//! Revision-reader cache and streamed range-read subsystem.
|
||||
|
||||
use super::*;
|
||||
use pdfs_vfs::open::{ReadFailure, assemble_open_read};
|
||||
|
||||
/// A read of an unpinned video at least this large streams *without* persisting
|
||||
/// its blocks to the on-disk cache. Playing a 2 GB film would otherwise pour it
|
||||
@@ -1049,10 +1050,11 @@ impl Core {
|
||||
offset: u64,
|
||||
size: u64,
|
||||
) -> Result<Vec<u8>, Errno> {
|
||||
let read = assemble_open_read(file, len, uid, base_size, written, offset, size, |s, n| {
|
||||
let read = assemble_open_read(file, len, base_size, written, offset, size, |s, n| {
|
||||
self.read_range(uid, base_mtime, base_size, s, n, true)
|
||||
.map(Some)
|
||||
})?;
|
||||
})
|
||||
.map_err(|failure| open_read_errno(uid, failure))?;
|
||||
Ok(read.unwrap_or_default())
|
||||
}
|
||||
|
||||
@@ -1075,9 +1077,10 @@ impl Core {
|
||||
offset: u64,
|
||||
size: u64,
|
||||
) -> Result<Option<Vec<u8>>, Errno> {
|
||||
assemble_open_read(file, len, uid, base_size, written, offset, size, |s, n| {
|
||||
assemble_open_read(file, len, base_size, written, offset, size, |s, n| {
|
||||
Ok(self.cached_range(uid, base_mtime, base_size, s, n))
|
||||
})
|
||||
.map_err(|failure| open_read_errno(uid, failure))
|
||||
}
|
||||
|
||||
/// Bytes `[offset, offset + size)` of file `ino` as `read` would serve
|
||||
@@ -1094,16 +1097,12 @@ impl Core {
|
||||
offset: u64,
|
||||
size: u64,
|
||||
) -> Result<Option<Vec<u8>>, Errno> {
|
||||
let handle = self.state().active_writes.get(&ino).map(|h| {
|
||||
(
|
||||
h.file.clone(),
|
||||
h.len,
|
||||
h.uid.clone(),
|
||||
h.base_mtime,
|
||||
h.base_size,
|
||||
h.written.clone(),
|
||||
)
|
||||
});
|
||||
// A writer still open, or one whose release is still queueing it.
|
||||
let handle = self
|
||||
.state()
|
||||
.open
|
||||
.reader(ino)
|
||||
.map(|v| (v.file, v.len, v.uid, v.base_mtime, v.base_size, v.written));
|
||||
if let Some((file, len, uid, base_mtime, base_size, written)) = handle {
|
||||
return self.serve_open_read_local(
|
||||
&file, len, &uid, base_mtime, base_size, &written, offset, size,
|
||||
@@ -1305,47 +1304,16 @@ impl Core {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes `[offset, offset + size)` of a file open for writing: authored
|
||||
/// ranges from its scratch `file`, the rest from its base through `base`,
|
||||
/// and zeros past the base. `Ok(None)` when `base` says it cannot answer.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn assemble_open_read(
|
||||
file: &File,
|
||||
len: u64,
|
||||
uid: &NodeUid,
|
||||
base_size: u64,
|
||||
written: &Intervals,
|
||||
offset: u64,
|
||||
size: u64,
|
||||
mut base: impl FnMut(u64, u64) -> Result<Option<Vec<u8>>, Errno>,
|
||||
) -> Result<Option<Vec<u8>>, Errno> {
|
||||
if offset >= len || size == 0 {
|
||||
return Ok(Some(Vec::new()));
|
||||
}
|
||||
let end = offset.saturating_add(size).min(len);
|
||||
let mut out = Vec::with_capacity((end - offset) as usize);
|
||||
for (s, e, authored) in written.segments(offset, end) {
|
||||
if authored {
|
||||
let mut buf = vec![0u8; (e - s) as usize];
|
||||
file.read_exact_at(&mut buf, s).map_err(|err| {
|
||||
warn!(%uid, error = %err, "scratch read failed");
|
||||
Errno::EIO
|
||||
})?;
|
||||
out.extend_from_slice(&buf);
|
||||
} else {
|
||||
let bend = e.min(base_size);
|
||||
if s < bend {
|
||||
match base(s, bend - s)? {
|
||||
Some(bytes) => out.extend_from_slice(&bytes),
|
||||
None => return Ok(None),
|
||||
}
|
||||
}
|
||||
// Anything past the base is a hole: zero-fill.
|
||||
let zeros = e.saturating_sub(s.max(base_size));
|
||||
out.resize(out.len() + zeros as usize, 0);
|
||||
/// The errno for a read of an open file that failed: the base's own, or
|
||||
/// `EIO` for the scratch file.
|
||||
fn open_read_errno(uid: &NodeUid, failure: ReadFailure<Errno>) -> Errno {
|
||||
match failure {
|
||||
ReadFailure::Base(errno) => errno,
|
||||
ReadFailure::Scratch(error) => {
|
||||
warn!(%uid, %error, "scratch read failed");
|
||||
Errno::EIO
|
||||
}
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1500,54 +1468,3 @@ mod prefetch_tests {
|
||||
assert!(prefetch.streams.lock().len() <= MAX_PREFETCH_STREAMS + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod open_read_tests {
|
||||
use super::*;
|
||||
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
|
||||
|
||||
fn scratch(bytes: &[u8]) -> (File, PathBuf) {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"pdfs-open-read-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
let mut file = File::options()
|
||||
.create_new(true)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.unwrap();
|
||||
file.write_all(bytes).unwrap();
|
||||
(file, path)
|
||||
}
|
||||
|
||||
/// The dispatch loop answers from what is on this machine and says so
|
||||
/// when the base would have to be downloaded, for a worker to do it
|
||||
/// (`docs/BUGS.md` B227).
|
||||
#[test]
|
||||
fn a_read_needing_the_base_says_so_instead_of_fetching() {
|
||||
let uid = NodeUid::new(VolumeId::from("v"), LinkId::from("f"));
|
||||
let (file, path) = scratch(b"ABCDEFGH");
|
||||
let mut written = Intervals::default();
|
||||
written.add(0, 4);
|
||||
|
||||
let authored = assemble_open_read(&file, 8, &uid, 8, &written, 0, 4, |_, _| {
|
||||
panic!("an authored range never asks the base")
|
||||
});
|
||||
assert_eq!(authored.unwrap().as_deref(), Some(&b"ABCD"[..]));
|
||||
|
||||
let missing = assemble_open_read(&file, 8, &uid, 8, &written, 2, 6, |_, _| Ok(None));
|
||||
assert_eq!(missing.unwrap(), None);
|
||||
|
||||
let base = assemble_open_read(&file, 10, &uid, 8, &written, 2, 8, |s, n| {
|
||||
assert_eq!((s, n), (4, 4));
|
||||
Ok(Some(b"efgh".to_vec()))
|
||||
});
|
||||
assert_eq!(base.unwrap().as_deref(), Some(&b"CDefgh\0\0"[..]));
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
//! recovering writes that were fsynced but not queued when the daemon stopped.
|
||||
|
||||
use super::*;
|
||||
use pdfs_vfs::namespace::{ReplaceOutcome, settle_from_drive, settle_from_queue};
|
||||
|
||||
impl Core {
|
||||
/// Rehydrate the in-memory `State` maps from the DB on mount, so a cold
|
||||
@@ -96,7 +97,7 @@ impl Core {
|
||||
st.hydrate_access();
|
||||
|
||||
// Pass 3: rebuild child listings for fully-enumerated folders.
|
||||
let listings = listed_children(&st.entries, listed_dirs);
|
||||
let listings = crate::state::listed_children(&st.entries, listed_dirs);
|
||||
st.children.extend(listings);
|
||||
info!(nodes = st.entries.len(), "hydrated metadata cache from db");
|
||||
}
|
||||
@@ -117,12 +118,48 @@ pub(crate) trait RecoveryHost: Send + Sync {
|
||||
/// Queue a write recovered from a blob fsynced before a stop, as if its
|
||||
/// handle had just been released.
|
||||
fn queue_recovered(&self, uid: &NodeUid, blob: &Path, meta: StagedWrite) -> Result<(), Errno>;
|
||||
|
||||
/// Drive's node `uid`: `None` when Drive cannot be asked now, and
|
||||
/// `Some(None)` when it does not have the node.
|
||||
fn remote_node(&self, uid: &NodeUid) -> Option<Option<Node>>;
|
||||
|
||||
/// Drop the queued trash of a replaced node whose rename was never
|
||||
/// queued, so it stays where it is.
|
||||
fn withdraw_victim_trash(&self, uid: &NodeUid) -> Result<(), Errno>;
|
||||
|
||||
/// Bring a replaced node back out of Drive's trash. Best effort; a failure
|
||||
/// is logged and recorded in the activity log.
|
||||
fn restore_victim(&self, uid: &NodeUid, parent: &NodeUid, name: &str);
|
||||
}
|
||||
|
||||
impl RecoveryHost for Core {
|
||||
fn queue_recovered(&self, uid: &NodeUid, blob: &Path, meta: StagedWrite) -> Result<(), Errno> {
|
||||
self.enqueue_staged_write(uid, 0, blob, meta)
|
||||
}
|
||||
|
||||
fn remote_node(&self, uid: &NodeUid) -> Option<Option<Node>> {
|
||||
if !self.is_online() {
|
||||
return None;
|
||||
}
|
||||
match self.block_on_bounded(self.drive.enumerate_nodes(std::slice::from_ref(uid))) {
|
||||
Ok(nodes) => Some(nodes.into_iter().find(|node| node.uid == *uid)),
|
||||
Err(error) if is_gone(&error) => Some(None),
|
||||
Err(error) => {
|
||||
self.lost_link(&error, "settle a replacing rename");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn withdraw_victim_trash(&self, uid: &NodeUid) -> Result<(), Errno> {
|
||||
self.discard_queued_ops(uid)?;
|
||||
self.writes.unhide(uid);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn restore_victim(&self, uid: &NodeUid, parent: &NodeUid, name: &str) {
|
||||
self.restore_replaced(Some(&(0, uid.clone())), parent, name);
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuilds the queue from the database and the staging area after a
|
||||
@@ -136,6 +173,97 @@ pub(crate) struct Recovery {
|
||||
}
|
||||
|
||||
impl Recovery {
|
||||
/// Settle the replacing renames an earlier run started and did not end
|
||||
/// (`docs/BUGS.md` B302): forget the ones that reached their end state,
|
||||
/// and put the victim back where the rename did not happen. One that needs
|
||||
/// Drive while Drive cannot be asked stays for a later pass.
|
||||
///
|
||||
/// Runs at mount, after [`hydrate_pending`](Self::hydrate_pending), and on
|
||||
/// the drain's idle passes. The journal holds only this run's own renames
|
||||
/// apart from cut-off ones, and those are left alone, so the idle pass
|
||||
/// never undoes a rename in progress.
|
||||
pub(crate) fn settle_replaces(&self) {
|
||||
let intents = match self.db.open_replaces() {
|
||||
Ok(intents) if intents.is_empty() => return,
|
||||
Ok(intents) => intents,
|
||||
Err(error) => {
|
||||
warn!(%error, "reading cut-off replacing renames failed");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let ops = match self.db.pending_ops() {
|
||||
Ok(ops) => ops,
|
||||
Err(error) => {
|
||||
warn!(%error, "reading the queue to settle replacing renames failed");
|
||||
return;
|
||||
}
|
||||
};
|
||||
for intent in intents {
|
||||
let (Some(source), Some(victim), Some(parent)) = (
|
||||
parse_node_uid(&intent.source_uid),
|
||||
parse_node_uid(&intent.victim_uid),
|
||||
parse_node_uid(&intent.new_parent_uid),
|
||||
) else {
|
||||
warn!(source = %intent.source_uid, "dropping a replace intent with an unparseable uid");
|
||||
let _ = self.db.end_replace(&intent.source_uid);
|
||||
continue;
|
||||
};
|
||||
// The source's end state is queued when one of its ops puts it at
|
||||
// the new name: a rename, or the create a queued node's rename
|
||||
// rewrote.
|
||||
let rename_queued = ops.iter().any(|op| {
|
||||
op.uid == intent.source_uid
|
||||
&& [OP_RENAME, OP_CREATE, OP_MKDIR].contains(&op.kind.as_str())
|
||||
&& op.parent_uid.as_deref() == Some(intent.new_parent_uid.as_str())
|
||||
&& op.name.as_deref() == Some(intent.new_name.as_str())
|
||||
});
|
||||
let victim_trash_queued = ops
|
||||
.iter()
|
||||
.any(|op| op.uid == intent.victim_uid && op.kind == OP_TRASH);
|
||||
let outcome = settle_from_queue(rename_queued, victim_trash_queued, is_local_uid(&victim))
|
||||
.unwrap_or_else(|| {
|
||||
if is_local_uid(&source) {
|
||||
// A queued node whose create landed under the rename;
|
||||
// Drive knows it by a uid this entry does not have.
|
||||
warn!(%source, %victim, name = intent.new_name,
|
||||
"cannot settle a replacing rename of a node created here; leaving the replaced node in the trash");
|
||||
return ReplaceOutcome::Done;
|
||||
}
|
||||
let source_node = self.host.remote_node(&source);
|
||||
let victim_node = match source_node {
|
||||
Some(_) => self.host.remote_node(&victim),
|
||||
None => None,
|
||||
};
|
||||
settle_from_drive(
|
||||
&parent,
|
||||
&intent.new_name,
|
||||
source_node.as_ref().map(Option::as_ref),
|
||||
victim_node.as_ref().map(Option::as_ref),
|
||||
)
|
||||
});
|
||||
match outcome {
|
||||
ReplaceOutcome::Wait => continue,
|
||||
ReplaceOutcome::Done => {
|
||||
info!(%source, name = intent.new_name, "a replacing rename cut off by a stop had finished");
|
||||
}
|
||||
ReplaceOutcome::WithdrawVictimTrash => {
|
||||
if let Err(error) = self.host.withdraw_victim_trash(&victim) {
|
||||
warn!(%victim, ?error, "withdrawing a replaced node's queued trash failed; trying again later");
|
||||
continue;
|
||||
}
|
||||
info!(%victim, name = intent.new_name, "kept a node a cut-off rename was replacing");
|
||||
}
|
||||
ReplaceOutcome::RestoreVictim => {
|
||||
self.host.restore_victim(&victim, &parent, &intent.new_name);
|
||||
info!(%victim, name = intent.new_name, "restored a node a cut-off rename had replaced");
|
||||
}
|
||||
}
|
||||
if let Err(error) = self.db.end_replace(&intent.source_uid) {
|
||||
warn!(%source, %error, "ending a settled replace intent failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuild the in-memory pending map from the `pending_op` table on mount.
|
||||
///
|
||||
/// A queued write survives a restart — that is the point of persisting it —
|
||||
|
||||
@@ -453,11 +453,7 @@ impl Core {
|
||||
// longer has that uid, so the move went ahead under an open write.
|
||||
let mut writing = false;
|
||||
self.for_each_state(|st| {
|
||||
writing = st
|
||||
.active_writes
|
||||
.keys()
|
||||
.chain(&st.releasing)
|
||||
.any(|&open| ino_is_under(st, open, ino));
|
||||
writing = st.open.owed(false).any(|open| ino_is_under(st, open, ino));
|
||||
});
|
||||
Ok(writing)
|
||||
}
|
||||
|
||||
@@ -485,11 +485,8 @@ impl Core {
|
||||
// Unsaved writes, or a release still queueing them, to the file or,
|
||||
// for a folder, to any file below it.
|
||||
let unsaved = st
|
||||
.active_writes
|
||||
.iter()
|
||||
.filter(|(_, w)| w.dirty)
|
||||
.map(|(&open, _)| open)
|
||||
.chain(st.releasing.iter().copied())
|
||||
.open
|
||||
.owed(true)
|
||||
.any(|open| relocate::ino_is_under(&st, open, ino));
|
||||
(entry.node.name.clone(), entry.node.is_folder(), unsaved)
|
||||
};
|
||||
|
||||
@@ -479,6 +479,7 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::sim::fake_drive::{Entry, FakeDrive, Faults};
|
||||
use pdfs_core::control::{RefreshScope, SyncIssue};
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[test]
|
||||
@@ -4556,4 +4557,115 @@ mod tests {
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The state a stop leaves between the two steps of a replacing rename
|
||||
/// sent to Drive inline: the replaced file in the trash, the source under
|
||||
/// its old name, and the journal entry. The next start puts the replaced
|
||||
/// file back (B302).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_replace_cut_off_after_its_trash_brings_the_replaced_file_back() {
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("replace-cut-trash");
|
||||
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
|
||||
std::fs::write(daemon.mountpoint.join("report.odt"), b"old").unwrap();
|
||||
std::fs::write(daemon.mountpoint.join("report.odt.tmp"), b"new").unwrap();
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
let tree = drive.tree();
|
||||
tree.contains_key("report.odt") && tree.contains_key("report.odt.tmp")
|
||||
}));
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
|
||||
let victim = drive.lookup("report.odt").unwrap();
|
||||
let source = drive.lookup("report.odt.tmp").unwrap();
|
||||
cut_off_replace(&dir, &source, &victim, &drive.root(), "report.odt");
|
||||
drive.device().trash("report.odt");
|
||||
|
||||
// Without the listing lag: a lagging read shows the trash made just
|
||||
// above as not done yet, and a restart quicker than the lag then left
|
||||
// the file in the trash as never removed. A real stop comes long
|
||||
// after its own trash.
|
||||
let daemon = Daemon::start(&dir, drive.client(1, Faults::none())).unwrap();
|
||||
assert!(
|
||||
wait_until(Duration::from_secs(30), || {
|
||||
drive.tree().get("report.odt") == Some(&Entry::File(Arc::new(b"old".to_vec())))
|
||||
}),
|
||||
"the replaced file came back: {:?}",
|
||||
drive.tree()
|
||||
);
|
||||
assert!(drive.tree().contains_key("report.odt.tmp"));
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
std::fs::read(daemon.mountpoint.join("report.odt")).is_ok_and(|b| b == b"old")
|
||||
}));
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let db = Db::open(&dir.join("pdfs.db")).unwrap();
|
||||
assert!(db.open_replaces().unwrap().is_empty());
|
||||
drop(db);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The state a stop leaves between the two steps of a queued replacing
|
||||
/// rename: the replaced file's trash queued, the rename not. The next
|
||||
/// start drops the queued trash, so the file is never trashed (B302).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_replace_cut_off_after_queueing_its_trash_keeps_the_replaced_file() {
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("replace-cut-queue");
|
||||
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
|
||||
std::fs::write(daemon.mountpoint.join("report.odt"), b"old").unwrap();
|
||||
std::fs::write(daemon.mountpoint.join("report.odt.tmp"), b"new").unwrap();
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
let tree = drive.tree();
|
||||
tree.contains_key("report.odt") && tree.contains_key("report.odt.tmp")
|
||||
}));
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
|
||||
let victim = drive.lookup("report.odt").unwrap();
|
||||
let source = drive.lookup("report.odt.tmp").unwrap();
|
||||
cut_off_replace(&dir, &source, &victim, &drive.root(), "report.odt");
|
||||
let db = Db::open(&dir.join("pdfs.db")).unwrap();
|
||||
db.replace_ops_with_trash(&victim.to_string(), "report.odt", 1)
|
||||
.unwrap();
|
||||
drop(db);
|
||||
|
||||
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
std::fs::read(daemon.mountpoint.join("report.odt")).is_ok_and(|b| b == b"old")
|
||||
}));
|
||||
// Long enough for the drain to have sent a trash it still held.
|
||||
std::thread::sleep(Duration::from_secs(3));
|
||||
assert!(
|
||||
drive.tree().contains_key("report.odt"),
|
||||
"the replaced file stayed: {:?}",
|
||||
drive.tree()
|
||||
);
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
let db = Db::open(&dir.join("pdfs.db")).unwrap();
|
||||
assert!(db.open_replaces().unwrap().is_empty());
|
||||
assert!(!db.has_pending_op(&victim.to_string(), "trash").unwrap());
|
||||
drop(db);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Write the journal entry of a replacing rename, as an earlier run would
|
||||
/// have before it removed the victim.
|
||||
fn cut_off_replace(
|
||||
dir: &Path,
|
||||
source: &NodeUid,
|
||||
victim: &NodeUid,
|
||||
parent: &NodeUid,
|
||||
name: &str,
|
||||
) {
|
||||
let db = Db::open(&dir.join("pdfs.db")).unwrap();
|
||||
db.begin_replace(&pdfs_store::db::ReplaceIntent {
|
||||
source_uid: source.to_string(),
|
||||
victim_uid: victim.to_string(),
|
||||
new_parent_uid: parent.to_string(),
|
||||
new_name: name.to_owned(),
|
||||
started_ms: 1,
|
||||
run: 0,
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -332,7 +332,7 @@ impl Core {
|
||||
};
|
||||
changed.push(ino);
|
||||
// An open write handle is ahead of the server too (B109).
|
||||
if st.active_writes.contains_key(&ino) {
|
||||
if st.open.is_writing(ino) {
|
||||
continue;
|
||||
}
|
||||
let NodeKind::File { claimed_size, .. } = &node.kind else {
|
||||
|
||||
@@ -189,8 +189,7 @@ impl Core {
|
||||
let Some(&ino) = st.by_uid.get(uid) else {
|
||||
return;
|
||||
};
|
||||
busy |=
|
||||
st.active_writes.contains_key(&ino) || st.handles.values().any(|&held| held == ino);
|
||||
busy |= st.open.is_busy(ino);
|
||||
});
|
||||
busy
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::time::{Duration, Instant};
|
||||
use proton_drive_rs::proton_sdk::ids::{LinkId, NodeUid, VolumeId};
|
||||
use proton_drive_rs::{Node, NodeKind};
|
||||
|
||||
pub(crate) const VIRTUAL_VOLUME: &str = "virtual";
|
||||
pub(crate) use pdfs_vfs::ids::{VIRTUAL_VOLUME, is_virtual_uid};
|
||||
pub(crate) const SHARED_WITH_ME_LINK: &str = "sharedwithme";
|
||||
pub(crate) const SHARED_WITH_ME_BASE: &str = "Shared with me";
|
||||
const MAX_COMPONENT_BYTES: usize = 255;
|
||||
@@ -18,10 +18,6 @@ pub(crate) fn shared_with_me_uid() -> NodeUid {
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn is_virtual_uid(uid: &NodeUid) -> bool {
|
||||
uid.volume_id.as_str() == VIRTUAL_VOLUME
|
||||
}
|
||||
|
||||
pub(crate) fn is_own_or_virtual_uid(uid: &NodeUid, own_volume: &VolumeId) -> bool {
|
||||
uid.volume_id == *own_volume || is_virtual_uid(uid)
|
||||
}
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
//! What the mount accepted and has not yet sent to Drive (`WriteState`).
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The write-back's state: writes accepted from the kernel and not yet sent,
|
||||
/// nodes removed here that a stale listing may still return, and the changes
|
||||
/// this daemon made that Drive's event feed will echo back.
|
||||
///
|
||||
/// The drain, the queue and recovery own it. Everything else, the read path,
|
||||
/// listings, the pin keeper and the event feed, asks through the methods
|
||||
/// below instead of taking its locks.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct WriteState {
|
||||
/// Writes accepted from the kernel but not yet uploaded, keyed by node.
|
||||
/// The in-memory face of the `pending_op` table, from
|
||||
/// which it is rebuilt on mount.
|
||||
///
|
||||
/// Two things read it: [`Core::read_range`], because until the op drains the
|
||||
/// staged blob *is* the file's content and the remote still holds the old
|
||||
/// revision; and the drain worker, which performs the uploads.
|
||||
pub(crate) pending: Arc<Mutex<HashMap<NodeUid, PendingRevision>>>,
|
||||
/// Nodes removed through this daemon which a briefly stale remote listing
|
||||
/// may still return. Uids are not reused; an explicit restore clears one.
|
||||
hidden: Arc<Mutex<HashSet<NodeUid>>>,
|
||||
/// Nodes this daemon changed on the remote itself, and how many echoes of
|
||||
/// those changes the event feed still owes us.
|
||||
///
|
||||
/// The feed replays our own writes back at us seconds later, and a
|
||||
/// `NodeUpdated` carries no revision id — nothing in it distinguishes "another
|
||||
/// device changed this file" from "you changed this file". Treating the echo
|
||||
/// as foreign is not free: it evicts the content blob we just uploaded, so the
|
||||
/// next read re-downloads a revision the API may not be serving yet. That is
|
||||
/// how a SQLite database written on the mount came back `malformed`, and how a
|
||||
/// mount doing bulk uploads spent its time re-fetching its own bytes.
|
||||
///
|
||||
/// So the first event for a node we changed ourselves, within
|
||||
/// [`SELF_CHANGE_TTL_MS`], is consumed rather than applied: the tree already
|
||||
/// holds what that event describes, because [`Core::refresh_after_upload`] put
|
||||
/// it there. Anything beyond that applies normally, which bounds the staleness
|
||||
/// a genuine remote change can suffer to one event.
|
||||
///
|
||||
/// Shared across forks like `pending`: the drain that records the change and
|
||||
/// the event task that consumes the echo are both per-daemon.
|
||||
self_changes: Arc<Mutex<HashMap<NodeUid, echoes::SelfChange>>>,
|
||||
}
|
||||
|
||||
impl WriteState {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
pending: Arc::new(Mutex::new(HashMap::new())),
|
||||
hidden: Arc::new(Mutex::new(HashSet::new())),
|
||||
self_changes: Arc::new(Mutex::new(HashMap::new())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The write queued for `uid`, if any: its staged blob is the file's
|
||||
/// content until the drain sends it.
|
||||
pub(crate) fn queued(&self, uid: &NodeUid) -> Option<PendingRevision> {
|
||||
self.pending.lock().get(uid).cloned()
|
||||
}
|
||||
|
||||
/// Whether a write for `uid` is queued and not yet sent. A remote change
|
||||
/// to such a node is not applied over it.
|
||||
pub(crate) fn is_queued(&self, uid: &NodeUid) -> bool {
|
||||
self.pending.lock().contains_key(uid)
|
||||
}
|
||||
|
||||
/// The size the queued write for `uid` gives the file, if one is queued.
|
||||
pub(crate) fn queued_len(&self, uid: &NodeUid) -> Option<u64> {
|
||||
self.pending.lock().get(uid).map(|queued| queued.meta.len)
|
||||
}
|
||||
|
||||
/// The size each queued write gives its file. Empty when nothing is
|
||||
/// queued.
|
||||
pub(crate) fn queued_sizes(&self) -> HashMap<NodeUid, u64> {
|
||||
self.pending
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|(uid, queued)| (uid.clone(), queued.meta.len))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The nodes removed here that a listing must leave out, even if Drive
|
||||
/// still returns them.
|
||||
pub(crate) fn hidden(&self) -> HashSet<NodeUid> {
|
||||
self.hidden.lock().clone()
|
||||
}
|
||||
|
||||
/// Leave `uid` out of listings from now on: it was removed here.
|
||||
pub(crate) fn hide(&self, uid: &NodeUid) {
|
||||
self.hidden.lock().insert(uid.clone());
|
||||
}
|
||||
|
||||
/// List `uid` again: it was restored or put back.
|
||||
pub(crate) fn unhide(&self, uid: &NodeUid) {
|
||||
self.hidden.lock().remove(uid);
|
||||
}
|
||||
|
||||
/// Record that this daemon just changed `uid` on Drive, so the event
|
||||
/// feed's echo of the change is recognised (see [`echoes`]).
|
||||
pub(crate) fn note_echo(&self, uid: &NodeUid, now_ms: i64) {
|
||||
echoes::note_self_change(&mut self.self_changes.lock(), uid, now_ms);
|
||||
}
|
||||
|
||||
/// Claim one outstanding echo for `uid`: whether the event being applied
|
||||
/// is one this daemon caused.
|
||||
pub(crate) fn take_echo(&self, uid: &NodeUid, now_ms: i64) -> bool {
|
||||
echoes::take_self_change(&mut self.self_changes.lock(), uid, now_ms)
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,7 @@ mod nodes;
|
||||
mod ops;
|
||||
mod photos;
|
||||
mod pins;
|
||||
mod replace;
|
||||
mod share_access;
|
||||
mod state;
|
||||
mod sync;
|
||||
@@ -63,6 +64,7 @@ pub use ops::{
|
||||
};
|
||||
pub use photos::{StoredPhoto, StoredPlace, THUMB_HAVE, THUMB_NONE, THUMB_UNKNOWN, TimelineRow};
|
||||
pub use pins::PinRow;
|
||||
pub use replace::ReplaceIntent;
|
||||
pub use sync::{SavedWalk, SavedWalkDir, SavedWalkItem, StoredSyncEntry, StoredSyncFolder};
|
||||
pub use trash::StoredTrash;
|
||||
|
||||
@@ -108,6 +110,10 @@ pub struct Db {
|
||||
/// to be owned here rather than by `open`'s stack frame. `None` for
|
||||
/// in-memory databases, which nothing else can reach.
|
||||
_single_writer: Option<File>,
|
||||
/// Tells this opening of the database from earlier ones, so that journal
|
||||
/// entries a previous run left behind can be told from this run's own
|
||||
/// (see `replace`).
|
||||
run: u64,
|
||||
}
|
||||
|
||||
/// Idle read-only connections, opened on demand and kept for reuse.
|
||||
@@ -294,6 +300,7 @@ impl Db {
|
||||
idle: Mutex::new(Vec::new()),
|
||||
}),
|
||||
_single_writer: single_writer,
|
||||
run: next_run(),
|
||||
};
|
||||
// A drain claim names a worker thread in the process that took it, and
|
||||
// the single-writer lock above says that process is not running. Any
|
||||
@@ -384,6 +391,7 @@ impl Db {
|
||||
conn: Ranked::new(Rank::DbWriter, conn),
|
||||
readers: None,
|
||||
_single_writer: None,
|
||||
run: next_run(),
|
||||
};
|
||||
db.migrate()?;
|
||||
Ok(db.into_conn())
|
||||
@@ -408,6 +416,7 @@ impl Db {
|
||||
conn: Ranked::new(Rank::DbWriter, conn),
|
||||
readers: None,
|
||||
_single_writer: None,
|
||||
run: next_run(),
|
||||
};
|
||||
db.migrate()?;
|
||||
Ok(db)
|
||||
@@ -448,6 +457,25 @@ fn is_in_memory(path: &Path) -> bool {
|
||||
/// not the descriptor. So a lock the process has just let go of can stay held
|
||||
/// for that moment, and a reopen right after a drop is refused
|
||||
/// (`docs/BUGS.md` B290).
|
||||
/// A value no other opening of a database has used: the time in nanoseconds,
|
||||
/// made unique within this process by a counter.
|
||||
fn next_run() -> u64 {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static LAST: AtomicU64 = AtomicU64::new(0);
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos() as u64)
|
||||
.unwrap_or(0);
|
||||
let mut last = LAST.load(Ordering::Relaxed);
|
||||
loop {
|
||||
let next = now.max(last + 1);
|
||||
match LAST.compare_exchange_weak(last, next, Ordering::Relaxed, Ordering::Relaxed) {
|
||||
Ok(_) => return next,
|
||||
Err(seen) => last = seen,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn acquire_single_writer_lock(path: &Path) -> Result<Option<File>> {
|
||||
if is_in_memory(path) {
|
||||
return Ok(None);
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! The journal of replacing renames.
|
||||
//!
|
||||
//! Drive has no rename that replaces its destination, so a `rename(2)` over an
|
||||
//! existing name removes the node there first and renames the source second.
|
||||
//! A stop between the two leaves the destination in Drive's trash and the
|
||||
//! source under its old name: neither the old state nor the new one. An entry
|
||||
//! here is written before the first step and removed after the last, so the
|
||||
//! next start finds every replace that was cut off and settles it
|
||||
//! (`docs/BUGS.md` B302).
|
||||
//!
|
||||
//! Kept in `sync_state` under [`REPLACE_PREFIX`], so the schema does not
|
||||
//! change.
|
||||
|
||||
use rusqlite::params;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::Db;
|
||||
use pdfs_core::Result;
|
||||
|
||||
/// The `sync_state` key prefix of a journal entry. The rest of the key is the
|
||||
/// source's uid.
|
||||
const REPLACE_PREFIX: &str = "replace:";
|
||||
|
||||
/// A replacing rename that has started: `source` is to be renamed to
|
||||
/// `new_name` in `new_parent`, over `victim`. Uids are in their `Display`
|
||||
/// form.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ReplaceIntent {
|
||||
pub source_uid: String,
|
||||
pub victim_uid: String,
|
||||
pub new_parent_uid: String,
|
||||
pub new_name: String,
|
||||
/// When the rename started, in milliseconds since the epoch.
|
||||
pub started_ms: i64,
|
||||
/// The opening of the database the rename started under. Set by
|
||||
/// [`Db::begin_replace`].
|
||||
#[serde(default)]
|
||||
pub run: u64,
|
||||
}
|
||||
|
||||
impl ReplaceIntent {
|
||||
fn run_is(&self, run: u64) -> bool {
|
||||
self.run == run
|
||||
}
|
||||
}
|
||||
|
||||
impl Db {
|
||||
/// Record that a replacing rename is about to remove its victim. Committed
|
||||
/// with a synced WAL before it returns, as the queue's own rows are: the
|
||||
/// removal that follows may reach Drive at once.
|
||||
pub fn begin_replace(&self, intent: &ReplaceIntent) -> Result<()> {
|
||||
let intent = ReplaceIntent {
|
||||
run: self.run,
|
||||
..intent.clone()
|
||||
};
|
||||
let value = serde_json::to_string(&intent)?;
|
||||
let conn = self.durable()?;
|
||||
conn.execute(
|
||||
"INSERT INTO sync_state (key, value) VALUES (?1, ?2)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||||
params![format!("{REPLACE_PREFIX}{}", intent.source_uid), value],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Forget the replacing rename of `source_uid`: it finished, failed and
|
||||
/// was undone, or was settled after a restart.
|
||||
pub fn end_replace(&self, source_uid: &str) -> Result<()> {
|
||||
self.conn.lock().execute(
|
||||
"DELETE FROM sync_state WHERE key = ?1",
|
||||
params![format!("{REPLACE_PREFIX}{source_uid}")],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every replacing rename an earlier run started and did not end. This
|
||||
/// run's own are in progress, and are not returned. An entry that cannot
|
||||
/// be read is dropped, with a warning: it cannot be settled.
|
||||
pub fn open_replaces(&self) -> Result<Vec<ReplaceIntent>> {
|
||||
let rows: Vec<(String, String)> = {
|
||||
let conn = self.read()?;
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT key, value FROM sync_state WHERE key >= ?1 AND key < ?2 ORDER BY key",
|
||||
)?;
|
||||
stmt.query_map(params![REPLACE_PREFIX, "replace;"], |row| {
|
||||
Ok((row.get(0)?, row.get(1)?))
|
||||
})?
|
||||
.collect::<rusqlite::Result<_>>()?
|
||||
};
|
||||
let mut out = Vec::with_capacity(rows.len());
|
||||
for (key, value) in rows {
|
||||
match serde_json::from_str::<ReplaceIntent>(&value) {
|
||||
Ok(intent) if intent.run_is(self.run) => {}
|
||||
Ok(intent) => out.push(intent),
|
||||
Err(error) => {
|
||||
tracing::warn!(key, %error, "dropping an unreadable replace intent");
|
||||
self.conn
|
||||
.lock()
|
||||
.execute("DELETE FROM sync_state WHERE key = ?1", params![key])?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
@@ -8381,3 +8381,42 @@ fn a_read_without_a_reader_connection_fails_instead_of_waiting_on_the_writer() {
|
||||
"the read must fail, not queue behind the writer"
|
||||
);
|
||||
}
|
||||
|
||||
/// A replacing rename's journal entry outlives the run that wrote it, and is
|
||||
/// gone once ended; other `sync_state` keys are not taken for entries.
|
||||
#[test]
|
||||
fn a_replace_intent_is_kept_until_it_ends() {
|
||||
let db = Db::open_in_memory().unwrap();
|
||||
let intent = ReplaceIntent {
|
||||
source_uid: "vol~src".into(),
|
||||
victim_uid: "vol~victim".into(),
|
||||
new_parent_uid: "vol~dir".into(),
|
||||
new_name: "report.odt".into(),
|
||||
started_ms: 7,
|
||||
run: 0,
|
||||
};
|
||||
db.begin_replace(&intent).unwrap();
|
||||
db.with_conn(|conn| {
|
||||
conn.execute(
|
||||
"INSERT INTO sync_state (key, value) VALUES ('replacement', 'x'), ('replace;', 'y')",
|
||||
[],
|
||||
)?;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// This run's own replace is in progress, not cut off.
|
||||
assert!(db.open_replaces().unwrap().is_empty());
|
||||
db.with_conn(|conn| {
|
||||
conn.execute(
|
||||
"UPDATE sync_state SET value = json_set(value, '$.run', 1) WHERE key = 'replace:vol~src'",
|
||||
[],
|
||||
)?;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let open = db.open_replaces().unwrap();
|
||||
assert_eq!(open.len(), 1);
|
||||
assert_eq!(open[0].victim_uid, intent.victim_uid);
|
||||
db.end_replace("vol~src").unwrap();
|
||||
assert!(db.open_replaces().unwrap().is_empty());
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "pdfs-vfs"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
description = "The mounted-files service of the Proton Drive Linux client, without a kernel adapter"
|
||||
|
||||
[features]
|
||||
# Helpers that let other crates' tests build and inspect a tree.
|
||||
test-support = []
|
||||
|
||||
[dependencies]
|
||||
pdfs-core.workspace = true
|
||||
pdfs-drive.workspace = true
|
||||
pdfs-store.workspace = true
|
||||
proton-drive-rs.workspace = true
|
||||
libc.workspace = true
|
||||
parking_lot.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,27 @@
|
||||
//! Inode numbers the tree reserves, and the volume of nodes that only exist
|
||||
//! here.
|
||||
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
|
||||
/// The root inode of every session. Each session calls its own root 1.
|
||||
pub const ROOT_INO: u64 = 1;
|
||||
|
||||
/// Parent inode for a persisted node whose parent row is missing from the
|
||||
/// database. No folder carries this inode, so such a node is listed by nobody
|
||||
/// and stays inert until a live enumeration re-parents it.
|
||||
pub const ORPHAN_INO: u64 = 0;
|
||||
|
||||
/// The volume id of the folders this client makes up, such as "Shared with
|
||||
/// me". No such volume exists on Drive.
|
||||
pub const VIRTUAL_VOLUME: &str = "virtual";
|
||||
|
||||
/// Whether `uid` names a folder this client made up rather than a Drive node.
|
||||
pub fn is_virtual_uid(uid: &NodeUid) -> bool {
|
||||
uid.volume_id.as_str() == VIRTUAL_VOLUME
|
||||
}
|
||||
|
||||
/// Whether this node exists only on this machine, so far. Such a uid is
|
||||
/// meaningless to the API and must never be sent to it.
|
||||
pub fn is_local_uid(uid: &NodeUid) -> bool {
|
||||
uid.volume_id.as_str() == pdfs_store::db::LOCAL_VOLUME
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
//! The mounted-files service: what a file open through a mount is, and what
|
||||
//! happens to its bytes between `open` and `close`.
|
||||
//!
|
||||
//! Step 5 of the 4.0 plan in `docs/ARCHITECTURE.md` moves the mount's
|
||||
//! state here, slice by slice, so that it can be built and tested without a
|
||||
//! kernel. Nothing in this crate knows about `fuser` or errno: the FUSE
|
||||
//! adapter in `pdfs-fuse` maps the typed errors at the boundary.
|
||||
//!
|
||||
//! So far it holds the tree ([`tree`]): the nodes a mount shows, their
|
||||
//! stable inode numbers, and the per-mount roots; and the open files
|
||||
//! ([`open`]): the scratch file a handle writes into, which bytes of it are
|
||||
//! authored, the released write that waits for its upload, and directory
|
||||
//! handles; what the mount accepted but has not sent to Drive yet
|
||||
//! ([`writes`]); the POSIX rules on names and on what a rename may replace
|
||||
//! ([`names`]); which nodes a folder lists ([`nodes`]); and two services
|
||||
//! behind host ports: the open files from open to close ([`files`]), and
|
||||
//! create, mkdir, unlink and rmdir ([`namespace`]).
|
||||
|
||||
pub mod files;
|
||||
pub mod ids;
|
||||
pub mod names;
|
||||
pub mod namespace;
|
||||
pub mod nodes;
|
||||
pub mod open;
|
||||
pub mod tree;
|
||||
pub mod writes;
|
||||
@@ -0,0 +1,110 @@
|
||||
//! The POSIX rules on names and on what a rename may replace.
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
|
||||
/// Why a pathname component cannot name a node.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum NameError {
|
||||
/// Longer than `NAME_MAX` (255 bytes).
|
||||
TooLong,
|
||||
/// Empty, `.` or `..`.
|
||||
Reserved,
|
||||
/// Not UTF-8, which Drive requires.
|
||||
NotUtf8,
|
||||
}
|
||||
|
||||
/// Why a rename may not replace its destination.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ReplaceError {
|
||||
/// A file would replace a directory.
|
||||
IsDirectory,
|
||||
/// A directory would replace a file.
|
||||
NotDirectory,
|
||||
/// The directory to replace is not empty.
|
||||
NotEmpty,
|
||||
}
|
||||
|
||||
/// Convert one kernel pathname component into the UTF-8 name accepted by Drive.
|
||||
/// Linux filesystems conventionally cap a component at `NAME_MAX` (255 bytes),
|
||||
/// but the FUSE kernel path can pass a longer component through to userspace.
|
||||
pub fn component(name: &OsStr) -> Result<String, NameError> {
|
||||
let bytes = name.as_bytes();
|
||||
if bytes.len() > 255 {
|
||||
return Err(NameError::TooLong);
|
||||
}
|
||||
if bytes.is_empty() || bytes == b"." || bytes == b".." {
|
||||
return Err(NameError::Reserved);
|
||||
}
|
||||
name.to_str().map(str::to_owned).ok_or(NameError::NotUtf8)
|
||||
}
|
||||
|
||||
/// Whether a `rename` may replace an existing destination, per POSIX.
|
||||
///
|
||||
/// Split out from the handler because it is the part that is pure and the part
|
||||
/// that is dangerous: every `Err` here is a refusal that happens *before*
|
||||
/// anything is trashed, and getting one wrong turns a refusal into the
|
||||
/// destruction of the destination (`docs/BUGS.md` B13).
|
||||
///
|
||||
/// `dst_empty` is only meaningful when `dst_dir`; pass `true` otherwise.
|
||||
pub fn check_replaceable(
|
||||
src_dir: bool,
|
||||
dst_dir: bool,
|
||||
dst_empty: bool,
|
||||
) -> Result<(), ReplaceError> {
|
||||
match (src_dir, dst_dir) {
|
||||
// A non-directory may not replace a directory, or vice versa.
|
||||
(false, true) => Err(ReplaceError::IsDirectory),
|
||||
(true, false) => Err(ReplaceError::NotDirectory),
|
||||
// Proton trashes a folder with its whole subtree, so replacing a
|
||||
// non-empty one would silently take its contents with it. POSIX says
|
||||
// ENOTEMPTY, which is also the safe answer.
|
||||
(true, true) if !dst_empty => Err(ReplaceError::NotEmpty),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod replace_tests {
|
||||
use super::{ReplaceError, check_replaceable};
|
||||
|
||||
/// The case that motivated all of this: rsync renaming its temp file over
|
||||
/// the real one. Two plain files, and it has to be allowed — refusing is
|
||||
/// what made every rsync transfer fail at the last step (`docs/BUGS.md` B13).
|
||||
#[test]
|
||||
fn a_file_may_replace_a_file() {
|
||||
assert!(check_replaceable(false, false, true).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_directory_may_be_replaced_by_a_directory() {
|
||||
assert!(check_replaceable(true, true, true).is_ok());
|
||||
}
|
||||
|
||||
/// Proton trashes a folder with its whole subtree, so allowing this would
|
||||
/// discard every file under the destination without ever naming them.
|
||||
#[test]
|
||||
fn a_non_empty_directory_is_never_replaced() {
|
||||
let e = check_replaceable(true, true, false).expect_err("must refuse");
|
||||
assert_eq!(e, ReplaceError::NotEmpty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_two_ends_must_agree_on_being_a_directory() {
|
||||
assert_eq!(
|
||||
check_replaceable(false, true, true).expect_err("a file may not replace a directory"),
|
||||
ReplaceError::IsDirectory
|
||||
);
|
||||
assert_eq!(
|
||||
check_replaceable(true, false, true).expect_err("a directory may not replace a file"),
|
||||
ReplaceError::NotDirectory
|
||||
);
|
||||
}
|
||||
|
||||
/// `dst_empty` describes a directory; it must not leak into the file case,
|
||||
/// where callers pass `true` by convention.
|
||||
#[test]
|
||||
fn emptiness_is_ignored_when_the_destination_is_a_file() {
|
||||
assert!(check_replaceable(false, false, false).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,896 @@
|
||||
//! The namespace service: create, mkdir, unlink and rmdir, and the rules for
|
||||
//! a replacing rename.
|
||||
//!
|
||||
//! [`Namespace`] does what the FUSE adapter in `pdfs-fuse` used to do inside
|
||||
//! its callbacks, and returns [`NamespaceError`] for the adapter to answer
|
||||
//! with. What it needs from Drive and from the upload queue goes through
|
||||
//! [`NamespaceHost`].
|
||||
//!
|
||||
//! The rules settle a replacing rename that a stop cut off, on the next start
|
||||
//! (`docs/BUGS.md` B302). The journal entry is
|
||||
//! [`pdfs_store::db::ReplaceIntent`].
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use pdfs_core::Access;
|
||||
use pdfs_core::lockrank::Ranked;
|
||||
use pdfs_core::syncignore::is_transient_name;
|
||||
use pdfs_store::cache::ContentCache;
|
||||
use pdfs_store::db::Db;
|
||||
use proton_drive_rs::Node;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use tracing::{debug, error, warn};
|
||||
|
||||
use crate::ids::is_local_uid;
|
||||
use crate::open::WriteHandle;
|
||||
use crate::tree::{State, StateGuard};
|
||||
use crate::writes::WriteState;
|
||||
|
||||
/// What to do with a replacing rename a previous run started and did not end.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ReplaceOutcome {
|
||||
/// It reached its end state, or nothing is left to undo: forget it.
|
||||
Done,
|
||||
/// The victim's trash is still queued but the rename never was: drop the
|
||||
/// queued trash, so the victim stays where it is.
|
||||
WithdrawVictimTrash,
|
||||
/// The rename did not happen and the victim is in Drive's trash: restore
|
||||
/// it.
|
||||
RestoreVictim,
|
||||
/// Drive cannot be asked now: try again later.
|
||||
Wait,
|
||||
}
|
||||
|
||||
/// What the queue says about a cut-off replace: whether the source's rename
|
||||
/// was queued, and whether the victim's trash is.
|
||||
///
|
||||
/// Answers without Drive where it can, which is every case the queued path
|
||||
/// left: a queued rename carries the end state and the drain finishes it, and
|
||||
/// a queued trash without a queued rename means the stop came between the two.
|
||||
/// A victim whose own create was still queued had nothing on Drive to restore.
|
||||
pub fn settle_from_queue(
|
||||
rename_queued: bool,
|
||||
victim_trash_queued: bool,
|
||||
victim_local: bool,
|
||||
) -> Option<ReplaceOutcome> {
|
||||
if rename_queued {
|
||||
return Some(ReplaceOutcome::Done);
|
||||
}
|
||||
if victim_trash_queued {
|
||||
return Some(ReplaceOutcome::WithdrawVictimTrash);
|
||||
}
|
||||
if victim_local {
|
||||
return Some(ReplaceOutcome::Done);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// What Drive says about a cut-off replace that went to Drive inline.
|
||||
///
|
||||
/// `source` and `victim` are `None` when Drive could not be asked, and
|
||||
/// `Some(None)` when it does not have the node. The rename happened when the
|
||||
/// source sits at the new name; then the victim's removal was meant. Otherwise
|
||||
/// the victim comes back if it is in the trash, and is left alone if it never
|
||||
/// got there.
|
||||
pub fn settle_from_drive(
|
||||
new_parent: &NodeUid,
|
||||
new_name: &str,
|
||||
source: Option<Option<&Node>>,
|
||||
victim: Option<Option<&Node>>,
|
||||
) -> ReplaceOutcome {
|
||||
let Some(source) = source else {
|
||||
return ReplaceOutcome::Wait;
|
||||
};
|
||||
let renamed = source.is_some_and(|node| {
|
||||
!node.trashed && node.parent_uid.as_ref() == Some(new_parent) && node.name == new_name
|
||||
});
|
||||
if renamed {
|
||||
return ReplaceOutcome::Done;
|
||||
}
|
||||
match victim {
|
||||
None => ReplaceOutcome::Wait,
|
||||
Some(Some(node)) if node.trashed => ReplaceOutcome::RestoreVictim,
|
||||
Some(_) => ReplaceOutcome::Done,
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the namespace service refused or failed an operation.
|
||||
///
|
||||
/// `E` is the host's own error ([`NamespaceHost::Error`]), passed through
|
||||
/// unchanged.
|
||||
#[derive(Debug)]
|
||||
pub enum NamespaceError<E> {
|
||||
/// The parent folder is not in the tree.
|
||||
NotFound,
|
||||
/// `unlink` named a folder.
|
||||
IsDirectory,
|
||||
/// `rmdir` named a file.
|
||||
NotDirectory,
|
||||
/// `rmdir` named a folder that still has children.
|
||||
NotEmpty,
|
||||
/// Something failed that the service already logged: the scratch file of
|
||||
/// a new file.
|
||||
Io,
|
||||
/// The host failed, with its own error.
|
||||
Host(E),
|
||||
}
|
||||
|
||||
impl<E> From<E> for NamespaceError<E> {
|
||||
fn from(error: E) -> Self {
|
||||
NamespaceError::Host(error)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the namespace service needs from the rest of the daemon: the access
|
||||
/// rules, the listing of a folder, Drive, and the upload queue.
|
||||
pub trait NamespaceHost {
|
||||
/// The error the host fails with.
|
||||
type Error: std::fmt::Debug;
|
||||
|
||||
/// Refuse a change under `ino` that its access does not allow.
|
||||
fn require_writable(&self, ino: u64) -> Result<(), Self::Error>;
|
||||
|
||||
/// Refuse a change to `uid` on Drive that its access does not allow.
|
||||
fn require_uid_writable(&self, uid: &NodeUid) -> Result<(), Self::Error>;
|
||||
|
||||
/// Make sure the tree holds the children of folder `ino`.
|
||||
fn ensure_children(&self, ino: u64) -> Result<(), Self::Error>;
|
||||
|
||||
/// The child `name` of folder `parent`, as its inode and uid.
|
||||
fn lookup_child(&self, parent: u64, name: &str) -> Result<(u64, NodeUid), Self::Error>;
|
||||
|
||||
/// Whether a change goes to Drive now rather than into the queue.
|
||||
fn sends_inline(&self) -> bool;
|
||||
|
||||
/// Create an empty file, or a folder when `folder`, named `name` under
|
||||
/// `parent_uid` on Drive, and return its node. `None` asks for the create
|
||||
/// to be queued instead: the link went down on the way, or Drive made the
|
||||
/// node but it could not be read back, which the queued create adopts by
|
||||
/// name.
|
||||
fn mint(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
name: &str,
|
||||
folder: bool,
|
||||
) -> Result<Option<Node>, Self::Error>;
|
||||
|
||||
/// Queue the create of `name` under `parent_uid` and return the node it is
|
||||
/// known by until the drain sends it. A `parked` create waits for a rename
|
||||
/// to a real name before it is sent.
|
||||
fn queue_create(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
name: &str,
|
||||
folder: bool,
|
||||
parked: bool,
|
||||
) -> Result<Node, Self::Error>;
|
||||
|
||||
/// Publish the access changes the tree recorded.
|
||||
fn access_changed(&self);
|
||||
|
||||
/// Drop the queued operations of `uid`. `keep_staged` keeps the bytes an
|
||||
/// open handle still writes into.
|
||||
fn drop_queued(&self, uid: &NodeUid, keep_staged: bool) -> Result<(), Self::Error>;
|
||||
|
||||
/// The uid the queued create of `ino` landed as, when it landed before its
|
||||
/// queued operations were dropped.
|
||||
fn landed_uid(&self, ino: u64) -> Option<NodeUid>;
|
||||
|
||||
/// Whether Drive still holds children that were moved out of `uid` here
|
||||
/// and not sent yet.
|
||||
fn has_pending_moves_out_of(&self, uid: &NodeUid) -> Result<bool, Self::Error>;
|
||||
|
||||
/// Queue the trash of `uid`. `open` keeps the bytes an open handle still
|
||||
/// writes into.
|
||||
fn queue_trash(&self, uid: &NodeUid, name: &str, open: bool) -> Result<(), Self::Error>;
|
||||
|
||||
/// Trash `uid` on Drive. `Ok(false)` asks for the trash to be queued
|
||||
/// instead, as the link went down on the way. The host logs a failure.
|
||||
fn trash_remote(&self, uid: &NodeUid, name: &str) -> Result<bool, Self::Error>;
|
||||
|
||||
/// Drive accepted the trash of `uid`, and its queued operations and
|
||||
/// cached bytes are gone: forget what else the host keeps of it and record
|
||||
/// the trash. `open` means a handle still has it open, and reads of it
|
||||
/// still work.
|
||||
fn trashed(&self, uid: &NodeUid, name: &str, open: bool);
|
||||
}
|
||||
|
||||
/// A node the namespace service made, as the tree holds it once made.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Made {
|
||||
pub ino: u64,
|
||||
/// The write handle a new file is open under; 0 for a folder.
|
||||
pub fh: u64,
|
||||
pub node: Node,
|
||||
pub access: Access,
|
||||
}
|
||||
|
||||
/// The namespace service of one daemon, shared by every mount: create,
|
||||
/// mkdir, unlink and rmdir.
|
||||
pub struct Namespace<H> {
|
||||
state: Arc<Ranked<State>>,
|
||||
db: Arc<Db>,
|
||||
cache: Arc<ContentCache>,
|
||||
writes: WriteState,
|
||||
host: H,
|
||||
}
|
||||
|
||||
impl<H: NamespaceHost> Namespace<H> {
|
||||
pub fn new(
|
||||
state: Arc<Ranked<State>>,
|
||||
db: Arc<Db>,
|
||||
cache: Arc<ContentCache>,
|
||||
writes: WriteState,
|
||||
host: H,
|
||||
) -> Self {
|
||||
Self {
|
||||
state,
|
||||
db,
|
||||
cache,
|
||||
writes,
|
||||
host,
|
||||
}
|
||||
}
|
||||
|
||||
fn state(&self) -> StateGuard<'_> {
|
||||
StateGuard::new(self.state.lock(), &self.db)
|
||||
}
|
||||
|
||||
/// The uid of folder `parent`, after its children are in the tree.
|
||||
fn listed_parent(&self, parent: u64, what: &str) -> Result<NodeUid, NamespaceError<H::Error>> {
|
||||
self.host.require_writable(parent)?;
|
||||
if let Err(error) = self.host.ensure_children(parent) {
|
||||
// The parent was looked up a moment ago, so a failure here often
|
||||
// means it left the tree in between. Log it: the caller only sees
|
||||
// "no such file" on a create.
|
||||
warn!(
|
||||
parent,
|
||||
what,
|
||||
?error,
|
||||
"the parent folder could not be listed"
|
||||
);
|
||||
return Err(NamespaceError::Host(error));
|
||||
}
|
||||
match self.state.lock().entries.get(&parent) {
|
||||
Some(entry) => Ok(entry.uid.clone()),
|
||||
None => {
|
||||
warn!(
|
||||
parent,
|
||||
what, "the parent folder left the tree during its listing"
|
||||
);
|
||||
Err(NamespaceError::NotFound)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mint `name` under `parent_uid` on Drive when changes go there now and
|
||||
/// the parent exists there, or queue its create otherwise.
|
||||
///
|
||||
/// Offline the server cannot mint a uid, so the queue invents one. A
|
||||
/// parent that is itself still queued forces the same path even online:
|
||||
/// the API has no folder to put this in yet. A create that set out online
|
||||
/// and lost the network on the way lands in the queue too, so a Wi-Fi drop
|
||||
/// costs the caller a wait, never an error.
|
||||
fn make(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
name: &str,
|
||||
folder: bool,
|
||||
parked: bool,
|
||||
) -> Result<Node, NamespaceError<H::Error>> {
|
||||
if !parked && self.host.sends_inline() && !is_local_uid(parent_uid) {
|
||||
self.host.require_uid_writable(parent_uid)?;
|
||||
if let Some(node) = self.host.mint(parent_uid, name, folder)? {
|
||||
return Ok(node);
|
||||
}
|
||||
}
|
||||
Ok(self.host.queue_create(parent_uid, name, folder, parked)?)
|
||||
}
|
||||
|
||||
/// Create the file `name` in folder `parent` and open it for writing.
|
||||
/// Returns the file and its write handle.
|
||||
///
|
||||
/// A transient scratch name, such as a browser's in-flight `*.crdownload`
|
||||
/// or an editor's `*.swp`, is kept local and parked: no remote node is
|
||||
/// minted and its bytes never upload while it has that name. The rename
|
||||
/// to the real name un-parks the create, so only the finished file reaches
|
||||
/// Drive. Minting an empty remote node here instead let a stalled and
|
||||
/// resumed download fork a conflict copy (`docs/BUGS.md` B70).
|
||||
pub fn create(&self, parent: u64, name: &str) -> Result<Made, NamespaceError<H::Error>> {
|
||||
let parent_uid = self.listed_parent(parent, "create")?;
|
||||
let node = self.make(&parent_uid, name, false, is_transient_name(name))?;
|
||||
let (file, path) = self.cache.create_scratch().map_err(|e| {
|
||||
error!(uid = %node.uid, error = %e, "create scratch file failed");
|
||||
NamespaceError::Io
|
||||
})?;
|
||||
let mut st = self.state();
|
||||
let ino = st.intern(parent, node.clone());
|
||||
if let Some(entry) = st.entries.get_mut(&ino) {
|
||||
entry.open_count = entry.open_count.saturating_add(1);
|
||||
}
|
||||
if let Some(kids) = st.children.get_mut(&parent)
|
||||
&& !kids.contains(&ino)
|
||||
{
|
||||
kids.push(ino);
|
||||
}
|
||||
let fh = st
|
||||
.open
|
||||
.open_writer(ino, || WriteHandle::created(ino, &node, file, path));
|
||||
let made = made(&st, ino, fh);
|
||||
drop(st);
|
||||
self.host.access_changed();
|
||||
made
|
||||
}
|
||||
|
||||
/// Create the folder `name` in folder `parent`.
|
||||
pub fn mkdir(&self, parent: u64, name: &str) -> Result<Made, NamespaceError<H::Error>> {
|
||||
let parent_uid = self.listed_parent(parent, "mkdir")?;
|
||||
let node = self.make(&parent_uid, name, true, false)?;
|
||||
let mut st = self.state();
|
||||
let local = is_local_uid(&node.uid);
|
||||
let uid = node.uid.clone();
|
||||
let ino = st.intern(parent, node);
|
||||
if let Some(kids) = st.children.get_mut(&parent)
|
||||
&& !kids.contains(&ino)
|
||||
{
|
||||
kids.push(ino);
|
||||
}
|
||||
// A folder that exists only here has nothing to enumerate, and asking
|
||||
// the API to enumerate a `local~` uid would fail. Record it as fully
|
||||
// listed and empty, which it is, so reads stay offline across a
|
||||
// restart too.
|
||||
if local {
|
||||
st.children.insert(ino, Vec::new());
|
||||
st.record_listed(uid);
|
||||
}
|
||||
let made = made(&st, ino, 0);
|
||||
drop(st);
|
||||
self.host.access_changed();
|
||||
made
|
||||
}
|
||||
|
||||
/// Remove the file `name` from folder `parent`.
|
||||
pub fn unlink(&self, parent: u64, name: &str) -> Result<(), NamespaceError<H::Error>> {
|
||||
self.host.require_writable(parent)?;
|
||||
if let Ok((ino, _)) = self.host.lookup_child(parent, name)
|
||||
&& self
|
||||
.state
|
||||
.lock()
|
||||
.entries
|
||||
.get(&ino)
|
||||
.is_some_and(|entry| entry.node.is_folder())
|
||||
{
|
||||
return Err(NamespaceError::IsDirectory);
|
||||
}
|
||||
self.trash_child(parent, name)
|
||||
}
|
||||
|
||||
/// Remove the empty folder `name` from folder `parent`.
|
||||
pub fn rmdir(&self, parent: u64, name: &str) -> Result<(), NamespaceError<H::Error>> {
|
||||
self.host.require_writable(parent)?;
|
||||
if let Ok((ino, _)) = self.host.lookup_child(parent, name) {
|
||||
if self
|
||||
.state
|
||||
.lock()
|
||||
.entries
|
||||
.get(&ino)
|
||||
.is_some_and(|entry| !entry.node.is_folder())
|
||||
{
|
||||
return Err(NamespaceError::NotDirectory);
|
||||
}
|
||||
// A missing cached listing says "unknown", not "empty". Proton's
|
||||
// trash call is recursive, so enumerate before applying rmdir's
|
||||
// POSIX emptiness rule.
|
||||
self.host.ensure_children(ino)?;
|
||||
if self.state.lock().has_children(ino) {
|
||||
return Err(NamespaceError::NotEmpty);
|
||||
}
|
||||
}
|
||||
self.trash_child(parent, name)
|
||||
}
|
||||
|
||||
/// Trash the child `name` of folder `parent`, on Drive or through the
|
||||
/// queue.
|
||||
fn trash_child(&self, parent: u64, name: &str) -> Result<(), NamespaceError<H::Error>> {
|
||||
self.host.require_writable(parent)?;
|
||||
let (ino, mut uid) = self.host.lookup_child(parent, name)?;
|
||||
let open_now = self
|
||||
.state
|
||||
.lock()
|
||||
.entries
|
||||
.get(&ino)
|
||||
.is_some_and(|e| e.open_count > 0);
|
||||
// A node the server has never heard of cannot be trashed there;
|
||||
// deleting it just means its queued creation is no longer wanted. This
|
||||
// works offline, which the remote path below cannot.
|
||||
if is_local_uid(&uid) {
|
||||
self.host.drop_queued(&uid, open_now)?;
|
||||
self.state().forget_or_unlink(&uid);
|
||||
// A create that landed before the operations were dropped left
|
||||
// none: Drive has the node, and the tree had not taken its uid
|
||||
// yet. It is trashed there like any other (`docs/BUGS.md` B173).
|
||||
match self.host.landed_uid(ino) {
|
||||
Some(real) => {
|
||||
debug!(local = %uid, %real, name, "create landed under a delete");
|
||||
uid = real;
|
||||
}
|
||||
None => {
|
||||
debug!(%uid, name, "deleted a node that had not been created remotely yet");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
// Queue a folder trash while Drive still holds children that were
|
||||
// moved out locally. The drain waits for those moves before sending
|
||||
// it.
|
||||
let queue = !self.host.sends_inline() || self.host.has_pending_moves_out_of(&uid)?;
|
||||
if queue {
|
||||
return Ok(self.host.queue_trash(&uid, name, open_now)?);
|
||||
}
|
||||
self.host.require_uid_writable(&uid)?;
|
||||
if !self.host.trash_remote(&uid, name)? {
|
||||
return Ok(self.host.queue_trash(&uid, name, open_now)?);
|
||||
}
|
||||
// Only remove the entry after Drive accepted the trash. Otherwise an
|
||||
// error answer still made the path disappear here.
|
||||
self.writes.hide(&uid);
|
||||
self.state().forget_or_unlink(&uid);
|
||||
// An open handle keeps its staged bytes, and the drain must not send
|
||||
// them to a node that is already in the trash (`docs/BUGS.md` B106).
|
||||
if let Err(error) = self.host.drop_queued(&uid, open_now) {
|
||||
warn!(%uid, ?error, "remote trash landed but queued-op cleanup failed");
|
||||
}
|
||||
if !open_now {
|
||||
self.cache.evict(&uid);
|
||||
}
|
||||
self.host.trashed(&uid, name, open_now);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// What the tree holds for `ino`, read under the same lock that made it, so
|
||||
/// the answer cannot see a later unlink.
|
||||
fn made<E>(st: &State, ino: u64, fh: u64) -> Result<Made, NamespaceError<E>> {
|
||||
let entry = st.entries.get(&ino).ok_or(NamespaceError::NotFound)?;
|
||||
Ok(Made {
|
||||
ino,
|
||||
fh,
|
||||
node: entry.node.clone(),
|
||||
access: entry.access,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn uid(link: &str) -> NodeUid {
|
||||
NodeUid::new(VolumeId::from("vol"), LinkId::from(link))
|
||||
}
|
||||
|
||||
fn node(link: &str, parent: &str, name: &str, trashed: bool) -> Node {
|
||||
let mut node = crate::nodes::local_node(uid(link), uid(parent), name.to_owned(), false);
|
||||
node.trashed = trashed;
|
||||
node
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_queue_settles_what_the_queued_path_left() {
|
||||
use ReplaceOutcome::*;
|
||||
assert_eq!(settle_from_queue(true, true, false), Some(Done));
|
||||
assert_eq!(
|
||||
settle_from_queue(false, true, false),
|
||||
Some(WithdrawVictimTrash)
|
||||
);
|
||||
assert_eq!(settle_from_queue(false, false, true), Some(Done));
|
||||
assert_eq!(settle_from_queue(false, false, false), None);
|
||||
}
|
||||
|
||||
/// The stop came after the victim went to the trash and before the
|
||||
/// source was renamed: the victim comes back.
|
||||
#[test]
|
||||
fn a_trashed_victim_comes_back_when_the_rename_did_not_happen() {
|
||||
let source = node("src", "dir", "report.odt.tmp", false);
|
||||
let victim = node("old", "dir", "report.odt", true);
|
||||
assert_eq!(
|
||||
settle_from_drive(
|
||||
&uid("dir"),
|
||||
"report.odt",
|
||||
Some(Some(&source)),
|
||||
Some(Some(&victim))
|
||||
),
|
||||
ReplaceOutcome::RestoreVictim
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finished_rename_keeps_its_victim_in_the_trash() {
|
||||
let source = node("src", "dir", "report.odt", false);
|
||||
let victim = node("old", "dir", "report.odt", true);
|
||||
assert_eq!(
|
||||
settle_from_drive(
|
||||
&uid("dir"),
|
||||
"report.odt",
|
||||
Some(Some(&source)),
|
||||
Some(Some(&victim))
|
||||
),
|
||||
ReplaceOutcome::Done
|
||||
);
|
||||
}
|
||||
|
||||
/// The stop came before the victim was removed: nothing to undo.
|
||||
#[test]
|
||||
fn a_victim_never_trashed_is_left_alone() {
|
||||
let source = node("src", "dir", "report.odt.tmp", false);
|
||||
let victim = node("old", "dir", "report.odt", false);
|
||||
assert_eq!(
|
||||
settle_from_drive(
|
||||
&uid("dir"),
|
||||
"report.odt",
|
||||
Some(Some(&source)),
|
||||
Some(Some(&victim))
|
||||
),
|
||||
ReplaceOutcome::Done
|
||||
);
|
||||
assert_eq!(
|
||||
settle_from_drive(&uid("dir"), "report.odt", Some(Some(&source)), Some(None)),
|
||||
ReplaceOutcome::Done
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_drive_it_waits() {
|
||||
let source = node("src", "dir", "report.odt.tmp", false);
|
||||
assert_eq!(
|
||||
settle_from_drive(&uid("dir"), "report.odt", None, None),
|
||||
ReplaceOutcome::Wait
|
||||
);
|
||||
assert_eq!(
|
||||
settle_from_drive(&uid("dir"), "report.odt", Some(Some(&source)), None),
|
||||
ReplaceOutcome::Wait
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod service_tests {
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use pdfs_core::lockrank::Rank;
|
||||
use pdfs_store::db::LOCAL_VOLUME;
|
||||
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
|
||||
|
||||
use super::*;
|
||||
use crate::nodes::local_node;
|
||||
|
||||
/// A unique temp directory removed on drop; avoids a dev-dependency.
|
||||
struct TempDir(PathBuf);
|
||||
impl TempDir {
|
||||
fn new() -> Self {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static N: AtomicU64 = AtomicU64::new(0);
|
||||
let p = std::env::temp_dir().join(format!(
|
||||
"pdfs-namespace-{}-{}",
|
||||
std::process::id(),
|
||||
N.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
std::fs::create_dir_all(&p).unwrap();
|
||||
TempDir(p)
|
||||
}
|
||||
}
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn uid(link: &str) -> NodeUid {
|
||||
NodeUid::new(VolumeId::from("vol"), LinkId::from(link))
|
||||
}
|
||||
|
||||
fn local_uid(link: &str) -> NodeUid {
|
||||
NodeUid::new(VolumeId::from(LOCAL_VOLUME), LinkId::from(link))
|
||||
}
|
||||
|
||||
/// A host that records what it was asked to do. `inline` says whether
|
||||
/// changes go to Drive now; `link_up` whether Drive answers when asked.
|
||||
struct Recorder {
|
||||
state: Arc<Ranked<State>>,
|
||||
inline: bool,
|
||||
link_up: bool,
|
||||
calls: Mutex<Vec<String>>,
|
||||
}
|
||||
|
||||
impl Recorder {
|
||||
fn record(&self, call: String) {
|
||||
self.calls.lock().push(call);
|
||||
}
|
||||
}
|
||||
|
||||
impl NamespaceHost for &'static Recorder {
|
||||
type Error = &'static str;
|
||||
|
||||
fn require_writable(&self, _ino: u64) -> Result<(), &'static str> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_uid_writable(&self, _uid: &NodeUid) -> Result<(), &'static str> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_children(&self, _ino: u64) -> Result<(), &'static str> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn lookup_child(&self, parent: u64, name: &str) -> Result<(u64, NodeUid), &'static str> {
|
||||
let st = self.state.lock();
|
||||
st.children
|
||||
.get(&parent)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|ino| st.entries.get(ino).map(|entry| (*ino, entry)))
|
||||
.find(|(_, entry)| entry.node.name == name)
|
||||
.map(|(ino, entry)| (ino, entry.uid.clone()))
|
||||
.ok_or("no such child")
|
||||
}
|
||||
|
||||
fn sends_inline(&self) -> bool {
|
||||
self.inline
|
||||
}
|
||||
|
||||
fn mint(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
name: &str,
|
||||
folder: bool,
|
||||
) -> Result<Option<Node>, &'static str> {
|
||||
self.record(format!("mint {name}"));
|
||||
Ok(self.link_up.then(|| {
|
||||
local_node(
|
||||
uid(&format!("minted-{name}")),
|
||||
parent_uid.clone(),
|
||||
name.to_owned(),
|
||||
folder,
|
||||
)
|
||||
}))
|
||||
}
|
||||
|
||||
fn queue_create(
|
||||
&self,
|
||||
parent_uid: &NodeUid,
|
||||
name: &str,
|
||||
folder: bool,
|
||||
parked: bool,
|
||||
) -> Result<Node, &'static str> {
|
||||
self.record(format!("queue create {name} parked={parked}"));
|
||||
Ok(local_node(
|
||||
local_uid(&format!("queued-{name}")),
|
||||
parent_uid.clone(),
|
||||
name.to_owned(),
|
||||
folder,
|
||||
))
|
||||
}
|
||||
|
||||
fn access_changed(&self) {}
|
||||
|
||||
fn drop_queued(&self, uid: &NodeUid, keep_staged: bool) -> Result<(), &'static str> {
|
||||
self.record(format!("drop queued {uid} keep_staged={keep_staged}"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn landed_uid(&self, _ino: u64) -> Option<NodeUid> {
|
||||
None
|
||||
}
|
||||
|
||||
fn has_pending_moves_out_of(&self, _uid: &NodeUid) -> Result<bool, &'static str> {
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
fn queue_trash(&self, uid: &NodeUid, _name: &str, open: bool) -> Result<(), &'static str> {
|
||||
self.record(format!("queue trash {uid} open={open}"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn trash_remote(&self, uid: &NodeUid, _name: &str) -> Result<bool, &'static str> {
|
||||
self.record(format!("trash {uid}"));
|
||||
Ok(self.link_up)
|
||||
}
|
||||
|
||||
fn trashed(&self, uid: &NodeUid, _name: &str, open: bool) {
|
||||
self.record(format!("trashed {uid} open={open}"));
|
||||
}
|
||||
}
|
||||
|
||||
struct Fixture {
|
||||
namespace: Namespace<&'static Recorder>,
|
||||
host: &'static Recorder,
|
||||
state: Arc<Ranked<State>>,
|
||||
db: Arc<Db>,
|
||||
/// The folder the tests work in.
|
||||
dir: u64,
|
||||
_dir: TempDir,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new(inline: bool, link_up: bool) -> Self {
|
||||
let tmp = TempDir::new();
|
||||
let db = Arc::new(Db::open(&tmp.0.join("cache.db")).unwrap());
|
||||
let cache = Arc::new(
|
||||
ContentCache::open(tmp.0.join("content"), tmp.0.join("pins"), 0, db.clone())
|
||||
.unwrap(),
|
||||
);
|
||||
let state = Arc::new(Ranked::new(
|
||||
Rank::State,
|
||||
State::new(db.clone(), HashMap::new()),
|
||||
));
|
||||
let host: &'static Recorder = Box::leak(Box::new(Recorder {
|
||||
state: state.clone(),
|
||||
inline,
|
||||
link_up,
|
||||
calls: Mutex::default(),
|
||||
}));
|
||||
let dir = {
|
||||
let mut st = StateGuard::new(state.lock(), &db);
|
||||
let node = local_node(uid("dir"), uid("root"), "dir".to_owned(), true);
|
||||
let ino = st.intern(0, node);
|
||||
st.entries.get_mut(&ino).unwrap().access = Access::Owner;
|
||||
st.children.insert(ino, Vec::new());
|
||||
ino
|
||||
};
|
||||
let namespace = Namespace::new(
|
||||
state.clone(),
|
||||
db.clone(),
|
||||
cache,
|
||||
WriteState::default(),
|
||||
host,
|
||||
);
|
||||
Fixture {
|
||||
namespace,
|
||||
host,
|
||||
state,
|
||||
db,
|
||||
dir,
|
||||
_dir: tmp,
|
||||
}
|
||||
}
|
||||
|
||||
fn calls(&self) -> Vec<String> {
|
||||
std::mem::take(&mut *self.host.calls.lock())
|
||||
}
|
||||
|
||||
fn listed(&self, name: &str) -> bool {
|
||||
self.host.lookup_child(self.dir, name).is_ok()
|
||||
}
|
||||
|
||||
fn state(&self) -> StateGuard<'_> {
|
||||
StateGuard::new(self.state.lock(), &self.db)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_online_create_mints_the_file_and_opens_it_for_writing() {
|
||||
let fx = Fixture::new(true, true);
|
||||
let made = fx.namespace.create(fx.dir, "a.txt").unwrap();
|
||||
assert_eq!(fx.calls(), ["mint a.txt"]);
|
||||
assert_eq!(made.node.uid, uid("minted-a.txt"));
|
||||
assert!(made.fh > 0);
|
||||
assert!(fx.listed("a.txt"));
|
||||
let st = fx.state();
|
||||
assert_eq!(st.entries[&made.ino].open_count, 1);
|
||||
assert!(st.open.writer(made.ino).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_create_that_loses_the_link_is_queued() {
|
||||
let fx = Fixture::new(true, false);
|
||||
let made = fx.namespace.create(fx.dir, "a.txt").unwrap();
|
||||
assert_eq!(
|
||||
fx.calls(),
|
||||
["mint a.txt", "queue create a.txt parked=false"]
|
||||
);
|
||||
assert!(is_local_uid(&made.node.uid));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_transient_name_is_parked_and_never_minted() {
|
||||
let fx = Fixture::new(true, true);
|
||||
fx.namespace.create(fx.dir, "song.mp3.crdownload").unwrap();
|
||||
assert_eq!(fx.calls(), ["queue create song.mp3.crdownload parked=true"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_offline_mkdir_is_queued_and_listed_empty() {
|
||||
let fx = Fixture::new(false, true);
|
||||
let made = fx.namespace.mkdir(fx.dir, "sub").unwrap();
|
||||
assert_eq!(fx.calls(), ["queue create sub parked=false"]);
|
||||
assert_eq!(made.fh, 0);
|
||||
assert_eq!(fx.state().children.get(&made.ino), Some(&Vec::new()));
|
||||
// Written through when the guard drops: a restart lists it from the
|
||||
// database without asking Drive.
|
||||
let listed = fx.db.children_if_listed(&made.node.uid).unwrap();
|
||||
assert!(listed.is_some_and(|kids| kids.is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unlink_and_rmdir_keep_to_their_kind_of_node() {
|
||||
let fx = Fixture::new(true, true);
|
||||
fx.namespace.mkdir(fx.dir, "sub").unwrap();
|
||||
fx.namespace.create(fx.dir, "a.txt").unwrap();
|
||||
let sub = fx.host.lookup_child(fx.dir, "sub").unwrap().0;
|
||||
fx.namespace.create(sub, "inner.txt").unwrap();
|
||||
fx.calls();
|
||||
|
||||
assert!(matches!(
|
||||
fx.namespace.unlink(fx.dir, "sub"),
|
||||
Err(NamespaceError::IsDirectory)
|
||||
));
|
||||
assert!(matches!(
|
||||
fx.namespace.rmdir(fx.dir, "a.txt"),
|
||||
Err(NamespaceError::NotDirectory)
|
||||
));
|
||||
assert!(matches!(
|
||||
fx.namespace.rmdir(fx.dir, "sub"),
|
||||
Err(NamespaceError::NotEmpty)
|
||||
));
|
||||
assert!(fx.calls().is_empty());
|
||||
assert!(fx.listed("sub") && fx.listed("a.txt"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_file_trashed_on_drive_keeps_its_bytes() {
|
||||
let fx = Fixture::new(true, true);
|
||||
let made = fx.namespace.create(fx.dir, "a.txt").unwrap();
|
||||
fx.calls();
|
||||
fx.namespace.unlink(fx.dir, "a.txt").unwrap();
|
||||
let uid = made.node.uid;
|
||||
assert_eq!(
|
||||
fx.calls(),
|
||||
[
|
||||
format!("trash {uid}"),
|
||||
format!("drop queued {uid} keep_staged=true"),
|
||||
format!("trashed {uid} open=true"),
|
||||
]
|
||||
);
|
||||
assert!(!fx.listed("a.txt"));
|
||||
assert!(fx.state().entries[&made.ino].unlinked);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trash_that_loses_the_link_is_queued_and_keeps_the_entry_until_then() {
|
||||
let fx = Fixture::new(true, false);
|
||||
let on_drive = uid("on-drive");
|
||||
let ino = {
|
||||
let node = local_node(on_drive.clone(), uid("dir"), "b.txt".to_owned(), false);
|
||||
let mut st = fx.state();
|
||||
let ino = st.intern(fx.dir, node);
|
||||
st.children.get_mut(&fx.dir).unwrap().push(ino);
|
||||
ino
|
||||
};
|
||||
fx.namespace.unlink(fx.dir, "b.txt").unwrap();
|
||||
assert_eq!(
|
||||
fx.calls(),
|
||||
[
|
||||
format!("trash {on_drive}"),
|
||||
format!("queue trash {on_drive} open=false"),
|
||||
]
|
||||
);
|
||||
// The queued trash hides it; the service does not drop it ahead.
|
||||
assert!(fx.state().entries.contains_key(&ino));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_queued_create_drops_it_without_a_trash() {
|
||||
let fx = Fixture::new(false, false);
|
||||
let made = fx.namespace.create(fx.dir, "a.txt").unwrap();
|
||||
fx.state().entries.get_mut(&made.ino).unwrap().open_count = 0;
|
||||
fx.calls();
|
||||
fx.namespace.unlink(fx.dir, "a.txt").unwrap();
|
||||
let uid = made.node.uid;
|
||||
assert_eq!(fx.calls(), [format!("drop queued {uid} keep_staged=false")]);
|
||||
assert!(!fx.listed("a.txt"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
//! Rules about the nodes a mount lists that need neither the kernel nor Drive:
|
||||
//! which of them a folder shows, how queued changes lie over a listing, and
|
||||
//! what a node made here looks like before Drive has seen it.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use pdfs_core::timestamp::now_secs;
|
||||
use pdfs_drive::{media_type_for, remote_name_is_safe};
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use proton_drive_rs::{Node, NodeKind};
|
||||
use tracing::warn;
|
||||
|
||||
/// Fabricate the node the server would have returned, for a `create`/`mkdir`
|
||||
/// that could not reach it. Everything the kernel asks about a fresh node —
|
||||
/// name, kind, size, times — is knowable locally; the uid is the only invention,
|
||||
/// and the drain replaces it with the real one.
|
||||
pub fn local_node(uid: NodeUid, parent_uid: NodeUid, name: String, is_dir: bool) -> Node {
|
||||
let now = now_secs();
|
||||
Node {
|
||||
uid,
|
||||
parent_uid: Some(parent_uid),
|
||||
kind: if is_dir {
|
||||
NodeKind::Folder
|
||||
} else {
|
||||
NodeKind::File {
|
||||
media_type: media_type_for(&name).to_string(),
|
||||
total_size_on_storage: 0,
|
||||
// No revision has been sealed: nothing has been uploaded yet.
|
||||
active_revision_state: None,
|
||||
active_revision_id: None,
|
||||
content_sha1: None,
|
||||
claimed_size: Some(0),
|
||||
claimed_modification_time: None,
|
||||
}
|
||||
},
|
||||
name,
|
||||
creation_time: now,
|
||||
modification_time: now,
|
||||
trashed: false,
|
||||
is_shared: false,
|
||||
is_shared_publicly: false,
|
||||
signature_email: None,
|
||||
membership: None,
|
||||
// A locally fabricated node is on the main volume, never a photo/album.
|
||||
photo: None,
|
||||
album: None,
|
||||
// Nothing signed it: it has never been near the crypto layer.
|
||||
verification: Default::default(),
|
||||
direct_role: None,
|
||||
share_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `node` is a file Drive lists without an active revision, as it does
|
||||
/// one whose create has not been committed.
|
||||
pub fn is_unrevised(node: &Node) -> bool {
|
||||
matches!(
|
||||
node.kind,
|
||||
NodeKind::File {
|
||||
active_revision_id: None,
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/// The plaintext size, in bytes, that a node reports.
|
||||
/// Overwrite each file node's `claimed_size` with the optimistic size of its
|
||||
/// queued write, where it has one. Folders and nodes with nothing queued are
|
||||
/// left alone. See [`Core::stamp_pending_sizes`] for why this exists.
|
||||
pub fn apply_pending_sizes(nodes: &mut [Node], sizes: &HashMap<NodeUid, u64>) {
|
||||
for node in nodes {
|
||||
if let Some(&len) = sizes.get(&node.uid)
|
||||
&& let NodeKind::File { claimed_size, .. } = &mut node.kind
|
||||
{
|
||||
*claimed_size = Some(len as i64);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn node_visible(node: &Node, folder_uid: &NodeUid, hidden: &HashSet<NodeUid>) -> bool {
|
||||
if !remote_name_is_safe(&node.name) {
|
||||
warn!(uid = %node.uid, "a remote name cannot be a local file name; leaving it out");
|
||||
return false;
|
||||
}
|
||||
!node.trashed && node.uid != *folder_uid && !hidden.contains(&node.uid)
|
||||
}
|
||||
|
||||
/// Lay what is queued for a folder over Drive's listing of it, from
|
||||
/// `Db::queued_children`: a node a queued rename moved away is dropped, and a
|
||||
/// node a queued create, mkdir or rename put there is listed as the DB has it.
|
||||
///
|
||||
/// That node holds its name here: a create Drive already has but whose answer
|
||||
/// is still on its way, or which the drain is still reading back, is listed by
|
||||
/// Drive under its new uid and by the queue under its stand-in. Both were
|
||||
/// listed, and a 128-file folder listed 129 (`docs/BUGS.md` B164).
|
||||
pub fn overlay_queued(nodes: &mut Vec<Node>, queued: Vec<Node>, gone: &HashSet<String>) {
|
||||
let here: HashSet<String> = queued.iter().map(|node| node.uid.to_string()).collect();
|
||||
let names: HashSet<&str> = queued.iter().map(|node| node.name.as_str()).collect();
|
||||
nodes.retain(|node| {
|
||||
let uid = node.uid.to_string();
|
||||
!gone.contains(&uid) && !here.contains(&uid) && !names.contains(node.name.as_str())
|
||||
});
|
||||
nodes.extend(queued);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod pending_size_tests {
|
||||
use super::{Node, NodeKind, NodeUid, apply_pending_sizes};
|
||||
use pdfs_drive::node_size;
|
||||
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn uid(link: &str) -> NodeUid {
|
||||
NodeUid::new(VolumeId::from("vol"), LinkId::from(link))
|
||||
}
|
||||
|
||||
fn file(link: &str, claimed: i64) -> Node {
|
||||
Node {
|
||||
uid: uid(link),
|
||||
parent_uid: Some(uid("parent")),
|
||||
kind: NodeKind::File {
|
||||
media_type: "text/plain".into(),
|
||||
total_size_on_storage: 0,
|
||||
active_revision_state: None,
|
||||
active_revision_id: None,
|
||||
content_sha1: None,
|
||||
claimed_size: Some(claimed),
|
||||
claimed_modification_time: None,
|
||||
},
|
||||
name: link.into(),
|
||||
creation_time: 100,
|
||||
modification_time: 100,
|
||||
trashed: false,
|
||||
is_shared: false,
|
||||
is_shared_publicly: false,
|
||||
signature_email: None,
|
||||
membership: None,
|
||||
photo: None,
|
||||
album: None,
|
||||
verification: Default::default(),
|
||||
direct_role: None,
|
||||
share_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn folder(link: &str) -> Node {
|
||||
Node {
|
||||
kind: NodeKind::Folder,
|
||||
..file(link, 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// B11: a re-enumeration mid-write must not revert the size to the
|
||||
/// server's. A file that stats as 0 gets no `read` from the kernel at all,
|
||||
/// so the staged blob is never served and the file reads as empty.
|
||||
#[test]
|
||||
fn a_queued_write_keeps_its_optimistic_size_through_a_re_enumeration() {
|
||||
let mut nodes = vec![file("queued", 0), file("settled", 4096)];
|
||||
let sizes = HashMap::from([(uid("queued"), 3)]);
|
||||
|
||||
apply_pending_sizes(&mut nodes, &sizes);
|
||||
|
||||
assert_eq!(
|
||||
node_size(&nodes[0]),
|
||||
3,
|
||||
"the remote's pre-write size must not win over the queued write's"
|
||||
);
|
||||
assert_eq!(
|
||||
node_size(&nodes[1]),
|
||||
4096,
|
||||
"a file with nothing queued keeps the size the server reported"
|
||||
);
|
||||
}
|
||||
|
||||
/// The map is keyed by uid and says nothing about kind; a folder that
|
||||
/// somehow collides must not grow a `claimed_size`.
|
||||
#[test]
|
||||
fn folders_are_left_alone() {
|
||||
let mut nodes = vec![folder("dir")];
|
||||
apply_pending_sizes(&mut nodes, &HashMap::from([(uid("dir"), 999)]));
|
||||
assert!(matches!(nodes[0].kind, NodeKind::Folder));
|
||||
assert_eq!(node_size(&nodes[0]), 0);
|
||||
}
|
||||
|
||||
/// The common case: nothing queued, nothing touched.
|
||||
#[test]
|
||||
fn an_empty_pending_map_changes_nothing() {
|
||||
let mut nodes = vec![file("a", 10), file("b", 20)];
|
||||
apply_pending_sizes(&mut nodes, &HashMap::new());
|
||||
assert_eq!(node_size(&nodes[0]), 10);
|
||||
assert_eq!(node_size(&nodes[1]), 20);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,268 @@
|
||||
//! What the mount accepted and has not yet sent to Drive (`WriteState`).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
|
||||
use pdfs_store::cache::Baseline;
|
||||
|
||||
use crate::ids::is_local_uid;
|
||||
use crate::open::PendingRevision;
|
||||
|
||||
/// The write-back's state: writes accepted from the kernel and not yet sent,
|
||||
/// nodes removed here that a stale listing may still return, and the changes
|
||||
/// this daemon made that Drive's event feed will echo back.
|
||||
///
|
||||
/// The drain, the queue and recovery own it. Everything else, the read path,
|
||||
/// listings, the pin keeper and the event feed, asks through the methods
|
||||
/// below instead of taking its locks.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct WriteState {
|
||||
/// Writes accepted from the kernel but not yet uploaded, keyed by node.
|
||||
/// The in-memory face of the `pending_op` table, from
|
||||
/// which it is rebuilt on mount.
|
||||
///
|
||||
/// Two things read it: [`Core::read_range`], because until the op drains the
|
||||
/// staged blob *is* the file's content and the remote still holds the old
|
||||
/// revision; and the drain worker, which performs the uploads.
|
||||
pub pending: Arc<Mutex<HashMap<NodeUid, PendingRevision>>>,
|
||||
/// Nodes removed through this daemon which a briefly stale remote listing
|
||||
/// may still return. Uids are not reused; an explicit restore clears one.
|
||||
hidden: Arc<Mutex<HashSet<NodeUid>>>,
|
||||
/// Nodes this daemon changed on the remote itself, and how many echoes of
|
||||
/// those changes the event feed still owes us.
|
||||
///
|
||||
/// The feed replays our own writes back at us seconds later, and a
|
||||
/// `NodeUpdated` carries no revision id — nothing in it distinguishes "another
|
||||
/// device changed this file" from "you changed this file". Treating the echo
|
||||
/// as foreign is not free: it evicts the content blob we just uploaded, so the
|
||||
/// next read re-downloads a revision the API may not be serving yet. That is
|
||||
/// how a SQLite database written on the mount came back `malformed`, and how a
|
||||
/// mount doing bulk uploads spent its time re-fetching its own bytes.
|
||||
///
|
||||
/// So the first event for a node we changed ourselves, within
|
||||
/// [`SELF_CHANGE_TTL_MS`], is consumed rather than applied: the tree already
|
||||
/// holds what that event describes, because [`Core::refresh_after_upload`] put
|
||||
/// it there. Anything beyond that applies normally, which bounds the staleness
|
||||
/// a genuine remote change can suffer to one event.
|
||||
///
|
||||
/// Shared across forks like `pending`: the drain that records the change and
|
||||
/// the event task that consumes the echo are both per-daemon.
|
||||
self_changes: Arc<Mutex<HashMap<NodeUid, SelfChange>>>,
|
||||
}
|
||||
|
||||
impl WriteState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
pending: Arc::new(Mutex::new(HashMap::new())),
|
||||
hidden: Arc::new(Mutex::new(HashSet::new())),
|
||||
self_changes: Arc::new(Mutex::new(HashMap::new())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The write queued for `uid`, if any: its staged blob is the file's
|
||||
/// content until the drain sends it.
|
||||
pub fn queued(&self, uid: &NodeUid) -> Option<PendingRevision> {
|
||||
self.pending.lock().get(uid).cloned()
|
||||
}
|
||||
|
||||
/// The remote revision a write to `uid` was made against, for the
|
||||
/// conflict check: the queued write's own base while one is queued, and
|
||||
/// otherwise the base the handle started from. `None` for a node that has
|
||||
/// never existed remotely: there is no revision to conflict with until its
|
||||
/// create drains.
|
||||
pub fn baseline(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
base_mtime: i64,
|
||||
base_size: u64,
|
||||
base_revision_id: Option<String>,
|
||||
) -> Option<Baseline> {
|
||||
if is_local_uid(uid) {
|
||||
return None;
|
||||
}
|
||||
match self.pending.lock().get(uid) {
|
||||
Some(p) => p.meta.based_on.clone(),
|
||||
None => Some(Baseline {
|
||||
mtime: base_mtime,
|
||||
size: base_size,
|
||||
hash: None,
|
||||
revision_id: base_revision_id,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a write for `uid` is queued and not yet sent. A remote change
|
||||
/// to such a node is not applied over it.
|
||||
pub fn is_queued(&self, uid: &NodeUid) -> bool {
|
||||
self.pending.lock().contains_key(uid)
|
||||
}
|
||||
|
||||
/// The size the queued write for `uid` gives the file, if one is queued.
|
||||
pub fn queued_len(&self, uid: &NodeUid) -> Option<u64> {
|
||||
self.pending.lock().get(uid).map(|queued| queued.meta.len)
|
||||
}
|
||||
|
||||
/// The size each queued write gives its file. Empty when nothing is
|
||||
/// queued.
|
||||
pub fn queued_sizes(&self) -> HashMap<NodeUid, u64> {
|
||||
self.pending
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|(uid, queued)| (uid.clone(), queued.meta.len))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The nodes removed here that a listing must leave out, even if Drive
|
||||
/// still returns them.
|
||||
pub fn hidden(&self) -> HashSet<NodeUid> {
|
||||
self.hidden.lock().clone()
|
||||
}
|
||||
|
||||
/// Leave `uid` out of listings from now on: it was removed here.
|
||||
pub fn hide(&self, uid: &NodeUid) {
|
||||
self.hidden.lock().insert(uid.clone());
|
||||
}
|
||||
|
||||
/// List `uid` again: it was restored or put back.
|
||||
pub fn unhide(&self, uid: &NodeUid) {
|
||||
self.hidden.lock().remove(uid);
|
||||
}
|
||||
|
||||
/// Record that this daemon just changed `uid` on Drive, so the event
|
||||
/// feed's echo of the change is recognised (see [`echoes`]).
|
||||
pub fn note_echo(&self, uid: &NodeUid, now_ms: i64) {
|
||||
note_self_change(&mut self.self_changes.lock(), uid, now_ms);
|
||||
}
|
||||
|
||||
/// Claim one outstanding echo for `uid`: whether the event being applied
|
||||
/// is one this daemon caused.
|
||||
pub fn take_echo(&self, uid: &NodeUid, now_ms: i64) -> bool {
|
||||
take_self_change(&mut self.self_changes.lock(), uid, now_ms)
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a change this daemon made stays recognisable as its own. Generous
|
||||
/// against a feed that can lag, but finite: past it, an event for the node is
|
||||
/// applied like any other. See [`writes::WriteState`].
|
||||
pub(crate) const SELF_CHANGE_TTL_MS: i64 = 120_000;
|
||||
|
||||
/// A remote change this daemon made, awaiting its echo from the event feed.
|
||||
pub(crate) struct SelfChange {
|
||||
/// When we made it, in the same epoch millis as [`now_millis`].
|
||||
at_ms: i64,
|
||||
/// Echoes not yet seen. More than one because a single file can be created
|
||||
/// and then have a revision uploaded, and the feed reports both.
|
||||
echoes: u32,
|
||||
}
|
||||
|
||||
/// Record one remote change this daemon made. Split from [`Core`] so the
|
||||
/// expiry and echo-counting rules can be tested against a clock the test owns.
|
||||
pub(crate) fn note_self_change(
|
||||
changes: &mut HashMap<NodeUid, SelfChange>,
|
||||
uid: &NodeUid,
|
||||
now_ms: i64,
|
||||
) {
|
||||
// Echoes that never arrived — a node trashed before its event came round, a
|
||||
// feed that skipped it — would otherwise accumulate for the life of the
|
||||
// daemon. Pruning on write keeps the map the size of the recent queue.
|
||||
changes.retain(|_, c| now_ms - c.at_ms < SELF_CHANGE_TTL_MS);
|
||||
let change = changes.entry(uid.clone()).or_insert(SelfChange {
|
||||
at_ms: now_ms,
|
||||
echoes: 0,
|
||||
});
|
||||
change.at_ms = now_ms;
|
||||
change.echoes += 1;
|
||||
}
|
||||
|
||||
/// Claim one echo, per [`Core::take_self_change`].
|
||||
pub(crate) fn take_self_change(
|
||||
changes: &mut HashMap<NodeUid, SelfChange>,
|
||||
uid: &NodeUid,
|
||||
now_ms: i64,
|
||||
) -> bool {
|
||||
let Some(change) = changes.get_mut(uid) else {
|
||||
return false;
|
||||
};
|
||||
// Too old to attribute: the feed is far enough behind that this is as likely
|
||||
// to be someone else's change as ours, and guessing wrong here costs the user
|
||||
// a stale file.
|
||||
if now_ms - change.at_ms >= SELF_CHANGE_TTL_MS {
|
||||
changes.remove(uid);
|
||||
return false;
|
||||
}
|
||||
change.echoes -= 1;
|
||||
if change.echoes == 0 {
|
||||
changes.remove(uid);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
|
||||
|
||||
/// An event feed carries no revision id, so the only thing that tells a
|
||||
/// remote change apart from the echo of one this daemon just made is this
|
||||
/// bookkeeping. Getting it wrong is expensive in both directions: too eager
|
||||
/// and we evict the bytes we uploaded and re-download them from an API that
|
||||
/// may still be serving the previous revision (a SQLite file on the mount
|
||||
/// read back `malformed`); too generous and a real change from another device
|
||||
/// is ignored.
|
||||
#[test]
|
||||
fn a_self_change_is_claimed_once_and_expires() {
|
||||
let mut changes = HashMap::new();
|
||||
let uid = NodeUid::new(VolumeId::from("vol"), LinkId::from("link"));
|
||||
let other = NodeUid::new(VolumeId::from("vol"), LinkId::from("other"));
|
||||
let t0 = 1_000_000;
|
||||
|
||||
assert!(
|
||||
!take_self_change(&mut changes, &uid, t0),
|
||||
"a node we never touched is never ours"
|
||||
);
|
||||
|
||||
note_self_change(&mut changes, &uid, t0);
|
||||
assert!(
|
||||
take_self_change(&mut changes, &uid, t0 + 5_000),
|
||||
"the echo of our own change is claimed"
|
||||
);
|
||||
assert!(
|
||||
!take_self_change(&mut changes, &uid, t0 + 6_000),
|
||||
"and only once, so a later foreign change still applies"
|
||||
);
|
||||
|
||||
// A create followed by a revision upload is two changes to one node, and
|
||||
// the feed reports both.
|
||||
note_self_change(&mut changes, &uid, t0);
|
||||
note_self_change(&mut changes, &uid, t0);
|
||||
assert!(take_self_change(&mut changes, &uid, t0 + 1));
|
||||
assert!(take_self_change(&mut changes, &uid, t0 + 2));
|
||||
assert!(!take_self_change(&mut changes, &uid, t0 + 3));
|
||||
|
||||
// Past the window the attribution is a guess, and a wrong guess leaves
|
||||
// the user looking at a stale file.
|
||||
note_self_change(&mut changes, &uid, t0);
|
||||
assert!(!take_self_change(
|
||||
&mut changes,
|
||||
&uid,
|
||||
t0 + SELF_CHANGE_TTL_MS
|
||||
));
|
||||
assert!(
|
||||
!changes.contains_key(&uid),
|
||||
"an expired change is dropped, not left to be re-tested"
|
||||
);
|
||||
|
||||
// An echo that never arrives must not accumulate for the life of the
|
||||
// daemon; the next recorded change prunes it.
|
||||
note_self_change(&mut changes, &uid, t0);
|
||||
note_self_change(&mut changes, &other, t0 + SELF_CHANGE_TTL_MS);
|
||||
assert_eq!(
|
||||
changes.len(),
|
||||
1,
|
||||
"recording a change prunes the ones whose echo never came"
|
||||
);
|
||||
}
|
||||
}
|
||||
+24
-1
@@ -51,7 +51,8 @@ graph TD
|
||||
| [`pdfs-store`](../crates/pdfs-store) | The SQLite schema and queries (`db/`), the content cache (`cache`) |
|
||||
| [`pdfs-drive`](../crates/pdfs-drive) | The `DriveApi` seam over the SDK, the call counter (`counted`), and `FakeDrive` for the simulations |
|
||||
| [`pdfs-sync`](../crates/pdfs-sync) | The mirror engine: its passes (`mirror`), split into the walks (`mirror::walk`), applying a plan (`mirror::apply`) and the push pass (`mirror::push`), its engine thread (`mirror::engine`), its reads and writes of the local disk in one module (`mirror::local`), and the parts with no I/O: planner, pass model and pass trace. It owns its state (`SyncParts`), reads and writes its tables only through `SyncStore`, and reaches the daemon only through `SyncHost` |
|
||||
| [`pdfs-fuse`](../crates/pdfs-fuse) | The daemon: FUSE handlers (`filesystem`), the tree (`state`), finding nodes (`resolve`), folder listings and file sizes (`listing`, `sizes`), reads (`reads`), queueing and the drain (`enqueue`, `queue`, `drain`, `upload`), calls sent straight to Drive (`remote`), requests by path (`requests`), startup recovery (`recovery`), pins, search, trash, the shared tree (`shared`), the link state (`link`), remote events (`background`), the daemon's side of the sync engine (`sync`, which implements `SyncHost`), moves between locations (`relocate`), control handlers (`control`), push events (`events`), photos, sharing, devices, the supervisor, and the simulation tests (`sim/`) |
|
||||
| [`pdfs-vfs`](../crates/pdfs-vfs) | The mounted-files service, with no kernel adapter: the tree (`tree`: nodes, stable inodes, per-mount roots), the reserved inodes (`ids`), the open files (`open`: write handles and their authored ranges, released writes waiting for upload, directory handles, `fallocate` rules), the open-file service (`files`: open, write, resize, fsync and close, behind the `FilesHost` port), the namespace service (`namespace`: create, mkdir, unlink and rmdir behind the `NamespaceHost` port, and the settling of a cut-off replacing rename), and what the mount accepted but has not sent yet (`writes`: queued revisions, nodes removed here, echoes of our own changes). Errors are typed; the FUSE adapter maps them to errno |
|
||||
| [`pdfs-fuse`](../crates/pdfs-fuse) | The daemon: FUSE handlers (`filesystem`), finding nodes (`resolve`), folder listings and file sizes (`listing`, `sizes`), reads (`reads`), queueing and the drain (`enqueue`, `queue`, `drain`, `upload`), calls sent straight to Drive (`remote`), requests by path (`requests`), startup recovery (`recovery`), pins, search, trash, the shared tree (`shared`), the link state (`link`), remote events (`background`), the daemon's side of the sync engine (`sync`, which implements `SyncHost`), moves between locations (`relocate`), control handlers (`control`), push events (`events`), photos, sharing, devices, the supervisor, and the simulation tests (`sim/`) |
|
||||
| [`pdfs-daemon`](../crates/pdfs-daemon) | The daemon's composition root: waits for a session, opens the database and the content cache, resumes the session and mounts, then remounts or retries with a backoff and records each failure |
|
||||
| [`pdfs-cli`](../crates/pdfs-cli) | The `pdfs` binary. `pdfs daemon` runs `pdfs_daemon::run` in-process; every other command is a control-socket client |
|
||||
| [`pdfs-gui`](../crates/pdfs-gui) | `pdfs-app`, `pdfs-tray` and `pdfs-prompt`. Pages in `src/app/pages/`, widgets in `src/app/widgets/`, CSS and icons in `resources/` |
|
||||
@@ -847,6 +848,28 @@ mounts. Step 5 turns that into the `pdfs-vfs` service. `Core` also implements th
|
||||
host ports and builds each service on demand, which moves to `pdfs-daemon` once the services no
|
||||
longer need the tree.
|
||||
|
||||
Step 5 has started. `pdfs-vfs` holds the tree (`tree::State`: every node a mount shows, its
|
||||
stable inode, the roots of each session) and the open files (`open::OpenFiles`: write handles by
|
||||
inode and by handle number, the inodes being released, and directory handles with their frozen
|
||||
listings). A write goes through `stage_write`, which reports a full disk as a typed error; the
|
||||
tree refuses a write to a read-only node with `NodeError`; the FUSE adapter maps both to errno.
|
||||
The crate depends on no kernel or GUI crate; `cargo tree -p pdfs-vfs` shows neither.
|
||||
|
||||
The open-file service, `files::Files`, serves a file from open to close: the write open and its
|
||||
base, writes, resizes and `fallocate`, flush, the fsync barrier and the release. Each write
|
||||
handle counts its changes in a generation, and an fsync holds the handle's barrier from reading
|
||||
it to writing its sidecar, so overlapping fsyncs record in order (B301). What the service needs
|
||||
from Drive and the upload queue goes through `files::FilesHost`, which `Core` implements; the
|
||||
FUSE callbacks keep the inode translation, the choice of thread and the reply.
|
||||
|
||||
The namespace service, `namespace::Namespace`, serves create, mkdir, unlink and rmdir: whether a
|
||||
new node is made on Drive at once or queued, the parked create of a transient name, the POSIX
|
||||
checks on what `unlink` and `rmdir` may remove, and the order of a trash (Drive first, then the
|
||||
tree). Drive calls, the queue and the access rules go through `namespace::NamespaceHost`, which
|
||||
`Core` implements. The module also holds the rules that settle a replacing rename a stop cut off
|
||||
(B302). What still sits in `pdfs-fuse` around the tree is the code that fills it (listings,
|
||||
sizes, the drain), the read path, and rename.
|
||||
|
||||
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.
|
||||
|
||||
+101
@@ -108,6 +108,9 @@ a live account since.
|
||||
|
||||
| Entry | Title |
|
||||
|---|---|
|
||||
| [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 |
|
||||
| [B300](#b300--a-read-during-a-release-can-be-served-the-revision-the-write-replaced) | A read during a release can be served the revision the write replaced |
|
||||
| [B299](#b299--a-synced-folder-in-the-trash-blocks-attaching-any-other-folder) | A synced folder in the trash blocks attaching any other folder |
|
||||
| [B298](#b298--a-synced-folder-edit-whose-upload-lost-its-answer-is-kept-as-a-conflict-copy-of-itself) | A synced-folder edit whose upload lost its answer is kept as a conflict copy of itself |
|
||||
| [B297](#b297--the-simulations-fail-and-hang-when-run-in-parallel-and-nothing-stops-that) | The simulations fail and hang when run in parallel, and nothing stops that |
|
||||
@@ -402,6 +405,104 @@ a live account since.
|
||||
|
||||
Newest first.
|
||||
|
||||
### B302 — A stop during a replacing rename leaves the replaced file in the trash
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
**Found:** 2026-11-27, from the review of the mounted filesystem in `FUSE.md`, while moving the
|
||||
namespace operations toward `pdfs-vfs` (step 5 of `docs/ARCHITECTURE.md`). It was not seen in a
|
||||
run.
|
||||
**Where:** `serve_rename` and `ReplaceJournal` in `crates/pdfs-fuse/src/filesystem.rs`;
|
||||
`Recovery::settle_replaces` in `crates/pdfs-fuse/src/recovery.rs`; `Db::begin_replace` in
|
||||
`crates/pdfs-store/src/db/replace.rs`; the settle rules in `crates/pdfs-vfs/src/namespace.rs`
|
||||
|
||||
**Repro:** Save a file with an editor that writes a temporary file and renames it over the
|
||||
original. Stop the daemon (a crash, a power loss or a `kill -9`) after the original has gone to the
|
||||
trash and before the rename. Online, the original is in Drive's trash and the new content is under
|
||||
the temporary name. With local-first or offline, the queue holds the original's trash and no rename,
|
||||
so the next start sends the trash. Either way, the file is gone from its name.
|
||||
|
||||
**Cause.** Drive has no rename that replaces its destination, so `rename(2)` over an existing name
|
||||
removes the destination first and renames the source second (B13). A failure between the two steps
|
||||
puts the destination back (`restore_replaced`), but a stop between them left nothing to say that a
|
||||
rename was half done.
|
||||
|
||||
**Fix.** A replacing rename writes a journal entry before it removes the destination, with a synced
|
||||
commit, and removes the entry when it returns, whichever way it returns. The entry lives in
|
||||
`sync_state`, so the schema does not change. On the next start, and on the drain's idle passes
|
||||
while Drive could not be asked, each entry from an earlier run is settled:
|
||||
- the source's rename, or the create it rewrote, is queued: the rename stands;
|
||||
- the destination's trash is queued and the rename is not: the queued trash is dropped;
|
||||
- otherwise Drive is asked. If the source has its new name, the rename stands. If the destination is
|
||||
in the trash, it is restored. If the destination never got there, nothing is undone.
|
||||
|
||||
Entries are tagged with the opening of the database that wrote them, so a rename in progress is
|
||||
never settled under it. A source created here whose create landed under the rename is known to Drive
|
||||
by a uid the entry does not have; it is logged and left as it is.
|
||||
|
||||
**Verified:** `a_replace_cut_off_after_its_trash_brings_the_replaced_file_back` and
|
||||
`a_replace_cut_off_after_queueing_its_trash_keeps_the_replaced_file` start a daemon on the state a
|
||||
stop leaves, and fail without the settle. They write that state directly; no test stops a daemon in
|
||||
the middle of a rename.
|
||||
|
||||
---
|
||||
|
||||
### B301 — Two overlapping fsyncs can leave the older one's record on disk
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
**Found:** 2026-11-27, from the review of the mounted filesystem in `FUSE.md`, while moving the
|
||||
fsync into `pdfs-vfs` (step 5 of `docs/ARCHITECTURE.md`). It was not seen in a run.
|
||||
**Where:** `Files::fsync` in `crates/pdfs-vfs/src/files.rs`; `WriteHandle::generation` and
|
||||
`WriteHandle::barrier` in `crates/pdfs-vfs/src/open.rs`
|
||||
|
||||
**Repro:** Write a file and call `fsync` from two threads on the same open file, with a write in
|
||||
between. Each fsync runs on a worker. If the first one finishes after the second, its record of the
|
||||
file goes to disk last. Kill the daemon before the file is closed. The restart recovers the file
|
||||
as the first fsync saw it and loses the bytes the second one had made durable.
|
||||
|
||||
**Cause.** An fsync copied what the handle held (length, written ranges, base), synced the scratch
|
||||
file and then wrote that copy as the sidecar a restart recovers from. Nothing ordered two of these
|
||||
on the same file, so the copy that was written last was not always the newest.
|
||||
|
||||
**Fix.** Each write handle counts its changes in `generation` and carries a `barrier` lock. An
|
||||
fsync takes the barrier before it reads the handle and holds it until the sidecar is written, so a
|
||||
later fsync records at least what an earlier one did. The barrier also keeps the generation last
|
||||
made durable, and an fsync with nothing new since then skips the sidecar.
|
||||
|
||||
**Verified:** `an_fsync_records_what_the_file_holds_when_its_turn_comes` holds the barrier, writes
|
||||
while an fsync waits for it, and checks that a restart recovers the later bytes. No test drives
|
||||
this through a mount.
|
||||
|
||||
---
|
||||
|
||||
### B300 — A read during a release can be served the revision the write replaced
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
**Found:** 2026-11-27, by reading the code while moving the open files into `pdfs-vfs` (step 5 of
|
||||
`docs/ARCHITECTURE.md`). It was not seen in a run.
|
||||
**Where:** `OpenFiles::release` and `OpenFiles::reader` in `crates/pdfs-vfs/src/open.rs`;
|
||||
`Core::read_local` in `crates/pdfs-fuse/src/reads.rs` and the `read` callback in
|
||||
`crates/pdfs-fuse/src/filesystem.rs`
|
||||
|
||||
**Repro:** Keep one read-only handle open on a file, and read through it from a second thread.
|
||||
Write the file through another handle and close it. A read that lands after the release took the
|
||||
write state out of the open files, but before the release queued the new revision, finds neither
|
||||
of them, and is answered with the revision on Drive from before the write.
|
||||
|
||||
**Cause.** The release removed the writer first and queued the revision second. Each read looks for
|
||||
an open writer, then for a queued revision, then goes to the cache or Drive. The release runs on the
|
||||
dispatch loop, so an `open` and `read` issued after `close(2)` are served after it. A read already
|
||||
running on a worker, through a handle opened earlier, is not ordered that way.
|
||||
|
||||
**Fix.** A release now keeps a read view of the writer (its scratch file, length, base and written
|
||||
ranges) until the revision is queued. `OpenFiles::reader` answers from the open writer, or from that
|
||||
view, and both read paths ask it first. The view was already kept in one form, as the set of inodes
|
||||
being released, which only the check for unsaved changes looked at.
|
||||
|
||||
**Verified:** `the_last_release_hands_back_the_write_and_marks_it_releasing` checks that a read finds
|
||||
the write until `finish_release`. No test drives the race through a mount.
|
||||
|
||||
---
|
||||
|
||||
### B299 — A synced folder in the trash blocks attaching any other folder
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
|
||||
Reference in new issue
Block a user