mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-27 11:42:14 +01:00
Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c44c1bccb5 | ||
|
|
275f40b24b | ||
|
|
695a810cea | ||
|
|
9dbb4c9950 | ||
|
|
c5884ba638 | ||
|
|
860593b655 | ||
|
|
4dcc2aa04e | ||
|
|
d891e24e96 | ||
|
|
957a7ff391 | ||
|
|
d9881810b7 | ||
|
|
d9dab26e86 | ||
|
|
eae7ce90d2 | ||
|
|
b674f3eb71 | ||
|
|
3a4812baae | ||
|
|
3da45c0bf9 | ||
|
|
dc72991da2 | ||
|
|
bdcabed1ee | ||
|
|
7def9e903b | ||
|
|
bb376d7dc4 | ||
|
|
57e654924a | ||
|
|
e3bc64df54 | ||
|
|
47576a389e | ||
|
|
7ed07e0056 | ||
|
|
be99fffe1b | ||
|
|
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" }
|
||||
|
||||
|
||||
@@ -21,7 +21,10 @@
|
||||
//!
|
||||
//! Work a request starts and does not wait for runs as a one-shot job
|
||||
//! ([`ServiceBoard::spawn_job`] on a thread, [`ServiceBoard::spawn_task_job`]
|
||||
//! on the runtime): listed on the board while it runs, and not joined on stop.
|
||||
//! on the runtime): listed on the board while it runs. A stop closes the
|
||||
//! board to new jobs, aborts the async ones and joins the rest up to the same
|
||||
//! deadline as the services. A job used to be left running, and one still
|
||||
//! waiting on Drive when the runtime went away panicked on its next timer.
|
||||
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
@@ -36,6 +39,32 @@ use crate::shutdown::Shutdown;
|
||||
/// Wakes a thread that blocks somewhere a [`Shutdown::stop`] alone does not reach.
|
||||
pub type Wake = Box<dyn Fn() + Send + Sync>;
|
||||
|
||||
/// A long-lived loop a mount runs on a thread of its own.
|
||||
///
|
||||
/// Each one says in one place what it is called, how a stop reaches it and
|
||||
/// whether the mount can do without it, next to the loop itself. The mount
|
||||
/// starts a list of them with [`Services::start`] instead of spelling out
|
||||
/// each spawn, wake and failure path.
|
||||
pub trait Service: Send + 'static {
|
||||
/// The thread's name, such as `pdfs-sync`.
|
||||
fn name(&self) -> String;
|
||||
|
||||
/// Whether a mount fails when this cannot start. An optional service is
|
||||
/// logged and skipped: the mount works without it, only less well.
|
||||
fn required(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// The call that wakes the loop on a stop, for one that blocks where the
|
||||
/// [`Shutdown`] signal does not reach: a condvar, a channel, an `accept`.
|
||||
fn wake(&self) -> Option<Wake> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Run the loop until the [`Shutdown`] signal or the wake ends it.
|
||||
fn run(self: Box<Self>);
|
||||
}
|
||||
|
||||
/// Whether one service thread is still running, for diagnostics.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ServiceHealth {
|
||||
@@ -57,6 +86,28 @@ struct Board {
|
||||
services: Mutex<Vec<Entry>>,
|
||||
jobs: Mutex<Vec<Job>>,
|
||||
next_job: AtomicU64,
|
||||
/// The running jobs' handles, and whether a stop closed the board. One
|
||||
/// lock for both, so a job is either refused or joined by the stop.
|
||||
handles: Mutex<JobHandles>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct JobHandles {
|
||||
closed: bool,
|
||||
running: Vec<Handle>,
|
||||
}
|
||||
|
||||
impl JobHandles {
|
||||
/// Keep `handle`, dropping the handles of jobs that already ended.
|
||||
fn keep(&mut self, handle: Handle) {
|
||||
self.running.retain(|handle| !handle.is_finished());
|
||||
self.running.push(handle);
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a job did not start: the board's mount is stopping.
|
||||
fn closed_error() -> std::io::Error {
|
||||
std::io::Error::other("the mount is stopping; no new jobs start")
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
@@ -106,37 +157,69 @@ impl ServiceBoard {
|
||||
/// folder pin. It shows in [`jobs`](Self::jobs) until it ends, by return
|
||||
/// or by panic.
|
||||
///
|
||||
/// Not joined on stop. A job's work is either safe to cut short (the
|
||||
/// process exits) or bounded by the deadlines of the calls it makes.
|
||||
/// A stop joins it up to its deadline; a job that may run long checks the
|
||||
/// [`Shutdown`] signal. Once a stop has begun, no job starts and this
|
||||
/// returns an error.
|
||||
pub fn spawn_job<F>(&self, name: &str, run: F) -> std::io::Result<()>
|
||||
where
|
||||
F: FnOnce() + Send + 'static,
|
||||
{
|
||||
let mut handles = self.0.handles.lock();
|
||||
if handles.closed {
|
||||
return Err(closed_error());
|
||||
}
|
||||
let guard = self.add_job(name);
|
||||
std::thread::Builder::new()
|
||||
let handle = std::thread::Builder::new()
|
||||
.name(name.to_owned())
|
||||
.spawn(move || {
|
||||
let _guard = guard;
|
||||
run();
|
||||
})
|
||||
// On an error the closure, and the guard in it, are already
|
||||
// dropped, so the job is off the list.
|
||||
.map(|_| ())
|
||||
})?;
|
||||
// On an error the closure, and the guard in it, are already dropped,
|
||||
// so the job is off the list.
|
||||
handles.keep(Handle::Thread(handle));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start `task` on `rt` as a one-shot job, like [`spawn_job`](Self::spawn_job)
|
||||
/// for work that is async: a refresh a listing starts and does not wait
|
||||
/// for. It shows in [`jobs`](Self::jobs) until it ends, by return, panic
|
||||
/// or the runtime going away.
|
||||
/// or abort. A stop aborts it at its next `.await`; once a stop has begun,
|
||||
/// `task` is dropped without running.
|
||||
pub fn spawn_task_job<F>(&self, rt: &tokio::runtime::Handle, name: &str, task: F)
|
||||
where
|
||||
F: Future<Output = ()> + Send + 'static,
|
||||
{
|
||||
let mut handles = self.0.handles.lock();
|
||||
if handles.closed {
|
||||
tracing::debug!(job = name, "not started: the mount is stopping");
|
||||
return;
|
||||
}
|
||||
let guard = self.add_job(name);
|
||||
rt.spawn(async move {
|
||||
let task = rt.spawn(async move {
|
||||
let _guard = guard;
|
||||
task.await;
|
||||
});
|
||||
handles.keep(Handle::Task {
|
||||
name: name.to_owned(),
|
||||
task,
|
||||
});
|
||||
}
|
||||
|
||||
/// Close the board to new jobs and abort the async ones. The thread jobs
|
||||
/// still running are handed back for [`join`](Handle::join_until).
|
||||
fn close(&self) -> Vec<Handle> {
|
||||
let running = {
|
||||
let mut handles = self.0.handles.lock();
|
||||
handles.closed = true;
|
||||
std::mem::take(&mut handles.running)
|
||||
};
|
||||
for handle in &running {
|
||||
if let Handle::Task { task, .. } = handle {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
running
|
||||
}
|
||||
|
||||
fn add_job(&self, name: &str) -> JobGuard {
|
||||
@@ -184,7 +267,7 @@ impl Drop for Running {
|
||||
}
|
||||
}
|
||||
|
||||
struct Service {
|
||||
struct Started {
|
||||
handle: Handle,
|
||||
wake: Option<Wake>,
|
||||
}
|
||||
@@ -205,12 +288,25 @@ impl Handle {
|
||||
Handle::Task { task, .. } => task.is_finished(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait for the thread or task to end, up to `deadline`, and name it if
|
||||
/// it is still running then.
|
||||
fn join_until(self, deadline: Instant) -> Option<String> {
|
||||
while !self.is_finished() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
match self {
|
||||
Handle::Thread(handle) => join_until([handle], deadline).pop(),
|
||||
Handle::Task { name, task } if !task.is_finished() => Some(name),
|
||||
Handle::Task { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The service threads one mount started, and how to stop them.
|
||||
pub struct Services {
|
||||
board: ServiceBoard,
|
||||
started: Vec<Service>,
|
||||
started: Vec<Started>,
|
||||
}
|
||||
|
||||
impl Services {
|
||||
@@ -239,7 +335,7 @@ impl Services {
|
||||
});
|
||||
match spawned {
|
||||
Ok(handle) => {
|
||||
self.started.push(Service {
|
||||
self.started.push(Started {
|
||||
handle: Handle::Thread(handle),
|
||||
wake,
|
||||
});
|
||||
@@ -253,6 +349,21 @@ impl Services {
|
||||
}
|
||||
}
|
||||
|
||||
/// Start `service` on a thread of its own. A required service that cannot
|
||||
/// start returns the error; an optional one is logged and skipped.
|
||||
pub fn start(&mut self, service: Box<dyn Service>) -> std::io::Result<()> {
|
||||
let name = service.name();
|
||||
let required = service.required();
|
||||
let wake = service.wake();
|
||||
match self.spawn(&name, wake, move || service.run()) {
|
||||
Err(error) if !required => {
|
||||
tracing::warn!(service = name, %error, "optional service did not start");
|
||||
Ok(())
|
||||
}
|
||||
started => started,
|
||||
}
|
||||
}
|
||||
|
||||
/// Start `task` on `rt` as a service named `name`. [`stop`](Self::stop)
|
||||
/// aborts it, so it ends at its next `.await`; a task does not need to
|
||||
/// watch the [`Shutdown`] signal itself. Code between two `.await`s runs
|
||||
@@ -266,7 +377,7 @@ impl Services {
|
||||
let _guard = guard;
|
||||
task.await;
|
||||
});
|
||||
self.started.push(Service {
|
||||
self.started.push(Started {
|
||||
handle: Handle::Task {
|
||||
name: name.to_owned(),
|
||||
task,
|
||||
@@ -285,12 +396,15 @@ impl Services {
|
||||
self.started.is_empty()
|
||||
}
|
||||
|
||||
/// Stop every service: signal `shutdown`, wake each thread and abort each
|
||||
/// task in reverse start order, then join them in the same order until
|
||||
/// `deadline`. Returns the names of the services still running at the
|
||||
/// deadline; they are left behind rather than waited for.
|
||||
/// Stop every service and every job: signal `shutdown`, close the board
|
||||
/// to new jobs, wake each thread and abort each task in reverse start
|
||||
/// order. Then join the jobs, which are the services' clients, and the
|
||||
/// services in the same reverse order, all until `deadline`. Returns the
|
||||
/// names of the services and jobs still running at the deadline; they are
|
||||
/// left behind rather than waited for.
|
||||
pub fn stop(self, shutdown: &Shutdown, deadline: Instant) -> Vec<String> {
|
||||
shutdown.stop();
|
||||
let jobs = self.board.close();
|
||||
for service in self.started.iter().rev() {
|
||||
if let Some(wake) = &service.wake {
|
||||
wake();
|
||||
@@ -299,18 +413,13 @@ impl Services {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
let mut running = Vec::new();
|
||||
for service in self.started.into_iter().rev() {
|
||||
while !service.handle.is_finished() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
match service.handle {
|
||||
Handle::Thread(handle) => running.extend(join_until([handle], deadline)),
|
||||
Handle::Task { name, task } if !task.is_finished() => running.push(name),
|
||||
Handle::Task { .. } => {}
|
||||
}
|
||||
}
|
||||
running
|
||||
let jobs = jobs.into_iter().filter_map(|job| job.join_until(deadline));
|
||||
let services = self
|
||||
.started
|
||||
.into_iter()
|
||||
.rev()
|
||||
.filter_map(|service| service.handle.join_until(deadline));
|
||||
jobs.chain(services).collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -531,4 +640,102 @@ mod tests {
|
||||
}
|
||||
assert!(board.jobs().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stop_joins_the_running_jobs_and_names_a_stuck_one() {
|
||||
let board = ServiceBoard::default();
|
||||
let shutdown = Arc::new(Shutdown::default());
|
||||
let services = Services::new(board.clone());
|
||||
let signalled = shutdown.clone();
|
||||
board
|
||||
.spawn_job("pdfs-test-polite", move || {
|
||||
while signalled.sleep(Duration::from_secs(3600)) {}
|
||||
})
|
||||
.unwrap();
|
||||
let (_hold, stuck) = mpsc::channel::<()>();
|
||||
board
|
||||
.spawn_job("pdfs-test-stuck", move || {
|
||||
let _ = stuck.recv();
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let left = services.stop(&shutdown, Instant::now() + Duration::from_millis(300));
|
||||
|
||||
assert_eq!(left, ["pdfs-test-stuck"]);
|
||||
let jobs: Vec<_> = board.jobs().into_iter().map(|job| job.name).collect();
|
||||
assert_eq!(jobs, ["pdfs-test-stuck"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stop_aborts_a_task_job_and_refuses_new_jobs() {
|
||||
let rt = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(1)
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let board = ServiceBoard::default();
|
||||
let services = Services::new(board.clone());
|
||||
board.spawn_task_job(rt.handle(), "pdfs-test-poller", async {
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
});
|
||||
|
||||
let left = services.stop(
|
||||
&Shutdown::default(),
|
||||
Instant::now() + Duration::from_secs(5),
|
||||
);
|
||||
|
||||
assert!(left.is_empty(), "still running: {left:?}");
|
||||
assert!(board.jobs().is_empty());
|
||||
assert!(board.spawn_job("pdfs-test-late", || {}).is_err());
|
||||
board.spawn_task_job(rt.handle(), "pdfs-test-late", async {});
|
||||
assert!(board.jobs().is_empty(), "a job started after the stop");
|
||||
}
|
||||
|
||||
struct Waiter {
|
||||
name: &'static str,
|
||||
rx: mpsc::Receiver<()>,
|
||||
tx: mpsc::Sender<()>,
|
||||
}
|
||||
|
||||
impl Service for Waiter {
|
||||
fn name(&self) -> String {
|
||||
self.name.to_owned()
|
||||
}
|
||||
|
||||
fn wake(&self) -> Option<Wake> {
|
||||
let tx = self.tx.clone();
|
||||
Some(Box::new(move || {
|
||||
let _ = tx.send(());
|
||||
}))
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
let _ = self.rx.recv();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_started_service_is_woken_and_joined_by_a_stop() {
|
||||
let board = ServiceBoard::default();
|
||||
let mut services = Services::new(board.clone());
|
||||
let (tx, rx) = mpsc::channel();
|
||||
services
|
||||
.start(Box::new(Waiter {
|
||||
name: "pdfs-test-waiter",
|
||||
rx,
|
||||
tx,
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(board.health()[0].name, "pdfs-test-waiter");
|
||||
|
||||
let left = services.stop(
|
||||
&Shutdown::default(),
|
||||
Instant::now() + Duration::from_secs(5),
|
||||
);
|
||||
|
||||
assert!(left.is_empty(), "still running: {left:?}");
|
||||
assert!(!board.health()[0].running);
|
||||
}
|
||||
}
|
||||
@@ -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"] }
|
||||
@@ -771,15 +771,18 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
|
||||
query,
|
||||
limit,
|
||||
scope,
|
||||
}) => match core.search(&query, clamp_limit(limit), scope.as_deref()) {
|
||||
}) => match core
|
||||
.searcher()
|
||||
.search(&query, clamp_limit(limit), scope.as_deref())
|
||||
{
|
||||
Ok(hits) => CtlResponse::SearchResults { hits },
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
Ok(CtlRequest::SearchLocal { query, limit }) => {
|
||||
match core.search_local(&query, clamp_limit(limit)) {
|
||||
match core.searcher().search_local(&query, clamp_limit(limit)) {
|
||||
Ok(hits) => CtlResponse::LocalResults {
|
||||
hits,
|
||||
indexing: core.indexing.load(Ordering::Relaxed),
|
||||
indexing: core.searcher().indexing(),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
}
|
||||
@@ -788,11 +791,14 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
|
||||
query,
|
||||
limit,
|
||||
filters,
|
||||
}) => match core.search_v2(&query, clamp_limit(limit), &filters) {
|
||||
}) => match core
|
||||
.searcher()
|
||||
.search_v2(&query, clamp_limit(limit), &filters)
|
||||
{
|
||||
Ok((drive_hits, local_hits)) => CtlResponse::SearchResultsV2 {
|
||||
drive_hits,
|
||||
local_hits,
|
||||
local_indexing: core.indexing.load(Ordering::Relaxed),
|
||||
local_indexing: core.searcher().indexing(),
|
||||
},
|
||||
Err(e) => CtlResponse::error(e),
|
||||
},
|
||||
@@ -1104,13 +1110,13 @@ pub(crate) fn run_control_socket(
|
||||
let core = core.clone();
|
||||
let username = username.clone();
|
||||
let mountpoint = mountpoint.clone();
|
||||
if let Err(e) = std::thread::Builder::new()
|
||||
.name("pdfs-control".into())
|
||||
.spawn(move || {
|
||||
let _permit = permit;
|
||||
handle_control_conn(&core, &username, &mountpoint, stream);
|
||||
})
|
||||
{
|
||||
// A job, so a stop joins it; a subscription ends on the
|
||||
// stop's wake (`EventHub::wake_all`).
|
||||
let board = core.services.clone();
|
||||
if let Err(e) = board.spawn_job("pdfs-control-conn", move || {
|
||||
let _permit = permit;
|
||||
handle_control_conn(&core, &username, &mountpoint, stream);
|
||||
}) {
|
||||
warn!(error = %e, "control: spawn handler failed");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
// problems found" and "never looked" are both an empty list;
|
||||
// `integrity_running` says a fresh answer is on its way.
|
||||
let (integrity_problems, integrity_checked, integrity_running) = if deep {
|
||||
core.start_or_read_integrity_check()
|
||||
core.maintenance.start_or_read_integrity_check()
|
||||
} else {
|
||||
(Vec::new(), false, false)
|
||||
};
|
||||
@@ -106,7 +106,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
|
||||
}
|
||||
Err(e) => CtlResponse::error(CoreError::internal(format!("read db stats: {e:?}"))),
|
||||
},
|
||||
CtlRequest::CacheVacuum => match core.start_vacuum() {
|
||||
CtlRequest::CacheVacuum => match core.maintenance.start_vacuum() {
|
||||
Ok(()) => CtlResponse::Ok {
|
||||
message: "compacting the cache database in the background".into(),
|
||||
},
|
||||
|
||||
@@ -20,6 +20,8 @@ use std::time::{Duration, Instant};
|
||||
use parking_lot::Mutex;
|
||||
use pdfs_core::control::{Diagnostics, DriveCallStat, InflightRequest, ServiceState, WorkerState};
|
||||
|
||||
use pdfs_core::lifecycle::ServiceBoard;
|
||||
|
||||
use super::Core;
|
||||
|
||||
/// When this process started. Read at the first touch, which
|
||||
@@ -207,10 +209,15 @@ impl Core {
|
||||
/// is not started until the first one has returned.
|
||||
fn pending_ops_quickly(&self) -> Option<u64> {
|
||||
let db = self.db.clone();
|
||||
probe_once(&self.pending_probe, PENDING_COUNT_DEADLINE, move || {
|
||||
let counts = db.pending_op_counts().ok()?;
|
||||
Some(counts.uploads.max(0) as u64 + counts.changes.max(0) as u64)
|
||||
})
|
||||
probe_once(
|
||||
&self.services,
|
||||
&self.pending_probe,
|
||||
PENDING_COUNT_DEADLINE,
|
||||
move || {
|
||||
let counts = db.pending_op_counts().ok()?;
|
||||
Some(counts.uploads.max(0) as u64 + counts.changes.max(0) as u64)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -219,6 +226,7 @@ impl Core {
|
||||
/// `None` when it did not answer in time, or when the previous probe sharing
|
||||
/// `busy` has not returned yet: then no new thread is started at all.
|
||||
fn probe_once<T: Send + 'static>(
|
||||
board: &ServiceBoard,
|
||||
busy: &Arc<AtomicBool>,
|
||||
deadline: Duration,
|
||||
probe: impl FnOnce() -> Option<T> + Send + 'static,
|
||||
@@ -228,13 +236,11 @@ fn probe_once<T: Send + 'static>(
|
||||
}
|
||||
let done = Arc::clone(busy);
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("pdfs-diagnostics".into())
|
||||
.spawn(move || {
|
||||
let answer = probe();
|
||||
done.store(false, Ordering::Release);
|
||||
let _ = tx.send(answer);
|
||||
});
|
||||
let spawned = board.spawn_job("pdfs-diagnostics", move || {
|
||||
let answer = probe();
|
||||
done.store(false, Ordering::Release);
|
||||
let _ = tx.send(answer);
|
||||
});
|
||||
if spawned.is_err() {
|
||||
busy.store(false, Ordering::Release);
|
||||
return None;
|
||||
@@ -310,11 +316,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_stuck_probe_is_not_started_again() {
|
||||
let board = ServiceBoard::default();
|
||||
let busy = Arc::new(AtomicBool::new(false));
|
||||
let (release, wait) = std::sync::mpsc::channel::<()>();
|
||||
let short = Duration::from_millis(50);
|
||||
|
||||
let stuck = probe_once(&busy, short, move || {
|
||||
let stuck = probe_once(&board, &busy, short, move || {
|
||||
let _ = wait.recv();
|
||||
Some(1)
|
||||
});
|
||||
@@ -322,7 +329,7 @@ mod tests {
|
||||
|
||||
let started = Arc::new(AtomicBool::new(false));
|
||||
let flag = Arc::clone(&started);
|
||||
let second = probe_once(&busy, short, move || {
|
||||
let second = probe_once(&board, &busy, short, move || {
|
||||
flag.store(true, Ordering::SeqCst);
|
||||
Some(2)
|
||||
});
|
||||
@@ -339,7 +346,7 @@ mod tests {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert_eq!(
|
||||
probe_once(&busy, Duration::from_secs(10), || Some(3)),
|
||||
probe_once(&board, &busy, Duration::from_secs(10), || Some(3)),
|
||||
Some(3)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -420,7 +420,7 @@ impl Core {
|
||||
// touches get written (`ContentCache::flush_touches`).
|
||||
// Cheap and a no-op when empty.
|
||||
self.cache.flush_touches();
|
||||
self.recover_fsynced_writes();
|
||||
self.recovery().recover_fsynced_writes();
|
||||
// Parked rows are invisible to `claim_next_due_op`, so
|
||||
// an idle queue is exactly when a park that has outlived
|
||||
// its writer has to be noticed.
|
||||
@@ -1135,9 +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()
|
||||
};
|
||||
|
||||
@@ -116,6 +116,14 @@ impl EventHub {
|
||||
.retain(|other| !Arc::ptr_eq(other, mailbox));
|
||||
}
|
||||
|
||||
/// Wake every subscription waiting on its mailbox, so it sees a stop
|
||||
/// now rather than at its next heartbeat.
|
||||
pub(crate) fn wake_all(&self) {
|
||||
for mailbox in self.mailboxes.lock().iter() {
|
||||
mailbox.ready.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
fn has_subscribers(&self) -> bool {
|
||||
!self.mailboxes.lock().is_empty()
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Kernel-facing FUSE callback adapter.
|
||||
|
||||
use super::*;
|
||||
use crate::state::DirListing;
|
||||
use pdfs_vfs::open::{DirListing, Fallocate, Released, WriteError, dir_page};
|
||||
|
||||
impl Filesystem for ProtonFs {
|
||||
/// Negotiate kernel-side behaviour once, before any other callback.
|
||||
@@ -201,7 +201,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 +225,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 +268,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,
|
||||
@@ -466,7 +460,7 @@ impl Filesystem for ProtonFs {
|
||||
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) {
|
||||
match st.open.writer_mut(ino.0) {
|
||||
Some(aw) => aw.resize(size).map(|()| true).map_err(Errno::from),
|
||||
None => Ok(false),
|
||||
}
|
||||
@@ -530,13 +524,13 @@ impl Filesystem for ProtonFs {
|
||||
// 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 {
|
||||
let Some(kind) = Fallocate::from_mode(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)) {
|
||||
match st.open.by_fh(_fh.0) {
|
||||
Some(aw) => aw.file.clone(),
|
||||
None => {
|
||||
reply.error(if st.entries.contains_key(&ino.0) {
|
||||
@@ -558,26 +552,12 @@ impl Filesystem for ProtonFs {
|
||||
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);
|
||||
}
|
||||
let grown = st
|
||||
.open
|
||||
.by_fh_mut(_fh.0)
|
||||
.and_then(|aw| aw.record_fallocate(kind, offset, new_end));
|
||||
if let Some(end) = grown {
|
||||
st.set_size(ino.0, end);
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
@@ -609,9 +589,8 @@ impl Filesystem for ProtonFs {
|
||||
) {
|
||||
let file = {
|
||||
let st = self.core.state();
|
||||
st.handles
|
||||
.get(&fh.0)
|
||||
.and_then(|ino| st.active_writes.get(ino))
|
||||
st.open
|
||||
.by_fh(fh.0)
|
||||
.filter(|aw| aw.dirty)
|
||||
.map(|aw| aw.file.clone())
|
||||
};
|
||||
@@ -669,20 +648,13 @@ impl Filesystem for ProtonFs {
|
||||
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 (h, releasing) = match st.open.release(fh.0) {
|
||||
Released::Last(h) => {
|
||||
let ino = h.ino;
|
||||
(Some(h), Some(ino))
|
||||
}
|
||||
});
|
||||
let releasing = ino.filter(|_| h.is_some());
|
||||
if let Some(ino) = releasing {
|
||||
st.releasing.insert(ino);
|
||||
}
|
||||
Released::StillOpen { .. } | Released::NotWriting => (None, None),
|
||||
};
|
||||
(h, unlinked_uid, releasing)
|
||||
};
|
||||
// Deliberately **not** handed to a worker, unlike the other slow
|
||||
@@ -701,7 +673,7 @@ impl Filesystem for ProtonFs {
|
||||
// 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);
|
||||
self.core.state().open.finish_release(ino);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1084,60 +1056,14 @@ fn build_listing(st: &State, ino: u64) -> DirListing {
|
||||
/// 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;
|
||||
}
|
||||
}
|
||||
@@ -1267,12 +1193,10 @@ impl ProtonFs {
|
||||
return;
|
||||
}
|
||||
let mut st = self.core.state();
|
||||
let listing = Arc::new(build_listing(&st, ino));
|
||||
let listing = build_listing(&st, 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());
|
||||
}
|
||||
@@ -1474,7 +1398,7 @@ impl ProtonFs {
|
||||
// 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);
|
||||
let creating = !st.open.is_writing(ino.0);
|
||||
if creating && current.as_ref() != pending_base.as_ref().map(|p| &p.path) {
|
||||
drop(st);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
@@ -1512,9 +1436,7 @@ impl ProtonFs {
|
||||
}
|
||||
}
|
||||
}
|
||||
let fh = st.next_fh;
|
||||
st.next_fh += 1;
|
||||
let aw = st.active_writes.entry(ino.0).or_insert_with(|| {
|
||||
let fh = st.open.open_writer(ino.0, || {
|
||||
WriteHandle {
|
||||
ino: ino.0,
|
||||
uid: uid.clone(),
|
||||
@@ -1531,8 +1453,6 @@ impl ProtonFs {
|
||||
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");
|
||||
@@ -1570,8 +1490,7 @@ impl ProtonFs {
|
||||
// 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| {
|
||||
st.open.by_fh(fh.0).map(|aw| {
|
||||
(
|
||||
aw.file.clone(),
|
||||
aw.path.clone(),
|
||||
@@ -1653,31 +1572,30 @@ impl ProtonFs {
|
||||
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)) {
|
||||
match st.open.by_fh(fh) {
|
||||
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");
|
||||
match pdfs_vfs::open::stage_write(&file, offset, data) {
|
||||
Ok(()) => {}
|
||||
// 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) {
|
||||
Err(WriteError::NoSpace) => {
|
||||
error!(ino, fh, "scratch write failed: no space");
|
||||
self.core.cache.emergency_evict();
|
||||
return Err(Errno::ENOSPC);
|
||||
}
|
||||
return Err(Errno::EIO);
|
||||
Err(WriteError::Io(e)) => {
|
||||
error!(ino, fh, error = %e, "scratch write failed");
|
||||
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 {
|
||||
let Some(aw) = st.open.by_fh_mut(fh) else {
|
||||
return Err(Errno::EBADF);
|
||||
};
|
||||
aw.record_write(offset, offset + data.len() as u64);
|
||||
@@ -1792,14 +1710,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);
|
||||
@@ -2505,60 +2418,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)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,8 @@ use pdfs_core::control::{
|
||||
GalleryAction, GalleryAlbum, GalleryFolder, GalleryPlace, PhotoItem, PhotoKind, Response,
|
||||
};
|
||||
use pdfs_core::{CoreError, CoreResult};
|
||||
use pdfs_store::db::Db;
|
||||
use proton_drive_rs::ProtonDriveClient;
|
||||
use proton_drive_rs::proton_sdk::session::ProtonApiSession;
|
||||
use proton_gallery_app_rs::{App, View};
|
||||
use proton_gallery_rs::CancellationToken;
|
||||
@@ -32,6 +34,9 @@ pub(super) struct Gallery {
|
||||
refresh: Notify,
|
||||
access: AtomicU64,
|
||||
video: video::Server,
|
||||
client: ProtonDriveClient,
|
||||
events: Arc<super::events::EventHub>,
|
||||
db: Arc<Db>,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Eq)]
|
||||
@@ -50,8 +55,17 @@ impl Visibility {
|
||||
}
|
||||
|
||||
impl Gallery {
|
||||
pub(super) fn new(root: PathBuf, session: ProtonApiSession) -> Self {
|
||||
pub(super) fn new(
|
||||
root: PathBuf,
|
||||
session: ProtonApiSession,
|
||||
client: ProtonDriveClient,
|
||||
events: Arc<super::events::EventHub>,
|
||||
db: Arc<Db>,
|
||||
) -> Self {
|
||||
Self {
|
||||
client,
|
||||
events,
|
||||
db,
|
||||
root,
|
||||
session,
|
||||
cancel: CancellationToken::new(),
|
||||
@@ -69,13 +83,13 @@ impl Gallery {
|
||||
self.video.close_all();
|
||||
}
|
||||
|
||||
async fn app(&self, core: &Core) -> CoreResult<&App> {
|
||||
async fn app(&self) -> CoreResult<&App> {
|
||||
self.app
|
||||
.get_or_try_init(|| async {
|
||||
App::open_hosted(
|
||||
self.root.clone(),
|
||||
self.session.clone(),
|
||||
core.client.clone(),
|
||||
self.client.clone(),
|
||||
self.cancel.child_token(),
|
||||
)
|
||||
.await
|
||||
@@ -84,12 +98,7 @@ impl Gallery {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn ensure_visibility(
|
||||
&self,
|
||||
core: &Core,
|
||||
app: &App,
|
||||
force: bool,
|
||||
) -> CoreResult<Arc<Visibility>> {
|
||||
async fn ensure_visibility(&self, app: &App, force: bool) -> CoreResult<Arc<Visibility>> {
|
||||
if self.cancel.is_cancelled() {
|
||||
return Err(CoreError::remote("The Gallery session expired"));
|
||||
}
|
||||
@@ -111,7 +120,7 @@ impl Gallery {
|
||||
.await
|
||||
.map_err(gallery_error)?
|
||||
{
|
||||
self.publish_visibility(core, self.read_visibility(core, app).await?);
|
||||
self.publish_visibility(self.read_visibility(app).await?);
|
||||
}
|
||||
let started = Instant::now();
|
||||
let result = tokio::select! {
|
||||
@@ -119,7 +128,7 @@ impl Gallery {
|
||||
_ = self.cancel.cancelled() => Err(CoreError::remote("The Gallery session expired")),
|
||||
result = tokio::time::timeout(Duration::from_secs(20), async {
|
||||
app.refresh_gallery_configuration(false).await.map_err(gallery_error)?;
|
||||
self.read_visibility(core, app).await
|
||||
self.read_visibility(app).await
|
||||
}) => result.unwrap_or_else(|_| Err(CoreError::remote("Gallery visibility check timed out"))),
|
||||
};
|
||||
tracing::debug!(
|
||||
@@ -129,7 +138,7 @@ impl Gallery {
|
||||
);
|
||||
*checked = Some(Instant::now());
|
||||
if let Ok(visibility) = result {
|
||||
self.publish_visibility(core, visibility.clone());
|
||||
self.publish_visibility(visibility.clone());
|
||||
return Ok(visibility);
|
||||
}
|
||||
if !force && let Some(visibility) = self.snapshot() {
|
||||
@@ -145,18 +154,18 @@ impl Gallery {
|
||||
.clone()
|
||||
}
|
||||
|
||||
fn publish_visibility(&self, core: &Core, visibility: Arc<Visibility>) {
|
||||
fn publish_visibility(&self, visibility: Arc<Visibility>) {
|
||||
let mut snapshot = self.visibility.write().unwrap_or_else(|e| e.into_inner());
|
||||
if snapshot.as_ref() != Some(&visibility) {
|
||||
*snapshot = Some(visibility);
|
||||
drop(snapshot);
|
||||
self.video.close_all();
|
||||
core.events
|
||||
self.events
|
||||
.publish(&[pdfs_core::control::Topic::GalleryVisibilitySynced]);
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_visibility(&self, core: &Core, app: &App) -> CoreResult<Arc<Visibility>> {
|
||||
async fn read_visibility(&self, app: &App) -> CoreResult<Arc<Visibility>> {
|
||||
let account = self.account()?;
|
||||
let mut visibility = Visibility::default();
|
||||
for (volume, node) in app
|
||||
@@ -170,7 +179,7 @@ impl Gallery {
|
||||
.insert(NodeUid::new(volume.into(), node.into()).to_string());
|
||||
}
|
||||
visibility.media.extend(
|
||||
core.db
|
||||
self.db
|
||||
.photo_group_members_for(&visibility.media)
|
||||
.map_err(CoreError::from)?,
|
||||
);
|
||||
@@ -328,7 +337,7 @@ impl Gallery {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn poll(self: Arc<Self>, core: Core) {
|
||||
pub(super) async fn poll(self: Arc<Self>) {
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
@@ -336,9 +345,8 @@ impl Gallery {
|
||||
_ = self.refresh.notified() => {},
|
||||
_ = tokio::time::sleep(Duration::from_secs(60)) => {}
|
||||
}
|
||||
if let Ok(Ok(app)) = tokio::time::timeout(Duration::from_secs(5), self.app(&core)).await
|
||||
{
|
||||
let _ = self.ensure_visibility(&core, app, false).await;
|
||||
if let Ok(Ok(app)) = tokio::time::timeout(Duration::from_secs(5), self.app()).await {
|
||||
let _ = self.ensure_visibility(app, false).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -422,8 +430,8 @@ impl Core {
|
||||
}
|
||||
let gallery = self.gallery_host()?;
|
||||
self.rt.block_on(async {
|
||||
let app = gallery.app(self).await?;
|
||||
gallery.ensure_visibility(self, app, false).await
|
||||
let app = gallery.app().await?;
|
||||
gallery.ensure_visibility(app, false).await
|
||||
})
|
||||
}
|
||||
|
||||
@@ -475,9 +483,9 @@ impl Core {
|
||||
other => other,
|
||||
};
|
||||
self.rt.block_on(async {
|
||||
let app = gallery.app(self).await?;
|
||||
let app = gallery.app().await?;
|
||||
gallery
|
||||
.ensure_visibility(self, app, matches!(action, GalleryAction::Refresh))
|
||||
.ensure_visibility(app, matches!(action, GalleryAction::Refresh))
|
||||
.await?;
|
||||
match action {
|
||||
GalleryAction::AuthenticateHidden | GalleryAction::Lock => unreachable!(),
|
||||
@@ -517,14 +525,14 @@ impl Core {
|
||||
app.add_drive_folder(uid(&node)?)
|
||||
.await
|
||||
.map_err(gallery_error)?;
|
||||
gallery.ensure_visibility(self, app, true).await?;
|
||||
gallery.ensure_visibility(app, true).await?;
|
||||
Ok(done())
|
||||
}
|
||||
GalleryAction::Remove { gallery: id } => {
|
||||
app.forget_drive_gallery(SourceId::new(id).map_err(gallery_error)?)
|
||||
.await
|
||||
.map_err(gallery_error)?;
|
||||
gallery.ensure_visibility(self, app, true).await?;
|
||||
gallery.ensure_visibility(app, true).await?;
|
||||
Ok(done())
|
||||
}
|
||||
GalleryAction::Refresh => {
|
||||
@@ -535,7 +543,7 @@ impl Core {
|
||||
);
|
||||
app.scan_drive_folder(root).await.map_err(gallery_error)?;
|
||||
}
|
||||
gallery.ensure_visibility(self, app, true).await?;
|
||||
gallery.ensure_visibility(app, true).await?;
|
||||
Ok(done())
|
||||
}
|
||||
GalleryAction::Cover { album, uid: node } => {
|
||||
@@ -565,7 +573,7 @@ impl Core {
|
||||
.set_album_settings_at(Some(root), id, settings)
|
||||
.await
|
||||
.map_err(gallery_error)?;
|
||||
gallery.ensure_visibility(self, app, true).await?;
|
||||
gallery.ensure_visibility(app, true).await?;
|
||||
Ok(done())
|
||||
}
|
||||
}
|
||||
@@ -576,8 +584,8 @@ impl Core {
|
||||
let gallery = self.gallery_host()?;
|
||||
let uid = uid(node)?;
|
||||
self.rt.block_on(async {
|
||||
let app = gallery.app(self).await?;
|
||||
let visibility = gallery.ensure_visibility(self, app, false).await?;
|
||||
let app = gallery.app().await?;
|
||||
let visibility = gallery.ensure_visibility(app, false).await?;
|
||||
let access = if private {
|
||||
Some(gallery.private_access()?)
|
||||
} else {
|
||||
@@ -605,7 +613,7 @@ impl Core {
|
||||
let access = gallery.private_access()?;
|
||||
let asset = gallery.asset(&uid(node)?)?;
|
||||
self.rt.block_on(async {
|
||||
let app = gallery.app(self).await?;
|
||||
let app = gallery.app().await?;
|
||||
let bytes = tokio::time::timeout(Duration::from_secs(30), async {
|
||||
if let Some(bytes) = app.preview(&asset).await? {
|
||||
Ok(bytes)
|
||||
@@ -633,8 +641,8 @@ impl Core {
|
||||
let gallery = self.gallery_host()?;
|
||||
let asset = gallery.asset(&uid(node)?)?;
|
||||
self.rt.block_on(async {
|
||||
let app = gallery.app(self).await?;
|
||||
let visibility = gallery.ensure_visibility(self, app, false).await?;
|
||||
let app = gallery.app().await?;
|
||||
let visibility = gallery.ensure_visibility(app, false).await?;
|
||||
let access = if private {
|
||||
Some(gallery.private_access()?)
|
||||
} else {
|
||||
|
||||
@@ -15,11 +15,10 @@
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::time::Duration;
|
||||
|
||||
use pdfs_store::db::PendingCounts;
|
||||
use pdfs_core::shutdown::Shutdown;
|
||||
use pdfs_store::db::{Db, PendingCounts};
|
||||
use tracing::{debug, warn};
|
||||
|
||||
use super::Core;
|
||||
|
||||
/// How often the queue is looked at.
|
||||
const CHECK_EVERY: Duration = Duration::from_secs(5);
|
||||
|
||||
@@ -29,11 +28,10 @@ fn sendable(counts: &PendingCounts) -> i64 {
|
||||
}
|
||||
|
||||
/// Run until the daemon stops, holding the inhibitor while changes wait.
|
||||
pub(crate) fn run(core: Core) {
|
||||
pub(crate) fn run(db: &Db, shutdown: &Shutdown) {
|
||||
let mut held: Option<Child> = None;
|
||||
loop {
|
||||
let waiting = core
|
||||
.db
|
||||
let waiting = db
|
||||
.pending_op_counts()
|
||||
.map(|counts| sendable(&counts))
|
||||
.unwrap_or(0);
|
||||
@@ -52,7 +50,7 @@ pub(crate) fn run(core: Core) {
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if !core.shutdown.sleep(CHECK_EVERY) {
|
||||
if !shutdown.sleep(CHECK_EVERY) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,16 @@ use proton_drive_rs::NodeKind;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use fuser::Errno;
|
||||
use parking_lot::Mutex;
|
||||
use pdfs_core::CoreResult;
|
||||
use pdfs_core::shutdown::Shutdown;
|
||||
use pdfs_store::cache::ContentCache;
|
||||
|
||||
use super::link::Link;
|
||||
use super::transfers::TransferRegistry;
|
||||
use super::{Core, is_local_uid, node_size, parse_uid};
|
||||
|
||||
/// How often the keeper looks for work.
|
||||
@@ -59,32 +69,76 @@ pub(crate) struct KeptFile {
|
||||
pub(crate) size: u64,
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// Have the keeper check every pin.
|
||||
pub(crate) fn recheck_all_pins(&self) {
|
||||
self.pin_work.lock().all = true;
|
||||
/// What the pin keeper needs from the tree.
|
||||
pub(crate) trait KeeperHost: Send + Sync {
|
||||
/// Where `uid` is in the tree: its inode, its parent's, and whether it is
|
||||
/// a folder.
|
||||
fn locate(&self, uid: &NodeUid) -> Option<(u64, u64, bool)>;
|
||||
/// Every file under the folder at `ino`, listing what is not listed yet.
|
||||
fn pin_subtree_files(&self, ino: u64) -> CoreResult<Vec<u64>>;
|
||||
/// List the folder at `ino` again if its listing was dropped.
|
||||
fn ensure_children(&self, ino: u64) -> Result<(), Errno>;
|
||||
/// The file at `ino`, as a pin keeps it. See [`Core::kept_file`].
|
||||
fn kept_file(&self, ino: u64) -> Option<KeptFile>;
|
||||
/// Download a pinned file and keep it.
|
||||
fn fetch_pinned(&self, uid: &NodeUid, name: &str, mtime: i64, size: u64) -> CoreResult<()>;
|
||||
}
|
||||
|
||||
impl KeeperHost for Core {
|
||||
fn locate(&self, uid: &NodeUid) -> Option<(u64, u64, bool)> {
|
||||
let st = self.state();
|
||||
st.by_uid.get(uid).and_then(|&ino| {
|
||||
let e = st.entries.get(&ino)?;
|
||||
Some((ino, e.parent, e.node.is_folder()))
|
||||
})
|
||||
}
|
||||
|
||||
/// Have the keeper check the pinned file or folder `uid`.
|
||||
pub(crate) fn recheck_pinned(&self, uid: &NodeUid) {
|
||||
self.pin_work.lock().nodes.insert(uid.clone());
|
||||
fn pin_subtree_files(&self, ino: u64) -> CoreResult<Vec<u64>> {
|
||||
Core::pin_subtree_files(self, ino)
|
||||
}
|
||||
|
||||
fn ensure_children(&self, ino: u64) -> Result<(), Errno> {
|
||||
Core::ensure_children(self, ino)
|
||||
}
|
||||
|
||||
fn kept_file(&self, ino: u64) -> Option<KeptFile> {
|
||||
Core::kept_file(self, ino)
|
||||
}
|
||||
|
||||
fn fetch_pinned(&self, uid: &NodeUid, name: &str, mtime: i64, size: u64) -> CoreResult<()> {
|
||||
Core::fetch_pinned(self, uid, name, mtime, size)
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks pins again and downloads what is missing or stale (the module
|
||||
/// documentation says when). Holds the content cache, the transfer list, the
|
||||
/// link, the stop signal and the queue of work; it reaches the tree through
|
||||
/// [`KeeperHost`].
|
||||
pub(crate) struct PinKeeper {
|
||||
cache: Arc<ContentCache>,
|
||||
transfers: Arc<TransferRegistry>,
|
||||
link: Arc<Link>,
|
||||
shutdown: Arc<Shutdown>,
|
||||
work: Arc<Mutex<PinWork>>,
|
||||
host: Arc<dyn KeeperHost>,
|
||||
}
|
||||
|
||||
impl PinKeeper {
|
||||
/// The keeper's loop, until the daemon stops. Starts with a check of every
|
||||
/// pin, which catches up on whatever changed while the daemon was down.
|
||||
///
|
||||
/// Work that failed waits out a backoff of its own. New work does not wait
|
||||
/// for it, so a file that keeps failing does not hold up the next change.
|
||||
pub(crate) fn run_pin_keeper(&self) {
|
||||
self.recheck_all_pins();
|
||||
pub(crate) fn run(&self) {
|
||||
self.work.lock().all = true;
|
||||
let mut backlog = PinWork::default();
|
||||
let mut backlog_due = Instant::now();
|
||||
let mut retry = RETRY_FIRST;
|
||||
while self.shutdown.sleep(KEEPER_TICK) {
|
||||
if !self.is_online() {
|
||||
if !self.link.is_online() {
|
||||
continue;
|
||||
}
|
||||
let mut work = std::mem::take(&mut *self.pin_work.lock());
|
||||
let mut work = std::mem::take(&mut *self.work.lock());
|
||||
let retrying = !backlog.is_empty() && Instant::now() >= backlog_due;
|
||||
if retrying {
|
||||
work.merge(std::mem::take(&mut backlog));
|
||||
@@ -128,19 +182,13 @@ impl Core {
|
||||
if !self.cache.is_pinned(&uid) {
|
||||
continue;
|
||||
}
|
||||
let found = {
|
||||
let st = self.state();
|
||||
st.by_uid.get(&uid).and_then(|&ino| {
|
||||
let e = st.entries.get(&ino)?;
|
||||
Some((ino, e.parent, e.node.is_folder()))
|
||||
})
|
||||
};
|
||||
let found = self.host.locate(&uid);
|
||||
let Some((ino, parent, is_folder)) = found else {
|
||||
debug!(%uid, "pin keeper: pinned node is not in the tree");
|
||||
continue;
|
||||
};
|
||||
if is_folder {
|
||||
match self.pin_subtree_files(ino) {
|
||||
match self.host.pin_subtree_files(ino) {
|
||||
Ok(inos) => files.extend(inos.into_iter().filter(|i| seen.insert(*i))),
|
||||
Err(e) => {
|
||||
warn!(%uid, error = %e, "pin keeper: listing a kept folder failed");
|
||||
@@ -154,7 +202,7 @@ impl Core {
|
||||
// now, which is what the cached copy is checked against.
|
||||
if !work.all
|
||||
&& parent != ino
|
||||
&& let Err(e) = self.ensure_children(parent)
|
||||
&& let Err(e) = self.host.ensure_children(parent)
|
||||
{
|
||||
warn!(%uid, error = ?e, "pin keeper: listing a kept file's folder failed");
|
||||
failed.nodes.insert(uid);
|
||||
@@ -167,7 +215,7 @@ impl Core {
|
||||
|
||||
let stale: Vec<KeptFile> = files
|
||||
.into_iter()
|
||||
.filter_map(|ino| self.kept_file(ino))
|
||||
.filter_map(|ino| self.host.kept_file(ino))
|
||||
.filter(|f| !self.cache.is_cached(&f.uid, f.mtime, f.size))
|
||||
.collect();
|
||||
if stale.is_empty() {
|
||||
@@ -186,7 +234,10 @@ impl Core {
|
||||
continue;
|
||||
}
|
||||
job.detail(file.name.clone());
|
||||
match self.fetch_pinned(&file.uid, &file.name, file.mtime, file.size) {
|
||||
match self
|
||||
.host
|
||||
.fetch_pinned(&file.uid, &file.name, file.mtime, file.size)
|
||||
{
|
||||
Ok(()) => fetched += 1,
|
||||
Err(e) => {
|
||||
warn!(uid = %file.uid, error = %e, "pin keeper: download failed");
|
||||
@@ -203,6 +254,30 @@ impl Core {
|
||||
);
|
||||
failed
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// The pin keeper, with this daemon as its host.
|
||||
pub(crate) fn pin_keeper(&self) -> PinKeeper {
|
||||
PinKeeper {
|
||||
cache: self.cache.clone(),
|
||||
transfers: self.transfers.clone(),
|
||||
link: self.link.clone(),
|
||||
shutdown: self.shutdown.clone(),
|
||||
work: self.pin_work.clone(),
|
||||
host: Arc::new(self.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Have the keeper check every pin.
|
||||
pub(crate) fn recheck_all_pins(&self) {
|
||||
self.pin_work.lock().all = true;
|
||||
}
|
||||
|
||||
/// Have the keeper check the pinned file or folder `uid`.
|
||||
pub(crate) fn recheck_pinned(&self, uid: &NodeUid) {
|
||||
self.pin_work.lock().nodes.insert(uid.clone());
|
||||
}
|
||||
|
||||
/// The file at `ino`, as a pin keeps it. `None` for a folder, a file this
|
||||
/// daemon still owes an upload for, or a file whose real size cannot be
|
||||
|
||||
+21
-166
@@ -86,7 +86,6 @@ mod attach;
|
||||
mod background;
|
||||
mod conflicts;
|
||||
mod control;
|
||||
use control::run_control_socket;
|
||||
mod devices;
|
||||
mod diagnostics;
|
||||
mod drain;
|
||||
@@ -94,12 +93,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;
|
||||
@@ -108,7 +108,6 @@ mod keeper;
|
||||
mod link;
|
||||
mod listing;
|
||||
mod session;
|
||||
mod writes;
|
||||
pub use filesystem::ProtonFs;
|
||||
mod maintenance;
|
||||
mod mount;
|
||||
@@ -126,6 +125,7 @@ mod requests;
|
||||
mod resolve;
|
||||
mod revisions;
|
||||
mod search;
|
||||
mod services;
|
||||
mod shared;
|
||||
mod sharing;
|
||||
mod sizes;
|
||||
@@ -133,7 +133,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;
|
||||
@@ -142,7 +142,7 @@ use pdfs_core::transfers;
|
||||
mod upload;
|
||||
mod r#virtual;
|
||||
mod workers;
|
||||
use background::{forget_and_notify, run_event_sync, run_local_index, run_photos_event_sync};
|
||||
use background::{forget_and_notify, run_event_sync, run_photos_event_sync};
|
||||
use link::BATCH_CALL_TIMEOUT;
|
||||
pub(crate) use mount::is_stale_mount;
|
||||
pub use mount::prepare_mountpoint;
|
||||
@@ -150,8 +150,9 @@ 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};
|
||||
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 +345,15 @@ 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;
|
||||
/// 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";
|
||||
@@ -608,7 +611,7 @@ struct Core {
|
||||
/// that needs the database — so the handler acknowledges the request and a
|
||||
/// thread does the work, exactly as the other long control requests already
|
||||
/// do. See [`Maintenance`].
|
||||
maintenance: Arc<Mutex<maintenance::Maintenance>>,
|
||||
maintenance: maintenance::Maintenance,
|
||||
/// The size upgrades running now, and the replies parked on them. Shared
|
||||
/// by every mount: the bound that matters is per daemon.
|
||||
sizes: sizes::SizeState,
|
||||
@@ -892,7 +895,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
|
||||
@@ -1858,17 +1861,6 @@ fn is_unrevised(node: &Node) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
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> {
|
||||
@@ -2407,14 +2399,13 @@ mod pending_size_tests {
|
||||
|
||||
#[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,
|
||||
@@ -3288,67 +3279,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 +3292,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 +3332,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();
|
||||
@@ -4149,7 +4004,7 @@ mod tests {
|
||||
"enumerate_folder_children_node_uids",
|
||||
);
|
||||
assert_eq!(ensure.matches("adopt_stale_listing(").count(), 3);
|
||||
let online = function_source(include_str!("link.rs"), "fn mark_online(");
|
||||
let online = function_source(include_str!("link.rs"), "fn after_reconnect(");
|
||||
assert!(online.contains("self.relist_offline_listings();"));
|
||||
}
|
||||
|
||||
|
||||
+171
-82
@@ -18,6 +18,11 @@ use proton_drive_rs::proton_sdk::api::ResponseCode;
|
||||
use proton_drive_rs::proton_sdk::error::{ProtonApiError, ProtonError};
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use pdfs_core::shutdown::Shutdown;
|
||||
use pdfs_drive::DriveApi;
|
||||
|
||||
use crate::{Core, ONLINE_PROBE_MAX, ONLINE_PROBE_MIN};
|
||||
|
||||
/// How long a remote call a FUSE handler is waiting on may take before the link
|
||||
@@ -88,6 +93,75 @@ impl Link {
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the mount currently believes Proton is reachable.
|
||||
pub(crate) fn is_online(&self) -> bool {
|
||||
self.online.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Whether Proton refused the session itself, so the mount stays offline
|
||||
/// until the user signs in again.
|
||||
pub(crate) fn session_expired(&self) -> bool {
|
||||
self.session_expired.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Flip the mount offline and wake the probe. Only the first caller of an
|
||||
/// outage logs it; the rest are the same outage.
|
||||
pub(crate) fn go_offline(&self, what: &str, error: &dyn std::fmt::Display) {
|
||||
let mut lost_at = self.lost_at.lock();
|
||||
if self.online.swap(false, Ordering::Relaxed) {
|
||||
*lost_at = Some(Instant::now());
|
||||
warn!(during = what, %error,
|
||||
"lost the connection to Proton; queueing changes until it returns");
|
||||
self.changed.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// Flip the mount back online and wake everything waiting for it.
|
||||
fn go_online(&self) {
|
||||
let mut lost_at = self.lost_at.lock();
|
||||
self.online.store(true, Ordering::Relaxed);
|
||||
match lost_at.take() {
|
||||
Some(since) => {
|
||||
info!(
|
||||
offline_secs = since.elapsed().as_secs(),
|
||||
"connection to Proton is back"
|
||||
)
|
||||
}
|
||||
None => info!("back online"),
|
||||
}
|
||||
self.changed.notify_all();
|
||||
}
|
||||
|
||||
/// Wait up to `budget` for the link to come back. Returns whether it is up.
|
||||
pub(crate) fn wait_online(&self, budget: Duration, shutdown: &Shutdown) -> bool {
|
||||
let deadline = Instant::now() + budget;
|
||||
let mut lost_at = self.lost_at.lock();
|
||||
while !self.is_online() {
|
||||
if shutdown.is_stopping() || self.changed.wait_until(&mut lost_at, deadline).timed_out()
|
||||
{
|
||||
return self.is_online();
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Wait while the link is up. Returns `false` if the daemon is stopping.
|
||||
fn wait_offline(&self, shutdown: &Shutdown) -> bool {
|
||||
let mut lost_at = self.lost_at.lock();
|
||||
while self.is_online() {
|
||||
if shutdown.is_stopping() {
|
||||
return false;
|
||||
}
|
||||
self.changed.wait_for(&mut lost_at, IDLE_CHECK);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// When the current outage began, if the link is down.
|
||||
fn lost_at(&self) -> Option<Instant> {
|
||||
*self.lost_at.lock()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) use pdfs_drive::is_network_error;
|
||||
@@ -160,7 +234,7 @@ fn next_probe_delay(delay: Duration, outage: Duration) -> Duration {
|
||||
impl Core {
|
||||
/// Whether the mount currently believes Proton is reachable.
|
||||
pub(crate) fn is_online(&self) -> bool {
|
||||
self.link.online.load(Ordering::Relaxed)
|
||||
self.link.is_online()
|
||||
}
|
||||
|
||||
/// Whether a namespace change through the mount goes to Drive inside the
|
||||
@@ -195,7 +269,7 @@ impl Core {
|
||||
/// Whether Proton refused the session itself, so nothing reaches it until
|
||||
/// the user signs in again.
|
||||
pub(crate) fn session_expired(&self) -> bool {
|
||||
self.link.session_expired.load(Ordering::Relaxed)
|
||||
self.link.session_expired()
|
||||
}
|
||||
|
||||
/// Report a failed remote call. Returns whether it failed for want of a
|
||||
@@ -239,65 +313,14 @@ impl Core {
|
||||
self.mark_offline(what, error);
|
||||
}
|
||||
|
||||
/// Flip the mount offline and wake the probe. Only the first caller of an
|
||||
/// outage logs it; the rest are the same outage.
|
||||
/// Flip the mount offline and wake the probe. See [`Link::go_offline`].
|
||||
pub(crate) fn mark_offline(&self, what: &str, error: &dyn std::fmt::Display) {
|
||||
let mut lost_at = self.link.lost_at.lock();
|
||||
if self.link.online.swap(false, Ordering::Relaxed) {
|
||||
*lost_at = Some(Instant::now());
|
||||
warn!(during = what, %error,
|
||||
"lost the connection to Proton; queueing changes until it returns");
|
||||
self.link.changed.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// Flip the mount back online, wake everything waiting for it, and let the
|
||||
/// queue drain.
|
||||
fn mark_online(&self) {
|
||||
{
|
||||
let mut lost_at = self.link.lost_at.lock();
|
||||
self.link.online.store(true, Ordering::Relaxed);
|
||||
match lost_at.take() {
|
||||
Some(since) => {
|
||||
info!(
|
||||
offline_secs = since.elapsed().as_secs(),
|
||||
"connection to Proton is back"
|
||||
)
|
||||
}
|
||||
None => info!("back online"),
|
||||
}
|
||||
self.link.changed.notify_all();
|
||||
}
|
||||
self.relist_offline_listings();
|
||||
// Anything written while offline is queued and waiting on exactly this,
|
||||
// including ops that failed on the way down and are sitting out a
|
||||
// backoff sized for a server that keeps refusing. Ops Drive refused
|
||||
// keep theirs: the link was not why.
|
||||
if let Err(e) = self.db.retry_unrefused_ops_now(crate::now_millis()) {
|
||||
warn!(error = %e, "moving backed-off ops up after a reconnect failed");
|
||||
}
|
||||
self.wake_drain();
|
||||
// Downloads for pins failed while the link was down, and the events
|
||||
// that would have named the files are behind us (`docs/BUGS.md` B282).
|
||||
self.recheck_all_pins();
|
||||
self.link.go_offline(what, error);
|
||||
}
|
||||
|
||||
/// Wait up to `budget` for the link to come back. Returns whether it is up.
|
||||
pub(crate) fn wait_online(&self, budget: Duration) -> bool {
|
||||
let deadline = Instant::now() + budget;
|
||||
let mut lost_at = self.link.lost_at.lock();
|
||||
while !self.is_online() {
|
||||
if self.shutdown.is_stopping()
|
||||
|| self
|
||||
.link
|
||||
.changed
|
||||
.wait_until(&mut lost_at, deadline)
|
||||
.timed_out()
|
||||
{
|
||||
return self.is_online();
|
||||
}
|
||||
}
|
||||
true
|
||||
self.link.wait_online(budget, &self.shutdown)
|
||||
}
|
||||
|
||||
/// Wait out `interval` before a background poll of Proton, and while the
|
||||
@@ -318,29 +341,103 @@ impl Core {
|
||||
}
|
||||
}
|
||||
|
||||
/// The online probe, with this daemon as its host.
|
||||
pub(crate) fn online_probe(&self) -> OnlineProbe {
|
||||
OnlineProbe {
|
||||
link: self.link.clone(),
|
||||
drive: self.drive.clone(),
|
||||
rt: self.rt.clone(),
|
||||
shutdown: self.shutdown.clone(),
|
||||
host: Arc::new(self.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The link is back: let everything that waited on it go. Anything
|
||||
/// written while offline is queued and waiting on exactly this, including
|
||||
/// ops that failed on the way down and are sitting out a backoff sized
|
||||
/// for a server that keeps refusing. Ops Drive refused keep theirs: the
|
||||
/// link was not why.
|
||||
fn after_reconnect(&self) {
|
||||
self.relist_offline_listings();
|
||||
if let Err(e) = self.db.retry_unrefused_ops_now(crate::now_millis()) {
|
||||
warn!(error = %e, "moving backed-off ops up after a reconnect failed");
|
||||
}
|
||||
self.wake_drain();
|
||||
// Downloads for pins failed while the link was down, and the events
|
||||
// that would have named the files are behind us (`docs/BUGS.md` B282).
|
||||
self.recheck_all_pins();
|
||||
}
|
||||
}
|
||||
|
||||
/// What the online probe needs from the rest of the daemon.
|
||||
pub(crate) trait LinkHost: Send + Sync {
|
||||
/// Drive answered with the My Files root: store it in the tree and the
|
||||
/// database before the mount goes online.
|
||||
fn refresh_root(&self, root: &proton_drive_rs::Node);
|
||||
/// The mount is online again: relist, retry and refetch what waited.
|
||||
fn reconnected(&self);
|
||||
/// Proton refused the session.
|
||||
fn session_refused(&self, what: &str, error: &ProtonError);
|
||||
/// Repair the primary root's share id, which an offline start could not.
|
||||
fn repair_share_id(&self);
|
||||
}
|
||||
|
||||
impl LinkHost for Core {
|
||||
fn refresh_root(&self, root: &proton_drive_rs::Node) {
|
||||
{
|
||||
let root_ino = self.root_ino();
|
||||
let mut st = self.state();
|
||||
if let Some(e) = st.entries.get_mut(&root_ino) {
|
||||
e.node = root.clone();
|
||||
}
|
||||
}
|
||||
if let Err(e) = self.db.upsert_node(root) {
|
||||
warn!(error = %e, "refresh root after reconnect failed");
|
||||
}
|
||||
}
|
||||
|
||||
fn reconnected(&self) {
|
||||
self.after_reconnect();
|
||||
}
|
||||
|
||||
fn session_refused(&self, what: &str, error: &ProtonError) {
|
||||
self.mark_session_expired(what, error);
|
||||
}
|
||||
|
||||
fn repair_share_id(&self) {
|
||||
self.repair_primary_share_id(&self.primary_root_uid);
|
||||
}
|
||||
}
|
||||
|
||||
/// Watches the link for the life of the mount and probes it back while it is
|
||||
/// down. Holds the link, Drive, the runtime and the stop signal; it reaches
|
||||
/// the tree and the queue through [`LinkHost`].
|
||||
pub(crate) struct OnlineProbe {
|
||||
link: Arc<Link>,
|
||||
drive: Arc<dyn DriveApi>,
|
||||
rt: tokio::runtime::Handle,
|
||||
shutdown: Arc<Shutdown>,
|
||||
host: Arc<dyn LinkHost>,
|
||||
}
|
||||
|
||||
impl OnlineProbe {
|
||||
/// Watch the link for the life of the mount: sleep while it is up, and
|
||||
/// probe it back while it is down.
|
||||
///
|
||||
/// A mount that started from the cache is down from the first moment; one
|
||||
/// that started online goes down when [`Core::mark_offline`] says so.
|
||||
pub(crate) fn run_online_probe(&self) {
|
||||
/// that started online goes down when [`Link::go_offline`] says so.
|
||||
pub(crate) fn run(&self) {
|
||||
// Only an offline start never had a chance to repair its share id.
|
||||
let mut repair_share_id = !self.is_online();
|
||||
let mut repair_share_id = !self.link.is_online();
|
||||
loop {
|
||||
{
|
||||
let mut lost_at = self.link.lost_at.lock();
|
||||
while self.is_online() {
|
||||
if self.shutdown.is_stopping() {
|
||||
return;
|
||||
}
|
||||
self.link.changed.wait_for(&mut lost_at, IDLE_CHECK);
|
||||
}
|
||||
if !self.link.wait_offline(&self.shutdown) {
|
||||
return;
|
||||
}
|
||||
if !self.probe_until_online() {
|
||||
return;
|
||||
}
|
||||
if std::mem::take(&mut repair_share_id) {
|
||||
self.repair_primary_share_id(&self.primary_root_uid);
|
||||
self.host.repair_share_id();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -351,7 +448,7 @@ impl Core {
|
||||
/// A refused session is not probed: every probe would be refused the same
|
||||
/// way, forever (issue #35). The thread waits for the stop instead.
|
||||
fn probe_until_online(&self) -> bool {
|
||||
let started = self.link.lost_at.lock().unwrap_or_else(Instant::now);
|
||||
let started = self.link.lost_at().unwrap_or_else(Instant::now);
|
||||
let mut delay = if started.elapsed() < YOUNG_OUTAGE {
|
||||
PROBE_AFTER_DROP
|
||||
} else {
|
||||
@@ -361,7 +458,7 @@ impl Core {
|
||||
if !self.shutdown.sleep(delay) {
|
||||
return false;
|
||||
}
|
||||
if self.session_expired() {
|
||||
if self.link.session_expired() {
|
||||
delay = ONLINE_PROBE_MAX;
|
||||
continue;
|
||||
}
|
||||
@@ -373,20 +470,12 @@ impl Core {
|
||||
});
|
||||
match probe {
|
||||
Ok(root) => {
|
||||
{
|
||||
let root_ino = self.root_ino();
|
||||
let mut st = self.state();
|
||||
if let Some(e) = st.entries.get_mut(&root_ino) {
|
||||
e.node = root.clone();
|
||||
}
|
||||
}
|
||||
if let Err(e) = self.db.upsert_node(&root) {
|
||||
warn!(error = %e, "refresh root after reconnect failed");
|
||||
}
|
||||
self.mark_online();
|
||||
self.host.refresh_root(&root);
|
||||
self.link.go_online();
|
||||
self.host.reconnected();
|
||||
return true;
|
||||
}
|
||||
Err(e) if session_revoked(&e) => self.mark_session_expired("online probe", &e),
|
||||
Err(e) if session_revoked(&e) => self.host.session_refused("online probe", &e),
|
||||
Err(e) => {
|
||||
debug!(error = %e, ?delay, "online probe failed; still offline");
|
||||
delay = next_probe_delay(delay, started.elapsed());
|
||||
|
||||
@@ -3,7 +3,31 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
impl Core {
|
||||
/// Runs `VACUUM` and the deep integrity check as jobs, one at a time, and
|
||||
/// keeps the last check's findings. Holds the database, the transfer list for
|
||||
/// the job's entry, and the board the job runs on.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Maintenance {
|
||||
db: Arc<Db>,
|
||||
transfers: Arc<TransferRegistry>,
|
||||
services: pdfs_core::lifecycle::ServiceBoard,
|
||||
state: Arc<Mutex<MaintenanceState>>,
|
||||
}
|
||||
|
||||
impl Maintenance {
|
||||
pub(crate) fn new(
|
||||
db: Arc<Db>,
|
||||
transfers: Arc<TransferRegistry>,
|
||||
services: pdfs_core::lifecycle::ServiceBoard,
|
||||
) -> Self {
|
||||
Self {
|
||||
db,
|
||||
transfers,
|
||||
services,
|
||||
state: Arc::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Start a background `VACUUM`, or refuse because maintenance is already
|
||||
/// running.
|
||||
///
|
||||
@@ -11,9 +35,9 @@ impl Core {
|
||||
/// request. The outcome is a log line and a job that disappears from
|
||||
/// `GetQueueStatus` when it is done — a vacuum has nothing to report that a
|
||||
/// follow-up `CacheInspect` cannot show.
|
||||
pub(super) fn start_vacuum(&self) -> CoreResult<()> {
|
||||
pub(crate) fn start_vacuum(&self) -> CoreResult<()> {
|
||||
{
|
||||
let mut m = self.maintenance.lock();
|
||||
let mut m = self.state.lock();
|
||||
if m.running {
|
||||
return Err(CoreError::conflict(
|
||||
"database maintenance is already running",
|
||||
@@ -21,12 +45,12 @@ impl Core {
|
||||
}
|
||||
m.running = true;
|
||||
}
|
||||
let core = self.clone();
|
||||
let this = self.clone();
|
||||
if let Err(error) = self.services.spawn_job("pdfs-vacuum", move || {
|
||||
let job = core.transfers.begin_job("Compacting the cache database");
|
||||
let job = this.transfers.begin_job("Compacting the cache database");
|
||||
job.detail("Rewriting the database file");
|
||||
let started = Instant::now();
|
||||
match core.db.vacuum() {
|
||||
match this.db.vacuum() {
|
||||
Ok(outcome) => info!(
|
||||
freed_bytes = outcome.freed_bytes(),
|
||||
before_bytes = outcome.before_bytes,
|
||||
@@ -37,7 +61,7 @@ impl Core {
|
||||
),
|
||||
Err(e) => warn!(error = %e, "vacuum failed"),
|
||||
}
|
||||
core.maintenance.lock().running = false;
|
||||
this.state.lock().running = false;
|
||||
}) {
|
||||
tracing::warn!(%error, "could not start pdfs-vacuum");
|
||||
}
|
||||
@@ -51,8 +75,8 @@ impl Core {
|
||||
/// `(_, false, true)` and the answer lands on a later one — the check reads
|
||||
/// every page of the database under the connection mutex, so the choice is
|
||||
/// between answering late and freezing the mount until it finishes.
|
||||
pub(super) fn start_or_read_integrity_check(&self) -> (Vec<String>, bool, bool) {
|
||||
let mut m = self.maintenance.lock();
|
||||
pub(crate) fn start_or_read_integrity_check(&self) -> (Vec<String>, bool, bool) {
|
||||
let mut m = self.state.lock();
|
||||
if let Some(problems) = m.integrity.clone() {
|
||||
return (problems, true, m.running);
|
||||
}
|
||||
@@ -62,13 +86,13 @@ impl Core {
|
||||
m.running = true;
|
||||
drop(m);
|
||||
|
||||
let core = self.clone();
|
||||
let this = self.clone();
|
||||
if let Err(error) = self.services.spawn_job("pdfs-integrity-check", move || {
|
||||
let job = core
|
||||
let job = this
|
||||
.transfers
|
||||
.begin_background_job("Checking the cache database");
|
||||
job.detail("Verifying every page");
|
||||
let problems = match core.db.integrity_check() {
|
||||
let problems = match this.db.integrity_check() {
|
||||
Ok(problems) => problems,
|
||||
Err(e) => vec![format!("integrity check failed: {e:?}")],
|
||||
};
|
||||
@@ -77,7 +101,7 @@ impl Core {
|
||||
} else {
|
||||
warn!(problems = problems.len(), "cache database integrity check");
|
||||
}
|
||||
let mut m = core.maintenance.lock();
|
||||
let mut m = this.state.lock();
|
||||
m.integrity = Some(problems);
|
||||
m.running = false;
|
||||
}) {
|
||||
@@ -94,7 +118,7 @@ impl Core {
|
||||
/// gain from overlapping them — and the result of a check outlives the request
|
||||
/// that asked for it, because the request is answered before the check finishes.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Maintenance {
|
||||
struct MaintenanceState {
|
||||
/// A vacuum or integrity check is running right now.
|
||||
running: bool,
|
||||
/// Findings of the most recent completed deep check. `None` means none has
|
||||
|
||||
+93
-138
@@ -1,7 +1,7 @@
|
||||
//! Mount lifecycle and background-service orchestration.
|
||||
|
||||
use super::*;
|
||||
use pdfs_core::lifecycle::{ServiceBoard, Services, Wake};
|
||||
use pdfs_core::lifecycle::{Service, ServiceBoard, Services};
|
||||
|
||||
/// Why a [`mount`] call returned. Lets the daemon decide whether to exit (clean
|
||||
/// shutdown) or remount (the mount went away under it).
|
||||
@@ -490,12 +490,21 @@ pub(crate) fn mount_with(
|
||||
let (sync_tx, sync_rx) = std::sync::mpsc::channel::<sync::SyncMsg>();
|
||||
|
||||
let pause = pause::SyncPause::load(db.clone());
|
||||
let events: Arc<events::EventHub> = Arc::default();
|
||||
let gallery_dir = control_socket.with_file_name("gallery-catalog");
|
||||
let gallery =
|
||||
gallery_session.map(|session| Arc::new(super::gallery::Gallery::new(gallery_dir, session)));
|
||||
let gallery = gallery_session.map(|session| {
|
||||
Arc::new(super::gallery::Gallery::new(
|
||||
gallery_dir,
|
||||
session,
|
||||
client.clone(),
|
||||
events.clone(),
|
||||
db.clone(),
|
||||
))
|
||||
});
|
||||
let cache = Arc::new(cache);
|
||||
let shutdown = Arc::new(crate::shutdown::Shutdown::default());
|
||||
let transfers = TransferRegistry::new();
|
||||
let services = ServiceBoard::default();
|
||||
let sync = sync::SyncParts {
|
||||
store: db.clone(),
|
||||
drive: drive.clone(),
|
||||
@@ -530,7 +539,11 @@ pub(crate) fn mount_with(
|
||||
client,
|
||||
gallery,
|
||||
rt: rt.clone(),
|
||||
maintenance: Arc::new(Mutex::new(Default::default())),
|
||||
maintenance: super::maintenance::Maintenance::new(
|
||||
db.clone(),
|
||||
transfers.clone(),
|
||||
services.clone(),
|
||||
),
|
||||
primary_root_uid: root.uid.clone(),
|
||||
state: state.clone(),
|
||||
cache,
|
||||
@@ -550,12 +563,12 @@ pub(crate) fn mount_with(
|
||||
writes: super::writes::WriteState::new(),
|
||||
session: super::session::SessionCells::new(),
|
||||
shutdown,
|
||||
services: ServiceBoard::default(),
|
||||
services: services.clone(),
|
||||
photo_jobs: super::photos::PhotoJobs::new(),
|
||||
local_first,
|
||||
transfers,
|
||||
sync,
|
||||
events: Arc::new(Default::default()),
|
||||
events,
|
||||
indexing: Arc::new(AtomicBool::new(false)),
|
||||
pending_probe: Arc::default(),
|
||||
mounts: Arc::new(Mutex::new(SecondaryMountRegistry::default())),
|
||||
@@ -568,14 +581,14 @@ pub(crate) fn mount_with(
|
||||
|
||||
// Writes queued by a previous run (or left behind by a crash) are still owed
|
||||
// an upload, and reads must be served from their staged blobs until they land.
|
||||
core.hydrate_pending();
|
||||
core.recovery().hydrate_pending();
|
||||
// Then the writes that were fsynced but never closed, which the cache moved
|
||||
// aside at open. After `hydrate_pending`, so a recovered partial write can
|
||||
// see an already-queued write to the same node.
|
||||
core.recover_fsynced_writes();
|
||||
core.recovery().recover_fsynced_writes();
|
||||
// And finally the staged blobs neither of those accounts for: bytes a
|
||||
// failed release left behind with nothing pointing at them.
|
||||
core.reconcile_staging();
|
||||
core.recovery().reconcile_staging();
|
||||
// Several drain workers over one queue. One thread meant a single large
|
||||
// upload held every queued rename, trash and small write behind it for as
|
||||
// long as it ran; the claim column (`Db::claim_next_due_op`) keeps the
|
||||
@@ -587,93 +600,49 @@ pub(crate) fn mount_with(
|
||||
// in-process remount into a second generation of drain workers, sync engines
|
||||
// and sweeps all operating on a mount that no longer exists (`docs/BUGS.md` B44).
|
||||
let mut workers = Services::new(core.services.clone());
|
||||
for worker in 0..DRAIN_WORKERS {
|
||||
let drain_core = core.clone();
|
||||
// The drain workers wait on their own condvar, which a stop has to
|
||||
// notify; one notify wakes them all.
|
||||
let wake: Option<Wake> = (worker == 0).then(|| {
|
||||
let core = core.clone();
|
||||
Box::new(move || core.wake_drain()) as Wake
|
||||
});
|
||||
let spawned = workers.spawn(&format!("pdfs-drain-{worker}"), wake, move || {
|
||||
drain_core.run_pending_drain(worker == 0)
|
||||
});
|
||||
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
|
||||
let mut list: Vec<Box<dyn Service>> = Vec::new();
|
||||
for index in 0..DRAIN_WORKERS {
|
||||
list.push(Box::new(services::DrainWorker {
|
||||
core: core.clone(),
|
||||
index,
|
||||
}));
|
||||
}
|
||||
|
||||
// Start the folder-sync engine. It watches every mirror folder, polls the
|
||||
// remotes, and reconciles on its own thread — never in front of a FUSE call.
|
||||
// It waits on its channel, so a stop sends it `Stop`.
|
||||
{
|
||||
let syncer = core.syncer();
|
||||
let tx = core.sync.tx.clone();
|
||||
let wake: Wake = Box::new(move || {
|
||||
let _ = tx.send(sync::SyncMsg::Stop);
|
||||
});
|
||||
if let Err(error) =
|
||||
workers.spawn("pdfs-sync", Some(wake), move || sync::run(syncer, sync_rx))
|
||||
{
|
||||
warn!(%error, "failed to start sync engine");
|
||||
}
|
||||
}
|
||||
// A timed pause persisted by an earlier run still has to end on time.
|
||||
if let Some(until) = core.pause.deadline() {
|
||||
core.arm_pause_timer(until);
|
||||
}
|
||||
|
||||
// Reconcile leftover `(sync-conflict …)` copies: drop the ones that turned
|
||||
// out identical to the live file, surface the ones that genuinely diverge.
|
||||
// Its own thread — it enumerates and trashes, and must never block a FUSE call.
|
||||
list.push(Box::new(services::SyncEngine {
|
||||
syncer: core.syncer(),
|
||||
tx: core.sync.tx.clone(),
|
||||
rx: sync_rx,
|
||||
}));
|
||||
// `Off` skips the thread entirely rather than starting an idle one, so the
|
||||
// setting is verifiable from the outside (`ls /proc/<pid>/task/*/comm`).
|
||||
if sweep_mode == SweepMode::Off {
|
||||
info!("conflict sweep disabled by configuration");
|
||||
} else {
|
||||
info!(mode = ?sweep_mode, "conflict sweep enabled");
|
||||
let sweep_core = core.clone();
|
||||
let spawned = workers.spawn("pdfs-conflict-sweep", None, move || {
|
||||
sweep_core.run_conflict_sweep_loop()
|
||||
});
|
||||
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
|
||||
list.push(Box::new(services::ConflictSweep(core.sweeper())));
|
||||
}
|
||||
|
||||
// Watch the link for the life of the mount: a mount from the cache waits for
|
||||
// the network to come back, and an online one can lose it at any moment and
|
||||
// must notice it coming back just the same.
|
||||
{
|
||||
let probe_core = core.clone();
|
||||
let spawned = workers.spawn("pdfs-online-probe", None, move || {
|
||||
probe_core.run_online_probe()
|
||||
});
|
||||
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
|
||||
}
|
||||
|
||||
// Keep pinned files on this computer through changes made elsewhere, and
|
||||
// fetch the ones a failed or missed download left out (`docs/BUGS.md`
|
||||
// B282). Its own thread: a check lists folders and downloads files.
|
||||
{
|
||||
let keeper_core = core.clone();
|
||||
let spawned = workers.spawn("pdfs-pin-keeper", None, move || {
|
||||
keeper_core.run_pin_keeper()
|
||||
});
|
||||
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
|
||||
}
|
||||
|
||||
// Keep the launcher prompt's "This computer" index fresh. Its own thread:
|
||||
// the walk is I/O-heavy and must never sit in front of a FUSE callback.
|
||||
list.push(Box::new(services::OnlineProbe(core.online_probe())));
|
||||
list.push(Box::new(services::PinKeeper(core.pin_keeper())));
|
||||
if matches!(host, Host::Daemon) {
|
||||
if let Some(gallery) = &core.gallery {
|
||||
workers.spawn_task(&rt, "pdfs-gallery", gallery.clone().poll(core.clone()));
|
||||
}
|
||||
let db = core.db.clone();
|
||||
let indexing = core.indexing.clone();
|
||||
let transfers = core.transfers.clone();
|
||||
let mountpoint = mountpoint.to_path_buf();
|
||||
let shutdown = core.shutdown.clone();
|
||||
let spawned = workers.spawn("pdfs-localindex", None, move || {
|
||||
run_local_index(db, indexing, transfers, mountpoint, shutdown)
|
||||
});
|
||||
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
|
||||
list.push(Box::new(services::LocalIndex {
|
||||
db: core.db.clone(),
|
||||
indexing: core.indexing.clone(),
|
||||
transfers: core.transfers.clone(),
|
||||
mountpoint: mountpoint.to_path_buf(),
|
||||
shutdown: core.shutdown.clone(),
|
||||
}));
|
||||
}
|
||||
for service in list {
|
||||
let started = workers.start(service);
|
||||
keep_or_abandon(&core, control_socket, &mut workers, started)?;
|
||||
}
|
||||
if matches!(host, Host::Daemon)
|
||||
&& let Some(gallery) = &core.gallery
|
||||
{
|
||||
workers.spawn_task(&rt, "pdfs-gallery", gallery.clone().poll());
|
||||
}
|
||||
// A timed pause persisted by an earlier run still has to end on time.
|
||||
if let Some(until) = core.pause.deadline() {
|
||||
core.arm_pause_timer(until);
|
||||
}
|
||||
|
||||
// Bind the control socket before the FUSE session takes over the thread. A
|
||||
@@ -713,23 +682,14 @@ pub(crate) fn mount_with(
|
||||
// mid-transfer can abort it rather than block `join` (see `abort_fuse_connection`).
|
||||
let main_conn = fuse_connection_id(mountpoint);
|
||||
{
|
||||
let control_core = core.clone();
|
||||
let username = username.clone();
|
||||
let mountpoint = mountpoint.to_path_buf();
|
||||
// The listener blocks in `accept`, which only returns when a connection
|
||||
// arrives, so a stop connects to it. Connect while the socket still
|
||||
// exists, which is the point of the poke, then unlink it so nothing else
|
||||
// can arrive behind it. The listener checks the stop flag after every
|
||||
// accept, so a connection that races the unlink cannot put it back to
|
||||
// sleep.
|
||||
let socket = control_socket.to_path_buf();
|
||||
let wake: Wake = Box::new(move || {
|
||||
let _ = std::os::unix::net::UnixStream::connect(&socket);
|
||||
let _ = std::fs::remove_file(&socket);
|
||||
});
|
||||
match workers.spawn("pdfs-control", Some(wake), move || {
|
||||
run_control_socket(control_core, username, mountpoint, listener)
|
||||
}) {
|
||||
let control = services::ControlListener {
|
||||
core: core.clone(),
|
||||
username: username.clone(),
|
||||
mountpoint: mountpoint.to_path_buf(),
|
||||
listener,
|
||||
socket: control_socket.to_path_buf(),
|
||||
};
|
||||
match workers.start(Box::new(control)) {
|
||||
Ok(()) => {}
|
||||
Err(error) => {
|
||||
// A failure here abandons the mount, so the background threads
|
||||
@@ -751,34 +711,19 @@ pub(crate) fn mount_with(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Publishes what changes without one place to publish it from (status,
|
||||
// transfers, sync progress) to the front-ends subscribed on that socket.
|
||||
{
|
||||
let sampler_core = core.clone();
|
||||
let username = username.clone();
|
||||
let mountpoint = mountpoint.to_path_buf();
|
||||
if let Err(error) = workers.spawn("pdfs-events", None, move || {
|
||||
events::run_event_sampler(sampler_core, username, mountpoint)
|
||||
}) {
|
||||
// Not fatal: front-ends still get every published change, only
|
||||
// not the sampled ones.
|
||||
warn!(error = %error, "could not start the event sampler");
|
||||
}
|
||||
}
|
||||
// The supervisor watches the pool and answers the systemd watchdog. Started
|
||||
// after the listener, because its liveness probe is a round trip over that
|
||||
// socket.
|
||||
{
|
||||
let supervisor_core = core.clone();
|
||||
let socket = control_socket.to_path_buf();
|
||||
if let Err(error) = workers.spawn("pdfs-supervisor", None, move || {
|
||||
supervisor::run(supervisor_core, socket)
|
||||
}) {
|
||||
// Not fatal: the mount works without a supervisor, it just goes back
|
||||
// to being undiagnosable if it wedges.
|
||||
warn!(error = %error, "could not start the daemon supervisor");
|
||||
}
|
||||
}
|
||||
// The supervisor's liveness probe is a round trip over the control socket,
|
||||
// so it starts after the listener. Both are optional.
|
||||
let sampler = services::EventSampler {
|
||||
core: core.clone(),
|
||||
username: username.clone(),
|
||||
mountpoint: mountpoint.to_path_buf(),
|
||||
};
|
||||
let watchdog = services::Supervisor {
|
||||
core: core.clone(),
|
||||
socket: control_socket.to_path_buf(),
|
||||
};
|
||||
start_late(&mut workers, Box::new(sampler));
|
||||
start_late(&mut workers, Box::new(watchdog));
|
||||
// The mount is live and the control socket answers: this is the moment the
|
||||
// unit is actually usable, which is what `Type=notify` reports. Whatever
|
||||
// failure an earlier attempt recorded for the front ends is over.
|
||||
@@ -831,12 +776,13 @@ pub(crate) fn mount_with(
|
||||
// Hold off a shutdown while changes exist only here (B66). Only the real
|
||||
// daemon: a simulation's queue is not the user's data.
|
||||
if matches!(host, Host::Daemon) {
|
||||
let inhibit_core = core.clone();
|
||||
if let Err(error) = workers.spawn("pdfs-inhibit", None, move || {
|
||||
crate::inhibit::run(inhibit_core)
|
||||
}) {
|
||||
warn!(%error, "start the shutdown inhibitor failed");
|
||||
}
|
||||
start_late(
|
||||
&mut workers,
|
||||
Box::new(services::Inhibitor {
|
||||
db: core.db.clone(),
|
||||
shutdown: core.shutdown.clone(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Stop signals (SIGTERM from `systemctl --user stop`, SIGINT from Ctrl-C)
|
||||
@@ -985,6 +931,15 @@ fn abandon_workers(core: &Core, control_socket: &Path, workers: Services) {
|
||||
halt_workers(core, control_socket, workers);
|
||||
}
|
||||
|
||||
/// Start a service once the session is live. Past that point a failure no
|
||||
/// longer abandons the mount, so even a required one is only logged.
|
||||
fn start_late(workers: &mut Services, service: Box<dyn Service>) {
|
||||
let name = service.name();
|
||||
if let Err(error) = workers.start(service) {
|
||||
warn!(service = name, %error, "service did not start");
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep a worker the mount just spawned, or, if the spawn failed, stop the
|
||||
/// ones already running and hand the error back.
|
||||
fn keep_or_abandon(
|
||||
|
||||
@@ -709,12 +709,32 @@ fn run_bounded(mut command: Command, timeout: Duration) -> Result<Vec<u8>, ToolE
|
||||
let _ = child.wait();
|
||||
return Err(ToolError::Unavailable);
|
||||
};
|
||||
let reader = std::thread::spawn(move || {
|
||||
let mut output = Vec::new();
|
||||
stdout.read_to_end(&mut output).map(|_| output)
|
||||
});
|
||||
// Scoped, so the reader cannot outlive the call even when the child
|
||||
// overruns and is killed.
|
||||
std::thread::scope(|scope| {
|
||||
let reader = scope.spawn(move || {
|
||||
let mut output = Vec::new();
|
||||
stdout.read_to_end(&mut output).map(|_| output)
|
||||
});
|
||||
let status = wait_bounded(&mut child, timeout);
|
||||
let output = reader
|
||||
.join()
|
||||
.ok()
|
||||
.and_then(Result::ok)
|
||||
.ok_or(ToolError::Unavailable)?;
|
||||
match status {
|
||||
Some(true) => Ok(output),
|
||||
Some(false) => Err(ToolError::Failed),
|
||||
None => Err(ToolError::Unavailable),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Wait for `child` to exit, up to `timeout`, killing it past that. `None`
|
||||
/// when it overran or could not be waited for.
|
||||
fn wait_bounded(child: &mut std::process::Child, timeout: Duration) -> Option<bool> {
|
||||
let started = Instant::now();
|
||||
let status = loop {
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break Some(status.success()),
|
||||
Ok(None) if started.elapsed() < timeout => {
|
||||
@@ -726,16 +746,6 @@ fn run_bounded(mut command: Command, timeout: Duration) -> Result<Vec<u8>, ToolE
|
||||
break None;
|
||||
}
|
||||
}
|
||||
};
|
||||
let output = reader
|
||||
.join()
|
||||
.ok()
|
||||
.and_then(Result::ok)
|
||||
.ok_or(ToolError::Unavailable)?;
|
||||
match status {
|
||||
Some(true) => Ok(output),
|
||||
Some(false) => Err(ToolError::Failed),
|
||||
None => Err(ToolError::Unavailable),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+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);
|
||||
}
|
||||
}
|
||||
@@ -101,6 +101,41 @@ impl Core {
|
||||
info!(nodes = st.entries.len(), "hydrated metadata cache from db");
|
||||
}
|
||||
|
||||
/// Startup recovery of the queue, with this daemon as its host.
|
||||
pub(crate) fn recovery(&self) -> Recovery {
|
||||
Recovery {
|
||||
db: self.db.clone(),
|
||||
cache: self.cache.clone(),
|
||||
writes: self.writes.clone(),
|
||||
host: Arc::new(self.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What recovery needs from the rest of the daemon.
|
||||
pub(crate) trait RecoveryHost: Send + Sync {
|
||||
/// Queue a write recovered from a blob fsynced before a stop, as if its
|
||||
/// handle had just been released.
|
||||
fn queue_recovered(&self, uid: &NodeUid, blob: &Path, meta: StagedWrite) -> Result<(), Errno>;
|
||||
}
|
||||
|
||||
impl RecoveryHost for Core {
|
||||
fn queue_recovered(&self, uid: &NodeUid, blob: &Path, meta: StagedWrite) -> Result<(), Errno> {
|
||||
self.enqueue_staged_write(uid, 0, blob, meta)
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuilds the queue from the database and the staging area after a
|
||||
/// restart. Holds the database, the content cache and the write-back's state;
|
||||
/// queueing a recovered write goes through [`RecoveryHost`].
|
||||
pub(crate) struct Recovery {
|
||||
db: Arc<Db>,
|
||||
cache: Arc<ContentCache>,
|
||||
writes: writes::WriteState,
|
||||
host: Arc<dyn RecoveryHost>,
|
||||
}
|
||||
|
||||
impl Recovery {
|
||||
/// Rebuild the in-memory pending map from the `pending_op` table on mount.
|
||||
///
|
||||
/// A queued write survives a restart — that is the point of persisting it —
|
||||
@@ -109,7 +144,7 @@ impl Core {
|
||||
///
|
||||
/// A row whose blob has gone missing is dropped: there is nothing left to
|
||||
/// upload, and keeping it would fail forever.
|
||||
pub(super) fn hydrate_pending(&self) {
|
||||
pub(crate) fn hydrate_pending(&self) {
|
||||
let ops = match self.db.pending_ops() {
|
||||
Ok(ops) => ops,
|
||||
Err(e) => {
|
||||
@@ -182,7 +217,7 @@ impl Core {
|
||||
/// `local~` placeholder whose create is gone) is left in place and named in
|
||||
/// the log: unexplained bytes are never evidence that user data is
|
||||
/// disposable.
|
||||
pub(super) fn reconcile_staging(&self) {
|
||||
pub(crate) fn reconcile_staging(&self) {
|
||||
let staged = self.cache.staged_writes();
|
||||
if staged.is_empty() {
|
||||
return;
|
||||
@@ -314,7 +349,7 @@ impl Core {
|
||||
/// Failure is per-write and never fatal: a node that no longer exists, or an
|
||||
/// op that cannot be queued, leaves its blob in `recovery/` for the next run
|
||||
/// (and for a human) instead of taking the mount down.
|
||||
pub(super) fn recover_fsynced_writes(&self) {
|
||||
pub(crate) fn recover_fsynced_writes(&self) {
|
||||
let recovered = self.cache.recovered_writes();
|
||||
if recovered.is_empty() {
|
||||
return;
|
||||
@@ -338,7 +373,7 @@ impl Core {
|
||||
// size, and nothing is interned this early — `hydrate` reads the
|
||||
// size back off `pending` when the node is first looked up, so 0
|
||||
// (no such inode) is correct rather than merely tolerable.
|
||||
match self.enqueue_staged_write(&uid, 0, &blob, meta) {
|
||||
match self.host.queue_recovered(&uid, &blob, meta) {
|
||||
Ok(()) => {
|
||||
self.cache.discard_recovered(&blob);
|
||||
queued += 1;
|
||||
@@ -371,7 +406,7 @@ impl Core {
|
||||
/// content is unrecoverable and nothing will ever mint it a real uid, so
|
||||
/// leaving the row would strand a file in the tree that can be listed but
|
||||
/// never read and never uploaded.
|
||||
pub(super) fn drop_unrecoverable_op(&self, op: &PendingOp, uid: &NodeUid) {
|
||||
fn drop_unrecoverable_op(&self, op: &PendingOp, uid: &NodeUid) {
|
||||
let _ = self.db.delete_op(op.id);
|
||||
if is_local_uid(uid) {
|
||||
error!(%uid, name = op.name.as_deref().unwrap_or("?"),
|
||||
|
||||
@@ -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)
|
||||
};
|
||||
|
||||
@@ -2,7 +2,49 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Search over the database's node and home indexes. Holds the database, the
|
||||
/// content cache (to say whether a hit is on this computer), the on-demand
|
||||
/// mounts (to say which folders a hit can be opened through) and the home
|
||||
/// indexer's busy flag.
|
||||
pub(crate) struct Search {
|
||||
db: Arc<Db>,
|
||||
cache: Arc<ContentCache>,
|
||||
mounts: Arc<Mutex<mount::SecondaryMountRegistry<SecondaryMount>>>,
|
||||
indexing: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// Search, over this daemon's indexes.
|
||||
pub(crate) fn searcher(&self) -> Search {
|
||||
Search {
|
||||
db: self.db.clone(),
|
||||
cache: self.cache.clone(),
|
||||
mounts: self.mounts.clone(),
|
||||
indexing: self.indexing.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// See [`Search::roots`].
|
||||
pub(super) fn search_roots(&self) -> SearchRoots {
|
||||
self.searcher().roots()
|
||||
}
|
||||
}
|
||||
|
||||
impl Search {
|
||||
/// Whether the home indexer is walking right now.
|
||||
pub(crate) fn indexing(&self) -> bool {
|
||||
self.indexing.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// The pinned uids, expanded through pinned folders, as one query.
|
||||
fn pinned_set(&self) -> HashSet<String> {
|
||||
self.db
|
||||
.pinned_uids()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The local locations a search result can be opened through, resolved once
|
||||
/// per search rather than once per hit.
|
||||
///
|
||||
@@ -14,7 +56,7 @@ impl Core {
|
||||
/// This used to be a per-hit call that re-read the sync-folder list and ran
|
||||
/// an ancestor walk per folder, against a candidate pool of up to a
|
||||
/// thousand: the whole cost of a keystroke was in here.
|
||||
pub(super) fn search_roots(&self) -> SearchRoots {
|
||||
pub(super) fn roots(&self) -> SearchRoots {
|
||||
let live_mounts = self.mounts.lock();
|
||||
let folders = self.db.sync_folder_list().unwrap_or_default();
|
||||
SearchRoots {
|
||||
@@ -43,7 +85,7 @@ impl Core {
|
||||
.db
|
||||
.search_in(query, limit, scope)
|
||||
.map_err(|e| CoreError::from_api(&e, "search"))?;
|
||||
let roots = self.search_roots();
|
||||
let roots = self.roots();
|
||||
let pinned = self.pinned_set();
|
||||
Ok(hits
|
||||
.into_iter()
|
||||
@@ -105,7 +147,7 @@ impl Core {
|
||||
// SQLite boundary to `limit` would recreate the old empty-filter bug.
|
||||
let candidate_limit = limit.saturating_mul(10).clamp(100, 1_000);
|
||||
let mut drive_hits = if filters.sources.contains(&SearchSource::Drive) {
|
||||
let roots = self.search_roots();
|
||||
let roots = self.roots();
|
||||
let pinned = self.pinned_set();
|
||||
self.db
|
||||
.search_candidates(query, candidate_limit)
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
//! The long-lived loops a mount runs, each as a [`Service`].
|
||||
//!
|
||||
//! Each type here names its thread, says how a stop reaches it and whether the
|
||||
//! mount can do without it. `mount.rs` builds the list and starts it with
|
||||
//! [`Services::start`](pdfs_core::lifecycle::Services::start); a stop wakes and
|
||||
//! joins them in reverse order.
|
||||
|
||||
use std::os::unix::net::UnixListener;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use pdfs_core::lifecycle::{Service, Wake};
|
||||
use pdfs_core::shutdown::Shutdown;
|
||||
use pdfs_store::db::Db;
|
||||
|
||||
use super::Core;
|
||||
use super::background::run_local_index;
|
||||
use super::control::run_control_socket;
|
||||
use super::events::{EventHub, run_event_sampler};
|
||||
use super::sync;
|
||||
use super::transfers::TransferRegistry;
|
||||
|
||||
/// One of the threads that send queued changes to Drive. The drain workers wait
|
||||
/// on one condvar, which a stop has to notify; one notify wakes them all, so
|
||||
/// only the first worker carries the wake.
|
||||
pub(crate) struct DrainWorker {
|
||||
pub(crate) core: Core,
|
||||
pub(crate) index: usize,
|
||||
}
|
||||
|
||||
impl Service for DrainWorker {
|
||||
fn name(&self) -> String {
|
||||
format!("pdfs-drain-{}", self.index)
|
||||
}
|
||||
|
||||
fn wake(&self) -> Option<Wake> {
|
||||
let core = self.core.clone();
|
||||
(self.index == 0).then(|| Box::new(move || core.wake_drain()) as Wake)
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
self.core.run_pending_drain(self.index == 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder-sync engine. It watches every mirror folder, polls the remotes and
|
||||
/// reconciles on its own thread, never in front of a FUSE call. It waits on its
|
||||
/// channel, so a stop sends it `Stop`.
|
||||
///
|
||||
/// Optional: the mount still serves files without it.
|
||||
pub(crate) struct SyncEngine {
|
||||
pub(crate) syncer: sync::Syncer,
|
||||
pub(crate) tx: std::sync::mpsc::Sender<sync::SyncMsg>,
|
||||
pub(crate) rx: std::sync::mpsc::Receiver<sync::SyncMsg>,
|
||||
}
|
||||
|
||||
impl Service for SyncEngine {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-sync".to_owned()
|
||||
}
|
||||
|
||||
fn required(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn wake(&self) -> Option<Wake> {
|
||||
let tx = self.tx.clone();
|
||||
Some(Box::new(move || {
|
||||
let _ = tx.send(sync::SyncMsg::Stop);
|
||||
}))
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
let Self { syncer, rx, .. } = *self;
|
||||
sync::run(syncer, rx);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconciles leftover `(sync-conflict …)` copies: drops the ones that turned
|
||||
/// out identical to the live file and surfaces the ones that differ. It
|
||||
/// enumerates and trashes, so it must never block a FUSE call.
|
||||
pub(crate) struct ConflictSweep(pub(crate) super::sweep::Sweeper);
|
||||
|
||||
impl Service for ConflictSweep {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-conflict-sweep".to_owned()
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
self.0.run();
|
||||
}
|
||||
}
|
||||
|
||||
/// Watches the link for the life of the mount: a mount from the cache waits
|
||||
/// for the network to come back, and an online one can lose it at any moment.
|
||||
pub(crate) struct OnlineProbe(pub(crate) super::link::OnlineProbe);
|
||||
|
||||
impl Service for OnlineProbe {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-online-probe".to_owned()
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
self.0.run();
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps pinned files on this computer through changes made elsewhere, and
|
||||
/// fetches the ones a failed or missed download left out (`docs/BUGS.md`
|
||||
/// B282). A check lists folders and downloads files.
|
||||
pub(crate) struct PinKeeper(pub(crate) super::keeper::PinKeeper);
|
||||
|
||||
impl Service for PinKeeper {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-pin-keeper".to_owned()
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
self.0.run();
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps the launcher prompt's "This computer" index fresh. The walk is
|
||||
/// I/O-heavy and must never sit in front of a FUSE callback.
|
||||
pub(crate) struct LocalIndex {
|
||||
pub(crate) db: Arc<Db>,
|
||||
pub(crate) indexing: Arc<AtomicBool>,
|
||||
pub(crate) transfers: Arc<TransferRegistry>,
|
||||
pub(crate) mountpoint: PathBuf,
|
||||
pub(crate) shutdown: Arc<Shutdown>,
|
||||
}
|
||||
|
||||
impl Service for LocalIndex {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-localindex".to_owned()
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
let Self {
|
||||
db,
|
||||
indexing,
|
||||
transfers,
|
||||
mountpoint,
|
||||
shutdown,
|
||||
} = *self;
|
||||
run_local_index(db, indexing, transfers, mountpoint, shutdown);
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers the control socket, one job per connection.
|
||||
///
|
||||
/// The listener blocks in `accept`, which only returns when a connection
|
||||
/// arrives, so a stop connects to it. It connects while the socket still
|
||||
/// exists, which is the point of the poke, then unlinks it so nothing else can
|
||||
/// arrive behind it. The listener checks the stop flag after every accept, so
|
||||
/// a connection that races the unlink cannot put it back to sleep. The
|
||||
/// connections it handed off are jobs, which a stop joins; a subscription
|
||||
/// among them waits on its mailbox, so the wake rings every mailbox too.
|
||||
pub(crate) struct ControlListener {
|
||||
pub(crate) core: Core,
|
||||
pub(crate) username: String,
|
||||
pub(crate) mountpoint: PathBuf,
|
||||
pub(crate) listener: UnixListener,
|
||||
pub(crate) socket: PathBuf,
|
||||
}
|
||||
|
||||
impl Service for ControlListener {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-control".to_owned()
|
||||
}
|
||||
|
||||
fn wake(&self) -> Option<Wake> {
|
||||
let socket = self.socket.clone();
|
||||
let events: Arc<EventHub> = self.core.events.clone();
|
||||
Some(Box::new(move || {
|
||||
let _ = std::os::unix::net::UnixStream::connect(&socket);
|
||||
let _ = std::fs::remove_file(&socket);
|
||||
events.wake_all();
|
||||
}))
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
let Self {
|
||||
core,
|
||||
username,
|
||||
mountpoint,
|
||||
listener,
|
||||
..
|
||||
} = *self;
|
||||
run_control_socket(core, username, mountpoint, listener);
|
||||
}
|
||||
}
|
||||
|
||||
/// Publishes what changes without one place to publish it from (status,
|
||||
/// transfers, sync progress) to the front ends subscribed on the control
|
||||
/// socket.
|
||||
///
|
||||
/// Optional: front ends still get every published change, only not the
|
||||
/// sampled ones.
|
||||
pub(crate) struct EventSampler {
|
||||
pub(crate) core: Core,
|
||||
pub(crate) username: String,
|
||||
pub(crate) mountpoint: PathBuf,
|
||||
}
|
||||
|
||||
impl Service for EventSampler {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-events".to_owned()
|
||||
}
|
||||
|
||||
fn required(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
run_event_sampler(self.core, self.username, self.mountpoint);
|
||||
}
|
||||
}
|
||||
|
||||
/// Watches the worker pool and answers the systemd watchdog. Its liveness
|
||||
/// probe is a round trip over the control socket, so it starts after the
|
||||
/// listener.
|
||||
///
|
||||
/// Optional: the mount works without it, only it is no longer diagnosable if
|
||||
/// it wedges.
|
||||
pub(crate) struct Supervisor {
|
||||
pub(crate) core: Core,
|
||||
pub(crate) socket: PathBuf,
|
||||
}
|
||||
|
||||
impl Service for Supervisor {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-supervisor".to_owned()
|
||||
}
|
||||
|
||||
fn required(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
super::supervisor::run(self.core, self.socket);
|
||||
}
|
||||
}
|
||||
|
||||
/// Holds off a shutdown while changes exist only here (B66).
|
||||
///
|
||||
/// Optional: without it a shutdown is not delayed, and queued changes go out
|
||||
/// on the next start.
|
||||
pub(crate) struct Inhibitor {
|
||||
pub(crate) db: Arc<Db>,
|
||||
pub(crate) shutdown: Arc<Shutdown>,
|
||||
}
|
||||
|
||||
impl Service for Inhibitor {
|
||||
fn name(&self) -> String {
|
||||
"pdfs-inhibit".to_owned()
|
||||
}
|
||||
|
||||
fn required(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn run(self: Box<Self>) {
|
||||
super::inhibit::run(&self.db, &self.shutdown);
|
||||
}
|
||||
}
|
||||
@@ -883,10 +883,16 @@ mod tests {
|
||||
|
||||
daemon.client.set_online(false);
|
||||
std::fs::write(daemon.mountpoint.join("f.txt"), b"0123456789").unwrap();
|
||||
// Usually the drain meets the outage first. Another caller (the event
|
||||
// poll, a sync pass) can meet it first and take the mount offline,
|
||||
// and then the drain claims nothing and the write has no failed
|
||||
// attempt to wait out. Both must end with the write going out soon
|
||||
// after the link returns.
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
daemon
|
||||
.pending()
|
||||
.is_ok_and(|items| items.iter().any(|item| item.attempts > 0))
|
||||
|| daemon.online().is_ok_and(|online| !online)
|
||||
}));
|
||||
// The drain records the failure just before it takes the mount
|
||||
// offline. Left online, only the event poll would, much later.
|
||||
|
||||
@@ -165,9 +165,9 @@ impl Core {
|
||||
return;
|
||||
}
|
||||
let queue = self.sizes.size_waiters.clone();
|
||||
if let Err(error) = std::thread::Builder::new()
|
||||
.name("pdfs-size-waiters".into())
|
||||
.spawn(move || queue.serve())
|
||||
if let Err(error) = self
|
||||
.services
|
||||
.spawn_job("pdfs-size-waiters", move || queue.serve())
|
||||
{
|
||||
// Without a thread nothing would ever answer these. A provisional
|
||||
// size is wrong; a `stat` that never returns wedges the caller.
|
||||
@@ -190,6 +190,11 @@ impl Core {
|
||||
let (mut key, mut uids, mut slot) = (key, uids, slot);
|
||||
loop {
|
||||
for chunk in uids.chunks(SIZE_UPGRADE_CHUNK) {
|
||||
// A stop joins this job; the rest of the folder can wait for
|
||||
// the next mount, which lists it afresh.
|
||||
if self.shutdown.is_stopping() {
|
||||
break;
|
||||
}
|
||||
let result =
|
||||
self.block_on_within(BATCH_CALL_TIMEOUT, self.drive.enumerate_nodes(chunk));
|
||||
self.apply_size_upgrade(key, result);
|
||||
@@ -327,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 {
|
||||
|
||||
+117
-43
@@ -30,6 +30,10 @@ use pdfs_core::control::ActivityKind;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use pdfs_core::shutdown::Shutdown;
|
||||
use pdfs_drive::DriveApi;
|
||||
use pdfs_store::db::Db;
|
||||
|
||||
use super::{Core, node_content_sha1, node_revision_id, node_size};
|
||||
|
||||
/// What the conflict sweep may do, and the copies it already checked this
|
||||
@@ -44,7 +48,7 @@ pub(crate) struct SweepState {
|
||||
/// Conflict copies the sweep has already checked against the activity log
|
||||
/// this run, so each pass does not ask the database again. The log itself
|
||||
/// is what keeps a copy from being flagged again after a restart. See
|
||||
/// [`Core::run_conflict_sweep_loop`] and `docs/BUGS.md` B99.
|
||||
/// [`Sweeper::run`] and `docs/BUGS.md` B99.
|
||||
pub(crate) conflict_notified: Arc<Mutex<HashSet<NodeUid>>>,
|
||||
}
|
||||
|
||||
@@ -107,17 +111,113 @@ pub(crate) fn conflict_base_name(name: &str) -> Option<String> {
|
||||
Some(base)
|
||||
}
|
||||
|
||||
/// What the conflict sweep needs from the rest of the daemon: the tree of
|
||||
/// every mount and the activity feed.
|
||||
pub(crate) trait SweepHost: Send + Sync {
|
||||
/// Whether `uid` is on this account's own volume, or a virtual node.
|
||||
fn is_own_or_virtual(&self, uid: &NodeUid) -> bool;
|
||||
/// Whether the mount believes Drive is reachable.
|
||||
fn is_online(&self) -> bool;
|
||||
/// Whether a node is being written or held open in any mount.
|
||||
fn is_busy(&self, uid: &NodeUid) -> bool;
|
||||
/// For one pass: whether the conflict listing can show a copy.
|
||||
fn conflict_locator(&self) -> Box<dyn Fn(&NodeUid) -> bool + '_>;
|
||||
/// Unhook a node Drive no longer has from every mount, and drop its
|
||||
/// cached content and open readers.
|
||||
fn forget(&self, uid: &NodeUid);
|
||||
fn log_activity(&self, kind: ActivityKind, target: &str, detail: String, ok: bool);
|
||||
}
|
||||
|
||||
impl SweepHost for Core {
|
||||
fn is_own_or_virtual(&self, uid: &NodeUid) -> bool {
|
||||
Core::is_own_or_virtual(self, uid)
|
||||
}
|
||||
|
||||
fn is_online(&self) -> bool {
|
||||
Core::is_online(self)
|
||||
}
|
||||
|
||||
fn is_busy(&self, uid: &NodeUid) -> bool {
|
||||
Core::is_busy(self, uid)
|
||||
}
|
||||
|
||||
fn conflict_locator(&self) -> Box<dyn Fn(&NodeUid) -> bool + '_> {
|
||||
let roots = Core::search_roots(self);
|
||||
Box::new(move |uid| self.conflict_path(&roots, uid).is_some())
|
||||
}
|
||||
|
||||
fn forget(&self, uid: &NodeUid) {
|
||||
// Leaving a conflict copy hooked up in the tree keeps a node we have
|
||||
// just trashed remotely visible and readable in whichever mount shows
|
||||
// it (`docs/BUGS.md` B74).
|
||||
self.for_each_state(|st| {
|
||||
st.forget_or_unlink(uid);
|
||||
});
|
||||
self.cache.evict(uid);
|
||||
self.evict_reader(uid);
|
||||
}
|
||||
|
||||
fn log_activity(&self, kind: ActivityKind, target: &str, detail: String, ok: bool) {
|
||||
Core::log_activity(self, kind, target, detail, ok);
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// The conflict sweep, with this daemon as its host.
|
||||
pub(crate) fn sweeper(&self) -> Sweeper {
|
||||
Sweeper {
|
||||
drive: self.drive.clone(),
|
||||
rt: self.rt.clone(),
|
||||
db: self.db.clone(),
|
||||
shutdown: self.shutdown.clone(),
|
||||
state: self.sweep.clone(),
|
||||
host: Arc::new(self.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a node has a write in flight or a file handle open against it.
|
||||
/// Read-only opens use fh 0 and are not tracked, so this is specifically the
|
||||
/// writer/holder check.
|
||||
/// Asked across **every** mount. The sweep runs on the primary Core but
|
||||
/// trashes nodes anywhere in the tree, and a file open inside a sync folder
|
||||
/// is tracked in that fork's `State` — so consulting `self.state` alone
|
||||
/// answered "idle" for every such file and let the sweep delete one with a
|
||||
/// writer attached (`docs/BUGS.md` B74). Busy anywhere means busy.
|
||||
pub(crate) fn is_busy(&self, uid: &NodeUid) -> bool {
|
||||
let mut busy = false;
|
||||
self.for_each_state(|st| {
|
||||
let Some(&ino) = st.by_uid.get(uid) else {
|
||||
return;
|
||||
};
|
||||
busy |= st.open.is_busy(ino);
|
||||
});
|
||||
busy
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconciles leftover conflict copies (the module documentation says how).
|
||||
/// Holds Drive, the runtime, the database, the stop signal and its own state;
|
||||
/// it reaches the mounts through [`SweepHost`].
|
||||
pub(crate) struct Sweeper {
|
||||
drive: Arc<dyn DriveApi>,
|
||||
rt: tokio::runtime::Handle,
|
||||
db: Arc<Db>,
|
||||
shutdown: Arc<Shutdown>,
|
||||
state: SweepState,
|
||||
host: Arc<dyn SweepHost>,
|
||||
}
|
||||
|
||||
impl Sweeper {
|
||||
/// Sweep for stale conflict copies forever, on its own thread. See the module
|
||||
/// docs for the identical/divergent policy.
|
||||
pub(crate) fn run_conflict_sweep_loop(&self) {
|
||||
pub(crate) fn run(&self) {
|
||||
// Both waits are interruptible, so teardown does not have to sit out a
|
||||
// five-minute interval to join this thread (`docs/BUGS.md` B44).
|
||||
if !self.shutdown.sleep(CONFLICT_SWEEP_WARMUP) {
|
||||
return;
|
||||
}
|
||||
loop {
|
||||
self.sweep_conflicts_once();
|
||||
self.sweep_once();
|
||||
if !self.shutdown.sleep(CONFLICT_SWEEP_INTERVAL) {
|
||||
return;
|
||||
}
|
||||
@@ -125,7 +225,7 @@ impl Core {
|
||||
}
|
||||
|
||||
/// One sweep pass over every node the daemon currently knows.
|
||||
fn sweep_conflicts_once(&self) {
|
||||
fn sweep_once(&self) {
|
||||
let stored = match self.db.load_all() {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
@@ -136,7 +236,7 @@ impl Core {
|
||||
let nodes: Vec<_> = stored
|
||||
.into_iter()
|
||||
.map(|stored| stored.node)
|
||||
.filter(|node| self.is_own_or_virtual(&node.uid))
|
||||
.filter(|node| self.host.is_own_or_virtual(&node.uid))
|
||||
.collect();
|
||||
|
||||
// Index live (non-trashed) files by (parent, name) for sibling lookup.
|
||||
@@ -153,8 +253,8 @@ impl Core {
|
||||
by_parent_name.insert((parent, node.name.as_str()), node);
|
||||
}
|
||||
|
||||
let roots = self.search_roots();
|
||||
let online = self.is_online();
|
||||
let listed = self.host.conflict_locator();
|
||||
let online = self.host.is_online();
|
||||
for node in &nodes {
|
||||
if node.trashed || node.is_folder() {
|
||||
continue;
|
||||
@@ -169,7 +269,7 @@ impl Core {
|
||||
.unwrap_or_default();
|
||||
let sibling = by_parent_name.get(&(parent, base.as_str())).copied();
|
||||
|
||||
match decide(node, sibling, &base, self.sweep.sweep_mode) {
|
||||
match decide(node, sibling, &base, self.state.sweep_mode) {
|
||||
SweepAction::Remove => {
|
||||
// Only while online — the remote trash is the point. Offline,
|
||||
// it waits for a later pass.
|
||||
@@ -181,7 +281,7 @@ impl Core {
|
||||
// would sit in the feed as "resolved" with no way to act on
|
||||
// it (`docs/BUGS.md` B99).
|
||||
SweepAction::Flag(detail) => {
|
||||
if self.conflict_path(&roots, &node.uid).is_some() {
|
||||
if listed(&node.uid) {
|
||||
self.flag_conflict(&node.uid, &node.name, detail);
|
||||
} else {
|
||||
debug!(uid = %node.uid, name = %node.name, "conflict sweep: copy is outside every location; not flagged");
|
||||
@@ -219,12 +319,7 @@ impl Core {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Leaving a conflict copy hooked up in the tree keeps a node we have
|
||||
// just trashed remotely visible and readable in whichever mount shows
|
||||
// it (`docs/BUGS.md` B74).
|
||||
self.for_each_state(|st| {
|
||||
st.forget_or_unlink(uid);
|
||||
});
|
||||
self.host.forget(uid);
|
||||
// Deliberately *not* `discard_queued_ops`: `duplicate_still_removable`
|
||||
// proved the queue empty before the trash above, but that proof is stale
|
||||
// the moment `trash_nodes` goes to the network. A `close(2)` landing in
|
||||
@@ -232,14 +327,12 @@ impl Core {
|
||||
// blob holding the only copy of them. Leaving the op queued is the
|
||||
// non-destructive outcome: the drain re-reads the node, sees it trashed,
|
||||
// and `revision_conflict` routes it to `keep_as_conflict_copy`.
|
||||
self.cache.evict(uid);
|
||||
self.evict_reader(uid);
|
||||
if let Err(e) = self.db.delete_node(uid) {
|
||||
warn!(%uid, error = ?e, "conflict sweep: db delete after trash failed");
|
||||
}
|
||||
self.invalidate_trash();
|
||||
self.sweep.conflict_notified.lock().remove(uid);
|
||||
self.log_activity(
|
||||
super::trash::invalidate_trash(&self.db);
|
||||
self.state.conflict_notified.lock().remove(uid);
|
||||
self.host.log_activity(
|
||||
ActivityKind::Trash,
|
||||
name,
|
||||
format!("auto-removed duplicate of {base}"),
|
||||
@@ -273,7 +366,7 @@ impl Core {
|
||||
|
||||
// Someone is writing to it, or holds it open. Trashing now would pull the
|
||||
// node out from under a live handle.
|
||||
if self.is_busy(uid) {
|
||||
if self.host.is_busy(uid) {
|
||||
debug!(%uid, name, "conflict sweep: skipping duplicate that is open or being written");
|
||||
return false;
|
||||
}
|
||||
@@ -306,32 +399,12 @@ impl Core {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a node has a write in flight or a file handle open against it.
|
||||
/// Read-only opens use fh 0 and are not tracked, so this is specifically the
|
||||
/// writer/holder check.
|
||||
/// Asked across **every** mount. The sweep runs on the primary Core but
|
||||
/// trashes nodes anywhere in the tree, and a file open inside a sync folder
|
||||
/// is tracked in that fork's `State` — so consulting `self.state` alone
|
||||
/// answered "idle" for every such file and let the sweep delete one with a
|
||||
/// writer attached (`docs/BUGS.md` B74). Busy anywhere means busy.
|
||||
pub(crate) fn is_busy(&self, uid: &NodeUid) -> bool {
|
||||
let mut busy = false;
|
||||
self.for_each_state(|st| {
|
||||
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
|
||||
}
|
||||
|
||||
/// Surface a conflict copy that needs the user's attention, once. The
|
||||
/// in-memory set spares the database each pass; the activity log itself is
|
||||
/// what keeps a restart from logging the same copy again (`docs/BUGS.md`
|
||||
/// B99). A copy's name carries its own timestamp, so the name identifies it.
|
||||
fn flag_conflict(&self, uid: &NodeUid, name: &str, detail: String) {
|
||||
if !self.sweep.conflict_notified.lock().insert(uid.clone()) {
|
||||
if !self.state.conflict_notified.lock().insert(uid.clone()) {
|
||||
return;
|
||||
}
|
||||
match self.db.activity_has(ActivityKind::Conflict, name) {
|
||||
@@ -342,7 +415,8 @@ impl Core {
|
||||
Err(e) => warn!(%uid, name, error = ?e, "conflict sweep: activity check failed"),
|
||||
}
|
||||
debug!(%uid, name, detail, "conflict sweep: flagged divergent conflict copy");
|
||||
self.log_activity(ActivityKind::Conflict, name, detail, false);
|
||||
self.host
|
||||
.log_activity(ActivityKind::Conflict, name, detail, false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -685,6 +685,6 @@ pub(super) fn expand_restore(
|
||||
|
||||
/// Mark the stored trash listing stale, so the next listing waits for a
|
||||
/// fresh one.
|
||||
fn invalidate_trash(db: &Db) {
|
||||
pub(crate) fn invalidate_trash(db: &Db) {
|
||||
let _ = db.clear_state(TRASH_SYNCED_MS);
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
//! 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
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
//! 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; and what the mount accepted but has not sent to Drive yet
|
||||
//! ([`writes`]).
|
||||
|
||||
pub mod ids;
|
||||
pub mod open;
|
||||
pub mod tree;
|
||||
pub mod writes;
|
||||
@@ -0,0 +1,967 @@
|
||||
//! A file open for writing, and a released write waiting for its upload.
|
||||
//!
|
||||
//! Authored bytes go to a scratch file on disk, not to memory. [`Intervals`]
|
||||
//! says which bytes of it were written here; the rest of the file still comes
|
||||
//! from the remote base. On release the handle becomes a [`PendingRevision`]:
|
||||
//! the staged blob and what its gaps refer to.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::os::unix::fs::FileExt;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use pdfs_drive::{node_revision_id, node_size};
|
||||
use pdfs_store::cache::StagedWrite;
|
||||
use proton_drive_rs::Node;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
|
||||
/// A set of non-overlapping `[start, end)` byte ranges, kept sorted and merged.
|
||||
/// Tracks which bytes of a [`WriteHandle`]'s scratch file were authored locally
|
||||
/// (vs. still living only in the remote base), so reads and the commit gap-fill
|
||||
/// know which regions to pull from the network.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Intervals(pub Vec<(u64, u64)>);
|
||||
|
||||
impl Intervals {
|
||||
/// Mark `[start, end)` as authored, coalescing with any touching ranges.
|
||||
pub fn add(&mut self, start: u64, end: u64) {
|
||||
if start >= end {
|
||||
return;
|
||||
}
|
||||
self.0.push((start, end));
|
||||
self.0.sort_by_key(|&(s, _)| s);
|
||||
let mut merged: Vec<(u64, u64)> = Vec::with_capacity(self.0.len());
|
||||
for &(s, e) in &self.0 {
|
||||
match merged.last_mut() {
|
||||
Some(last) if s <= last.1 => last.1 = last.1.max(e),
|
||||
_ => merged.push((s, e)),
|
||||
}
|
||||
}
|
||||
self.0 = merged;
|
||||
}
|
||||
|
||||
/// Drop everything at or beyond `len` (a shrink/truncate).
|
||||
pub fn clip(&mut self, len: u64) {
|
||||
self.0.retain(|&(s, _)| s < len);
|
||||
for iv in &mut self.0 {
|
||||
iv.1 = iv.1.min(len);
|
||||
}
|
||||
}
|
||||
|
||||
/// Split `[start, end)` into contiguous `(s, e, authored)` segments, in
|
||||
/// order. `authored == true` means the bytes live in the scratch file;
|
||||
/// `false` means they must come from the remote base (or are a hole).
|
||||
pub fn segments(&self, start: u64, end: u64) -> Vec<(u64, u64, bool)> {
|
||||
let mut out = Vec::new();
|
||||
let mut pos = start;
|
||||
for &(s, e) in &self.0 {
|
||||
if e <= start {
|
||||
continue;
|
||||
}
|
||||
if s >= end {
|
||||
break;
|
||||
}
|
||||
let ws = s.max(start);
|
||||
let we = e.min(end);
|
||||
if pos < ws {
|
||||
out.push((pos, ws, false));
|
||||
}
|
||||
out.push((ws, we, true));
|
||||
pos = we;
|
||||
}
|
||||
if pos < end {
|
||||
out.push((pos, end, false));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// State for a file opened for writing. Authored bytes are staged in an on-disk
|
||||
/// scratch file (positional reads/writes) rather than RAM, so a multi-GiB write
|
||||
/// never balloons the daemon. On flush/release the scratch file — gap-filled
|
||||
/// from the remote base where untouched — is streamed up as one new revision,
|
||||
/// since the SDK seals whole revisions rather than byte ranges.
|
||||
pub struct WriteHandle {
|
||||
pub ino: u64,
|
||||
pub uid: NodeUid,
|
||||
/// Disk-backed staging buffer. Shared (`Arc`) so reads can use it without
|
||||
/// holding the state lock across I/O. Accessed positionally (`read_at`/
|
||||
/// `write_at`), so a clone never disturbs another's file offset.
|
||||
pub file: Arc<File>,
|
||||
/// Scratch file path, removed on release.
|
||||
pub path: PathBuf,
|
||||
/// Byte ranges authored into `file`. Everything else in `[0, len)` is base.
|
||||
pub written: Intervals,
|
||||
/// Logical file size (may exceed authored bytes after a truncate-extend).
|
||||
pub len: u64,
|
||||
/// Size of the remote base at open, for serving untouched ranges.
|
||||
pub base_size: u64,
|
||||
/// Modification time of the remote base at open, validating its block cache.
|
||||
pub base_mtime: i64,
|
||||
/// Server revision id of the remote base at open, if it had one. This is the
|
||||
/// stable identity the drain conflict-checks against: `base_mtime` alone
|
||||
/// drifts when the server re-stamps the *same* revision, which reads as a
|
||||
/// spurious conflict (see B16/B25). `None` for a file with no sealed remote
|
||||
/// revision, or one read through a surface that does not carry the id.
|
||||
pub base_revision_id: Option<String>,
|
||||
/// Whether anything diverged from the remote and needs an upload.
|
||||
pub dirty: bool,
|
||||
/// Number of file handles currently sharing this scratch state.
|
||||
pub open_count: usize,
|
||||
}
|
||||
|
||||
impl WriteHandle {
|
||||
/// A handle on a file `create` just made: an empty base, so everything
|
||||
/// written through it is authored.
|
||||
///
|
||||
/// The base is `node` as it actually exists — the empty file the server just
|
||||
/// minted, or a queued create's placeholder — never the local clock or a
|
||||
/// blank. `queue_revision` turns it into `StagedWrite::based_on` and the
|
||||
/// drain compares the remote against that. A `now_secs()` mtime differs from
|
||||
/// the server's stamp by the create round-trip. A missing revision id drops
|
||||
/// the check to `(mtime, size)`, and moving or renaming the file advances
|
||||
/// its mtime on the server. Either way the first write to a brand-new file
|
||||
/// lands as a conflict copy of its own empty create (`docs/BUGS.md` B113).
|
||||
pub fn created(ino: u64, node: &Node, file: File, path: PathBuf) -> Self {
|
||||
Self {
|
||||
ino,
|
||||
uid: node.uid.clone(),
|
||||
file: Arc::new(file),
|
||||
path,
|
||||
written: Intervals::default(),
|
||||
len: 0,
|
||||
base_size: 0,
|
||||
base_mtime: node.modification_time,
|
||||
base_revision_id: node_revision_id(node),
|
||||
dirty: false,
|
||||
open_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Write over `node` from now on: a revision this daemon has just put on the
|
||||
/// server under the handle, by sealing an upload or by landing the queued
|
||||
/// create the handle was opened on. The base the handle opened over is gone,
|
||||
/// and keeping it would make the drain read our own revision as another
|
||||
/// device's edit.
|
||||
pub fn rebase_onto(&mut self, node: &Node) {
|
||||
self.base_mtime = node.modification_time;
|
||||
self.base_size = node_size(node);
|
||||
self.base_revision_id = node_revision_id(node);
|
||||
}
|
||||
|
||||
/// Resize the file to `size`, as `setattr` does through an open handle.
|
||||
///
|
||||
/// The scratch file goes first: a resize it refuses (a full disk on a
|
||||
/// grow) fails with nothing recorded. Otherwise the length and the
|
||||
/// authored ranges would describe bytes the scratch file does not hold,
|
||||
/// and the call would have succeeded.
|
||||
pub fn resize(&mut self, size: u64) -> std::io::Result<()> {
|
||||
self.file.set_len(size)?;
|
||||
if size < self.len {
|
||||
// Shrink: drop authored ranges past the new end.
|
||||
self.written.clip(size);
|
||||
} else if size > self.len {
|
||||
// Grow: the new tail is defined as zeros, so claim it as authored
|
||||
// rather than base content.
|
||||
self.written.add(self.len, size);
|
||||
}
|
||||
self.len = size;
|
||||
self.dirty = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record an `fallocate` of `[offset, end)` that the scratch file took.
|
||||
/// Zeroed or punched bytes read as zero, so they count as written: left
|
||||
/// unwritten, the commit refilled them from the remote base and undid
|
||||
/// them. Returns the new length if the file grew.
|
||||
pub fn record_fallocate(&mut self, kind: Fallocate, offset: u64, end: u64) -> Option<u64> {
|
||||
let (written, grown) = kind.effect(offset, end, self.len);
|
||||
if let Some((from, to)) = written {
|
||||
self.written.add(from, to);
|
||||
self.dirty = true;
|
||||
}
|
||||
if let Some(end) = grown {
|
||||
self.len = end;
|
||||
self.dirty = true;
|
||||
}
|
||||
grown
|
||||
}
|
||||
|
||||
/// What a read needs of this handle, copied out so no lock is held
|
||||
/// across the read.
|
||||
pub fn read_view(&self) -> ReadView {
|
||||
ReadView {
|
||||
file: self.file.clone(),
|
||||
len: self.len,
|
||||
uid: self.uid.clone(),
|
||||
base_mtime: self.base_mtime,
|
||||
base_size: self.base_size,
|
||||
written: self.written.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Account for `[offset, end)` having been written through this handle.
|
||||
///
|
||||
/// A write past the end leaves a hole that reads as zeros, exactly like a
|
||||
/// grow through `setattr`, so the hole is authored too. Left unauthored, a
|
||||
/// hole below the base size was refilled from the base at commit: a file
|
||||
/// shrunk and then written past its new end got its old bytes back.
|
||||
pub fn record_write(&mut self, offset: u64, end: u64) {
|
||||
if offset > self.len {
|
||||
self.written.add(self.len, offset);
|
||||
}
|
||||
self.written.add(offset, end);
|
||||
self.len = self.len.max(end);
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// The files open through one tree: write handles by inode, file handles
|
||||
/// by `fh`, and the inodes whose last handle is being released.
|
||||
///
|
||||
/// One `fh` counter serves file and directory handles, so the two never
|
||||
/// collide in the kernel's one space of handle numbers.
|
||||
pub struct OpenFiles {
|
||||
/// Write state by inode. Concurrent writers share the scratch file.
|
||||
writes: HashMap<u64, WriteHandle>,
|
||||
/// Inodes whose last write handle a release has taken out of
|
||||
/// [`OpenFiles::writes`] and is still queueing, with a read view of what
|
||||
/// they held. `close(2)` returns before the queueing ends, and in between
|
||||
/// the edit is in neither the handles nor the queue. A check for changes
|
||||
/// not on Drive yet looks here, and so does a read: without the view, a
|
||||
/// read on a worker in that window was served Drive's older revision.
|
||||
retiring: HashMap<u64, ReadView>,
|
||||
/// The inode each write `fh` is open on. Read-only opens use `fh` 0 and
|
||||
/// have no entry.
|
||||
handles: HashMap<u64, u64>,
|
||||
/// One frozen listing per open directory handle, taken at `opendir`.
|
||||
///
|
||||
/// `readdir` resumes from an offset into the listing it is walking, so
|
||||
/// that listing has to stay the same across the calls of one `getdents`
|
||||
/// sequence. Rebuilt live, a create or a trash landing between two pages
|
||||
/// shifted every later entry, and the caller silently skipped or repeated
|
||||
/// whatever crossed the page boundary (`docs/BUGS.md` B43).
|
||||
dirs: HashMap<u64, Arc<DirListing>>,
|
||||
next_fh: u64,
|
||||
}
|
||||
|
||||
/// One directory's entries as `readdir` reports them: `(ino, is_dir, name)`
|
||||
/// per entry, in reply order, starting with `.` and `..`.
|
||||
pub type DirListing = Vec<(u64, bool, String)>;
|
||||
|
||||
/// The entries of `listing` a `readdir` at `offset` replies with, each with
|
||||
/// the offset that resumes after it.
|
||||
pub fn dir_page(
|
||||
listing: &DirListing,
|
||||
offset: u64,
|
||||
) -> impl Iterator<Item = (u64, &(u64, bool, String))> {
|
||||
listing
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(offset as usize)
|
||||
.map(|(i, entry)| ((i + 1) as u64, entry))
|
||||
}
|
||||
|
||||
impl Default for OpenFiles {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
writes: HashMap::new(),
|
||||
retiring: HashMap::new(),
|
||||
handles: HashMap::new(),
|
||||
dirs: HashMap::new(),
|
||||
next_fh: 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a release of one file handle left behind.
|
||||
pub enum Released {
|
||||
/// The handle was not a write handle, or was already gone.
|
||||
NotWriting,
|
||||
/// Other handles still share the inode's write state.
|
||||
StillOpen { ino: u64 },
|
||||
/// The last handle: the write state, now the caller's to queue. The inode
|
||||
/// stays [releasing](OpenFiles::owed) until
|
||||
/// [`OpenFiles::finish_release`].
|
||||
Last(WriteHandle),
|
||||
}
|
||||
|
||||
impl OpenFiles {
|
||||
/// A new handle number, for a file or a directory.
|
||||
pub fn next_fh(&mut self) -> u64 {
|
||||
let fh = self.next_fh;
|
||||
self.next_fh += 1;
|
||||
fh
|
||||
}
|
||||
|
||||
/// Open a directory handle on a snapshot of its listing. Returns the
|
||||
/// handle number.
|
||||
pub fn open_dir(&mut self, listing: DirListing) -> u64 {
|
||||
let fh = self.next_fh();
|
||||
self.dirs.insert(fh, Arc::new(listing));
|
||||
fh
|
||||
}
|
||||
|
||||
/// The listing directory handle `fh` was opened on.
|
||||
pub fn dir(&self, fh: u64) -> Option<Arc<DirListing>> {
|
||||
self.dirs.get(&fh).cloned()
|
||||
}
|
||||
|
||||
/// Close directory handle `fh`.
|
||||
pub fn close_dir(&mut self, fh: u64) {
|
||||
self.dirs.remove(&fh);
|
||||
}
|
||||
|
||||
/// Open a write handle on `ino`: share the inode's write state, or start
|
||||
/// it with `start`. Returns the handle number.
|
||||
pub fn open_writer(&mut self, ino: u64, start: impl FnOnce() -> WriteHandle) -> u64 {
|
||||
let fh = self.next_fh();
|
||||
self.writes.entry(ino).or_insert_with(start).open_count += 1;
|
||||
self.handles.insert(fh, ino);
|
||||
fh
|
||||
}
|
||||
|
||||
/// The write state of `ino`, if a handle has it open for writing.
|
||||
pub fn writer(&self, ino: u64) -> Option<&WriteHandle> {
|
||||
self.writes.get(&ino)
|
||||
}
|
||||
|
||||
pub fn writer_mut(&mut self, ino: u64) -> Option<&mut WriteHandle> {
|
||||
self.writes.get_mut(&ino)
|
||||
}
|
||||
|
||||
/// What a read of `ino` serves from instead of Drive: an open writer's
|
||||
/// scratch file, or one a release is still queueing.
|
||||
pub fn reader(&self, ino: u64) -> Option<ReadView> {
|
||||
match self.writes.get(&ino) {
|
||||
Some(writer) => Some(writer.read_view()),
|
||||
None => self.retiring.get(&ino).cloned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The inode write handle `fh` is open on.
|
||||
pub fn ino_of(&self, fh: u64) -> Option<u64> {
|
||||
self.handles.get(&fh).copied()
|
||||
}
|
||||
|
||||
/// The write state behind file handle `fh`.
|
||||
pub fn by_fh(&self, fh: u64) -> Option<&WriteHandle> {
|
||||
self.writes.get(&self.ino_of(fh)?)
|
||||
}
|
||||
|
||||
pub fn by_fh_mut(&mut self, fh: u64) -> Option<&mut WriteHandle> {
|
||||
let ino = self.ino_of(fh)?;
|
||||
self.writes.get_mut(&ino)
|
||||
}
|
||||
|
||||
/// Whether `ino` is open for writing.
|
||||
pub fn is_writing(&self, ino: u64) -> bool {
|
||||
self.writes.contains_key(&ino)
|
||||
}
|
||||
|
||||
/// Whether `ino` is being written or held by a write handle.
|
||||
pub fn is_busy(&self, ino: u64) -> bool {
|
||||
self.is_writing(ino) || self.handles.values().any(|&held| held == ino)
|
||||
}
|
||||
|
||||
/// Every inode with changes that may not be queued yet: open for writing,
|
||||
/// or released and still queueing. `dirty_only` leaves out write handles
|
||||
/// that changed nothing.
|
||||
pub fn owed(&self, dirty_only: bool) -> impl Iterator<Item = u64> + '_ {
|
||||
self.writes
|
||||
.iter()
|
||||
.filter(move |(_, w)| !dirty_only || w.dirty)
|
||||
.map(|(&ino, _)| ino)
|
||||
.chain(self.retiring.keys().copied())
|
||||
}
|
||||
|
||||
/// Every write state, to rebase or inspect in place.
|
||||
pub fn writers_mut(&mut self) -> impl Iterator<Item = &mut WriteHandle> {
|
||||
self.writes.values_mut()
|
||||
}
|
||||
|
||||
/// Release file handle `fh`. On the last handle of an inode, the write
|
||||
/// state is handed back and the inode is marked as releasing.
|
||||
pub fn release(&mut self, fh: u64) -> Released {
|
||||
let Some(ino) = self.handles.remove(&fh) else {
|
||||
return Released::NotWriting;
|
||||
};
|
||||
let Some(writer) = self.writes.get_mut(&ino) else {
|
||||
return Released::NotWriting;
|
||||
};
|
||||
writer.open_count = writer.open_count.saturating_sub(1);
|
||||
if writer.open_count > 0 {
|
||||
return Released::StillOpen { ino };
|
||||
}
|
||||
let writer = self.writes.remove(&ino).expect("looked up above");
|
||||
self.retiring.insert(ino, writer.read_view());
|
||||
Released::Last(writer)
|
||||
}
|
||||
|
||||
/// The release of `ino` has queued what it wrote.
|
||||
pub fn finish_release(&mut self, ino: u64) {
|
||||
self.retiring.remove(&ino);
|
||||
}
|
||||
|
||||
/// Take every write state, for a stop that queues what open handles
|
||||
/// wrote. Forgets every handle.
|
||||
pub fn take_all(&mut self) -> Vec<WriteHandle> {
|
||||
self.handles.clear();
|
||||
self.writes.drain().map(|(_, writer)| writer).collect()
|
||||
}
|
||||
|
||||
/// Put write state in place directly, for tests that build a tree.
|
||||
pub fn insert_writer(&mut self, writer: WriteHandle) {
|
||||
self.writes.insert(writer.ino, writer);
|
||||
}
|
||||
|
||||
/// Drop the write state of `ino` without queueing it, for tests.
|
||||
pub fn remove_writer(&mut self, ino: u64) -> Option<WriteHandle> {
|
||||
self.writes.remove(&ino)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)]
|
||||
pub enum Fallocate {
|
||||
/// 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 },
|
||||
}
|
||||
|
||||
impl Fallocate {
|
||||
/// The kind of `mode`, or `None` for a mode a handle cannot record.
|
||||
pub fn from_mode(mode: i32) -> Option<Self> {
|
||||
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(Fallocate::Allocate { keep_size: false }),
|
||||
KEEP => Some(Fallocate::Allocate { keep_size: true }),
|
||||
m if m == PUNCH | KEEP => Some(Fallocate::Punch),
|
||||
ZERO => Some(Fallocate::Zero { keep_size: false }),
|
||||
m if m == ZERO | KEEP => Some(Fallocate::Zero { keep_size: true }),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub 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))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a read of a file open for writing, or just released, serves from:
|
||||
/// the authored ranges of the scratch file, and the remote base for the
|
||||
/// rest.
|
||||
#[derive(Clone)]
|
||||
pub struct ReadView {
|
||||
pub file: Arc<File>,
|
||||
pub len: u64,
|
||||
pub uid: NodeUid,
|
||||
pub base_mtime: i64,
|
||||
pub base_size: u64,
|
||||
pub written: Intervals,
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// `base` gets `(offset, len)` of a range below the base size.
|
||||
pub fn assemble_open_read<E>(
|
||||
file: &File,
|
||||
len: u64,
|
||||
base_size: u64,
|
||||
written: &Intervals,
|
||||
offset: u64,
|
||||
size: u64,
|
||||
mut base: impl FnMut(u64, u64) -> Result<Option<Vec<u8>>, E>,
|
||||
) -> Result<Option<Vec<u8>>, ReadFailure<E>> {
|
||||
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(ReadFailure::Scratch)?;
|
||||
out.extend_from_slice(&buf);
|
||||
} else {
|
||||
let bend = e.min(base_size);
|
||||
if s < bend {
|
||||
match base(s, bend - s).map_err(ReadFailure::Base)? {
|
||||
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);
|
||||
}
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
/// Why [`assemble_open_read`] failed.
|
||||
#[derive(Debug)]
|
||||
pub enum ReadFailure<E> {
|
||||
/// Reading the scratch file failed.
|
||||
Scratch(std::io::Error),
|
||||
/// Reading the base failed, with the caller's own error.
|
||||
Base(E),
|
||||
}
|
||||
|
||||
/// Why staging a write failed.
|
||||
#[derive(Debug)]
|
||||
pub enum WriteError {
|
||||
/// The disk holding the scratch file is full. Not a broken file: the
|
||||
/// caller says so, so the application can take its out-of-space path, and
|
||||
/// frees what the cache holds on the same disk.
|
||||
NoSpace,
|
||||
/// Any other failure to write the scratch file.
|
||||
Io(std::io::Error),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for WriteError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
WriteError::NoSpace => f.write_str("no space left for the scratch file"),
|
||||
WriteError::Io(error) => write!(f, "scratch write failed: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for WriteError {}
|
||||
|
||||
/// Write `data` at `offset` into a handle's scratch file. Positional, so it
|
||||
/// needs no lock on the handle: the caller records the range with
|
||||
/// [`WriteHandle::record_write`] afterwards, and only on success.
|
||||
pub fn stage_write(file: &File, offset: u64, data: &[u8]) -> Result<(), WriteError> {
|
||||
file.write_all_at(data, offset).map_err(|error| {
|
||||
if error.raw_os_error() == Some(libc::ENOSPC) {
|
||||
WriteError::NoSpace
|
||||
} else {
|
||||
WriteError::Io(error)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// A released write whose upload has not happened yet.
|
||||
///
|
||||
/// The bytes live in the content cache's staging dir and the intent lives in the
|
||||
/// `pending_op` table; this pairs them in memory so a read can be served without
|
||||
/// a database round trip.
|
||||
#[derive(Clone)]
|
||||
pub struct PendingRevision {
|
||||
/// Staged blob holding the written bytes.
|
||||
pub path: PathBuf,
|
||||
/// Which of those bytes are real, and what base the gaps refer to.
|
||||
pub meta: StagedWrite,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use proton_drive_rs::NodeKind;
|
||||
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
|
||||
use std::io::Write;
|
||||
|
||||
/// Flatten `segments` into a readable form for assertions.
|
||||
fn segs(iv: &Intervals, start: u64, end: u64) -> Vec<(u64, u64, bool)> {
|
||||
iv.segments(start, end)
|
||||
}
|
||||
|
||||
#[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 uid(link: &str) -> NodeUid {
|
||||
NodeUid::new(VolumeId::from("vol"), LinkId::from(link))
|
||||
}
|
||||
|
||||
fn node(link: &str, _parent: &str, name: &str, _is_dir: bool) -> Node {
|
||||
Node {
|
||||
uid: uid(link),
|
||||
parent_uid: Some(uid("root")),
|
||||
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(0),
|
||||
claimed_modification_time: None,
|
||||
},
|
||||
name: name.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 handle(len: u64, base_size: u64) -> WriteHandle {
|
||||
let path = std::env::temp_dir().join(format!("pdfs-handle-test-{}", std::process::id()));
|
||||
let file = File::create(&path).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
WriteHandle {
|
||||
ino: 2,
|
||||
uid: uid("file"),
|
||||
file: Arc::new(file),
|
||||
path,
|
||||
written: Intervals::default(),
|
||||
len,
|
||||
base_size,
|
||||
base_mtime: 0,
|
||||
base_revision_id: None,
|
||||
dirty: false,
|
||||
open_count: 1,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resize_the_scratch_file_refuses_changes_nothing() {
|
||||
let mut h = handle(4, 4);
|
||||
h.written.add(0, 4);
|
||||
// A read-only descriptor refuses `ftruncate`, as a full disk does a grow.
|
||||
let path = std::env::temp_dir().join(format!("pdfs-resize-test-{}", std::process::id()));
|
||||
std::fs::write(&path, b"kept").unwrap();
|
||||
h.file = Arc::new(File::open(&path).unwrap());
|
||||
let _ = std::fs::remove_file(&path);
|
||||
|
||||
assert!(h.resize(10).is_err());
|
||||
assert_eq!((h.len, h.dirty), (4, false));
|
||||
assert_eq!(h.written.segments(4, 10), vec![(4, 10, false)]);
|
||||
|
||||
let mut h = handle(4, 4);
|
||||
h.resize(10).unwrap();
|
||||
assert_eq!((h.len, h.dirty), (10, true));
|
||||
assert_eq!(h.written.segments(4, 10), vec![(4, 10, true)]);
|
||||
}
|
||||
|
||||
/// A file created offline is written while its queued create lands. The
|
||||
/// placeholder had no revision, so the handle takes the empty file the
|
||||
/// create made as its base (docs/BUGS.md B113).
|
||||
#[test]
|
||||
fn a_handle_on_a_placeholder_is_based_on_the_create_that_landed() {
|
||||
let mut h = handle(0, 0);
|
||||
assert_eq!(h.base_revision_id, None);
|
||||
let mut landed = node("real", "root", "f.mkv", false);
|
||||
landed.modification_time = 160;
|
||||
if let NodeKind::File {
|
||||
active_revision_id, ..
|
||||
} = &mut landed.kind
|
||||
{
|
||||
*active_revision_id = Some("empty".into());
|
||||
}
|
||||
h.rebase_onto(&landed);
|
||||
assert_eq!(h.base_mtime, 160);
|
||||
assert_eq!(h.base_size, 0);
|
||||
assert_eq!(h.base_revision_id.as_deref(), Some("empty"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_write_past_the_end_authors_the_hole_it_leaves() {
|
||||
// Opened over a 100-byte base, shrunk to 10, then written at 50: bytes
|
||||
// 10..50 are zeros now, not the base's bytes 10..50.
|
||||
let mut h = handle(100, 100);
|
||||
h.written.clip(10);
|
||||
h.len = 10;
|
||||
h.record_write(50, 60);
|
||||
assert_eq!(h.len, 60);
|
||||
assert_eq!(
|
||||
h.written.segments(0, 60),
|
||||
vec![(0, 10, false), (10, 60, true)],
|
||||
"only the head still comes from the base"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_write_inside_the_file_leaves_the_rest_to_the_base() {
|
||||
let mut h = handle(100, 100);
|
||||
h.record_write(40, 50);
|
||||
assert_eq!(h.len, 100);
|
||||
assert_eq!(
|
||||
h.written.segments(0, 100),
|
||||
vec![(0, 40, false), (40, 50, true), (50, 100, false)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_write_to_a_full_disk_is_no_space() {
|
||||
let full = File::options().write(true).open("/dev/full").unwrap();
|
||||
assert!(matches!(
|
||||
stage_write(&full, 0, b"bytes"),
|
||||
Err(WriteError::NoSpace)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_last_release_hands_back_the_write_and_marks_it_releasing() {
|
||||
let mut open = OpenFiles::default();
|
||||
// As a fresh open starts it: no handle shares it yet.
|
||||
let fresh = || WriteHandle {
|
||||
open_count: 0,
|
||||
..handle(0, 0)
|
||||
};
|
||||
let first = open.open_writer(2, fresh);
|
||||
let second = open.open_writer(2, || unreachable!("the state is shared"));
|
||||
assert_ne!(first, second);
|
||||
assert!(open.is_busy(2));
|
||||
|
||||
assert!(matches!(
|
||||
open.release(first),
|
||||
Released::StillOpen { ino: 2 }
|
||||
));
|
||||
assert!(open.is_writing(2));
|
||||
let Released::Last(writer) = open.release(second) else {
|
||||
panic!("the second release is the last");
|
||||
};
|
||||
assert_eq!(writer.ino, 2);
|
||||
assert!(!open.is_writing(2));
|
||||
assert_eq!(open.owed(false).collect::<Vec<_>>(), [2]);
|
||||
// Until the release has queued it, a read still finds what it wrote.
|
||||
assert!(open.reader(2).is_some());
|
||||
|
||||
open.finish_release(2);
|
||||
assert_eq!(open.owed(false).count(), 0);
|
||||
assert!(open.reader(2).is_none());
|
||||
assert!(matches!(open.release(second), Released::NotWriting));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directory_handle_never_takes_a_file_handle_number() {
|
||||
let mut open = OpenFiles::default();
|
||||
let dir = open.next_fh();
|
||||
let file = open.open_writer(2, || handle(0, 0));
|
||||
assert_ne!(dir, file);
|
||||
assert_eq!(open.ino_of(file), Some(2));
|
||||
assert_eq!(open.ino_of(dir), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_modes_a_handle_can_record_are_accepted() {
|
||||
let keep = libc::FALLOC_FL_KEEP_SIZE;
|
||||
assert_eq!(
|
||||
Fallocate::from_mode(0),
|
||||
Some(Fallocate::Allocate { keep_size: false })
|
||||
);
|
||||
assert_eq!(
|
||||
Fallocate::from_mode(keep),
|
||||
Some(Fallocate::Allocate { keep_size: true })
|
||||
);
|
||||
assert_eq!(
|
||||
Fallocate::from_mode(libc::FALLOC_FL_PUNCH_HOLE | keep),
|
||||
Some(Fallocate::Punch)
|
||||
);
|
||||
assert_eq!(
|
||||
Fallocate::from_mode(libc::FALLOC_FL_ZERO_RANGE),
|
||||
Some(Fallocate::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!(Fallocate::from_mode(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 = Fallocate::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 = Fallocate::Zero { keep_size: true };
|
||||
assert_eq!(zero_keep.effect(90, 120, 100), (Some((90, 100)), None));
|
||||
assert_eq!(
|
||||
Fallocate::Punch.effect(90, 120, 100),
|
||||
(Some((90, 100)), None)
|
||||
);
|
||||
assert_eq!(Fallocate::Punch.effect(120, 130, 100), (None, None));
|
||||
let alloc = Fallocate::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!(
|
||||
Fallocate::Allocate { keep_size: true }.effect(90, 120, 100),
|
||||
(None, None)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recorded_fallocate_grows_and_authors_what_it_zeroed() {
|
||||
let mut h = handle(100, 100);
|
||||
let grown = h.record_fallocate(Fallocate::Zero { keep_size: false }, 90, 120);
|
||||
assert_eq!(grown, Some(120));
|
||||
assert_eq!((h.len, h.dirty), (120, true));
|
||||
assert_eq!(
|
||||
h.written.segments(0, 120),
|
||||
vec![(0, 90, false), (90, 120, true)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directory_page_resumes_after_the_last_entry_it_gave() {
|
||||
let mut open = OpenFiles::default();
|
||||
let listing: DirListing = vec![
|
||||
(1, true, ".".into()),
|
||||
(1, true, "..".into()),
|
||||
(5, false, "a".into()),
|
||||
(6, false, "b".into()),
|
||||
];
|
||||
let fh = open.open_dir(listing);
|
||||
let snapshot = open.dir(fh).unwrap();
|
||||
let first: Vec<_> = dir_page(&snapshot, 0)
|
||||
.take(3)
|
||||
.map(|(next, e)| (next, e.0))
|
||||
.collect();
|
||||
assert_eq!(first, [(1, 1), (2, 1), (3, 5)]);
|
||||
let rest: Vec<_> = dir_page(&snapshot, 3)
|
||||
.map(|(next, e)| (next, e.0))
|
||||
.collect();
|
||||
assert_eq!(rest, [(4, 6)]);
|
||||
open.close_dir(fh);
|
||||
assert!(open.dir(fh).is_none());
|
||||
}
|
||||
|
||||
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 (file, path) = scratch(b"ABCDEFGH");
|
||||
let mut written = Intervals::default();
|
||||
written.add(0, 4);
|
||||
|
||||
let authored = assemble_open_read::<()>(&file, 8, 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, 8, &written, 2, 6, |_, _| Ok(None));
|
||||
assert_eq!(missing.unwrap(), None);
|
||||
|
||||
let base = assemble_open_read::<()>(&file, 10, 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);
|
||||
}
|
||||
}
|
||||
@@ -1,246 +1,65 @@
|
||||
//! Inode bookkeeping: the maps that give a remote node a stable kernel inode,
|
||||
//! The tree: inode bookkeeping, the maps that give a remote node a stable kernel inode,
|
||||
//! the open write handles, and the interval set that tracks which bytes of a
|
||||
//! staged write are authored locally.
|
||||
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::fs::File;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::open::OpenFiles;
|
||||
use pdfs_core::{Access, access_for};
|
||||
use pdfs_store::cache::StagedWrite;
|
||||
use pdfs_store::db::Db;
|
||||
#[cfg(test)]
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
use proton_drive_rs::MemberRole;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use proton_drive_rs::{Node, NodeKind};
|
||||
use tracing::warn;
|
||||
|
||||
/// Why the tree refused an operation on a node. The kernel adapter maps it
|
||||
/// to an errno.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum NodeError {
|
||||
/// No node has the inode.
|
||||
NotFound,
|
||||
/// The node is there, but the share it is in does not allow writing.
|
||||
NotWritable,
|
||||
}
|
||||
|
||||
/// A node known to the filesystem, addressed by its kernel inode.
|
||||
pub(crate) struct Entry {
|
||||
pub(crate) uid: NodeUid,
|
||||
pub(crate) parent: u64,
|
||||
pub(crate) node: Node,
|
||||
pub(crate) access: Access,
|
||||
pub(crate) lookup_count: u64,
|
||||
pub(crate) open_count: u32,
|
||||
pub(crate) unlinked: bool,
|
||||
pub struct Entry {
|
||||
pub uid: NodeUid,
|
||||
pub parent: u64,
|
||||
pub node: Node,
|
||||
pub access: Access,
|
||||
pub lookup_count: u64,
|
||||
pub open_count: u32,
|
||||
pub unlinked: bool,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
pub(crate) fn writable(&self) -> bool {
|
||||
pub fn writable(&self) -> bool {
|
||||
self.access.writable()
|
||||
}
|
||||
}
|
||||
|
||||
/// A set of non-overlapping `[start, end)` byte ranges, kept sorted and merged.
|
||||
/// Tracks which bytes of a [`WriteHandle`]'s scratch file were authored locally
|
||||
/// (vs. still living only in the remote base), so reads and the commit gap-fill
|
||||
/// know which regions to pull from the network.
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct Intervals(pub(crate) Vec<(u64, u64)>);
|
||||
|
||||
impl Intervals {
|
||||
/// Mark `[start, end)` as authored, coalescing with any touching ranges.
|
||||
pub(crate) fn add(&mut self, start: u64, end: u64) {
|
||||
if start >= end {
|
||||
return;
|
||||
}
|
||||
self.0.push((start, end));
|
||||
self.0.sort_by_key(|&(s, _)| s);
|
||||
let mut merged: Vec<(u64, u64)> = Vec::with_capacity(self.0.len());
|
||||
for &(s, e) in &self.0 {
|
||||
match merged.last_mut() {
|
||||
Some(last) if s <= last.1 => last.1 = last.1.max(e),
|
||||
_ => merged.push((s, e)),
|
||||
}
|
||||
}
|
||||
self.0 = merged;
|
||||
}
|
||||
|
||||
/// Drop everything at or beyond `len` (a shrink/truncate).
|
||||
pub(crate) fn clip(&mut self, len: u64) {
|
||||
self.0.retain(|&(s, _)| s < len);
|
||||
for iv in &mut self.0 {
|
||||
iv.1 = iv.1.min(len);
|
||||
}
|
||||
}
|
||||
|
||||
/// Split `[start, end)` into contiguous `(s, e, authored)` segments, in
|
||||
/// order. `authored == true` means the bytes live in the scratch file;
|
||||
/// `false` means they must come from the remote base (or are a hole).
|
||||
pub(crate) fn segments(&self, start: u64, end: u64) -> Vec<(u64, u64, bool)> {
|
||||
let mut out = Vec::new();
|
||||
let mut pos = start;
|
||||
for &(s, e) in &self.0 {
|
||||
if e <= start {
|
||||
continue;
|
||||
}
|
||||
if s >= end {
|
||||
break;
|
||||
}
|
||||
let ws = s.max(start);
|
||||
let we = e.min(end);
|
||||
if pos < ws {
|
||||
out.push((pos, ws, false));
|
||||
}
|
||||
out.push((ws, we, true));
|
||||
pos = we;
|
||||
}
|
||||
if pos < end {
|
||||
out.push((pos, end, false));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// State for a file opened for writing. Authored bytes are staged in an on-disk
|
||||
/// scratch file (positional reads/writes) rather than RAM, so a multi-GiB write
|
||||
/// never balloons the daemon. On flush/release the scratch file — gap-filled
|
||||
/// from the remote base where untouched — is streamed up as one new revision,
|
||||
/// since the SDK seals whole revisions rather than byte ranges.
|
||||
pub(crate) struct WriteHandle {
|
||||
pub(crate) ino: u64,
|
||||
pub(crate) uid: NodeUid,
|
||||
/// Disk-backed staging buffer. Shared (`Arc`) so reads can use it without
|
||||
/// holding the state lock across I/O. Accessed positionally (`read_at`/
|
||||
/// `write_at`), so a clone never disturbs another's file offset.
|
||||
pub(crate) file: Arc<File>,
|
||||
/// Scratch file path, removed on release.
|
||||
pub(crate) path: PathBuf,
|
||||
/// Byte ranges authored into `file`. Everything else in `[0, len)` is base.
|
||||
pub(crate) written: Intervals,
|
||||
/// Logical file size (may exceed authored bytes after a truncate-extend).
|
||||
pub(crate) len: u64,
|
||||
/// Size of the remote base at open, for serving untouched ranges.
|
||||
pub(crate) base_size: u64,
|
||||
/// Modification time of the remote base at open, validating its block cache.
|
||||
pub(crate) base_mtime: i64,
|
||||
/// Server revision id of the remote base at open, if it had one. This is the
|
||||
/// stable identity the drain conflict-checks against: `base_mtime` alone
|
||||
/// drifts when the server re-stamps the *same* revision, which reads as a
|
||||
/// spurious conflict (see B16/B25). `None` for a file with no sealed remote
|
||||
/// revision, or one read through a surface that does not carry the id.
|
||||
pub(crate) base_revision_id: Option<String>,
|
||||
/// Whether anything diverged from the remote and needs an upload.
|
||||
pub(crate) dirty: bool,
|
||||
/// Number of file handles currently sharing this scratch state.
|
||||
pub(crate) open_count: usize,
|
||||
}
|
||||
|
||||
impl WriteHandle {
|
||||
/// A handle on a file `create` just made: an empty base, so everything
|
||||
/// written through it is authored.
|
||||
///
|
||||
/// The base is `node` as it actually exists — the empty file the server just
|
||||
/// minted, or a queued create's placeholder — never the local clock or a
|
||||
/// blank. `queue_revision` turns it into `StagedWrite::based_on` and the
|
||||
/// drain compares the remote against that. A `now_secs()` mtime differs from
|
||||
/// the server's stamp by the create round-trip. A missing revision id drops
|
||||
/// the check to `(mtime, size)`, and moving or renaming the file advances
|
||||
/// its mtime on the server. Either way the first write to a brand-new file
|
||||
/// lands as a conflict copy of its own empty create (`docs/BUGS.md` B113).
|
||||
pub(crate) fn created(ino: u64, node: &Node, file: File, path: PathBuf) -> Self {
|
||||
Self {
|
||||
ino,
|
||||
uid: node.uid.clone(),
|
||||
file: Arc::new(file),
|
||||
path,
|
||||
written: Intervals::default(),
|
||||
len: 0,
|
||||
base_size: 0,
|
||||
base_mtime: node.modification_time,
|
||||
base_revision_id: crate::node_revision_id(node),
|
||||
dirty: false,
|
||||
open_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Write over `node` from now on: a revision this daemon has just put on the
|
||||
/// server under the handle, by sealing an upload or by landing the queued
|
||||
/// create the handle was opened on. The base the handle opened over is gone,
|
||||
/// and keeping it would make the drain read our own revision as another
|
||||
/// device's edit.
|
||||
pub(crate) fn rebase_onto(&mut self, node: &Node) {
|
||||
self.base_mtime = node.modification_time;
|
||||
self.base_size = crate::node_size(node);
|
||||
self.base_revision_id = crate::node_revision_id(node);
|
||||
}
|
||||
|
||||
/// Resize the file to `size`, as `setattr` does through an open handle.
|
||||
///
|
||||
/// The scratch file goes first: a resize it refuses (a full disk on a
|
||||
/// grow) fails with nothing recorded. Otherwise the length and the
|
||||
/// authored ranges would describe bytes the scratch file does not hold,
|
||||
/// and the call would have succeeded.
|
||||
pub(crate) fn resize(&mut self, size: u64) -> std::io::Result<()> {
|
||||
self.file.set_len(size)?;
|
||||
if size < self.len {
|
||||
// Shrink: drop authored ranges past the new end.
|
||||
self.written.clip(size);
|
||||
} else if size > self.len {
|
||||
// Grow: the new tail is defined as zeros, so claim it as authored
|
||||
// rather than base content.
|
||||
self.written.add(self.len, size);
|
||||
}
|
||||
self.len = size;
|
||||
self.dirty = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Account for `[offset, end)` having been written through this handle.
|
||||
///
|
||||
/// A write past the end leaves a hole that reads as zeros, exactly like a
|
||||
/// grow through `setattr`, so the hole is authored too. Left unauthored, a
|
||||
/// hole below the base size was refilled from the base at commit: a file
|
||||
/// shrunk and then written past its new end got its old bytes back.
|
||||
pub(crate) fn record_write(&mut self, offset: u64, end: u64) {
|
||||
if offset > self.len {
|
||||
self.written.add(self.len, offset);
|
||||
}
|
||||
self.written.add(offset, end);
|
||||
self.len = self.len.max(end);
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// A released write whose upload has not happened yet.
|
||||
///
|
||||
/// The bytes live in the content cache's staging dir and the intent lives in the
|
||||
/// `pending_op` table; this pairs them in memory so a read can be served without
|
||||
/// a database round trip.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct PendingRevision {
|
||||
/// Staged blob holding the written bytes.
|
||||
pub(crate) path: PathBuf,
|
||||
/// Which of those bytes are real, and what base the gaps refer to.
|
||||
pub(crate) meta: StagedWrite,
|
||||
}
|
||||
|
||||
/// One directory's entries as `readdir` reports them: `(ino, is_dir, name)` per
|
||||
/// entry, in reply order. The kernel's file-type enum is mapped in at reply
|
||||
/// time so this module stays free of `fuser`.
|
||||
pub(crate) type DirListing = Vec<(u64, bool, String)>;
|
||||
|
||||
/// Where [`State::next_ino`] starts: far above any local id a database hands
|
||||
/// out, so a fallback inode never names a node that has a row.
|
||||
pub(crate) const FALLBACK_INO: u64 = 1 << 48;
|
||||
pub const FALLBACK_INO: u64 = 1 << 48;
|
||||
|
||||
/// The inode of the node with local id `lid` ([`Db::lids_for`]). One above the
|
||||
/// lid, so no node takes [`crate::ROOT_INO`], which each session uses for its
|
||||
/// lid, so no node takes [`crate::ids::ROOT_INO`], which each session uses for its
|
||||
/// own root. The same in every mount and after a restart.
|
||||
pub(crate) fn lid_ino(lid: i64) -> u64 {
|
||||
lid.unsigned_abs() + crate::ROOT_INO
|
||||
pub fn lid_ino(lid: i64) -> u64 {
|
||||
lid.unsigned_abs() + crate::ids::ROOT_INO
|
||||
}
|
||||
|
||||
/// The inodes of the stored nodes among `nodes`, from their local ids, for
|
||||
/// [`State::intern_batch_with_inos`]. Called before the state lock is taken;
|
||||
/// a node that already has a row keeps its id. Empty when the database fails,
|
||||
/// which leaves the allocation to the lock holder, as before.
|
||||
pub(crate) fn inos_for(db: &Db, nodes: &[Node]) -> HashMap<NodeUid, u64> {
|
||||
pub fn inos_for(db: &Db, nodes: &[Node]) -> HashMap<NodeUid, u64> {
|
||||
let stored: Vec<&Node> = nodes
|
||||
.iter()
|
||||
.filter(|node| !crate::r#virtual::is_virtual_uid(&node.uid))
|
||||
.filter(|node| !crate::ids::is_virtual_uid(&node.uid))
|
||||
.collect();
|
||||
if stored.is_empty() {
|
||||
return HashMap::new();
|
||||
@@ -260,8 +79,8 @@ pub(crate) fn inos_for(db: &Db, nodes: &[Node]) -> HashMap<NodeUid, u64> {
|
||||
|
||||
/// The local id of the node at inode `ino`, the inverse of [`lid_ino`]:
|
||||
/// `None` for the root and a fallback inode.
|
||||
pub(crate) fn ino_lid(ino: u64) -> Option<i64> {
|
||||
(ino > crate::ROOT_INO && ino < FALLBACK_INO).then(|| (ino - crate::ROOT_INO) as i64)
|
||||
pub fn ino_lid(ino: u64) -> Option<i64> {
|
||||
(ino > crate::ids::ROOT_INO && ino < FALLBACK_INO).then(|| (ino - crate::ids::ROOT_INO) as i64)
|
||||
}
|
||||
|
||||
/// Mutable inode bookkeeping, guarded by a mutex because fuser drives the
|
||||
@@ -270,54 +89,35 @@ pub(crate) fn ino_lid(ino: u64) -> Option<i64> {
|
||||
/// One tree for every mount of the daemon. Each FUSE session sees it from its
|
||||
/// own root ([`State::roots`]) and calls that root inode 1; `ProtonFs`
|
||||
/// translates at the kernel boundary.
|
||||
pub(crate) struct State {
|
||||
pub struct State {
|
||||
/// inode -> node metadata.
|
||||
pub(crate) entries: HashMap<u64, Entry>,
|
||||
pub entries: HashMap<u64, Entry>,
|
||||
/// Dedupe inodes by node uid so a node keeps a stable inode across lookups.
|
||||
pub(crate) by_uid: HashMap<NodeUid, u64>,
|
||||
pub by_uid: HashMap<NodeUid, u64>,
|
||||
/// Cached directory listings: parent inode -> child inodes. Presence of a
|
||||
/// key means the directory has been enumerated.
|
||||
pub(crate) children: HashMap<u64, Vec<u64>>,
|
||||
pub children: HashMap<u64, Vec<u64>>,
|
||||
/// The inodes some session has been rooted at ([`State::install_root`]).
|
||||
/// A root is its own parent. Kept after its session unmounts: the node is
|
||||
/// still one of ours.
|
||||
pub(crate) roots: HashSet<u64>,
|
||||
pub roots: HashSet<u64>,
|
||||
/// The next inode for a node the database could not give a local id, from
|
||||
/// a range lids never reach ([`FALLBACK_INO`]).
|
||||
pub(crate) next_ino: u64,
|
||||
/// Shared write state keyed by inode. Concurrent writers share the scratch file.
|
||||
pub(crate) active_writes: HashMap<u64, WriteHandle>,
|
||||
/// Inodes whose last write handle `release` has taken out of
|
||||
/// [`State::active_writes`] and is still queueing. `close(2)` returns
|
||||
/// before that, and in between the edit is in neither the handles nor the
|
||||
/// queue, so a check for changes not on Drive yet looks here too.
|
||||
pub(crate) releasing: HashSet<u64>,
|
||||
/// Maps file handle id (fh) to inode (ino). Read-only opens use fh 0 and
|
||||
/// have no entry here.
|
||||
pub(crate) handles: HashMap<u64, u64>,
|
||||
pub(crate) next_fh: u64,
|
||||
/// One frozen listing per open directory handle, taken at `opendir`.
|
||||
///
|
||||
/// `readdir` resumes from a byte offset into the listing it is walking, so
|
||||
/// that listing has to stay the same across the calls of one `getdents`
|
||||
/// sequence. Rebuilding it live meant a create or a trash landing between
|
||||
/// two pages shifted every later entry, and the caller silently skipped or
|
||||
/// repeated whatever crossed the page boundary. Each entry is
|
||||
/// `(ino, is_dir, name)` — the kernel type is mapped at reply time so this
|
||||
/// module stays free of `fuser` (`docs/BUGS.md` B43).
|
||||
pub(crate) dir_snapshots: HashMap<u64, Arc<DirListing>>,
|
||||
pub next_ino: u64,
|
||||
/// The files open for writing, their handles and their releases.
|
||||
pub open: OpenFiles,
|
||||
/// Resident inode attributes whose effective access changed during an
|
||||
/// intern/root refresh. Core drains this set and notifies the matching
|
||||
/// kernel only after releasing the State lock.
|
||||
pub(crate) access_changes: HashSet<u64>,
|
||||
pub access_changes: HashSet<u64>,
|
||||
/// Persisted shared-root authority, loaded once and updated
|
||||
/// on every explicit role/tombstone change. Descendant inheritance reads
|
||||
/// this map instead of issuing one SQLite query per interned inode.
|
||||
pub(crate) share_access: HashMap<NodeUid, Access>,
|
||||
pub share_access: HashMap<NodeUid, Access>,
|
||||
/// Unified SQLite metadata cache. Read from here (`has_children`) but never
|
||||
/// written: mutations go to [`State::outbox`] and are applied after the lock
|
||||
/// is released. See [`StateGuard`].
|
||||
pub(crate) db: Arc<Db>,
|
||||
pub db: Arc<Db>,
|
||||
/// Write-throughs this mutation owes SQLite, applied by [`StateGuard`] once
|
||||
/// the inode lock is released.
|
||||
///
|
||||
@@ -334,7 +134,7 @@ pub(crate) struct State {
|
||||
///
|
||||
/// Deliberately a small closed set rather than a boxed closure: these run
|
||||
/// outside the lock, and what they can touch should be readable here.
|
||||
pub(crate) enum DbWrite {
|
||||
pub enum DbWrite {
|
||||
/// One node or a whole listing. Both go through `upsert_nodes`, which is a
|
||||
/// single transaction either way, so there is nothing to gain by splitting
|
||||
/// them — and a `Node` is large enough that a variant holding one inline
|
||||
@@ -373,13 +173,13 @@ impl DbWrite {
|
||||
/// — several fsyncs' worth — and nothing about that needs the maps frozen. The
|
||||
/// write still happens synchronously on this thread before the caller proceeds,
|
||||
/// so a read that follows a mutation still sees it.
|
||||
pub(crate) struct StateGuard<'a> {
|
||||
pub struct StateGuard<'a> {
|
||||
guard: Option<pdfs_core::lockrank::RankedGuard<'a, State>>,
|
||||
db: &'a Arc<Db>,
|
||||
}
|
||||
|
||||
impl<'a> StateGuard<'a> {
|
||||
pub(crate) fn new(guard: pdfs_core::lockrank::RankedGuard<'a, State>, db: &'a Arc<Db>) -> Self {
|
||||
pub fn new(guard: pdfs_core::lockrank::RankedGuard<'a, State>, db: &'a Arc<Db>) -> Self {
|
||||
Self {
|
||||
guard: Some(guard),
|
||||
db,
|
||||
@@ -424,8 +224,8 @@ impl State {
|
||||
/// first and then applies them, which is the whole point. A test driving a
|
||||
/// bare `State` has no guard, so it calls this where the daemon would have
|
||||
/// dropped one.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn flush_outbox(&mut self) {
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn flush_outbox(&mut self) {
|
||||
let db = self.db.clone();
|
||||
for write in std::mem::take(&mut self.outbox) {
|
||||
write.apply(&db);
|
||||
@@ -438,26 +238,22 @@ impl State {
|
||||
/// which in the daemon is the state after the guard dropped. Handing back an
|
||||
/// owned `Arc` rather than a borrow keeps it usable inside an `assert_eq!`
|
||||
/// that also touches `st`.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn flushed_db(&mut self) -> Arc<Db> {
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn flushed_db(&mut self) -> Arc<Db> {
|
||||
self.flush_outbox();
|
||||
self.db.clone()
|
||||
}
|
||||
|
||||
/// A fresh, empty tree over `db`. A node's inode comes from its local id
|
||||
/// ([`lid_ino`]).
|
||||
pub(crate) fn new(db: Arc<Db>, share_access: HashMap<NodeUid, Access>) -> Self {
|
||||
pub fn new(db: Arc<Db>, share_access: HashMap<NodeUid, Access>) -> Self {
|
||||
Self {
|
||||
entries: HashMap::new(),
|
||||
by_uid: HashMap::new(),
|
||||
children: HashMap::new(),
|
||||
roots: HashSet::new(),
|
||||
next_ino: FALLBACK_INO,
|
||||
active_writes: HashMap::new(),
|
||||
releasing: HashSet::new(),
|
||||
handles: HashMap::new(),
|
||||
next_fh: 1,
|
||||
dir_snapshots: HashMap::new(),
|
||||
open: OpenFiles::default(),
|
||||
access_changes: HashSet::new(),
|
||||
share_access,
|
||||
db,
|
||||
@@ -473,7 +269,7 @@ impl State {
|
||||
/// may have left for it is dropped. A node already in the tree keeps its
|
||||
/// inode and its lookups, and stops naming a parent: a session's `..` at
|
||||
/// its root is the root.
|
||||
pub(crate) fn install_root(&mut self, root: Node) -> u64 {
|
||||
pub fn install_root(&mut self, root: Node) -> u64 {
|
||||
if let Err(e) = self.db.upsert_node(&root) {
|
||||
warn!(uid = %root.uid, error = %e, "db upsert root failed");
|
||||
}
|
||||
@@ -512,7 +308,7 @@ impl State {
|
||||
/// can outlive their dentries for open-handle and access-revocation
|
||||
/// semantics, so `by_uid` membership alone is not proof that a
|
||||
/// control-socket operation may address the node.
|
||||
pub(crate) fn owns_visible_uid(&self, uid: &NodeUid, roots: &[u64]) -> bool {
|
||||
pub fn owns_visible_uid(&self, uid: &NodeUid, roots: &[u64]) -> bool {
|
||||
let Some(&target) = self.by_uid.get(uid) else {
|
||||
return false;
|
||||
};
|
||||
@@ -558,22 +354,23 @@ impl State {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn require_writable(&self, ino: u64) -> Result<(), fuser::Errno> {
|
||||
/// Whether the node at `ino` may be written.
|
||||
pub fn require_writable(&self, ino: u64) -> Result<(), NodeError> {
|
||||
match self.entries.get(&ino) {
|
||||
Some(entry) if entry.writable() => Ok(()),
|
||||
Some(_) => Err(fuser::Errno::EACCES),
|
||||
None => Err(fuser::Errno::ENOENT),
|
||||
Some(_) => Err(NodeError::NotWritable),
|
||||
None => Err(NodeError::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn access_by_uid(&self, uid: &NodeUid) -> Option<Access> {
|
||||
pub fn access_by_uid(&self, uid: &NodeUid) -> Option<Access> {
|
||||
self.by_uid
|
||||
.get(uid)
|
||||
.and_then(|ino| self.entries.get(ino))
|
||||
.map(|entry| entry.access)
|
||||
}
|
||||
|
||||
pub(crate) fn take_access_changes(&mut self) -> Vec<u64> {
|
||||
pub fn take_access_changes(&mut self) -> Vec<u64> {
|
||||
self.access_changes.drain().collect()
|
||||
}
|
||||
|
||||
@@ -582,7 +379,7 @@ impl State {
|
||||
/// Used to decide how a node with no resolvable parent is classified:
|
||||
/// our own volume fails open (it is owned content), a foreign volume
|
||||
/// fails closed (it can only be there because of a share).
|
||||
pub(crate) fn is_own_volume(&self, uid: &NodeUid) -> bool {
|
||||
pub fn is_own_volume(&self, uid: &NodeUid) -> bool {
|
||||
self.roots.iter().any(|ino| {
|
||||
self.entries
|
||||
.get(ino)
|
||||
@@ -594,7 +391,7 @@ impl State {
|
||||
self.share_access.get(uid).copied()
|
||||
}
|
||||
|
||||
pub(crate) fn access_for_node(&mut self, parent: u64, node: &Node) -> Access {
|
||||
pub fn access_for_node(&mut self, parent: u64, node: &Node) -> Access {
|
||||
let parent_access = self
|
||||
.entries
|
||||
.get(&parent)
|
||||
@@ -625,8 +422,8 @@ impl State {
|
||||
/// `share_access`. P3 can call this method only when its share-root endpoint
|
||||
/// explicitly observed a role; explicit absence or an unknown wire role is
|
||||
/// represented by `None` and fails closed to Viewer.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn record_observed_share_root_role(
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn record_observed_share_root_role(
|
||||
&mut self,
|
||||
uid: &NodeUid,
|
||||
role: Option<MemberRole>,
|
||||
@@ -665,12 +462,7 @@ impl State {
|
||||
/// Install access already committed atomically with the root node. Unlike
|
||||
/// the observation hook this performs no database write and cannot swallow
|
||||
/// a publication failure.
|
||||
pub(crate) fn intern_published_share_root(
|
||||
&mut self,
|
||||
parent: u64,
|
||||
node: Node,
|
||||
access: Access,
|
||||
) -> u64 {
|
||||
pub fn intern_published_share_root(&mut self, parent: u64, node: Node, access: Access) -> u64 {
|
||||
self.share_access.insert(node.uid.clone(), access);
|
||||
self.intern_mem_with_access(parent, node, access)
|
||||
}
|
||||
@@ -679,7 +471,7 @@ impl State {
|
||||
/// resident inode or persisted authority. Open handles remain usable for
|
||||
/// reads, while removing the root's cached listing guarantees a later
|
||||
/// reappearance re-enumerates descendants instead of exposing stale rows.
|
||||
pub(crate) fn hide_shared_root(&mut self, uid: &NodeUid) -> Vec<u64> {
|
||||
pub fn hide_shared_root(&mut self, uid: &NodeUid) -> Vec<u64> {
|
||||
let changed = self.downgrade_shared_subtree(uid);
|
||||
self.hide_subtree_mem(uid);
|
||||
changed
|
||||
@@ -687,7 +479,7 @@ impl State {
|
||||
|
||||
/// Withdraw a foreign child removed by its authoritative folder listing.
|
||||
/// Authority is retained because this is content deletion, not access loss.
|
||||
pub(crate) fn hide_foreign_subtree(&mut self, uid: &NodeUid) {
|
||||
pub fn hide_foreign_subtree(&mut self, uid: &NodeUid) {
|
||||
self.hide_subtree_mem(uid);
|
||||
}
|
||||
|
||||
@@ -753,7 +545,7 @@ impl State {
|
||||
///
|
||||
/// This intentionally ignores nested authorities: losing access to an
|
||||
/// outer tree must not leave a cached inner entry writable.
|
||||
pub(crate) fn downgrade_shared_subtree(&mut self, uid: &NodeUid) -> Vec<u64> {
|
||||
pub fn downgrade_shared_subtree(&mut self, uid: &NodeUid) -> Vec<u64> {
|
||||
self.share_access.insert(uid.clone(), Access::Viewer);
|
||||
let Some(&root) = self.by_uid.get(uid) else {
|
||||
return Vec::new();
|
||||
@@ -780,7 +572,7 @@ impl State {
|
||||
/// Downgrade resident shared subtrees identified by persisted authority,
|
||||
/// live membership, or already-inherited non-owner access. Owned and device
|
||||
/// entries remain `Owner`.
|
||||
pub(crate) fn downgrade_known_shared_access(&mut self) -> Vec<u64> {
|
||||
pub fn downgrade_known_shared_access(&mut self) -> Vec<u64> {
|
||||
for access in self.share_access.values_mut() {
|
||||
*access = Access::Viewer;
|
||||
}
|
||||
@@ -821,7 +613,7 @@ impl State {
|
||||
|
||||
/// Rebuild effective access after cold hydration. The memo makes each
|
||||
/// parent edge resolve once, then every child is a direct inheritance.
|
||||
pub(crate) fn hydrate_access(&mut self) {
|
||||
pub fn hydrate_access(&mut self) {
|
||||
fn resolve(
|
||||
state: &State,
|
||||
ino: u64,
|
||||
@@ -937,11 +729,11 @@ impl State {
|
||||
}
|
||||
|
||||
/// Write `node` through as it is, in order with the tree's other changes.
|
||||
pub(crate) fn write_through(&mut self, node: Node) {
|
||||
pub fn write_through(&mut self, node: Node) {
|
||||
self.outbox.push(DbWrite::Upsert(vec![node]));
|
||||
}
|
||||
|
||||
pub(crate) fn intern(&mut self, parent: u64, mut node: Node) -> u64 {
|
||||
pub fn intern(&mut self, parent: u64, mut node: Node) -> u64 {
|
||||
self.keep_revision_mtime(&mut node);
|
||||
self.outbox.push(DbWrite::Upsert(vec![node.clone()]));
|
||||
self.intern_mem(parent, node)
|
||||
@@ -992,7 +784,7 @@ impl State {
|
||||
/// Allocate (or reuse) a stable inode for a node, updating the hot-cache maps
|
||||
/// only. Every caller owes the DB a write-through — see the callers below;
|
||||
/// the split exists so a batch can pay for one transaction instead of `n`.
|
||||
pub(crate) fn intern_mem(&mut self, parent: u64, node: Node) -> u64 {
|
||||
pub fn intern_mem(&mut self, parent: u64, node: Node) -> u64 {
|
||||
let access = self.access_for_node(parent, &node);
|
||||
self.intern_mem_with_access(parent, node, access)
|
||||
}
|
||||
@@ -1059,7 +851,7 @@ impl State {
|
||||
fn new_inos(&mut self, nodes: &[&Node]) -> HashMap<NodeUid, u64> {
|
||||
let (virtual_nodes, stored): (Vec<&Node>, Vec<&Node>) = nodes
|
||||
.iter()
|
||||
.partition(|node| crate::r#virtual::is_virtual_uid(&node.uid));
|
||||
.partition(|node| crate::ids::is_virtual_uid(&node.uid));
|
||||
let mut inos = match self.db.lids_for(&stored) {
|
||||
Ok(lids) => stored
|
||||
.iter()
|
||||
@@ -1087,7 +879,7 @@ impl State {
|
||||
}
|
||||
|
||||
/// Decrement lookup count for an inode and prune if lookup_count == 0 && open_count == 0 && unlinked.
|
||||
pub(crate) fn forget_lookup(&mut self, ino: u64, nlookup: u64) -> Option<(u64, String)> {
|
||||
pub fn forget_lookup(&mut self, ino: u64, nlookup: u64) -> Option<(u64, String)> {
|
||||
if let Some(entry) = self.entries.get_mut(&ino) {
|
||||
entry.lookup_count = entry.lookup_count.saturating_sub(nlookup);
|
||||
if entry.lookup_count == 0 && entry.open_count == 0 && entry.unlinked {
|
||||
@@ -1107,8 +899,8 @@ impl State {
|
||||
/// queues it. Taking the remote's size shrank a SQLite database to its empty
|
||||
/// create while SQLite held it open, and the kernel then capped every read
|
||||
/// at that size (docs/BUGS.md B109).
|
||||
pub(crate) fn keep_open_write_size(&self, ino: u64, node: &mut Node) {
|
||||
let (Some(aw), Some(entry)) = (self.active_writes.get(&ino), self.entries.get(&ino)) else {
|
||||
pub fn keep_open_write_size(&self, ino: u64, node: &mut Node) {
|
||||
let (Some(aw), Some(entry)) = (self.open.writer(ino), self.entries.get(&ino)) else {
|
||||
return;
|
||||
};
|
||||
if let NodeKind::File { claimed_size, .. } = &mut node.kind {
|
||||
@@ -1117,7 +909,7 @@ impl State {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn intern_from_db(&mut self, parent: u64, node: Node) -> u64 {
|
||||
pub fn intern_from_db(&mut self, parent: u64, node: Node) -> u64 {
|
||||
self.intern_mem(parent, node)
|
||||
}
|
||||
|
||||
@@ -1126,8 +918,8 @@ impl State {
|
||||
///
|
||||
/// This is what keeps `ls` on a large folder quick: one commit for the
|
||||
/// listing, rather than one autocommit — and one fsync — per child.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn intern_batch(&mut self, parent: u64, nodes: Vec<Node>) -> Vec<u64> {
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn intern_batch(&mut self, parent: u64, nodes: Vec<Node>) -> Vec<u64> {
|
||||
self.intern_batch_with_inos(parent, nodes, HashMap::new())
|
||||
}
|
||||
|
||||
@@ -1136,7 +928,7 @@ impl State {
|
||||
/// is a write transaction, and under the lock every inline handler of
|
||||
/// every mount waited for it (`docs/BUGS.md` B221). A node missing from
|
||||
/// `inos` still gets one here.
|
||||
pub(crate) fn intern_batch_with_inos(
|
||||
pub fn intern_batch_with_inos(
|
||||
&mut self,
|
||||
parent: u64,
|
||||
mut nodes: Vec<Node>,
|
||||
@@ -1167,12 +959,12 @@ impl State {
|
||||
/// Record `uid`'s listing as complete once the lock is released, after the
|
||||
/// rows of its children: written the other way round, a crash between the
|
||||
/// two left a folder marked complete with no children to show.
|
||||
pub(crate) fn record_listed(&mut self, uid: NodeUid) {
|
||||
pub fn record_listed(&mut self, uid: NodeUid) {
|
||||
self.outbox.push(DbWrite::SetListed(uid, true));
|
||||
}
|
||||
|
||||
/// Check if a directory inode has any child nodes in memory or in the database.
|
||||
pub(crate) fn has_children(&self, parent: u64) -> bool {
|
||||
pub fn has_children(&self, parent: u64) -> bool {
|
||||
// A resident listing is authoritative even when empty. Falling through
|
||||
// from `Some([])` to SQLite lets an obsolete child row contradict the
|
||||
// listing `ensure_children` just established, so readdir says empty but
|
||||
@@ -1189,7 +981,7 @@ impl State {
|
||||
}
|
||||
|
||||
/// Check if `ancestor_ino` is `target_ino` or an ancestor of `target_ino` (for rename cycle prevention).
|
||||
pub(crate) fn is_ancestor_of(&self, ancestor_ino: u64, mut target_ino: u64) -> bool {
|
||||
pub fn is_ancestor_of(&self, ancestor_ino: u64, mut target_ino: u64) -> bool {
|
||||
if ancestor_ino == target_ino {
|
||||
return true;
|
||||
}
|
||||
@@ -1210,7 +1002,7 @@ impl State {
|
||||
|
||||
/// Forget a node or, if open handles exist (open_count > 0), mark it unlinked
|
||||
/// and remove it from parent children so lookups fail while open reads succeed.
|
||||
pub(crate) fn forget_or_unlink(&mut self, uid: &NodeUid) -> Option<(u64, String)> {
|
||||
pub fn forget_or_unlink(&mut self, uid: &NodeUid) -> Option<(u64, String)> {
|
||||
if let Some(&ino) = self.by_uid.get(uid)
|
||||
&& let Some(entry) = self.entries.get_mut(&ino)
|
||||
&& entry.open_count > 0
|
||||
@@ -1227,7 +1019,7 @@ impl State {
|
||||
/// Remove a dentry while retaining both open inode state and the persisted
|
||||
/// node row. Queued trash needs the row as drain-time authority; if the node
|
||||
/// is open, POSIX also requires its inode to survive until the final close.
|
||||
pub(crate) fn unlink_mem(&mut self, uid: &NodeUid) -> Option<(u64, String)> {
|
||||
pub fn unlink_mem(&mut self, uid: &NodeUid) -> Option<(u64, String)> {
|
||||
if let Some(&ino) = self.by_uid.get(uid)
|
||||
&& let Some(entry) = self.entries.get_mut(&ino)
|
||||
&& entry.open_count > 0
|
||||
@@ -1245,7 +1037,7 @@ impl State {
|
||||
/// listing, its slot in its parent's listing, and its DB row. Returns
|
||||
/// `(parent_ino, name)` when the node was known, so the caller can notify
|
||||
/// the kernel.
|
||||
pub(crate) fn forget(&mut self, uid: &NodeUid) -> Option<(u64, String)> {
|
||||
pub fn forget(&mut self, uid: &NodeUid) -> Option<(u64, String)> {
|
||||
self.outbox.push(DbWrite::Delete(uid.clone()));
|
||||
self.forget_mem(uid)
|
||||
}
|
||||
@@ -1254,7 +1046,7 @@ impl State {
|
||||
///
|
||||
/// A queued trash uses the row as its drain-time access authority and only
|
||||
/// deletes it after the remote mutation lands.
|
||||
pub(crate) fn forget_mem(&mut self, uid: &NodeUid) -> Option<(u64, String)> {
|
||||
pub fn forget_mem(&mut self, uid: &NodeUid) -> Option<(u64, String)> {
|
||||
let ino = self.by_uid.remove(uid)?;
|
||||
let entry = self.entries.remove(&ino)?;
|
||||
self.children.remove(&ino);
|
||||
@@ -1272,7 +1064,7 @@ impl State {
|
||||
/// server did. A queued rename cannot: re-enumerating needs the network, and
|
||||
/// the server has not been told yet in any case — so this *is* the tree's
|
||||
/// new truth until the op drains.
|
||||
pub(crate) fn rename_in_place(
|
||||
pub fn rename_in_place(
|
||||
&mut self,
|
||||
ino: u64,
|
||||
new_parent: u64,
|
||||
@@ -1320,7 +1112,7 @@ impl State {
|
||||
/// trimmed from the hot cache but still `listed` in the DB is exactly the
|
||||
/// case that needs invalidating — returning early there would leave
|
||||
/// `ensure_children` free to rebuild the stale listing from disk.
|
||||
pub(crate) fn invalidate_listing(&mut self, ino: u64) {
|
||||
pub fn invalidate_listing(&mut self, ino: u64) {
|
||||
self.children.remove(&ino);
|
||||
if let Some(e) = self.entries.get(&ino) {
|
||||
let uid = e.uid.clone();
|
||||
@@ -1350,7 +1142,7 @@ impl State {
|
||||
/// entry TTL expires. Keeping the inode keeps the kernel's dentry valid.
|
||||
///
|
||||
/// A pure rename (`from == to`) invalidates that one directory once.
|
||||
pub(crate) fn relocate(
|
||||
pub fn relocate(
|
||||
&mut self,
|
||||
ino: u64,
|
||||
from_parent: u64,
|
||||
@@ -1367,7 +1159,7 @@ impl State {
|
||||
|
||||
/// Update a file entry's recorded plaintext size so `getattr` reflects an
|
||||
/// in-progress write before the new revision is sealed.
|
||||
pub(crate) fn set_size(&mut self, ino: u64, size: u64) {
|
||||
pub fn set_size(&mut self, ino: u64, size: u64) {
|
||||
if let Some(e) = self.entries.get_mut(&ino)
|
||||
&& let NodeKind::File { claimed_size, .. } = &mut e.node.kind
|
||||
{
|
||||
@@ -1376,7 +1168,7 @@ impl State {
|
||||
}
|
||||
|
||||
/// Update a file entry's modification time (epoch seconds).
|
||||
pub(crate) fn touch_mtime(&mut self, ino: u64, secs: i64) {
|
||||
pub fn touch_mtime(&mut self, ino: u64, secs: i64) {
|
||||
if let Some(e) = self.entries.get_mut(&ino) {
|
||||
e.node.modification_time = secs;
|
||||
}
|
||||
@@ -1396,7 +1188,7 @@ impl State {
|
||||
/// failure has to be reported, not logged. Dropping the row silently means
|
||||
/// the daemon acknowledged a write and then serves the old size for it, so
|
||||
/// the caller has to be able to turn it into a failed `release`.
|
||||
pub(crate) fn record_pending_write(&mut self, ino: u64, size: u64, mtime: i64) -> Option<Node> {
|
||||
pub fn record_pending_write(&mut self, ino: u64, size: u64, mtime: i64) -> Option<Node> {
|
||||
self.set_size(ino, size);
|
||||
self.touch_mtime(ino, mtime);
|
||||
self.entries.get(&ino).map(|e| e.node.clone())
|
||||
@@ -1406,13 +1198,16 @@ impl State {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::open::{Intervals, WriteHandle};
|
||||
use proton_drive_rs::ShareMembership;
|
||||
use proton_drive_rs::proton_sdk::ids::{LinkId, ShareId, ShareMembershipId, VolumeId};
|
||||
use std::fs::File;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn an_inode_gives_back_the_lid_it_was_made_from() {
|
||||
assert_eq!(ino_lid(lid_ino(7)), Some(7));
|
||||
assert_eq!(ino_lid(crate::ROOT_INO), None);
|
||||
assert_eq!(ino_lid(crate::ids::ROOT_INO), None);
|
||||
assert_eq!(ino_lid(FALLBACK_INO + 3), None);
|
||||
}
|
||||
|
||||
@@ -1525,7 +1320,7 @@ mod tests {
|
||||
st.flush_outbox();
|
||||
let db = st.db.clone();
|
||||
assert_ne!(inos[0], inos[1]);
|
||||
assert!(!inos.contains(&crate::ROOT_INO));
|
||||
assert!(!inos.contains(&crate::ids::ROOT_INO));
|
||||
|
||||
let mut other = State::new(db.clone(), HashMap::new());
|
||||
assert_eq!(other.intern(0, node("b", "root", "b.txt", false)), inos[1]);
|
||||
@@ -1860,11 +1655,17 @@ mod tests {
|
||||
assert_eq!(st.entries[&child].access, Access::Viewer);
|
||||
assert_eq!(st.entries[&leaf].access, Access::Viewer);
|
||||
assert_eq!(
|
||||
st.require_writable(shared).unwrap_err().code(),
|
||||
libc::EACCES
|
||||
st.require_writable(shared).unwrap_err(),
|
||||
NodeError::NotWritable
|
||||
);
|
||||
assert_eq!(
|
||||
st.require_writable(child).unwrap_err(),
|
||||
NodeError::NotWritable
|
||||
);
|
||||
assert_eq!(
|
||||
st.require_writable(leaf).unwrap_err(),
|
||||
NodeError::NotWritable
|
||||
);
|
||||
assert_eq!(st.require_writable(child).unwrap_err().code(), libc::EACCES);
|
||||
assert_eq!(st.require_writable(leaf).unwrap_err().code(), libc::EACCES);
|
||||
assert!(st.require_writable(owned_root).is_ok());
|
||||
}
|
||||
|
||||
@@ -1880,24 +1681,24 @@ mod tests {
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, node)| {
|
||||
let ino = crate::ROOT_INO + i as u64;
|
||||
let ino = crate::ids::ROOT_INO + i as u64;
|
||||
st.by_uid.insert(node.uid.clone(), ino);
|
||||
ino
|
||||
})
|
||||
.collect();
|
||||
st.next_ino = crate::ROOT_INO + nodes.len() as u64;
|
||||
st.roots.insert(crate::ROOT_INO);
|
||||
st.next_ino = crate::ids::ROOT_INO + nodes.len() as u64;
|
||||
st.roots.insert(crate::ids::ROOT_INO);
|
||||
// Reverse order so entries are inserted before their parents, matching
|
||||
// the hydration path's non-topological materialization.
|
||||
for (i, node) in nodes.iter().enumerate().rev() {
|
||||
let ino = inos[i];
|
||||
let parent = if ino == crate::ROOT_INO {
|
||||
crate::ROOT_INO
|
||||
let parent = if ino == crate::ids::ROOT_INO {
|
||||
crate::ids::ROOT_INO
|
||||
} else {
|
||||
node.parent_uid
|
||||
.as_ref()
|
||||
.and_then(|p| st.by_uid.get(p).copied())
|
||||
.unwrap_or(crate::ORPHAN_INO)
|
||||
.unwrap_or(crate::ids::ORPHAN_INO)
|
||||
};
|
||||
st.entries.insert(
|
||||
ino,
|
||||
@@ -1964,7 +1765,10 @@ mod tests {
|
||||
assert_eq!(st.entries[&inos[0]].access, Access::Owner);
|
||||
for ino in &inos[1..] {
|
||||
assert_eq!(st.entries[ino].access, Access::Unknown);
|
||||
assert_eq!(st.require_writable(*ino).unwrap_err().code(), libc::EACCES);
|
||||
assert_eq!(
|
||||
st.require_writable(*ino).unwrap_err(),
|
||||
NodeError::NotWritable
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1987,7 +1791,10 @@ mod tests {
|
||||
assert_eq!(st.entries[&inos[0]].access, Access::Owner);
|
||||
for ino in &inos[1..] {
|
||||
assert_eq!(st.entries[ino].access, Access::Viewer);
|
||||
assert_eq!(st.require_writable(*ino).unwrap_err().code(), libc::EACCES);
|
||||
assert_eq!(
|
||||
st.require_writable(*ino).unwrap_err(),
|
||||
NodeError::NotWritable
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2007,7 +1814,10 @@ mod tests {
|
||||
|
||||
for ino in [shared, child, leaf] {
|
||||
assert_eq!(st.entries[&ino].access, Access::Viewer);
|
||||
assert_eq!(st.require_writable(ino).unwrap_err().code(), libc::EACCES);
|
||||
assert_eq!(
|
||||
st.require_writable(ino).unwrap_err(),
|
||||
NodeError::NotWritable
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
st.flushed_db().share_access(&uid("shared")).unwrap(),
|
||||
@@ -2154,7 +1964,10 @@ mod tests {
|
||||
assert!(!st.entries.contains_key(&shared));
|
||||
assert_eq!(st.entries[&child].access, Access::Viewer);
|
||||
assert_eq!(st.entries[&leaf].access, Access::Viewer);
|
||||
assert_eq!(st.require_writable(leaf).unwrap_err().code(), libc::EACCES);
|
||||
assert_eq!(
|
||||
st.require_writable(leaf).unwrap_err(),
|
||||
NodeError::NotWritable
|
||||
);
|
||||
assert_eq!(
|
||||
st.flushed_db().effective_node_access(&uid("leaf")).unwrap(),
|
||||
Some(Access::Viewer)
|
||||
@@ -2199,7 +2012,10 @@ mod tests {
|
||||
|
||||
assert_eq!(st.entries[&child].access, Access::Viewer);
|
||||
assert_eq!(st.entries[&leaf].access, Access::Viewer);
|
||||
assert_eq!(st.require_writable(leaf).unwrap_err().code(), libc::EACCES);
|
||||
assert_eq!(
|
||||
st.require_writable(leaf).unwrap_err(),
|
||||
NodeError::NotWritable
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2295,13 +2111,13 @@ mod tests {
|
||||
assert_eq!(st.entries[&ino].node.name, "b.txt");
|
||||
// A listing that leaves the size out still describes revision r1.
|
||||
let mut bare = at_revision(file.clone(), "r1", 170);
|
||||
assert_eq!(crate::node_size(&st.entries[&ino].node), 7);
|
||||
assert_eq!(pdfs_drive::node_size(&st.entries[&ino].node), 7);
|
||||
if let NodeKind::File { claimed_size, .. } = &mut bare.kind {
|
||||
*claimed_size = None;
|
||||
}
|
||||
st.intern(root, bare);
|
||||
assert_eq!(st.entries[&ino].node.modification_time, 100);
|
||||
assert_eq!(crate::node_size(&st.entries[&ino].node), 7);
|
||||
assert_eq!(pdfs_drive::node_size(&st.entries[&ino].node), 7);
|
||||
st.intern(root, at_revision(file, "r2", 200));
|
||||
assert_eq!(st.entries[&ino].node.modification_time, 200);
|
||||
}
|
||||
@@ -2325,92 +2141,24 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resize_the_scratch_file_refuses_changes_nothing() {
|
||||
let mut h = handle(4, 4);
|
||||
h.written.add(0, 4);
|
||||
// A read-only descriptor refuses `ftruncate`, as a full disk does a grow.
|
||||
let path = std::env::temp_dir().join(format!("pdfs-resize-test-{}", std::process::id()));
|
||||
std::fs::write(&path, b"kept").unwrap();
|
||||
h.file = Arc::new(File::open(&path).unwrap());
|
||||
let _ = std::fs::remove_file(&path);
|
||||
|
||||
assert!(h.resize(10).is_err());
|
||||
assert_eq!((h.len, h.dirty), (4, false));
|
||||
assert_eq!(h.written.segments(4, 10), vec![(4, 10, false)]);
|
||||
|
||||
let mut h = handle(4, 4);
|
||||
h.resize(10).unwrap();
|
||||
assert_eq!((h.len, h.dirty), (10, true));
|
||||
assert_eq!(h.written.segments(4, 10), vec![(4, 10, true)]);
|
||||
}
|
||||
|
||||
/// A file created offline is written while its queued create lands. The
|
||||
/// placeholder had no revision, so the handle takes the empty file the
|
||||
/// create made as its base (docs/BUGS.md B113).
|
||||
#[test]
|
||||
fn a_handle_on_a_placeholder_is_based_on_the_create_that_landed() {
|
||||
let mut h = handle(0, 0);
|
||||
assert_eq!(h.base_revision_id, None);
|
||||
let mut landed = node("real", "root", "f.mkv", false);
|
||||
landed.modification_time = 160;
|
||||
if let NodeKind::File {
|
||||
active_revision_id, ..
|
||||
} = &mut landed.kind
|
||||
{
|
||||
*active_revision_id = Some("empty".into());
|
||||
}
|
||||
h.rebase_onto(&landed);
|
||||
assert_eq!(h.base_mtime, 160);
|
||||
assert_eq!(h.base_size, 0);
|
||||
assert_eq!(h.base_revision_id.as_deref(), Some("empty"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_listing_does_not_shrink_a_file_open_for_writing() {
|
||||
let (mut st, _dir) = state();
|
||||
let ino = st.intern(0, node("file", "root", "workload.db", false));
|
||||
let mut h = handle(16384, 0);
|
||||
h.ino = ino;
|
||||
st.active_writes.insert(ino, h);
|
||||
st.open.insert_writer(h);
|
||||
st.set_size(ino, 16384);
|
||||
st.touch_mtime(ino, 500);
|
||||
|
||||
// The remote still holds the empty file the create sealed.
|
||||
st.intern(0, node("file", "root", "workload.db", false));
|
||||
assert_eq!(crate::node_size(&st.entries[&ino].node), 16384);
|
||||
assert_eq!(pdfs_drive::node_size(&st.entries[&ino].node), 16384);
|
||||
assert_eq!(st.entries[&ino].node.modification_time, 500);
|
||||
|
||||
// Once the handle is gone the remote is authoritative again.
|
||||
st.active_writes.remove(&ino);
|
||||
st.open.remove_writer(ino);
|
||||
st.intern(0, node("file", "root", "workload.db", false));
|
||||
assert_eq!(crate::node_size(&st.entries[&ino].node), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_write_past_the_end_authors_the_hole_it_leaves() {
|
||||
// Opened over a 100-byte base, shrunk to 10, then written at 50: bytes
|
||||
// 10..50 are zeros now, not the base's bytes 10..50.
|
||||
let mut h = handle(100, 100);
|
||||
h.written.clip(10);
|
||||
h.len = 10;
|
||||
h.record_write(50, 60);
|
||||
assert_eq!(h.len, 60);
|
||||
assert_eq!(
|
||||
h.written.segments(0, 60),
|
||||
vec![(0, 10, false), (10, 60, true)],
|
||||
"only the head still comes from the base"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_write_inside_the_file_leaves_the_rest_to_the_base() {
|
||||
let mut h = handle(100, 100);
|
||||
h.record_write(40, 50);
|
||||
assert_eq!(h.len, 100);
|
||||
assert_eq!(
|
||||
h.written.segments(0, 100),
|
||||
vec![(0, 40, false), (40, 50, true), (50, 100, false)]
|
||||
);
|
||||
assert_eq!(pdfs_drive::node_size(&st.entries[&ino].node), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
//! 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 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()
|
||||
}
|
||||
|
||||
/// 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"
|
||||
);
|
||||
}
|
||||
}
|
||||
+59
-10
@@ -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`), and the open files (`open`: write handles and their authored ranges, released writes waiting for upload, directory handles, `fallocate` rules), 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/` |
|
||||
@@ -479,10 +480,14 @@ both with `pdfs_core::search::relevance_score`, so the prompt can merge them int
|
||||
| Smaller helpers | `pdfs-localindex` (home index for search), `pdfs-pause` (ends a timed pause), `pdfs-similar` (similar photos, on request), `pdfs-diagnostics` |
|
||||
|
||||
Long-running loops wait on one shared `Shutdown` signal instead of sleeping, so a stop joins them
|
||||
instead of leaving them behind (`docs/BUGS.md` B44). The mount starts its long-lived threads
|
||||
through `pdfs_core::lifecycle::Services`. Each one is started with its name and, if it blocks where
|
||||
the signal does not reach, the call that wakes it: the drain's condvar, the sync engine's `Stop`
|
||||
message, a connection to the control socket. A stop signals, wakes and joins them in reverse start
|
||||
instead of leaving them behind (`docs/BUGS.md` B44). Each long-lived thread is a
|
||||
`pdfs_core::lifecycle::Service`, defined in `pdfs-fuse/src/services.rs`. A service says what its
|
||||
thread is called, whether the mount can run without it, and, if it blocks where the signal does
|
||||
not reach, the call that wakes it: the drain's condvar, the sync engine's `Stop` message, a
|
||||
connection to the control socket. The mount builds the list and starts it through
|
||||
`Services::start`. A required service that cannot start fails the mount attempt, which is retried;
|
||||
an optional one (the sync engine, the event sampler, the supervisor, the inhibitor) is logged and
|
||||
skipped. A stop signals, wakes and joins them in reverse start
|
||||
order, up to one 10-second deadline, and names any that are still running at the end. A
|
||||
service can also be an async task on the runtime (`Services::spawn_task`): the event streams and
|
||||
the gallery refresh. A stop aborts such a task at its next `.await` and waits for it to end. These
|
||||
@@ -496,7 +501,10 @@ re-date, a profile backup, a size upgrade) runs as a one-shot job:
|
||||
`ServiceBoard::spawn_job` starts it on a named thread and lists it until it ends. `pdfs
|
||||
diagnostics` shows the jobs running and how long each has run. Async work of the same kind (the
|
||||
trash, timeline and album refreshes a listing starts) goes through `ServiceBoard::spawn_task_job`
|
||||
and is listed the same way. Jobs are not joined on stop.
|
||||
and is listed the same way. Each control connection is a job too. A stop closes the board to new
|
||||
jobs, aborts the async ones and joins the thread jobs before the services, up to the same
|
||||
deadline. A long job checks the `Shutdown` signal between steps. Jobs used to be left running, and
|
||||
one still waiting on Drive when the runtime went away panicked on its next timer.
|
||||
|
||||
---
|
||||
|
||||
@@ -764,8 +772,9 @@ State that several owners share sits behind a narrow interface of its own:
|
||||
- `session::SessionCells` holds what belongs to one mount's FUSE session: whether it is the
|
||||
primary mount, its root inode, its kernel channel and whether it is up. An on-demand fork gets
|
||||
fresh cells from `SessionCells::fork`, and shares the rest of `Core`.
|
||||
- `link::Link` holds whether Drive answers, next to when the link went down. Code reads it through
|
||||
`Core::is_online`.
|
||||
- `link::Link` holds whether Drive answers, next to when the link went down, and is the only
|
||||
code that changes it: it flips the flag, logs the outage and wakes whoever waits. Code reads it
|
||||
through `Core::is_online`.
|
||||
|
||||
Some areas are services of their own rather than methods on `Core`. `sharing::Sharing` holds
|
||||
only the handles it calls (the client, Drive, the content cache, the transfer list and a read of
|
||||
@@ -799,14 +808,54 @@ folders and on-demand mounts are still methods on `Core`.
|
||||
machines wrote, to offer their folders for restore. It needs nothing from the filesystem, so it
|
||||
has no host. Turning the offered folders into synced folders stays on `Core`.
|
||||
|
||||
`maintenance::Maintenance` runs `VACUUM` and the deep integrity check as jobs, one at a time, and
|
||||
keeps the last check's findings.
|
||||
|
||||
`search::Search` answers searches over the node and home indexes. It holds the database, the
|
||||
content cache, the on-demand mounts and the home indexer's busy flag.
|
||||
|
||||
`recovery::Recovery` rebuilds the queue after a restart: the pending map, the staging area and
|
||||
writes fsynced before the stop. Its `RecoveryHost` port queues a recovered write. Rebuilding the
|
||||
tree stays on `Core`.
|
||||
|
||||
The mount's background loops are services of their own too, each started from the list in
|
||||
`services.rs`:
|
||||
|
||||
- `link::OnlineProbe` probes the link back while it is down. Its `LinkHost` port stores the root
|
||||
Drive answered with, lets what waited on the link go (relisting, retrying backed-off ops,
|
||||
waking the drain, rechecking pins), reports a refused session and repairs the root's share id.
|
||||
- `sweep::Sweeper` is the conflict sweep. Its `SweepHost` port asks whether a node is the
|
||||
account's own, whether the mount is online, whether a node is busy in any mount and whether
|
||||
the conflict listing can show a copy; it unhooks a trashed copy from every mount and adds
|
||||
activity entries.
|
||||
- `keeper::PinKeeper` keeps pinned files current. Its `KeeperHost` port finds a node in the tree,
|
||||
lists kept folders, describes a file as a pin keeps it and downloads it.
|
||||
- The inhibitor takes only the database and the stop signal.
|
||||
|
||||
The drain workers, the control listener, the event sampler and the supervisor still take a whole
|
||||
`Core`. The drain is the write-back, which is part of the mounted-files service (step 5); the
|
||||
other three answer front ends with reports drawn from every area.
|
||||
|
||||
The control socket answers each area's requests in a module of its own under `control/`:
|
||||
sharing, Photos, synced folders and devices, revisions, and the trash and cache. Each module
|
||||
exports a pattern macro naming its requests, and the main match hands them over in one arm, so
|
||||
the compiler still checks that every request has an answer. A module turns a path or a uid into a
|
||||
node once, then asks the service.
|
||||
|
||||
What is left in `Core` is the tree, the database, the cache and the Drive client, which most
|
||||
owners use, plus single fields that belong to one module each.
|
||||
What is left in `Core` is the mounted-files side: the tree and its per-mount state, reads,
|
||||
queued writes and the drain, listings and sizes, path requests, and the registry of on-demand
|
||||
mounts. Step 5 turns that into the `pdfs-vfs` service. `Core` also implements the services'
|
||||
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. What still
|
||||
sits in `pdfs-fuse` around the tree is the code that fills it (listings, sizes, the drain) and
|
||||
the code that reads and queues content.
|
||||
|
||||
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
|
||||
|
||||
+31
-1
@@ -108,6 +108,7 @@ a live account since.
|
||||
|
||||
| Entry | Title |
|
||||
|---|---|
|
||||
| [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 +403,35 @@ a live account since.
|
||||
|
||||
Newest first.
|
||||
|
||||
### 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)
|
||||
@@ -6004,7 +6034,7 @@ since Sep 20, 13:13 · Resolved`. `find` showed all six copies still on disk, in
|
||||
journal showed the daemon mounting at 17:29:33, and the entries were stamped 17:30. That is the
|
||||
sweep's 30-second warmup.
|
||||
|
||||
**Where:** `crates/pdfs-fuse/src/sweep.rs` (`flag_conflict`, `sweep_conflicts_once`),
|
||||
**Where:** `crates/pdfs-fuse/src/sweep.rs` (`flag_conflict`, `Sweeper::sweep_once`),
|
||||
`crates/pdfs-fuse/src/conflicts.rs` (`list_conflicts`), `crates/pdfs-fuse/src/control.rs`
|
||||
(`ResolveConflict`).
|
||||
|
||||
|
||||
Reference in new issue
Block a user