mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-27 19:52:14 +01:00
Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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;
|
||||
|
||||
@@ -1135,9 +1135,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
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Kernel-facing FUSE callback adapter.
|
||||
|
||||
use super::*;
|
||||
use crate::state::DirListing;
|
||||
use pdfs_vfs::files::Files;
|
||||
use pdfs_vfs::open::{DirListing, dir_page};
|
||||
|
||||
impl Filesystem for ProtonFs {
|
||||
/// Negotiate kernel-side behaviour once, before any other callback.
|
||||
@@ -201,7 +202,7 @@ impl Filesystem for ProtonFs {
|
||||
// in-memory walk with no chance of a remote call, so it never needs a
|
||||
// worker. Only a handle whose `opendir` failed to snapshot (or a kernel
|
||||
// that issued `readdir` without one) falls back to the live path.
|
||||
if let Some(listing) = self.core.state().dir_snapshots.get(&fh.0).cloned() {
|
||||
if let Some(listing) = self.core.state().open.dir(fh.0) {
|
||||
reply_listing(&listing, offset, self.root, reply);
|
||||
return;
|
||||
}
|
||||
@@ -225,7 +226,7 @@ impl Filesystem for ProtonFs {
|
||||
_flags: OpenFlags,
|
||||
reply: ReplyEmpty,
|
||||
) {
|
||||
self.core.state().dir_snapshots.remove(&fh.0);
|
||||
self.core.state().open.close_dir(fh.0);
|
||||
reply.ok();
|
||||
}
|
||||
|
||||
@@ -268,19 +269,13 @@ impl Filesystem for ProtonFs {
|
||||
// issued the read before any write that comes after it, so that is
|
||||
// the content it asked for. On the loop, the download held every
|
||||
// request of the mount (`docs/BUGS.md` B227).
|
||||
let handle = {
|
||||
let st = self.core.state();
|
||||
st.active_writes.get(&ino.0).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
|
||||
.core
|
||||
.state()
|
||||
.open
|
||||
.reader(ino.0)
|
||||
.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 {
|
||||
match self.core.serve_open_read_local(
|
||||
&file,
|
||||
@@ -464,14 +459,7 @@ impl Filesystem for ProtonFs {
|
||||
// accepted and ignored so tools that chmod/utimes after writing succeed.
|
||||
if let Some(size) = size {
|
||||
let fh = fh.map(|f| f.0).filter(|&f| f != 0);
|
||||
let handled = {
|
||||
let mut st = self.core.state();
|
||||
match st.active_writes.get_mut(&ino.0) {
|
||||
Some(aw) => aw.resize(size).map(|()| true).map_err(Errno::from),
|
||||
None => Ok(false),
|
||||
}
|
||||
};
|
||||
let handled = match handled {
|
||||
let handled = match self.files.resize(ino.0, size).map_err(file_errno) {
|
||||
Ok(handled) => handled,
|
||||
Err(error) => {
|
||||
debug!(ino = ino.0, size, ?error, "setattr resize refused");
|
||||
@@ -503,7 +491,6 @@ impl Filesystem for ProtonFs {
|
||||
});
|
||||
return;
|
||||
}
|
||||
self.core.state().set_size(ino.0, size);
|
||||
}
|
||||
self.reply_attr(ino.0, reply);
|
||||
}
|
||||
@@ -523,67 +510,12 @@ impl Filesystem for ProtonFs {
|
||||
reply.error(error);
|
||||
return;
|
||||
}
|
||||
let new_end = offset.saturating_add(length);
|
||||
// Only the modes whose effect on the scratch file this handle can
|
||||
// record. Anything else went through to the scratch file untracked:
|
||||
// a zeroed range was refilled from the base at commit, and a collapse
|
||||
// or insert shifted bytes that `len` and `written` did not follow
|
||||
// (`docs/BUGS.md` B224). `EOPNOTSUPP` is also what makes glibc's
|
||||
// `posix_fallocate` fall back to writing zeros.
|
||||
let Some(kind) = falloc_kind(mode) else {
|
||||
reply.error(Errno::EOPNOTSUPP);
|
||||
return;
|
||||
};
|
||||
let file = {
|
||||
let st = self.core.state();
|
||||
match st.handles.get(&_fh.0).and_then(|i| st.active_writes.get(i)) {
|
||||
Some(aw) => aw.file.clone(),
|
||||
None => {
|
||||
reply.error(if st.entries.contains_key(&ino.0) {
|
||||
Errno::EBADF
|
||||
} else {
|
||||
Errno::ENOENT
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
// The syscall can take a while on a large range; the state lock is
|
||||
// not held across it, as `write` does not hold it across its I/O.
|
||||
let ret = {
|
||||
use std::os::unix::io::AsRawFd;
|
||||
unsafe { libc::fallocate(file.as_raw_fd(), mode, offset as i64, length as i64) }
|
||||
};
|
||||
let res = if ret != 0 {
|
||||
Err(Errno::from(std::io::Error::last_os_error()))
|
||||
} else {
|
||||
let mut st = self.core.state();
|
||||
if let Some(aw) = st
|
||||
.handles
|
||||
.get(&_fh.0)
|
||||
.copied()
|
||||
.and_then(|i| st.active_writes.get_mut(&i))
|
||||
{
|
||||
let len = aw.len;
|
||||
let (authored, grown) = kind.effect(offset, new_end, len);
|
||||
if let Some((from, to)) = authored {
|
||||
// Zeroed or punched bytes read as zero. Marked authored so
|
||||
// queue_revision does not refill them from the remote
|
||||
// baseline and silently undo them at commit.
|
||||
aw.written.add(from, to);
|
||||
aw.dirty = true;
|
||||
}
|
||||
if let Some(end) = grown {
|
||||
aw.len = end;
|
||||
aw.dirty = true;
|
||||
st.set_size(ino.0, end);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
|
||||
match res {
|
||||
Ok(_) => reply.ok(),
|
||||
match self
|
||||
.files
|
||||
.fallocate(ino.0, _fh.0, offset, length, mode)
|
||||
.map_err(file_errno)
|
||||
{
|
||||
Ok(()) => reply.ok(),
|
||||
Err(e) => reply.error(e),
|
||||
}
|
||||
}
|
||||
@@ -607,28 +539,17 @@ impl Filesystem for ProtonFs {
|
||||
_lock_owner: LockOwner,
|
||||
reply: ReplyEmpty,
|
||||
) {
|
||||
let file = {
|
||||
let st = self.core.state();
|
||||
st.handles
|
||||
.get(&fh.0)
|
||||
.and_then(|ino| st.active_writes.get(ino))
|
||||
.filter(|aw| aw.dirty)
|
||||
.map(|aw| aw.file.clone())
|
||||
};
|
||||
let Some(file) = file else {
|
||||
let Some(file) = self.files.dirty_scratch(fh.0) else {
|
||||
reply.ok();
|
||||
return;
|
||||
};
|
||||
let fs = self.clone();
|
||||
self.core
|
||||
.workers
|
||||
.run(Lane::Transfer, "flush", move || match file.sync_data() {
|
||||
self.core.workers.run(Lane::Transfer, "flush", move || {
|
||||
match fs.files.flush(fh.0, &file) {
|
||||
Ok(()) => reply.ok(),
|
||||
Err(e) => {
|
||||
error!(fh = fh.0, error = %e, "flush of scratch file failed");
|
||||
reply.error(fs.scratch_sync_errno(&e));
|
||||
}
|
||||
});
|
||||
Err(error) => reply.error(file_errno(error)),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Durability here means the scratch file, not the remote: a caller asking
|
||||
@@ -666,25 +587,6 @@ impl Filesystem for ProtonFs {
|
||||
reply: ReplyEmpty,
|
||||
) {
|
||||
let ino = self.tree(ino);
|
||||
let (handle, unlinked_uid, releasing) = {
|
||||
let mut st = self.core.state();
|
||||
let unlinked_uid = release_unlinked_entry(&mut st, ino.0);
|
||||
let ino = st.handles.remove(&fh.0);
|
||||
let h = ino.and_then(|i| {
|
||||
let aw = st.active_writes.get_mut(&i)?;
|
||||
aw.open_count = aw.open_count.saturating_sub(1);
|
||||
if aw.open_count == 0 {
|
||||
st.active_writes.remove(&i)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
let releasing = ino.filter(|_| h.is_some());
|
||||
if let Some(ino) = releasing {
|
||||
st.releasing.insert(ino);
|
||||
}
|
||||
(h, unlinked_uid, releasing)
|
||||
};
|
||||
// Deliberately **not** handed to a worker, unlike the other slow
|
||||
// handlers here. The kernel does not wait for a `release` reply before
|
||||
// letting `close(2)` return, so the only thing sequencing this against
|
||||
@@ -699,9 +601,9 @@ impl Filesystem for ProtonFs {
|
||||
// did not touch, it stages an incomplete blob and lets the drain thread
|
||||
// finish it (audit F1). What is left is a rename, two fsyncs, a database
|
||||
// insert, and at most a bounded copy out of the local cache.
|
||||
self.finish_release(handle, unlinked_uid, reply);
|
||||
if let Some(ino) = releasing {
|
||||
self.core.state().releasing.remove(&ino);
|
||||
match self.files.release(ino.0, fh.0) {
|
||||
Ok(()) => reply.ok(),
|
||||
Err(error) => reply.error(file_errno(error)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1034,6 +936,8 @@ impl Filesystem for ProtonFs {
|
||||
#[derive(Clone)]
|
||||
pub struct ProtonFs {
|
||||
core: Core,
|
||||
/// The open-file service, shared with every other mount of the daemon.
|
||||
files: Arc<Files<Core>>,
|
||||
uid: u32,
|
||||
gid: u32,
|
||||
/// The tree inode of this session's root, which the kernel knows as
|
||||
@@ -1041,103 +945,24 @@ pub struct ProtonFs {
|
||||
root: u64,
|
||||
}
|
||||
|
||||
/// How many times a write `open` will re-read its base after a `release`
|
||||
/// published a newer queued revision underneath it (`docs/BUGS.md` B32).
|
||||
///
|
||||
/// One retry covers the race, which needs a close and an open of the same file
|
||||
/// to overlap on different threads. More than that is not contention, it is a
|
||||
/// file being republished continuously, and looping on it would keep a FUSE
|
||||
/// worker busy indefinitely.
|
||||
const OPEN_BASE_ATTEMPTS: u32 = 3;
|
||||
|
||||
/// The most one `copy_file_range` call copies; the caller loops for the rest.
|
||||
/// A local copy of this much takes milliseconds, which is how long it holds
|
||||
/// the dispatch loop.
|
||||
const COPY_RANGE_MAX: u64 = 16 * 1024 * 1024;
|
||||
|
||||
/// One directory's entries as `readdir` reports them: `.` and `..` first, then
|
||||
/// the interned children in `children` order.
|
||||
///
|
||||
/// Split out because it is built from two places that must agree — `opendir`
|
||||
/// freezes it, and the fallback `readdir` builds it live — and a divergence
|
||||
/// between them would show up as entries appearing or vanishing depending on
|
||||
/// whether the kernel happened to send an `opendir`.
|
||||
fn build_listing(st: &State, ino: u64) -> DirListing {
|
||||
let parent = st.entries.get(&ino).map_or(ROOT_INO, |e| e.parent);
|
||||
// "." and ".." occupy offsets 0 and 1; real children follow.
|
||||
let mut listing = vec![
|
||||
(ino, true, ".".to_string()),
|
||||
(parent, true, "..".to_string()),
|
||||
];
|
||||
if let Some(kids) = st.children.get(&ino) {
|
||||
for &kid in kids {
|
||||
if let Some(e) = st.entries.get(&kid) {
|
||||
listing.push((kid, e.node.is_folder(), e.node.name.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
listing
|
||||
}
|
||||
|
||||
/// Fill a `readdir` reply from `listing`, resuming at `offset`.
|
||||
///
|
||||
/// The cookie handed back is the index of the *next* entry, so a resumed call
|
||||
/// continues exactly where the last one stopped — which is only true because
|
||||
/// the listing behind those indexes is a snapshot (`docs/BUGS.md` B43).
|
||||
/// What an `fallocate` mode does to a write handle, for the modes it can
|
||||
/// record (`docs/BUGS.md` B224).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum FallocKind {
|
||||
/// Reserve space; past the end it grows the file unless `keep_size`.
|
||||
Allocate { keep_size: bool },
|
||||
/// Deallocate a range inside the file, which then reads as zero.
|
||||
Punch,
|
||||
/// Zero a range; past the end it grows the file unless `keep_size`.
|
||||
Zero { keep_size: bool },
|
||||
}
|
||||
|
||||
fn falloc_kind(mode: i32) -> Option<FallocKind> {
|
||||
const KEEP: i32 = libc::FALLOC_FL_KEEP_SIZE;
|
||||
const PUNCH: i32 = libc::FALLOC_FL_PUNCH_HOLE;
|
||||
const ZERO: i32 = libc::FALLOC_FL_ZERO_RANGE;
|
||||
match mode {
|
||||
0 => Some(FallocKind::Allocate { keep_size: false }),
|
||||
KEEP => Some(FallocKind::Allocate { keep_size: true }),
|
||||
m if m == PUNCH | KEEP => Some(FallocKind::Punch),
|
||||
ZERO => Some(FallocKind::Zero { keep_size: false }),
|
||||
m if m == ZERO | KEEP => Some(FallocKind::Zero { keep_size: true }),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl FallocKind {
|
||||
/// For `[offset, end)` on a file `len` bytes long: the range that now
|
||||
/// reads as zero and must count as written, and the new length if it grew.
|
||||
fn effect(self, offset: u64, end: u64, len: u64) -> (Option<(u64, u64)>, Option<u64>) {
|
||||
let grow = |keep_size: bool| (!keep_size && end > len).then_some(end);
|
||||
let zeroed = |to: u64| (offset < to).then_some((offset, to));
|
||||
match self {
|
||||
// Space past the old end reads as zero, and nothing before it moved.
|
||||
Self::Allocate { keep_size } => {
|
||||
(grow(keep_size).map(|end| (len, end)), grow(keep_size))
|
||||
}
|
||||
Self::Punch => (zeroed(end.min(len)), None),
|
||||
Self::Zero { keep_size } => {
|
||||
let to = if keep_size { end.min(len) } else { end };
|
||||
(zeroed(to), grow(keep_size))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reply_listing(listing: &DirListing, offset: u64, root: u64, mut reply: ReplyDirectory) {
|
||||
for (i, (ino, is_dir, name)) in listing.iter().enumerate().skip(offset as usize) {
|
||||
for (next, (ino, is_dir, name)) in dir_page(listing, offset) {
|
||||
let ft = if *is_dir {
|
||||
FileType::Directory
|
||||
} else {
|
||||
FileType::RegularFile
|
||||
};
|
||||
if reply.add(kernel_ino(root, *ino), (i + 1) as u64, ft, name) {
|
||||
if reply.add(kernel_ino(root, *ino), next, ft, name) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -1164,6 +989,7 @@ impl ProtonFs {
|
||||
// SAFETY: geteuid/getegid are infallible and have no preconditions.
|
||||
let (uid, gid) = unsafe { (libc::geteuid(), libc::getegid()) };
|
||||
Self {
|
||||
files: core.files(),
|
||||
core,
|
||||
uid,
|
||||
gid,
|
||||
@@ -1267,12 +1093,10 @@ impl ProtonFs {
|
||||
return;
|
||||
}
|
||||
let mut st = self.core.state();
|
||||
let listing = Arc::new(build_listing(&st, ino));
|
||||
let listing = st.listing(ino);
|
||||
// Shares the counter with write handles, so a directory handle can never
|
||||
// collide with a file handle (both are `fh` values in one kernel space).
|
||||
let fh = st.next_fh;
|
||||
st.next_fh += 1;
|
||||
st.dir_snapshots.insert(fh, listing);
|
||||
let fh = st.open.open_dir(listing);
|
||||
drop(st);
|
||||
reply.opened(FileHandle(fh), FopenFlags::empty());
|
||||
}
|
||||
@@ -1285,7 +1109,7 @@ impl ProtonFs {
|
||||
return;
|
||||
}
|
||||
let st = self.core.state();
|
||||
let listing = build_listing(&st, ino);
|
||||
let listing = st.listing(ino);
|
||||
drop(st);
|
||||
reply_listing(&listing, offset, self.root, reply);
|
||||
}
|
||||
@@ -1324,371 +1148,27 @@ impl ProtonFs {
|
||||
/// The body of [`Filesystem::open`], run off the dispatch loop for a write
|
||||
/// open.
|
||||
fn serve_open(&self, ino: INodeNo, flags: OpenFlags, reply: ReplyOpen) {
|
||||
let write_requested = flags.acc_mode() != OpenAccMode::O_RDONLY;
|
||||
let (uid, mut base_mtime, mut base_size, mut provisional, mut base_revision_id) = {
|
||||
let mut st = self.core.state();
|
||||
match st.entries.get_mut(&ino.0) {
|
||||
Some(e) if e.node.is_file() => {
|
||||
if write_requested && !e.writable() {
|
||||
reply.error(Errno::EACCES);
|
||||
return;
|
||||
}
|
||||
e.open_count = e.open_count.saturating_add(1);
|
||||
(
|
||||
e.uid.clone(),
|
||||
e.node.modification_time,
|
||||
node_size(&e.node),
|
||||
// Still the cheap enumeration's ciphertext size (B12).
|
||||
matches!(
|
||||
&e.node.kind,
|
||||
NodeKind::File {
|
||||
claimed_size: None,
|
||||
..
|
||||
}
|
||||
),
|
||||
node_revision_id(&e.node),
|
||||
)
|
||||
}
|
||||
Some(_) => {
|
||||
reply.error(Errno::EISDIR);
|
||||
return;
|
||||
}
|
||||
None => {
|
||||
reply.error(Errno::ENOENT);
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
debug!(ino = ino.0, ?flags, base_size, base_mtime, "open");
|
||||
// Read-only opens stay stateless (fh 0). A write open allocates a
|
||||
// disk-backed handle; bytes are authored into a scratch file and the
|
||||
// untouched remainder is pulled from the base lazily (on read / commit).
|
||||
if flags.acc_mode() == OpenAccMode::O_RDONLY {
|
||||
reply.opened(FileHandle(0), FopenFlags::empty());
|
||||
return;
|
||||
}
|
||||
// A previous close may already have newer bytes queued locally while
|
||||
// the server still holds the older revision. That staged blob, not the
|
||||
// remote, is the base for this handle. In particular, `truncate file`
|
||||
// opens for writing and then shrinks via setattr; starting its scratch
|
||||
// as a sparse zero file would turn the preserved prefix into zeros.
|
||||
//
|
||||
// Complete pending blobs are the common case and can be copied without
|
||||
// any network access. An incomplete blob still has gaps referring to
|
||||
// the remote base, and stacking another write on it cannot be
|
||||
// represented by WriteHandle, so the copy's gaps are filled from that
|
||||
// base first, as the drain fills them before an upload. Only when that
|
||||
// fails (offline, or the base is gone) does the open fail: refusing
|
||||
// every such open failed a create over a file whose partial edit had
|
||||
// not drained yet (`docs/BUGS.md` B204).
|
||||
//
|
||||
// Reading that blob and installing the handle cannot be done under one
|
||||
// lock — the copy is the size of the file — so the base is re-checked at
|
||||
// the moment the handle goes in, and a `release` that published a newer
|
||||
// revision in between sends this around again. Without the re-check the
|
||||
// new handle carried the *older* base, and its own release published
|
||||
// content that silently discarded the revision closed a moment earlier
|
||||
// (`docs/BUGS.md` B32). A second attempt is already unlikely and a third would
|
||||
// mean something is republishing continuously, so give up rather than
|
||||
// spin: the caller's `open` fails instead of its data being lost.
|
||||
//
|
||||
// `reply` is consumed by whichever arm answers, so the loop yields an
|
||||
// outcome and the answer is sent once, after it.
|
||||
let outcome = 'install: {
|
||||
for attempt in 0..OPEN_BASE_ATTEMPTS {
|
||||
// The handle starts at the base's size. A provisional one is the
|
||||
// ciphertext size, so the file would grow by the encryption
|
||||
// overhead and reading the base would fail (`docs/BUGS.md` B100). A
|
||||
// queued revision stamps a real size, so this only goes to the
|
||||
// network for a file the listing has not sized yet.
|
||||
if provisional && self.core.pending_blob(&uid).is_none() {
|
||||
match self.core.resolve_provisional_size(ino.0, &uid) {
|
||||
Some(size) => {
|
||||
base_size = size;
|
||||
provisional = false;
|
||||
}
|
||||
None => {
|
||||
error!(%uid, "could not settle the size of the base for a write open");
|
||||
break 'install Err(Errno::EIO);
|
||||
}
|
||||
}
|
||||
}
|
||||
let pending_base = self.core.writes.queued(&uid);
|
||||
let (file, path) = match self.core.cache.create_scratch() {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
error!(%uid, error = %e, "create scratch file failed");
|
||||
break 'install Err(Errno::EIO);
|
||||
}
|
||||
};
|
||||
let mut initial_written = Intervals::default();
|
||||
if let Some(pending) = &pending_base {
|
||||
// Reflink where the filesystem can: this blob is the whole
|
||||
// file, and a byte-for-byte copy of a multi-GB pending
|
||||
// revision is the kind of work `open` must not do
|
||||
// (`ContentCache::clone_or_copy`).
|
||||
if let Err(e) = ContentCache::clone_or_copy(&pending.path, &path) {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
// The drain lets go of the pending entry before it
|
||||
// discards the blob, so a blob that went away under the
|
||||
// copy is a revision that landed or was replaced: the
|
||||
// same race the re-check below catches, only earlier.
|
||||
if self.core.pending_blob(&uid).as_ref() != Some(&pending.path) {
|
||||
warn!(%uid, attempt, "queued revision went away while opening for write; retrying");
|
||||
continue;
|
||||
}
|
||||
error!(%uid, source = %pending.path.display(), error = %e,
|
||||
"copy queued revision into write scratch failed");
|
||||
break 'install Err(Errno::EIO);
|
||||
}
|
||||
if !pending.meta.complete {
|
||||
let mut authored = Intervals::default();
|
||||
for &(s, e) in &pending.meta.authored {
|
||||
authored.add(s, e);
|
||||
}
|
||||
if let Err(error) = self.core.fill_gaps(
|
||||
&uid,
|
||||
&file,
|
||||
pending.meta.len,
|
||||
pending.meta.base_mtime,
|
||||
pending.meta.base_size,
|
||||
&authored,
|
||||
) {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
error!(%uid, ?error, "cannot complete the queued revision a write open is based on");
|
||||
break 'install Err(error);
|
||||
}
|
||||
debug!(%uid, "write open completed an incomplete queued revision");
|
||||
}
|
||||
initial_written.add(0, pending.meta.len);
|
||||
}
|
||||
// Sampled *before* the state lock, never under it: no site in
|
||||
// the daemon holds `pending` and `state` at once (see
|
||||
// `stamp_pending_sizes`) and this must not become the first.
|
||||
// What that costs is a window of a few instructions instead of
|
||||
// a lock-tight comparison — against the multi-gigabyte copy
|
||||
// above, which is the window that actually loses data.
|
||||
let current = self.core.pending_blob(&uid);
|
||||
let landed = self.core.drain.landed.lock().get(&uid).cloned();
|
||||
let mut st = self.core.state();
|
||||
// Only a handle this open is about to *create* can carry a stale
|
||||
// base; if one already exists, that handle is authoritative and
|
||||
// the scratch prepared above is discarded either way.
|
||||
let creating = !st.active_writes.contains_key(&ino.0);
|
||||
if creating && current.as_ref() != pending_base.as_ref().map(|p| &p.path) {
|
||||
drop(st);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
warn!(%uid, attempt, "queued revision changed while opening for write; retrying");
|
||||
continue;
|
||||
}
|
||||
// With no queued revision, the base's bytes come from the cache,
|
||||
// keyed by the base's mtime and size. The ones sampled above can
|
||||
// name a revision this daemon has since replaced: an upload that
|
||||
// lands lets go of its blob before the tree has its node, and
|
||||
// the cache holds its bytes under the node only. So the base is
|
||||
// the landing node while there is one, and the tree's otherwise
|
||||
// (docs/BUGS.md B170).
|
||||
if creating && pending_base.is_none() {
|
||||
let now = landed.or_else(|| st.entries.get(&ino.0).map(|e| e.node.clone()));
|
||||
if let Some(node) = now
|
||||
&& (node.modification_time != base_mtime
|
||||
|| node_revision_id(&node) != base_revision_id)
|
||||
{
|
||||
base_mtime = node.modification_time;
|
||||
base_size = node_size(&node);
|
||||
base_revision_id = node_revision_id(&node);
|
||||
provisional = matches!(
|
||||
&node.kind,
|
||||
NodeKind::File {
|
||||
claimed_size: None,
|
||||
..
|
||||
}
|
||||
);
|
||||
debug!(%uid, base_mtime, base_size, "write open took the base the file has now");
|
||||
if provisional {
|
||||
drop(st);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
let fh = st.next_fh;
|
||||
st.next_fh += 1;
|
||||
let aw = st.active_writes.entry(ino.0).or_insert_with(|| {
|
||||
WriteHandle {
|
||||
ino: ino.0,
|
||||
uid: uid.clone(),
|
||||
file: Arc::new(file),
|
||||
path,
|
||||
written: initial_written,
|
||||
// Starts at the current size; reads in [0, base_size)
|
||||
// come from the base until overwritten.
|
||||
len: base_size,
|
||||
base_size,
|
||||
base_mtime,
|
||||
base_revision_id,
|
||||
dirty: false,
|
||||
open_count: 0,
|
||||
}
|
||||
});
|
||||
aw.open_count += 1;
|
||||
st.handles.insert(fh, ino.0);
|
||||
break 'install Ok(fh);
|
||||
}
|
||||
error!(%uid, "queued revision kept changing while opening for write");
|
||||
Err(Errno::EIO)
|
||||
};
|
||||
match outcome {
|
||||
let write = flags.acc_mode() != OpenAccMode::O_RDONLY;
|
||||
match self.files.open(ino.0, write) {
|
||||
Ok(fh) => reply.opened(FileHandle(fh), FopenFlags::empty()),
|
||||
Err(error) => {
|
||||
// The lookup count was raised before any of this could fail.
|
||||
if let Some(entry) = self.core.state().entries.get_mut(&ino.0) {
|
||||
entry.open_count = entry.open_count.saturating_sub(1);
|
||||
}
|
||||
reply.error(error);
|
||||
}
|
||||
Err(error) => reply.error(file_errno(error)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The body of [`Filesystem::fsync`], run off the dispatch loop.
|
||||
/// The errno to give a program for a failed sync of a scratch file.
|
||||
/// Delayed allocation means a full disk usually surfaces at the sync
|
||||
/// rather than at `write(2)`, and `ENOSPC` is what a program checks for.
|
||||
fn scratch_sync_errno(&self, e: &std::io::Error) -> Errno {
|
||||
match e.raw_os_error() {
|
||||
Some(libc::ENOSPC) => {
|
||||
self.core.cache.emergency_evict();
|
||||
Errno::ENOSPC
|
||||
}
|
||||
Some(libc::EDQUOT) => Errno::EDQUOT,
|
||||
_ => Errno::EIO,
|
||||
fn serve_fsync(&self, fh: FileHandle, reply: ReplyEmpty) {
|
||||
match self.files.fsync(fh.0) {
|
||||
Ok(()) => reply.ok(),
|
||||
Err(error) => reply.error(file_errno(error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn serve_fsync(&self, fh: FileHandle, reply: ReplyEmpty) {
|
||||
// Everything the durability sidecar needs, copied out so no lock is held
|
||||
// across the sync.
|
||||
let handle = {
|
||||
let st = self.core.state();
|
||||
let ino = st.handles.get(&fh.0).copied();
|
||||
ino.and_then(|i| st.active_writes.get(&i)).map(|aw| {
|
||||
(
|
||||
aw.file.clone(),
|
||||
aw.path.clone(),
|
||||
aw.uid.clone(),
|
||||
aw.dirty,
|
||||
aw.written.clone(),
|
||||
aw.len,
|
||||
aw.base_size,
|
||||
aw.base_mtime,
|
||||
aw.base_revision_id.clone(),
|
||||
)
|
||||
})
|
||||
};
|
||||
// A handle opened for reading has nothing of its own to make durable,
|
||||
// and POSIX allows `fsync` on it; `EBADF` failed `sync FILE` and
|
||||
// backup tools that sync what they read (`docs/BUGS.md` B222).
|
||||
let Some((f, path, uid, dirty, written, len, base_size, base_mtime, base_revision_id)) =
|
||||
handle
|
||||
else {
|
||||
reply.ok();
|
||||
return;
|
||||
};
|
||||
if let Err(e) = f.sync_all() {
|
||||
error!(fh = fh.0, error = %e, "fsync of scratch file failed");
|
||||
reply.error(self.scratch_sync_errno(&e));
|
||||
return;
|
||||
}
|
||||
// A clean handle has nothing on it that the remote does not already
|
||||
// hold, so there is nothing for a crash to lose.
|
||||
if !dirty {
|
||||
reply.ok();
|
||||
return;
|
||||
}
|
||||
// The bytes are on stable storage, but only the scratch file knows that,
|
||||
// and the scratch directory is cleared at open. Record what the blob is
|
||||
// so a restart can hand it to the upload queue instead of deleting it.
|
||||
//
|
||||
// Deliberately *not* the full release path: staging the blob here would
|
||||
// move the file out from under a handle the application still has open,
|
||||
// and queueing an upload per `fsync` would push a revision for every
|
||||
// barrier in a write loop. This only makes the existing file findable.
|
||||
let authored: Vec<(u64, u64)> = written
|
||||
.segments(0, len)
|
||||
.into_iter()
|
||||
.filter(|&(_, _, authored)| authored)
|
||||
.map(|(s, e, _)| (s, e))
|
||||
.collect();
|
||||
let meta = StagedWrite {
|
||||
uid: uid.to_string(),
|
||||
len,
|
||||
base_size,
|
||||
base_mtime,
|
||||
complete: StagedWrite::covers(&authored, len),
|
||||
authored,
|
||||
based_on: self
|
||||
.core
|
||||
.remote_baseline(&uid, base_mtime, base_size, base_revision_id),
|
||||
};
|
||||
// A failed sidecar means the write is not durable, and `fsync` promising
|
||||
// otherwise is the defect this exists to fix — so it is an error, not a
|
||||
// warning.
|
||||
if let Err(e) = self.core.cache.mark_scratch_durable(&path, &meta) {
|
||||
error!(%uid, error = %e, "recording fsync durability failed");
|
||||
if e.is_disk_full() {
|
||||
self.core.cache.emergency_evict();
|
||||
reply.error(Errno::ENOSPC);
|
||||
} else {
|
||||
reply.error(Errno::EIO);
|
||||
}
|
||||
return;
|
||||
}
|
||||
reply.ok();
|
||||
/// Stage `data` at `offset` of the write handle `fh` on `ino`.
|
||||
fn stage_write(&self, ino: u64, fh: u64, offset: u64, data: &[u8]) -> Result<(), Errno> {
|
||||
self.files.write(ino, fh, offset, data).map_err(file_errno)
|
||||
}
|
||||
|
||||
/// The body of [`Filesystem::create`], run off the dispatch loop.
|
||||
/// Stage `data` at `offset` of the write handle `fh` on `ino`, straight into
|
||||
/// its scratch file (no base download): only the untouched remainder is
|
||||
/// pulled from the remote, and only at commit.
|
||||
fn stage_write(&self, ino: u64, fh: u64, offset: u64, data: &[u8]) -> Result<(), Errno> {
|
||||
let file = {
|
||||
let st = self.core.state();
|
||||
match st.handles.get(&fh).and_then(|&i| st.active_writes.get(&i)) {
|
||||
Some(aw) => aw.file.clone(),
|
||||
None => return Err(Errno::EBADF),
|
||||
}
|
||||
};
|
||||
if let Err(e) = file.write_all_at(data, offset) {
|
||||
error!(ino, fh, error = %e, "scratch write failed");
|
||||
// A full local disk is not a broken file: answer `ENOSPC` so the
|
||||
// application can say so (and so `cp`/editors take their own
|
||||
// out-of-space path), and free what the cache is holding — the
|
||||
// scratch file the next write goes to shares that filesystem.
|
||||
if e.raw_os_error() == Some(libc::ENOSPC) {
|
||||
self.core.cache.emergency_evict();
|
||||
return Err(Errno::ENOSPC);
|
||||
}
|
||||
return Err(Errno::EIO);
|
||||
}
|
||||
let new_len = {
|
||||
let mut st = self.core.state();
|
||||
let Some(aw) = st
|
||||
.handles
|
||||
.get(&fh)
|
||||
.copied()
|
||||
.and_then(|i| st.active_writes.get_mut(&i))
|
||||
else {
|
||||
return Err(Errno::EBADF);
|
||||
};
|
||||
aw.record_write(offset, offset + data.len() as u64);
|
||||
let len = aw.len;
|
||||
st.set_size(ino, len);
|
||||
len
|
||||
};
|
||||
debug!(ino, fh, offset, len = data.len(), new_len, "staged write");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serve_create(&self, parent: u64, name: &str, reply: ReplyCreate) {
|
||||
if let Err(error) = self.core.require_writable(parent) {
|
||||
reply.error(error);
|
||||
@@ -1792,14 +1272,9 @@ impl ProtonFs {
|
||||
{
|
||||
kids.push(ino);
|
||||
}
|
||||
let fh = st.next_fh;
|
||||
st.next_fh += 1;
|
||||
let aw = st
|
||||
.active_writes
|
||||
.entry(ino)
|
||||
.or_insert_with(|| WriteHandle::created(ino, &node, file, path));
|
||||
aw.open_count += 1;
|
||||
st.handles.insert(fh, ino);
|
||||
let fh = st
|
||||
.open
|
||||
.open_writer(ino, || WriteHandle::created(ino, &node, file, path));
|
||||
let entry = st.entries.get(&ino).unwrap();
|
||||
let attr = self.attr(ino, &entry.node, entry.access);
|
||||
drop(st);
|
||||
@@ -1945,61 +1420,6 @@ impl ProtonFs {
|
||||
self.trash_child(parent, name_str, reply);
|
||||
}
|
||||
|
||||
/// The tail of [`Filesystem::release`], run off the dispatch loop: retire
|
||||
/// what the closed handle leaves behind.
|
||||
fn finish_release(
|
||||
&self,
|
||||
handle: Option<WriteHandle>,
|
||||
unlinked_uid: Option<NodeUid>,
|
||||
reply: ReplyEmpty,
|
||||
) {
|
||||
let was_unlinked = unlinked_uid.is_some();
|
||||
if let Some(uid) = unlinked_uid
|
||||
&& release_can_discard_unlinked(&self.core.db, &uid)
|
||||
{
|
||||
// Ops withdrawn at unlink left the bytes this handle read behind,
|
||||
// owned by no op any more; they go with the last handle.
|
||||
let withdrawn = self.core.pending_blob(&uid);
|
||||
if let Err(error) = self.core.discard_queued_ops(&uid) {
|
||||
warn!(%uid, ?error, "queued-op cleanup failed; retaining unlinked state");
|
||||
} else {
|
||||
if let Err(error) = self.core.db.delete_node(&uid) {
|
||||
warn!(%uid, %error, "deleting released unlinked node state failed");
|
||||
}
|
||||
if let Some(blob) = withdrawn {
|
||||
self.core.cache.discard_staged(&blob);
|
||||
}
|
||||
self.core.cache.evict(&uid);
|
||||
self.core.evict_reader(&uid);
|
||||
}
|
||||
}
|
||||
// Hand the bytes to the queue rather than uploading them here: the
|
||||
// scratch file is the only copy of what was just written, and blocking
|
||||
// the caller on the network is what made a copy into the mount run at
|
||||
// upload speed (and fail outright offline).
|
||||
match (handle, was_unlinked) {
|
||||
(Some(h), true) => {
|
||||
// POSIX keeps an unlinked file usable until the last close, but
|
||||
// closing it must not resurrect those bytes as a new revision.
|
||||
if let Err(e) = std::fs::remove_file(&h.path)
|
||||
&& e.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
warn!(path = %h.path.display(), error = %e, "discarding unlinked scratch file failed");
|
||||
}
|
||||
self.core.cache.clear_scratch_durable(&h.path);
|
||||
reply.ok();
|
||||
}
|
||||
(Some(mut h), false) => {
|
||||
self.core.follow_landed_create(&mut h);
|
||||
match self.core.queue_revision(&mut h) {
|
||||
Ok(()) => reply.ok(),
|
||||
Err(e) => reply.error(e),
|
||||
}
|
||||
}
|
||||
(None, _) => reply.ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The body of [`Filesystem::rename`], run off the dispatch loop.
|
||||
fn serve_rename(
|
||||
&self,
|
||||
@@ -2505,60 +1925,3 @@ impl ProtonFs {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod falloc_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_the_modes_a_handle_can_record_are_accepted() {
|
||||
let keep = libc::FALLOC_FL_KEEP_SIZE;
|
||||
assert_eq!(
|
||||
falloc_kind(0),
|
||||
Some(FallocKind::Allocate { keep_size: false })
|
||||
);
|
||||
assert_eq!(
|
||||
falloc_kind(keep),
|
||||
Some(FallocKind::Allocate { keep_size: true })
|
||||
);
|
||||
assert_eq!(
|
||||
falloc_kind(libc::FALLOC_FL_PUNCH_HOLE | keep),
|
||||
Some(FallocKind::Punch)
|
||||
);
|
||||
assert_eq!(
|
||||
falloc_kind(libc::FALLOC_FL_ZERO_RANGE),
|
||||
Some(FallocKind::Zero { keep_size: false })
|
||||
);
|
||||
for mode in [
|
||||
libc::FALLOC_FL_PUNCH_HOLE,
|
||||
libc::FALLOC_FL_COLLAPSE_RANGE,
|
||||
libc::FALLOC_FL_INSERT_RANGE,
|
||||
libc::FALLOC_FL_UNSHARE_RANGE,
|
||||
] {
|
||||
assert_eq!(falloc_kind(mode), None, "{mode:#x}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A zeroed range was left unwritten, so the commit filled it back in
|
||||
/// from the remote base (`docs/BUGS.md` B224).
|
||||
#[test]
|
||||
fn a_zeroed_or_punched_range_counts_as_written() {
|
||||
let zero = FallocKind::Zero { keep_size: false };
|
||||
assert_eq!(zero.effect(10, 20, 100), (Some((10, 20)), None));
|
||||
assert_eq!(zero.effect(90, 120, 100), (Some((90, 120)), Some(120)));
|
||||
let zero_keep = FallocKind::Zero { keep_size: true };
|
||||
assert_eq!(zero_keep.effect(90, 120, 100), (Some((90, 100)), None));
|
||||
assert_eq!(
|
||||
FallocKind::Punch.effect(90, 120, 100),
|
||||
(Some((90, 100)), None)
|
||||
);
|
||||
assert_eq!(FallocKind::Punch.effect(120, 130, 100), (None, None));
|
||||
let alloc = FallocKind::Allocate { keep_size: false };
|
||||
assert_eq!(alloc.effect(0, 50, 100), (None, None));
|
||||
assert_eq!(alloc.effect(90, 120, 100), (Some((100, 120)), Some(120)));
|
||||
assert_eq!(
|
||||
FallocKind::Allocate { keep_size: true }.effect(90, 120, 100),
|
||||
(None, None)
|
||||
);
|
||||
}
|
||||
}
|
||||
+129
-719
@@ -37,7 +37,6 @@ use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::ffi::OsStr;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::os::unix::fs::FileExt;
|
||||
use std::os::unix::net::UnixListener;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
@@ -93,12 +92,13 @@ mod enqueue;
|
||||
use drive::{DriveApi, RevisionRead};
|
||||
use pdfs_core::timestamp::now_secs;
|
||||
use pdfs_drive as drive;
|
||||
use pdfs_drive::node_revision_id;
|
||||
pub(crate) use pdfs_drive::{media_type_for, node_content_sha1, parse_uid, remote_name_is_safe};
|
||||
use pdfs_drive::{node_revision_id, node_size};
|
||||
#[cfg(test)]
|
||||
use pdfs_sync::naming::{conflict_label, conflict_label_of, conflict_name_as};
|
||||
use pdfs_sync::naming::{conflict_name, this_hostname};
|
||||
mod echoes;
|
||||
pub(crate) use pdfs_vfs::writes;
|
||||
mod events;
|
||||
mod filesystem;
|
||||
mod gallery;
|
||||
@@ -107,7 +107,6 @@ mod keeper;
|
||||
mod link;
|
||||
mod listing;
|
||||
mod session;
|
||||
mod writes;
|
||||
pub use filesystem::ProtonFs;
|
||||
mod maintenance;
|
||||
mod mount;
|
||||
@@ -133,7 +132,7 @@ mod trash;
|
||||
use pdfs_core::shutdown;
|
||||
#[cfg(test)]
|
||||
mod sim;
|
||||
mod state;
|
||||
pub(crate) use pdfs_vfs::tree as state;
|
||||
mod supervisor;
|
||||
mod sweep;
|
||||
mod sync;
|
||||
@@ -150,8 +149,11 @@ pub use mount::{MountOptions, MountOutcome, mount};
|
||||
use mount::{
|
||||
SecondaryInsertRejection, SecondaryMount, clear_stale_mount, fuse_connection_id, spawn_session,
|
||||
};
|
||||
use pdfs_vfs::open::{
|
||||
Intervals, PendingRevision, WriteHandle, copy_pending_for_truncate, merge_over_pending,
|
||||
};
|
||||
use reads::STREAM_BYPASS_MIN;
|
||||
use state::{Entry, Intervals, PendingRevision, State, StateGuard, WriteHandle};
|
||||
use state::{Entry, State, StateGuard};
|
||||
pub use systemd::{
|
||||
idle_sleep, status as notify_status, stretch_watchdog_for_startup, wait_for_restart,
|
||||
};
|
||||
@@ -344,13 +346,117 @@ const LOCAL_INDEX_TTL: Duration = Duration::from_secs(15 * 60);
|
||||
/// How often the scanner thread wakes to check whether the index went stale.
|
||||
const LOCAL_INDEX_CHECK: Duration = Duration::from_secs(60);
|
||||
|
||||
/// The FUSE root inode is always 1.
|
||||
const ROOT_INO: u64 = 1;
|
||||
use pdfs_vfs::ids::{ORPHAN_INO, ROOT_INO};
|
||||
|
||||
/// Parent inode for a persisted node whose parent row is missing from the DB.
|
||||
/// No folder carries this inode, so such a node is listed by nobody and stays
|
||||
/// inert until a live enumeration re-parents it.
|
||||
const ORPHAN_INO: u64 = 0;
|
||||
use pdfs_vfs::nodes::{
|
||||
apply_pending_sizes, is_unrevised, local_node, node_visible, overlay_queued,
|
||||
};
|
||||
|
||||
/// Convert one kernel pathname component into the UTF-8 name accepted by Drive.
|
||||
fn fuse_name(name: &OsStr) -> Result<String, Errno> {
|
||||
pdfs_vfs::names::component(name).map_err(|error| match error {
|
||||
pdfs_vfs::names::NameError::TooLong => Errno::ENAMETOOLONG,
|
||||
pdfs_vfs::names::NameError::Reserved => Errno::EINVAL,
|
||||
pdfs_vfs::names::NameError::NotUtf8 => Errno::EILSEQ,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a `rename` may replace an existing destination, as an errno.
|
||||
fn check_replaceable(src_dir: bool, dst_dir: bool, dst_empty: bool) -> Result<(), Errno> {
|
||||
pdfs_vfs::names::check_replaceable(src_dir, dst_dir, dst_empty).map_err(|error| match error {
|
||||
pdfs_vfs::names::ReplaceError::IsDirectory => Errno::EISDIR,
|
||||
pdfs_vfs::names::ReplaceError::NotDirectory => Errno::ENOTDIR,
|
||||
pdfs_vfs::names::ReplaceError::NotEmpty => Errno::ENOTEMPTY,
|
||||
})
|
||||
}
|
||||
|
||||
/// The errno the kernel gets for an operation the open-file service refused.
|
||||
fn file_errno(error: pdfs_vfs::files::FileError<Errno>) -> Errno {
|
||||
use pdfs_vfs::files::FileError;
|
||||
match error {
|
||||
FileError::NotFound => Errno::ENOENT,
|
||||
FileError::IsDirectory => Errno::EISDIR,
|
||||
FileError::Denied => Errno::EACCES,
|
||||
FileError::BadHandle => Errno::EBADF,
|
||||
FileError::NoSpace => Errno::ENOSPC,
|
||||
FileError::QuotaExceeded => Errno::EDQUOT,
|
||||
FileError::Io => Errno::EIO,
|
||||
FileError::Storage(error) => Errno::from(error),
|
||||
FileError::Unsupported => Errno::EOPNOTSUPP,
|
||||
FileError::Host(errno) => errno,
|
||||
}
|
||||
}
|
||||
|
||||
impl pdfs_vfs::files::FilesHost for Core {
|
||||
type Error = Errno;
|
||||
|
||||
fn settle_size(&self, ino: u64, uid: &NodeUid) -> Option<u64> {
|
||||
self.resolve_provisional_size(ino, uid)
|
||||
}
|
||||
|
||||
fn fill_gaps(
|
||||
&self,
|
||||
uid: &NodeUid,
|
||||
file: &File,
|
||||
len: u64,
|
||||
base_mtime: i64,
|
||||
base_size: u64,
|
||||
written: &Intervals,
|
||||
) -> Result<(), Errno> {
|
||||
Core::fill_gaps(self, uid, file, len, base_mtime, base_size, written)
|
||||
}
|
||||
|
||||
fn landed(&self, uid: &NodeUid) -> Option<Node> {
|
||||
self.drain.landed.lock().get(uid).cloned()
|
||||
}
|
||||
|
||||
fn commit(&self, handle: &mut WriteHandle) -> Result<(), Errno> {
|
||||
self.follow_landed_create(handle);
|
||||
self.queue_revision(handle)
|
||||
}
|
||||
|
||||
fn discard_unlinked(&self, uid: &NodeUid) {
|
||||
if !release_can_discard_unlinked(&self.db, uid) {
|
||||
return;
|
||||
}
|
||||
// Ops withdrawn at unlink left the bytes this handle read behind,
|
||||
// owned by no op any more; they go with the last handle.
|
||||
let withdrawn = self.pending_blob(uid);
|
||||
if let Err(error) = self.discard_queued_ops(uid) {
|
||||
warn!(%uid, ?error, "queued-op cleanup failed; retaining unlinked state");
|
||||
return;
|
||||
}
|
||||
if let Err(error) = self.db.delete_node(uid) {
|
||||
warn!(%uid, %error, "deleting released unlinked node state failed");
|
||||
}
|
||||
if let Some(blob) = withdrawn {
|
||||
self.cache.discard_staged(&blob);
|
||||
}
|
||||
self.cache.evict(uid);
|
||||
self.evict_reader(uid);
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// The open-file service over this daemon's tree, cache and write-back.
|
||||
fn files(&self) -> Arc<pdfs_vfs::files::Files<Core>> {
|
||||
Arc::new(pdfs_vfs::files::Files::new(
|
||||
self.state.clone(),
|
||||
self.db.clone(),
|
||||
self.cache.clone(),
|
||||
self.writes.clone(),
|
||||
self.clone(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// The errno the kernel gets for a node the tree refused.
|
||||
fn node_errno(error: pdfs_vfs::tree::NodeError) -> Errno {
|
||||
match error {
|
||||
pdfs_vfs::tree::NodeError::NotFound => Errno::ENOENT,
|
||||
pdfs_vfs::tree::NodeError::NotWritable => Errno::EACCES,
|
||||
}
|
||||
}
|
||||
|
||||
/// Extended attribute exposing the small server-side thumbnail of a file.
|
||||
const XATTR_THUMBNAIL: &str = "user.proton.thumbnail";
|
||||
@@ -892,7 +998,7 @@ impl Core {
|
||||
}
|
||||
|
||||
fn require_writable(&self, ino: u64) -> Result<(), Errno> {
|
||||
self.state().require_writable(ino)
|
||||
self.state().require_writable(ino).map_err(node_errno)
|
||||
}
|
||||
|
||||
/// Mutation admission point. Persisted and every resident authority must
|
||||
@@ -1172,73 +1278,6 @@ fn preserve_on_access_denied(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Fold the staged blob of an undrained write into the blob at `src` that is
|
||||
/// about to supersede it, so the newer write inherits the older one's bytes
|
||||
/// instead of losing them.
|
||||
///
|
||||
/// Only the ranges the older write authored and the newer one did not are
|
||||
/// copied, so a small edit over a small edit moves almost nothing. What neither
|
||||
/// wrote is untouched remote content, which is why `base_size`, `base_mtime` and
|
||||
/// the baseline all come from the write being superseded: that is the revision
|
||||
/// those ranges were last observed against, and the one the drain must gap-fill
|
||||
/// and conflict-check them against.
|
||||
fn merge_over_pending(
|
||||
meta: &mut StagedWrite,
|
||||
src: &Path,
|
||||
previous: &PendingRevision,
|
||||
) -> std::io::Result<()> {
|
||||
let mut written = Intervals::default();
|
||||
for &(s, e) in &meta.authored {
|
||||
written.add(s, e);
|
||||
}
|
||||
let mut earlier = Intervals::default();
|
||||
for &(s, e) in &previous.meta.authored {
|
||||
earlier.add(s, e);
|
||||
}
|
||||
let blob = File::open(&previous.path)?;
|
||||
let dst = std::fs::OpenOptions::new().write(true).open(src)?;
|
||||
for (s, e, authored) in written.clone().segments(0, meta.len) {
|
||||
if authored {
|
||||
continue;
|
||||
}
|
||||
for (ps, pe, have) in earlier.segments(s, e.min(previous.meta.len)) {
|
||||
if !have {
|
||||
continue;
|
||||
}
|
||||
let mut buf = vec![0u8; (pe - ps) as usize];
|
||||
blob.read_exact_at(&mut buf, ps)?;
|
||||
dst.write_all_at(&buf, ps)?;
|
||||
written.add(ps, pe);
|
||||
}
|
||||
}
|
||||
dst.sync_all()?;
|
||||
meta.base_size = previous.meta.base_size;
|
||||
meta.base_mtime = previous.meta.base_mtime;
|
||||
meta.based_on = previous.meta.based_on.clone();
|
||||
meta.authored = written
|
||||
.segments(0, meta.len)
|
||||
.into_iter()
|
||||
.filter(|&(_, _, authored)| authored)
|
||||
.map(|(s, e, _)| (s, e))
|
||||
.collect();
|
||||
meta.complete = StagedWrite::covers(&meta.authored, meta.len);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Retire the last resident reference to an unlinked inode without touching its
|
||||
/// persisted node row. The namespace path already chose whether that row is
|
||||
/// disposable or retained as queued-trash authority.
|
||||
fn release_unlinked_entry(state: &mut State, ino: u64) -> Option<NodeUid> {
|
||||
let entry = state.entries.get_mut(&ino)?;
|
||||
entry.open_count = entry.open_count.saturating_sub(1);
|
||||
if entry.open_count != 0 || !entry.unlinked {
|
||||
return None;
|
||||
}
|
||||
let uid = entry.uid.clone();
|
||||
state.forget_mem(&uid);
|
||||
Some(uid)
|
||||
}
|
||||
|
||||
fn release_must_retain_queued_trash(db: &Db, uid: &NodeUid) -> pdfs_core::Result<bool> {
|
||||
db.has_pending_op(&uid.to_string(), OP_TRASH)
|
||||
}
|
||||
@@ -1644,11 +1683,7 @@ fn local_node_uid(lid: i64) -> NodeUid {
|
||||
NodeUid::new(VolumeId::from(LOCAL_VOLUME), LinkId::from(lid.to_string()))
|
||||
}
|
||||
|
||||
/// 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.
|
||||
fn is_local_uid(uid: &NodeUid) -> bool {
|
||||
uid.volume_id.as_str() == LOCAL_VOLUME
|
||||
}
|
||||
use pdfs_vfs::ids::is_local_uid;
|
||||
|
||||
/// [`is_local_uid`] for a uid in its persisted `Display` form.
|
||||
fn is_local_uid_str(s: &str) -> bool {
|
||||
@@ -1729,47 +1764,6 @@ fn is_gone(e: &(dyn std::error::Error + 'static)) -> bool {
|
||||
api_code(e) == Some(ResponseCode::DoesNotExist)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
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 `dir` has no entries.
|
||||
fn dir_is_empty(dir: &Path) -> std::io::Result<bool> {
|
||||
Ok(std::fs::read_dir(dir)?.next().is_none())
|
||||
@@ -1811,64 +1805,6 @@ fn sync_folder_info(
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
fn check_replaceable(src_dir: bool, dst_dir: bool, dst_empty: bool) -> Result<(), Errno> {
|
||||
match (src_dir, dst_dir) {
|
||||
// A non-directory may not replace a directory, or vice versa.
|
||||
(false, true) => Err(Errno::EISDIR),
|
||||
(true, false) => Err(Errno::ENOTDIR),
|
||||
// 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(Errno::ENOTEMPTY),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `node` is a file Drive lists without an active revision, as it does
|
||||
/// one whose create has not been committed.
|
||||
fn is_unrevised(node: &Node) -> bool {
|
||||
matches!(
|
||||
node.kind,
|
||||
NodeKind::File {
|
||||
active_revision_id: None,
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
/// `call`, failed with a remote error once it has run for
|
||||
/// [`TRASH_CALL_TIMEOUT`].
|
||||
async fn within_trash_call<T>(what: &str, call: impl Future<Output = T>) -> CoreResult<T> {
|
||||
@@ -1888,27 +1824,6 @@ fn count_noun(n: usize, one: &str, many: &str) -> String {
|
||||
format!("{n} {}", if n == 1 { one } else { many })
|
||||
}
|
||||
|
||||
/// Seed a truncate scratch file from a complete queued revision.
|
||||
///
|
||||
/// `File` writes use an explicit offset so this is independent of either
|
||||
/// descriptor's cursor and remains correct when the destination came from the
|
||||
/// cache's scratch allocator.
|
||||
fn copy_pending_for_truncate(pending: &PendingRevision, destination: &File) -> std::io::Result<()> {
|
||||
let source = File::open(&pending.path)?;
|
||||
destination.set_len(0)?;
|
||||
let mut offset = 0u64;
|
||||
let mut buffer = vec![0u8; 1024 * 1024];
|
||||
loop {
|
||||
let count = source.read_at(&mut buffer, offset)?;
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
destination.write_all_at(&buffer[..count], offset)?;
|
||||
offset += count as u64;
|
||||
}
|
||||
destination.set_len(offset)
|
||||
}
|
||||
|
||||
/// Whether a rename must be represented as a durable desired end state.
|
||||
/// Local-first, offline, or into a not-yet-uploaded directory, the API is not
|
||||
/// called in the syscall. Only remote-to-remote renames sent inline
|
||||
@@ -1923,69 +1838,6 @@ fn rename_needs_queue(
|
||||
!inline || destination_is_local
|
||||
}
|
||||
|
||||
/// 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.
|
||||
fn fuse_name(name: &OsStr) -> Result<String, Errno> {
|
||||
let bytes = name.as_bytes();
|
||||
if bytes.len() > 255 {
|
||||
return Err(Errno::ENAMETOOLONG);
|
||||
}
|
||||
if bytes.is_empty() || bytes == b"." || bytes == b".." {
|
||||
return Err(Errno::EINVAL);
|
||||
}
|
||||
name.to_str().map(str::to_owned).ok_or(Errno::EILSEQ)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
/// The children `entries` hold for each folder in `listed`, gathered in one
|
||||
/// pass over them.
|
||||
///
|
||||
/// The root is its own parent (that is what `..` resolves to), so it would
|
||||
/// count as its own child; a directory listed inside itself makes the kernel
|
||||
/// fail the lookup with EIO, taking the whole listing down with it.
|
||||
///
|
||||
/// A pass per listed folder took 1.7 s on a tree of 37,000 nodes with 4,600 of
|
||||
/// them listed, at every start before the mount came up (`docs/BUGS.md` B167).
|
||||
fn listed_children(entries: &HashMap<u64, Entry>, listed: Vec<u64>) -> HashMap<u64, Vec<u64>> {
|
||||
let mut children: HashMap<u64, Vec<u64>> =
|
||||
listed.into_iter().map(|ino| (ino, Vec::new())).collect();
|
||||
for (&ino, entry) in entries {
|
||||
if ino != entry.parent
|
||||
&& !entry.node.trashed
|
||||
&& let Some(kids) = children.get_mut(&entry.parent)
|
||||
{
|
||||
kids.push(ino);
|
||||
}
|
||||
}
|
||||
children
|
||||
}
|
||||
|
||||
/// 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).
|
||||
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);
|
||||
}
|
||||
|
||||
/// Bytes rendered with a binary unit and one decimal place (e.g. `"1.2 GB"`),
|
||||
/// for the activity log. Uses 1024-based steps but the shorter SI labels.
|
||||
fn human_bytes(bytes: u64) -> String {
|
||||
@@ -2032,223 +1884,6 @@ fn unix_secs(secs: i64) -> SystemTime {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod merge_over_pending_tests {
|
||||
use super::{PendingRevision, merge_over_pending};
|
||||
use pdfs_store::cache::{Baseline, StagedWrite};
|
||||
use std::io::Write as _;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A unique temp directory removed on drop; avoids a dev-dependency, as in
|
||||
/// `state.rs`.
|
||||
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-merge-{}-{}",
|
||||
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 staged(len: u64, base_size: u64, authored: &[(u64, u64)]) -> StagedWrite {
|
||||
StagedWrite {
|
||||
uid: "vol~link".into(),
|
||||
len,
|
||||
base_size,
|
||||
base_mtime: 100,
|
||||
complete: StagedWrite::covers(authored, len),
|
||||
authored: authored.to_vec(),
|
||||
based_on: Some(Baseline {
|
||||
mtime: 100,
|
||||
size: base_size,
|
||||
hash: None,
|
||||
revision_id: Some("r1".into()),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write a file of `len` bytes with `fill` at every offset in `ranges`.
|
||||
fn blob(
|
||||
dir: &std::path::Path,
|
||||
name: &str,
|
||||
len: u64,
|
||||
ranges: &[(u64, u64)],
|
||||
fill: u8,
|
||||
) -> std::path::PathBuf {
|
||||
let path = dir.join(name);
|
||||
let mut bytes = vec![0u8; len as usize];
|
||||
for &(s, e) in ranges {
|
||||
bytes[s as usize..e as usize].fill(fill);
|
||||
}
|
||||
let mut f = std::fs::File::create(&path).unwrap();
|
||||
f.write_all(&bytes).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
/// The case the merge exists for: two small edits to different parts of a
|
||||
/// file, the second closing before the first has drained. The second blob
|
||||
/// must come out holding both, or the first edit is silently lost.
|
||||
#[test]
|
||||
fn the_superseding_write_inherits_the_earlier_ones_bytes() {
|
||||
let dir = TempDir::new();
|
||||
let previous = PendingRevision {
|
||||
path: blob(&dir.0, "old", 64, &[(0, 16)], 0xAA),
|
||||
meta: staged(64, 64, &[(0, 16)]),
|
||||
};
|
||||
let src = blob(&dir.0, "new", 64, &[(32, 48)], 0xBB);
|
||||
let mut meta = staged(64, 64, &[(32, 48)]);
|
||||
|
||||
merge_over_pending(&mut meta, &src, &previous).unwrap();
|
||||
|
||||
assert_eq!(meta.authored, vec![(0, 16), (32, 48)]);
|
||||
assert!(
|
||||
!meta.complete,
|
||||
"the untouched middle still comes from the base"
|
||||
);
|
||||
let merged = std::fs::read(&src).unwrap();
|
||||
assert!(
|
||||
merged[0..16].iter().all(|&b| b == 0xAA),
|
||||
"earlier edit kept"
|
||||
);
|
||||
assert!(merged[32..48].iter().all(|&b| b == 0xBB), "newer edit kept");
|
||||
}
|
||||
|
||||
/// Where they overlap, the newer write wins — it is the later state of the
|
||||
/// file, and the older bytes were never visible to anyone after it landed.
|
||||
#[test]
|
||||
fn the_newer_write_wins_the_ranges_it_authored() {
|
||||
let dir = TempDir::new();
|
||||
let previous = PendingRevision {
|
||||
path: blob(&dir.0, "old", 32, &[(0, 32)], 0xAA),
|
||||
meta: staged(32, 32, &[(0, 32)]),
|
||||
};
|
||||
let src = blob(&dir.0, "new", 32, &[(8, 16)], 0xBB);
|
||||
let mut meta = staged(32, 32, &[(8, 16)]);
|
||||
|
||||
merge_over_pending(&mut meta, &src, &previous).unwrap();
|
||||
|
||||
assert_eq!(meta.authored, vec![(0, 32)]);
|
||||
assert!(meta.complete, "between them they cover the file");
|
||||
let merged = std::fs::read(&src).unwrap();
|
||||
assert!(
|
||||
merged[8..16].iter().all(|&b| b == 0xBB),
|
||||
"newer edit survives"
|
||||
);
|
||||
assert!(merged[16..32].iter().all(|&b| b == 0xAA));
|
||||
}
|
||||
|
||||
/// The baseline has to come from the write being superseded. This one's own
|
||||
/// "base" is the earlier *staged blob*, whose size and mtime are ours, not
|
||||
/// the server's — filling or conflict-checking against that would compare
|
||||
/// the remote to a revision it never had.
|
||||
#[test]
|
||||
fn the_baseline_is_inherited_from_the_write_being_superseded() {
|
||||
let dir = TempDir::new();
|
||||
let mut earlier = staged(64, 64, &[(0, 16)]);
|
||||
earlier.base_mtime = 42;
|
||||
earlier.base_size = 50;
|
||||
earlier.based_on = Some(Baseline {
|
||||
mtime: 42,
|
||||
size: 50,
|
||||
hash: None,
|
||||
revision_id: Some("original".into()),
|
||||
});
|
||||
let previous = PendingRevision {
|
||||
path: blob(&dir.0, "old", 64, &[(0, 16)], 0xAA),
|
||||
meta: earlier,
|
||||
};
|
||||
let src = blob(&dir.0, "new", 64, &[(32, 48)], 0xBB);
|
||||
// Opened over the staged blob, so this write thinks its base is 64/100.
|
||||
let mut meta = staged(64, 64, &[(32, 48)]);
|
||||
|
||||
merge_over_pending(&mut meta, &src, &previous).unwrap();
|
||||
|
||||
assert_eq!(meta.base_mtime, 42);
|
||||
assert_eq!(meta.base_size, 50);
|
||||
assert_eq!(
|
||||
meta.based_on.unwrap().revision_id.as_deref(),
|
||||
Some("original")
|
||||
);
|
||||
}
|
||||
|
||||
/// A shrink must not drag the earlier write's tail back in.
|
||||
#[test]
|
||||
fn a_truncating_write_does_not_inherit_past_its_own_length() {
|
||||
let dir = TempDir::new();
|
||||
let previous = PendingRevision {
|
||||
path: blob(&dir.0, "old", 64, &[(0, 64)], 0xAA),
|
||||
meta: staged(64, 64, &[(0, 64)]),
|
||||
};
|
||||
let src = blob(&dir.0, "new", 16, &[(8, 16)], 0xBB);
|
||||
let mut meta = staged(16, 64, &[(8, 16)]);
|
||||
|
||||
merge_over_pending(&mut meta, &src, &previous).unwrap();
|
||||
|
||||
assert_eq!(meta.authored, vec![(0, 16)]);
|
||||
assert!(meta.complete);
|
||||
assert_eq!(std::fs::metadata(&src).unwrap().len(), 16);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod replace_tests {
|
||||
use super::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.code(), libc::ENOTEMPTY);
|
||||
}
|
||||
|
||||
#[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")
|
||||
.code(),
|
||||
libc::EISDIR
|
||||
);
|
||||
assert_eq!(
|
||||
check_replaceable(true, false, true)
|
||||
.expect_err("a directory may not replace a file")
|
||||
.code(),
|
||||
libc::ENOTDIR
|
||||
);
|
||||
}
|
||||
|
||||
/// `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());
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod local_uid_tests {
|
||||
use super::*;
|
||||
@@ -2317,108 +1952,19 @@ mod local_uid_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod pending_size_tests {
|
||||
use super::{Node, NodeKind, NodeUid, apply_pending_sizes, 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);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::echoes::{SELF_CHANGE_TTL_MS, note_self_change, take_self_change};
|
||||
use super::trash::{expand_restore, first_seen_in_trash};
|
||||
use super::{
|
||||
Access, AccessFlags, Errno, HashMap, Intervals, PendingRevision, RootListingSnapshot,
|
||||
ShareId, SharedWithMeItem, StateRegistry, VirtualRootPlan, accepted_share_provenance,
|
||||
Access, AccessFlags, Errno, HashMap, PendingRevision, RootListingSnapshot, ShareId,
|
||||
SharedWithMeItem, StateRegistry, VirtualRootPlan, accepted_share_provenance,
|
||||
conflict_label, conflict_label_of, conflict_name, conflict_name_as,
|
||||
copy_pending_for_truncate, fuse_name, is_stale_mount, node_visible, off_the_runtime,
|
||||
orphan_past_retention, parse_node_uid, prepare_shared_roots, preserve_on_access_denied,
|
||||
orphan_past_retention, prepare_shared_roots, preserve_on_access_denied,
|
||||
publish_virtual_root_in_listing, reconcile_virtual_root_in_listing,
|
||||
release_can_discard_unlinked, release_must_retain_queued_trash, release_unlinked_entry,
|
||||
rename_needs_queue, require_node_parent_access, require_rename_access,
|
||||
resolve_anywhere_with, shared_with_me_uid, uid_write_authority, virtual_node,
|
||||
release_can_discard_unlinked, release_must_retain_queued_trash, rename_needs_queue,
|
||||
require_node_parent_access, require_rename_access, resolve_anywhere_with,
|
||||
shared_with_me_uid, uid_write_authority, virtual_node,
|
||||
};
|
||||
use super::{Db, WriteAuthority};
|
||||
use std::time::Duration;
|
||||
@@ -3288,67 +2834,6 @@ mod tests {
|
||||
assert!(db_error.message.contains("lookup failed"));
|
||||
}
|
||||
|
||||
/// 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 = parse_node_uid("vol~link").unwrap();
|
||||
let other = parse_node_uid("vol~other").unwrap();
|
||||
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"
|
||||
);
|
||||
}
|
||||
|
||||
/// The predicate must answer *only* for a dead FUSE connection. A healthy
|
||||
/// directory and an absent path are both "not stale" — widening it to any
|
||||
/// `metadata` error would make the on-demand restore lazily unmount paths
|
||||
@@ -3362,11 +2847,6 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Flatten `segments` into a readable form for assertions.
|
||||
fn segs(iv: &Intervals, start: u64, end: u64) -> Vec<(u64, u64, bool)> {
|
||||
iv.segments(start, end)
|
||||
}
|
||||
|
||||
/// The conflict copy has to stay openable, so the extension survives — and
|
||||
/// the shape matches the sync engine's `conflict_path` so the two features
|
||||
/// name the same situation the same way.
|
||||
@@ -3407,76 +2887,6 @@ mod tests {
|
||||
assert_eq!(conflict_label_of(&"x".repeat(40)).len(), 32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn append_merges_into_one_run() {
|
||||
// Sequential writes (an append) coalesce into a single authored range.
|
||||
let mut iv = Intervals::default();
|
||||
iv.add(0, 10);
|
||||
iv.add(10, 20);
|
||||
iv.add(20, 25);
|
||||
assert_eq!(segs(&iv, 0, 25), vec![(0, 25, true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_overwrite_leaves_base_gap() {
|
||||
// Author [0,4) and [8,12); [4,8) stays base. A read of [0,12) must stitch
|
||||
// authored / base / authored in order.
|
||||
let mut iv = Intervals::default();
|
||||
iv.add(0, 4);
|
||||
iv.add(8, 12);
|
||||
assert_eq!(
|
||||
segs(&iv, 0, 12),
|
||||
vec![(0, 4, true), (4, 8, false), (8, 12, true)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_writes_coalesce() {
|
||||
let mut iv = Intervals::default();
|
||||
iv.add(0, 10);
|
||||
iv.add(5, 15);
|
||||
iv.add(14, 20);
|
||||
assert_eq!(segs(&iv, 0, 20), vec![(0, 20, true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn segments_clamp_to_request_window() {
|
||||
let mut iv = Intervals::default();
|
||||
iv.add(0, 100);
|
||||
// A sub-window of one big authored range is a single authored segment.
|
||||
assert_eq!(segs(&iv, 20, 50), vec![(20, 50, true)]);
|
||||
// A window entirely outside any authored range is all base.
|
||||
let empty = Intervals::default();
|
||||
assert_eq!(segs(&empty, 0, 8), vec![(0, 8, false)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_shrink_drops_tail() {
|
||||
// Grow-then-shrink: clip removes/truncates authored ranges past the end.
|
||||
let mut iv = Intervals::default();
|
||||
iv.add(0, 100);
|
||||
iv.clip(40);
|
||||
assert_eq!(segs(&iv, 0, 40), vec![(0, 40, true)]);
|
||||
// Authored ranges wholly past the new end disappear.
|
||||
let mut iv2 = Intervals::default();
|
||||
iv2.add(0, 10);
|
||||
iv2.add(50, 60);
|
||||
iv2.clip(40);
|
||||
assert_eq!(segs(&iv2, 0, 40), vec![(0, 10, true), (10, 40, false)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_extend_authors_zero_tail() {
|
||||
// setattr grow claims the new tail as authored (defined zeros), so commit
|
||||
// never pulls it from the base.
|
||||
let mut iv = Intervals::default();
|
||||
iv.add(0, 10); // base content authored over
|
||||
let old_len = 10u64;
|
||||
let new_len = 30u64;
|
||||
iv.add(old_len, new_len);
|
||||
assert_eq!(segs(&iv, 0, 30), vec![(0, 30, true)]);
|
||||
}
|
||||
|
||||
fn pending_revision(dir: &TestDir, bytes: &[u8], complete: bool) -> PendingRevision {
|
||||
let path = dir.0.join("pending");
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
@@ -4260,10 +3670,10 @@ mod tests {
|
||||
trash.matches("self.core.withdraw_queued_ops(&uid)").count(),
|
||||
2
|
||||
);
|
||||
let release = function_source(filesystem, "fn finish_release(");
|
||||
let release = function_source(CORE_SOURCE, "fn discard_unlinked(");
|
||||
assert_before(
|
||||
release,
|
||||
"let withdrawn = self.core.pending_blob(&uid)",
|
||||
"let withdrawn = self.pending_blob(uid)",
|
||||
"discard_queued_ops",
|
||||
);
|
||||
assert_before(release, "discard_queued_ops", "discard_staged(&blob)");
|
||||
@@ -4605,7 +4015,7 @@ mod tests {
|
||||
.is_some()
|
||||
);
|
||||
|
||||
let released = release_unlinked_entry(&mut state, ino).unwrap();
|
||||
let released = state.release_unlinked(ino).unwrap();
|
||||
assert_eq!(released, uid);
|
||||
assert!(!state.by_uid.contains_key(&uid));
|
||||
assert!(release_must_retain_queued_trash(&state.db, &uid).unwrap());
|
||||
@@ -4684,7 +4094,7 @@ mod tests {
|
||||
]
|
||||
.into_iter()
|
||||
.collect();
|
||||
let mut listings = super::listed_children(&entries, vec![1, 2]);
|
||||
let mut listings = pdfs_vfs::tree::listed_children(&entries, vec![1, 2]);
|
||||
listings.values_mut().for_each(|kids| kids.sort());
|
||||
assert_eq!(listings, HashMap::from([(1, vec![2, 3]), (2, vec![4])]));
|
||||
}
|
||||
|
||||
+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);
|
||||
}
|
||||
}
|
||||
@@ -96,7 +96,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");
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
};
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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,23 @@
|
||||
//! 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`]); and which nodes a folder lists ([`nodes`]).
|
||||
|
||||
pub mod files;
|
||||
pub mod ids;
|
||||
pub mod names;
|
||||
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,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"
|
||||
);
|
||||
}
|
||||
}
|
||||
+18
-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), 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,22 @@ 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. What still sits in
|
||||
`pdfs-fuse` around the tree is the code that fills it (listings, sizes, the drain), the read
|
||||
path, and the namespace operations (create, mkdir, rename, unlink).
|
||||
|
||||
Steps 0 to 3 are 4.0.0. Steps 4 to 6 follow in 4.x, one service at a time. Out of scope for
|
||||
now: an encrypted local vault (full-disk encryption covers a copied disk today), Windows and
|
||||
macOS adapters, and a separate repository for the sync engine.
|
||||
|
||||
@@ -108,6 +108,8 @@ a live account since.
|
||||
|
||||
| Entry | Title |
|
||||
|---|---|
|
||||
| [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 +404,63 @@ a live account since.
|
||||
|
||||
Newest first.
|
||||
|
||||
### 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