mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-12-01 12:32:13 +01:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
afbf88aa2d | ||
|
|
e93e2a3ef9 |
No files matched your search
@@ -323,6 +323,14 @@ pub(super) fn cmd_diagnostics() -> Result<()> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if !d.jobs.is_empty() {
|
||||||
|
let jobs: Vec<String> = d
|
||||||
|
.jobs
|
||||||
|
.iter()
|
||||||
|
.map(|job| format!("{} ({})", job.name, human_secs(job.age_secs)))
|
||||||
|
.collect();
|
||||||
|
println!("jobs: {}", jobs.join(", "));
|
||||||
|
}
|
||||||
if let Some(sync) = &d.sync {
|
if let Some(sync) = &d.sync {
|
||||||
println!("sync engine: {}", sync_engine_line(sync));
|
println!("sync engine: {}", sync_engine_line(sync));
|
||||||
for trace in &sync.traces {
|
for trace in &sync.traces {
|
||||||
|
|||||||
@@ -2378,9 +2378,14 @@ pub struct Diagnostics {
|
|||||||
/// still running. Empty from a daemon that predates the field.
|
/// still running. Empty from a daemon that predates the field.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub services: Vec<ServiceState>,
|
pub services: Vec<ServiceState>,
|
||||||
|
/// The one-shot jobs running now, such as a cache check, an import or a
|
||||||
|
/// folder pin, oldest first. Empty from a daemon that predates the field.
|
||||||
|
#[serde(default)]
|
||||||
|
pub jobs: Vec<ServiceState>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One long-lived daemon thread, in [`Diagnostics::services`].
|
/// One long-lived daemon thread, in [`Diagnostics::services`], or one
|
||||||
|
/// one-shot job, in [`Diagnostics::jobs`].
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
||||||
pub struct ServiceState {
|
pub struct ServiceState {
|
||||||
/// The thread's name, such as `pdfs-sync`.
|
/// The thread's name, such as `pdfs-sync`.
|
||||||
|
|||||||
@@ -12,9 +12,13 @@
|
|||||||
//! reverse start order: it signals [`Shutdown`], wakes each one, and joins each
|
//! reverse start order: it signals [`Shutdown`], wakes each one, and joins each
|
||||||
//! one up to a shared deadline, naming any that is still running then.
|
//! one up to a shared deadline, naming any that is still running then.
|
||||||
//! [`ServiceBoard`] is the live view of the same threads, for diagnostics.
|
//! [`ServiceBoard`] is the live view of the same threads, for diagnostics.
|
||||||
|
//!
|
||||||
|
//! Work a request starts and does not wait for runs as a one-shot job
|
||||||
|
//! ([`ServiceBoard::spawn_job`]): a named thread, listed on the board while
|
||||||
|
//! it runs, and not joined on stop.
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||||
use std::thread::JoinHandle;
|
use std::thread::JoinHandle;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
@@ -35,10 +39,18 @@ pub struct ServiceHealth {
|
|||||||
pub age: Duration,
|
pub age: Duration,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The live view of the service threads: which ones were started, and which
|
/// The live view of the service threads, which were started and which are
|
||||||
/// are still running. Cheap to clone and to read; never blocks on a service.
|
/// still running, and of the one-shot jobs running now. Cheap to clone and to
|
||||||
|
/// read; never blocks on a service or a job.
|
||||||
#[derive(Clone, Default)]
|
#[derive(Clone, Default)]
|
||||||
pub struct ServiceBoard(Arc<Mutex<Vec<Entry>>>);
|
pub struct ServiceBoard(Arc<Board>);
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Board {
|
||||||
|
services: Mutex<Vec<Entry>>,
|
||||||
|
jobs: Mutex<Vec<Job>>,
|
||||||
|
next_job: AtomicU64,
|
||||||
|
}
|
||||||
|
|
||||||
struct Entry {
|
struct Entry {
|
||||||
name: String,
|
name: String,
|
||||||
@@ -46,10 +58,17 @@ struct Entry {
|
|||||||
running: Arc<AtomicBool>,
|
running: Arc<AtomicBool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct Job {
|
||||||
|
id: u64,
|
||||||
|
name: String,
|
||||||
|
started: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
impl ServiceBoard {
|
impl ServiceBoard {
|
||||||
/// Every service thread started so far, in start order.
|
/// Every service thread started so far, in start order.
|
||||||
pub fn health(&self) -> Vec<ServiceHealth> {
|
pub fn health(&self) -> Vec<ServiceHealth> {
|
||||||
self.0
|
self.0
|
||||||
|
.services
|
||||||
.lock()
|
.lock()
|
||||||
.iter()
|
.iter()
|
||||||
.map(|entry| ServiceHealth {
|
.map(|entry| ServiceHealth {
|
||||||
@@ -60,9 +79,56 @@ impl ServiceBoard {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The one-shot jobs running now, oldest first. A job leaves the list
|
||||||
|
/// when its thread ends.
|
||||||
|
pub fn jobs(&self) -> Vec<ServiceHealth> {
|
||||||
|
self.0
|
||||||
|
.jobs
|
||||||
|
.lock()
|
||||||
|
.iter()
|
||||||
|
.map(|job| ServiceHealth {
|
||||||
|
name: job.name.clone(),
|
||||||
|
running: true,
|
||||||
|
age: job.started.elapsed(),
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start `run` on a thread named `name`, as a one-shot job: a request's
|
||||||
|
/// work that outlasts the request, such as a cache check, an import or a
|
||||||
|
/// 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.
|
||||||
|
pub fn spawn_job<F>(&self, name: &str, run: F) -> std::io::Result<()>
|
||||||
|
where
|
||||||
|
F: FnOnce() + Send + 'static,
|
||||||
|
{
|
||||||
|
let id = self.0.next_job.fetch_add(1, Ordering::Relaxed);
|
||||||
|
self.0.jobs.lock().push(Job {
|
||||||
|
id,
|
||||||
|
name: name.to_owned(),
|
||||||
|
started: Instant::now(),
|
||||||
|
});
|
||||||
|
let guard = JobGuard {
|
||||||
|
board: self.0.clone(),
|
||||||
|
id,
|
||||||
|
};
|
||||||
|
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(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
fn add(&self, name: &str) -> Arc<AtomicBool> {
|
fn add(&self, name: &str) -> Arc<AtomicBool> {
|
||||||
let running = Arc::new(AtomicBool::new(true));
|
let running = Arc::new(AtomicBool::new(true));
|
||||||
self.0.lock().push(Entry {
|
self.0.services.lock().push(Entry {
|
||||||
name: name.to_owned(),
|
name: name.to_owned(),
|
||||||
started: Instant::now(),
|
started: Instant::now(),
|
||||||
running: running.clone(),
|
running: running.clone(),
|
||||||
@@ -71,6 +137,18 @@ impl ServiceBoard {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Takes a job off the board when its thread ends, by return or by panic.
|
||||||
|
struct JobGuard {
|
||||||
|
board: Arc<Board>,
|
||||||
|
id: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for JobGuard {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.board.jobs.lock().retain(|job| job.id != self.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Clears a service's `running` flag when its thread ends, by return or by panic.
|
/// Clears a service's `running` flag when its thread ends, by return or by panic.
|
||||||
struct Running(Arc<AtomicBool>);
|
struct Running(Arc<AtomicBool>);
|
||||||
|
|
||||||
@@ -260,4 +338,40 @@ mod tests {
|
|||||||
assert!(left.is_empty());
|
assert!(left.is_empty());
|
||||||
assert!(!board.health()[0].running);
|
assert!(!board.health()[0].running);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_job_shows_while_it_runs_and_leaves_when_it_ends() {
|
||||||
|
let board = ServiceBoard::default();
|
||||||
|
let (release, wait) = mpsc::channel::<()>();
|
||||||
|
let (done_tx, done_rx) = mpsc::channel::<()>();
|
||||||
|
board
|
||||||
|
.spawn_job("pdfs-test-job", move || {
|
||||||
|
let _ = wait.recv();
|
||||||
|
let _done = done_tx;
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
let jobs = board.jobs();
|
||||||
|
assert_eq!(jobs.len(), 1);
|
||||||
|
assert_eq!(jobs[0].name, "pdfs-test-job");
|
||||||
|
assert!(board.health().is_empty(), "a job is not a service");
|
||||||
|
|
||||||
|
release.send(()).unwrap();
|
||||||
|
let _ = done_rx.recv_timeout(Duration::from_secs(5));
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(5);
|
||||||
|
while !board.jobs().is_empty() && Instant::now() < deadline {
|
||||||
|
std::thread::sleep(Duration::from_millis(5));
|
||||||
|
}
|
||||||
|
assert!(board.jobs().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_job_that_panics_leaves_the_list() {
|
||||||
|
let board = ServiceBoard::default();
|
||||||
|
board.spawn_job("doomed-job", || panic!("boom")).unwrap();
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(5);
|
||||||
|
while !board.jobs().is_empty() && Instant::now() < deadline {
|
||||||
|
std::thread::sleep(Duration::from_millis(5));
|
||||||
|
}
|
||||||
|
assert!(board.jobs().is_empty());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1291,7 +1291,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
|
|||||||
let core = core.clone();
|
let core = core.clone();
|
||||||
let paths: Vec<PathBuf> = sources.into_iter().map(PathBuf::from).collect();
|
let paths: Vec<PathBuf> = sources.into_iter().map(PathBuf::from).collect();
|
||||||
let n = paths.len();
|
let n = paths.len();
|
||||||
std::thread::spawn(move || {
|
if let Err(error) = core.services.clone().spawn_job("pdfs-upload", move || {
|
||||||
let started = Instant::now();
|
let started = Instant::now();
|
||||||
match core.upload_paths(&parent_rel, &paths) {
|
match core.upload_paths(&parent_rel, &paths) {
|
||||||
Ok(stats) => {
|
Ok(stats) => {
|
||||||
@@ -1327,7 +1327,9 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
|
|||||||
core.log_activity(ActivityKind::Upload, "bulk upload", &e, false);
|
core.log_activity(ActivityKind::Upload, "bulk upload", &e, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
}) {
|
||||||
|
tracing::warn!(%error, "could not start pdfs-upload");
|
||||||
|
}
|
||||||
CtlResponse::Ok {
|
CtlResponse::Ok {
|
||||||
message: format!("uploading {n} item(s)"),
|
message: format!("uploading {n} item(s)"),
|
||||||
}
|
}
|
||||||
@@ -1514,29 +1516,35 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
|
|||||||
// completion (and any failures) go to the activity log.
|
// completion (and any failures) go to the activity log.
|
||||||
let core = core.clone();
|
let core = core.clone();
|
||||||
let path = PathBuf::from(&local_path);
|
let path = PathBuf::from(&local_path);
|
||||||
std::thread::spawn(move || {
|
if let Err(error) = core
|
||||||
let started = Instant::now();
|
.services
|
||||||
match core.add_sync_folder(&path) {
|
.clone()
|
||||||
Ok(folder) => {
|
.spawn_job("pdfs-add-sync-folder", move || {
|
||||||
core.touch_profile();
|
let started = Instant::now();
|
||||||
let name = Path::new(&folder.local_path)
|
match core.add_sync_folder(&path) {
|
||||||
.file_name()
|
Ok(folder) => {
|
||||||
.and_then(|n| n.to_str())
|
core.touch_profile();
|
||||||
.unwrap_or(&folder.local_path)
|
let name = Path::new(&folder.local_path)
|
||||||
.to_string();
|
.file_name()
|
||||||
core.log_activity(
|
.and_then(|n| n.to_str())
|
||||||
ActivityKind::Upload,
|
.unwrap_or(&folder.local_path)
|
||||||
format!("synced {name}"),
|
.to_string();
|
||||||
human_duration(started.elapsed()),
|
core.log_activity(
|
||||||
folder.state != "error",
|
ActivityKind::Upload,
|
||||||
);
|
format!("synced {name}"),
|
||||||
|
human_duration(started.elapsed()),
|
||||||
|
folder.state != "error",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
warn!(error = %e, "add sync folder failed");
|
||||||
|
core.log_activity(ActivityKind::Upload, "add sync folder", &e, false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Err(e) => {
|
})
|
||||||
warn!(error = %e, "add sync folder failed");
|
{
|
||||||
core.log_activity(ActivityKind::Upload, "add sync folder", &e, false);
|
tracing::warn!(%error, "could not start pdfs-add-sync-folder");
|
||||||
}
|
}
|
||||||
}
|
|
||||||
});
|
|
||||||
CtlResponse::Ok {
|
CtlResponse::Ok {
|
||||||
message: format!("adding {local_path}"),
|
message: format!("adding {local_path}"),
|
||||||
}
|
}
|
||||||
@@ -1682,26 +1690,37 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
|
|||||||
// Like AddSyncFolder: each restored folder downloads a whole tree,
|
// Like AddSyncFolder: each restored folder downloads a whole tree,
|
||||||
// which outlasts the socket timeout. Ack, then work.
|
// which outlasts the socket timeout. Ack, then work.
|
||||||
let core = core.clone();
|
let core = core.clone();
|
||||||
std::thread::spawn(move || {
|
if let Err(error) =
|
||||||
match core.restore_sync_folders(&items, device.as_deref()) {
|
core.services
|
||||||
Ok(outcome) => {
|
.clone()
|
||||||
core.touch_profile();
|
.spawn_job("pdfs-restore-sync-folders", move || {
|
||||||
if !outcome.complete() {
|
match core.restore_sync_folders(&items, device.as_deref()) {
|
||||||
warn!(skipped = ?outcome.skipped, "restore skipped folders");
|
Ok(outcome) => {
|
||||||
|
core.touch_profile();
|
||||||
|
if !outcome.complete() {
|
||||||
|
warn!(skipped = ?outcome.skipped, "restore skipped folders");
|
||||||
|
}
|
||||||
|
core.log_activity(
|
||||||
|
ActivityKind::Download,
|
||||||
|
outcome.summary(),
|
||||||
|
outcome.skipped.join("; "),
|
||||||
|
outcome.complete(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
warn!(error = %e, "restore failed");
|
||||||
|
core.log_activity(
|
||||||
|
ActivityKind::Download,
|
||||||
|
"restore folders",
|
||||||
|
&e,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
core.log_activity(
|
})
|
||||||
ActivityKind::Download,
|
{
|
||||||
outcome.summary(),
|
tracing::warn!(%error, "could not start pdfs-restore-sync-folders");
|
||||||
outcome.skipped.join("; "),
|
}
|
||||||
outcome.complete(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
warn!(error = %e, "restore failed");
|
|
||||||
core.log_activity(ActivityKind::Download, "restore folders", &e, false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
CtlResponse::Ok {
|
CtlResponse::Ok {
|
||||||
message: "restoring folders".to_string(),
|
message: "restoring folders".to_string(),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -174,6 +174,16 @@ impl Core {
|
|||||||
age_secs: service.age.as_secs(),
|
age_secs: service.age.as_secs(),
|
||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
|
jobs: self
|
||||||
|
.services
|
||||||
|
.jobs()
|
||||||
|
.into_iter()
|
||||||
|
.map(|job| ServiceState {
|
||||||
|
name: job.name,
|
||||||
|
running: job.running,
|
||||||
|
age_secs: job.age.as_secs(),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
drive_calls: self
|
drive_calls: self
|
||||||
.drive_calls
|
.drive_calls
|
||||||
.snapshot()
|
.snapshot()
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ impl Core {
|
|||||||
m.running = true;
|
m.running = true;
|
||||||
}
|
}
|
||||||
let core = self.clone();
|
let core = self.clone();
|
||||||
std::thread::spawn(move || {
|
if let Err(error) = self.services.spawn_job("pdfs-vacuum", move || {
|
||||||
let job = core.transfers.begin_job("Compacting the cache database");
|
let job = core.transfers.begin_job("Compacting the cache database");
|
||||||
job.detail("Rewriting the database file");
|
job.detail("Rewriting the database file");
|
||||||
let started = Instant::now();
|
let started = Instant::now();
|
||||||
@@ -38,7 +38,9 @@ impl Core {
|
|||||||
Err(e) => warn!(error = %e, "vacuum failed"),
|
Err(e) => warn!(error = %e, "vacuum failed"),
|
||||||
}
|
}
|
||||||
core.maintenance.lock().running = false;
|
core.maintenance.lock().running = false;
|
||||||
});
|
}) {
|
||||||
|
tracing::warn!(%error, "could not start pdfs-vacuum");
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,7 +63,7 @@ impl Core {
|
|||||||
drop(m);
|
drop(m);
|
||||||
|
|
||||||
let core = self.clone();
|
let core = self.clone();
|
||||||
std::thread::spawn(move || {
|
if let Err(error) = self.services.spawn_job("pdfs-integrity-check", move || {
|
||||||
let job = core
|
let job = core
|
||||||
.transfers
|
.transfers
|
||||||
.begin_background_job("Checking the cache database");
|
.begin_background_job("Checking the cache database");
|
||||||
@@ -78,7 +80,9 @@ impl Core {
|
|||||||
let mut m = core.maintenance.lock();
|
let mut m = core.maintenance.lock();
|
||||||
m.integrity = Some(problems);
|
m.integrity = Some(problems);
|
||||||
m.running = false;
|
m.running = false;
|
||||||
});
|
}) {
|
||||||
|
tracing::warn!(%error, "could not start pdfs-integrity-check");
|
||||||
|
}
|
||||||
(Vec::new(), false, true)
|
(Vec::new(), false, true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -182,24 +182,22 @@ impl Core {
|
|||||||
pub(crate) fn arm_pause_timer(&self, until: i64) {
|
pub(crate) fn arm_pause_timer(&self, until: i64) {
|
||||||
let core = self.clone();
|
let core = self.clone();
|
||||||
let wait = Duration::from_secs(until.saturating_sub(now_secs()).max(0) as u64);
|
let wait = Duration::from_secs(until.saturating_sub(now_secs()).max(0) as u64);
|
||||||
let spawned = std::thread::Builder::new()
|
let spawned = self.services.spawn_job("pdfs-pause", move || {
|
||||||
.name("pdfs-pause".into())
|
if !core.shutdown.sleep(wait) {
|
||||||
.spawn(move || {
|
return;
|
||||||
if !core.shutdown.sleep(wait) {
|
}
|
||||||
return;
|
if core
|
||||||
|
.sync_paused_until
|
||||||
|
.compare_exchange(until, 0, Ordering::Relaxed, Ordering::Relaxed)
|
||||||
|
.is_ok()
|
||||||
|
{
|
||||||
|
if let Err(error) = core.db.clear_state(PAUSED_UNTIL_KEY) {
|
||||||
|
warn!(%error, "clearing an expired sync pause failed");
|
||||||
}
|
}
|
||||||
if core
|
info!("sync pause ended");
|
||||||
.sync_paused_until
|
core.resume_sync_work();
|
||||||
.compare_exchange(until, 0, Ordering::Relaxed, Ordering::Relaxed)
|
}
|
||||||
.is_ok()
|
});
|
||||||
{
|
|
||||||
if let Err(error) = core.db.clear_state(PAUSED_UNTIL_KEY) {
|
|
||||||
warn!(%error, "clearing an expired sync pause failed");
|
|
||||||
}
|
|
||||||
info!("sync pause ended");
|
|
||||||
core.resume_sync_work();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
if let Err(error) = spawned {
|
if let Err(error) = spawned {
|
||||||
// The drain and the reconcile still read the clock, so the pause
|
// The drain and the reconcile still read the clock, so the pause
|
||||||
// still ends — just at the next idle poll instead of on time.
|
// still ends — just at the next idle poll instead of on time.
|
||||||
|
|||||||
@@ -159,16 +159,14 @@ impl Core {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let core = self.clone();
|
let core = self.clone();
|
||||||
let spawned = std::thread::Builder::new()
|
let spawned = self.services.spawn_job("pdfs-similar", move || {
|
||||||
.name("pdfs-similar".into())
|
if let Err(e) = core.hash_similar() {
|
||||||
.spawn(move || {
|
warn!(error = %e, "similar-photo hashing failed");
|
||||||
if let Err(e) = core.hash_similar() {
|
}
|
||||||
warn!(error = %e, "similar-photo hashing failed");
|
core.photo_jobs
|
||||||
}
|
.similar_hashing
|
||||||
core.photo_jobs
|
.store(false, Ordering::SeqCst);
|
||||||
.similar_hashing
|
});
|
||||||
.store(false, Ordering::SeqCst);
|
|
||||||
});
|
|
||||||
if let Err(e) = spawned {
|
if let Err(e) = spawned {
|
||||||
warn!(error = %e, "could not start similar-photo hashing");
|
warn!(error = %e, "could not start similar-photo hashing");
|
||||||
self.photo_jobs
|
self.photo_jobs
|
||||||
|
|||||||
@@ -42,9 +42,10 @@ impl Core {
|
|||||||
.map_err(|e| CoreError::from_api(&e, "pin"))?;
|
.map_err(|e| CoreError::from_api(&e, "pin"))?;
|
||||||
let core = self.clone();
|
let core = self.clone();
|
||||||
let folder = name.clone();
|
let folder = name.clone();
|
||||||
std::thread::Builder::new()
|
self.services
|
||||||
.name("pin-folder".into())
|
.spawn_job("pdfs-pin-folder", move || {
|
||||||
.spawn(move || core.pin_subtree(ino, &uid, &folder))
|
core.pin_subtree(ino, &uid, &folder)
|
||||||
|
})
|
||||||
.map_err(|e| CoreError::internal(format!("spawn pin: {e}")))?;
|
.map_err(|e| CoreError::internal(format!("spawn pin: {e}")))?;
|
||||||
return Ok(format!("{name}: downloading its files in the background"));
|
return Ok(format!("{name}: downloading its files in the background"));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ impl Core {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let core = self.clone();
|
let core = self.clone();
|
||||||
std::thread::spawn(move || {
|
if let Err(error) = self.services.spawn_job("pdfs-profile-backup", move || {
|
||||||
let (saving, dirty) = save_state();
|
let (saving, dirty) = save_state();
|
||||||
while dirty.swap(false, Ordering::SeqCst) {
|
while dirty.swap(false, Ordering::SeqCst) {
|
||||||
if let Err(e) = core.save_profile() {
|
if let Err(e) = core.save_profile() {
|
||||||
@@ -64,7 +64,9 @@ impl Core {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
saving.store(false, Ordering::SeqCst);
|
saving.store(false, Ordering::SeqCst);
|
||||||
});
|
}) {
|
||||||
|
tracing::warn!(%error, "could not start pdfs-profile-backup");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Serialize this machine's arrangement and upload it to its own
|
/// Serialize this machine's arrangement and upload it to its own
|
||||||
|
|||||||
@@ -288,7 +288,7 @@ impl Core {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let core = self.clone();
|
let core = self.clone();
|
||||||
std::thread::spawn(move || {
|
if let Err(error) = self.services.spawn_job("pdfs-redate", move || {
|
||||||
let outcome = core.redate_photos(dry_run, limit, range, cancel);
|
let outcome = core.redate_photos(dry_run, limit, range, cancel);
|
||||||
let mut state = REDATE.lock();
|
let mut state = REDATE.lock();
|
||||||
state.running = false;
|
state.running = false;
|
||||||
@@ -310,7 +310,9 @@ impl Core {
|
|||||||
),
|
),
|
||||||
Err(e) => warn!(error = %e, "photo re-date failed"),
|
Err(e) => warn!(error = %e, "photo re-date failed"),
|
||||||
}
|
}
|
||||||
});
|
}) {
|
||||||
|
tracing::warn!(%error, "could not start pdfs-redate");
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -130,7 +130,13 @@ impl Core {
|
|||||||
SizeUpgradeClaim::Start(slot, uids) => {
|
SizeUpgradeClaim::Start(slot, uids) => {
|
||||||
let core = self.clone();
|
let core = self.clone();
|
||||||
let worker = slot.clone();
|
let worker = slot.clone();
|
||||||
std::thread::spawn(move || core.run_size_upgrade(key, uids, worker));
|
if let Err(error) = self.services.spawn_job("pdfs-size-upgrade", move || {
|
||||||
|
core.run_size_upgrade(key, uids, worker)
|
||||||
|
}) {
|
||||||
|
// The waiters give up on the slot at their deadline and
|
||||||
|
// answer with the size they have.
|
||||||
|
warn!(%error, "could not start a size upgrade");
|
||||||
|
}
|
||||||
Some(slot)
|
Some(slot)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1153,7 +1153,7 @@ impl Core {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let core = self.clone();
|
let core = self.clone();
|
||||||
std::thread::spawn(move || {
|
if let Err(error) = self.services.spawn_job("pdfs-import", move || {
|
||||||
// The job is dropped only after the final state is stored: the
|
// The job is dropped only after the final state is stored: the
|
||||||
// job leaving the transfer snapshot is the front-ends' cue to ask
|
// job leaving the transfer snapshot is the front-ends' cue to ask
|
||||||
// for the result, which must then be there.
|
// for the result, which must then be there.
|
||||||
@@ -1186,7 +1186,9 @@ impl Core {
|
|||||||
summary.complete(),
|
summary.complete(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
});
|
}) {
|
||||||
|
tracing::warn!(%error, "could not start pdfs-import");
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-1454
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,578 @@
|
|||||||
|
//! Applying a pass's plan: uploads, downloads and the other effects, in
|
||||||
|
//! batches, and the baseline each one leaves behind.
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
impl Syncer {
|
||||||
|
/// Store the revision id of each file in one listing whose baseline row has
|
||||||
|
/// none, when the size the walk just read shows that file unchanged.
|
||||||
|
///
|
||||||
|
/// The classification step does the same, but only a pass that gets all the
|
||||||
|
/// way through the walk reaches it. A large folder whose walk is cut short
|
||||||
|
/// every time (a restart, a logout) then reads the size of every such file
|
||||||
|
/// again, one key unlock each, on every pass, and never finishes (B294).
|
||||||
|
pub(super) fn record_revisions(
|
||||||
|
&self,
|
||||||
|
folder_id: i64,
|
||||||
|
prefix: &str,
|
||||||
|
nodes: &[Node],
|
||||||
|
sized: &HashMap<String, (i64, Option<String>)>,
|
||||||
|
baseline: &HashMap<String, StoredSyncEntry>,
|
||||||
|
) {
|
||||||
|
let rows = revisions_to_record(prefix, nodes, sized, baseline);
|
||||||
|
if rows.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match self.store.sync_entries_set_revision(folder_id, &rows) {
|
||||||
|
Ok(n) => self.trace_count(Count::Revisions, n),
|
||||||
|
Err(e) => debug!(folder = prefix, error = ?e, "sync: cannot record revision ids"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Record a folder's baseline row (folders carry no content signature).
|
||||||
|
pub(super) fn baseline_dir(
|
||||||
|
&self,
|
||||||
|
folder_id: i64,
|
||||||
|
rel: &str,
|
||||||
|
uid: &NodeUid,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
self.store
|
||||||
|
.sync_entry_upsert(folder_id, &dir_row(rel, uid))
|
||||||
|
.map_err(|e| format!("baseline dir {rel}: {e:?}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run a batch of queued [`Pending`] ops concurrently (bounded by
|
||||||
|
/// [`SYNC_CONCURRENCY`]) and fold their results back into the reconcile's
|
||||||
|
/// shared state on the engine thread: created folders are registered in
|
||||||
|
/// `remote_dirs` (so deeper paths resolve their parent), and what each op did
|
||||||
|
/// is tallied into `outcome`. Driven by `block_on` from the (non-runtime) sync
|
||||||
|
/// engine thread, spawning the tasks onto the shared runtime.
|
||||||
|
///
|
||||||
|
/// Fails with [`PassAbort::Stopped`] once the daemon is stopping, after the
|
||||||
|
/// ops already sending have finished.
|
||||||
|
pub(super) fn flush_batch(
|
||||||
|
&self,
|
||||||
|
folder_id: i64,
|
||||||
|
local_root: &Path,
|
||||||
|
remote_dirs: &mut HashMap<String, NodeUid>,
|
||||||
|
batch: Vec<Pending>,
|
||||||
|
outcome: &mut Outcome,
|
||||||
|
) -> Result<(), PassAbort> {
|
||||||
|
if batch.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
self.progress_queued(folder_id, batch.len());
|
||||||
|
self.trace_count(Count::Queued, batch.len());
|
||||||
|
let applying = Instant::now();
|
||||||
|
let core = self.clone();
|
||||||
|
let root = local_root.to_path_buf();
|
||||||
|
let results = self.rt.block_on(async move {
|
||||||
|
let sem = Arc::new(tokio::sync::Semaphore::new(SYNC_CONCURRENCY));
|
||||||
|
let mut set = tokio::task::JoinSet::new();
|
||||||
|
for op in batch {
|
||||||
|
let core = core.clone();
|
||||||
|
let sem = sem.clone();
|
||||||
|
let root = root.clone();
|
||||||
|
set.spawn(async move {
|
||||||
|
let _permit = sem.acquire_owned().await.expect("semaphore not closed");
|
||||||
|
// An op still waiting for its turn when the stop comes is
|
||||||
|
// not started; the ones already sending finish.
|
||||||
|
if core.shutdown.is_stopping() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(core.apply_pending(folder_id, &root, op).await)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut join_errors = 0usize;
|
||||||
|
while let Some(joined) = set.join_next().await {
|
||||||
|
match joined {
|
||||||
|
Ok(Some(result)) => out.push(result),
|
||||||
|
Ok(None) => {}
|
||||||
|
// The runtime ends with the daemon and cancels what is left.
|
||||||
|
Err(e) if e.is_cancelled() => {}
|
||||||
|
Err(e) => {
|
||||||
|
join_errors += 1;
|
||||||
|
warn!(error = %e, "sync: task panicked");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(out, join_errors)
|
||||||
|
});
|
||||||
|
self.trace_phase(Phase::Apply, applying.elapsed());
|
||||||
|
let (results, join_errors) = results;
|
||||||
|
outcome.errors += join_errors;
|
||||||
|
for result in results {
|
||||||
|
match result {
|
||||||
|
Ok(applied) => {
|
||||||
|
outcome.record(&applied);
|
||||||
|
if let Applied::Dir(rel, uid) = applied {
|
||||||
|
remote_dirs.insert(rel, uid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
warn!(error = %e, "sync: step failed; continuing");
|
||||||
|
outcome.failed(&e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The pass goes no further: the next depth's paths may need a folder
|
||||||
|
// this batch did not get to make, and went on to fail one by one
|
||||||
|
// (`docs/BUGS.md` B169).
|
||||||
|
if self.shutdown.is_stopping() {
|
||||||
|
return Err(PassAbort::Stopped);
|
||||||
|
}
|
||||||
|
if self.pass_abandoned(folder_id) {
|
||||||
|
return Err(PassAbort::Abandoned);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a removal of `folder_id` is waiting for its running pass.
|
||||||
|
pub(super) fn pass_abandoned(&self, folder_id: i64) -> bool {
|
||||||
|
self.abandon.lock().contains(&folder_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Apply one [`Pending`] op (async, so it can run concurrently in a batch),
|
||||||
|
/// reporting it to the folder's live progress and to the activity feed. Each
|
||||||
|
/// item logs its own line — the feed is meant to answer "what is it doing",
|
||||||
|
/// which a pass-level summary alone cannot.
|
||||||
|
pub(super) async fn apply_pending(
|
||||||
|
&self,
|
||||||
|
folder_id: i64,
|
||||||
|
local_root: &Path,
|
||||||
|
op: Pending,
|
||||||
|
) -> Result<Applied, String> {
|
||||||
|
self.progress_started(folder_id, base_name(op.rel()));
|
||||||
|
let step = Instant::now();
|
||||||
|
let result = self.apply_one(folder_id, local_root, &op).await;
|
||||||
|
self.trace_call(op.call(), step.elapsed());
|
||||||
|
self.progress_finished(folder_id);
|
||||||
|
let name = base_name(op.rel());
|
||||||
|
match &result {
|
||||||
|
Ok(Applied::Adopted) => {}
|
||||||
|
Ok(_) => self.log_activity(op.kind(), name, op.detail(), true),
|
||||||
|
Err(e) => self.log_activity(op.kind(), name, e.clone(), false),
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The body of one [`Pending`] op, without the progress/activity bookkeeping.
|
||||||
|
pub(super) async fn apply_one(
|
||||||
|
&self,
|
||||||
|
folder_id: i64,
|
||||||
|
local_root: &Path,
|
||||||
|
op: &Pending,
|
||||||
|
) -> Result<Applied, String> {
|
||||||
|
match op {
|
||||||
|
Pending::CreateDir { rel, parent } => {
|
||||||
|
let uid = self
|
||||||
|
.drive
|
||||||
|
.create_folder(parent, base_name(rel), Some(now_secs()))
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("create remote folder {rel}: {e}"))?;
|
||||||
|
// The parent has gained a child that no cached listing of it
|
||||||
|
// knows about (B86).
|
||||||
|
self.invalidate_children_of(parent);
|
||||||
|
self.baseline_dir(folder_id, rel, &uid)?;
|
||||||
|
Ok(Applied::Dir(rel.clone(), uid))
|
||||||
|
}
|
||||||
|
Pending::UploadNew { rel, parent } => {
|
||||||
|
self.upload_new(folder_id, local_root, rel, parent).await
|
||||||
|
}
|
||||||
|
Pending::UploadRevision { rel, uid, seen } => {
|
||||||
|
self.upload_revision(folder_id, local_root, rel, uid, seen)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
Pending::Download {
|
||||||
|
rel,
|
||||||
|
uid,
|
||||||
|
seen,
|
||||||
|
local,
|
||||||
|
} => {
|
||||||
|
self.download_file(folder_id, local_root, rel, uid, seen, *local)
|
||||||
|
.await?;
|
||||||
|
Ok(Applied::Downloaded)
|
||||||
|
}
|
||||||
|
Pending::Adopt {
|
||||||
|
rel,
|
||||||
|
uid,
|
||||||
|
seen: remote,
|
||||||
|
sha1,
|
||||||
|
local,
|
||||||
|
} => {
|
||||||
|
let path = local_root.join(rel_to_path(rel));
|
||||||
|
let hashed = tokio::task::spawn_blocking(move || local_sha1(&path))
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("hash {rel}: {e}"))?
|
||||||
|
.map_err(|e| format!("hash {rel}: {e}"))?;
|
||||||
|
let Some((seen, digest)) = hashed else {
|
||||||
|
return Ok(Applied::Vanished);
|
||||||
|
};
|
||||||
|
// Edited since the scan: the next pass plans it again.
|
||||||
|
if !seen.same_content(local) {
|
||||||
|
return Ok(Applied::Vanished);
|
||||||
|
}
|
||||||
|
if !digest.eq_ignore_ascii_case(sha1) {
|
||||||
|
info!(
|
||||||
|
rel,
|
||||||
|
"sync: same size as on Drive but different content; keeping a conflict copy"
|
||||||
|
);
|
||||||
|
return self
|
||||||
|
.take_remote_keeping_local(folder_id, local_root, rel, uid, remote)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
self.store
|
||||||
|
.sync_entry_upsert(
|
||||||
|
folder_id,
|
||||||
|
&StoredSyncEntry {
|
||||||
|
rel_path: rel.clone(),
|
||||||
|
remote_uid: Some(uid.to_string()),
|
||||||
|
local_mtime: seen.mtime,
|
||||||
|
local_mtime_ns: seen.mtime_ns,
|
||||||
|
local_size: seen.size,
|
||||||
|
remote_rev: Some(remote.mtime.to_string()),
|
||||||
|
remote_hash: Some(remote.size.to_string()),
|
||||||
|
remote_revision_id: remote.revision.clone(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map_err(|e| format!("adopt baseline {rel}: {e:?}"))?;
|
||||||
|
Ok(Applied::Adopted)
|
||||||
|
}
|
||||||
|
Pending::Conflict { rel, uid, seen } => {
|
||||||
|
self.take_remote_keeping_local(folder_id, local_root, rel, uid, seen)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
Pending::PushConflict { rel, parent } => {
|
||||||
|
// The ordinary conflict resolution — rename the local copy aside and
|
||||||
|
// let the next pass upload it — loses the file here: the folder is
|
||||||
|
// going on-demand, so "next pass" comes after the local tree has been
|
||||||
|
// evicted. Push the conflict copy now, while it still exists, and
|
||||||
|
// leave the remote file holding the original path.
|
||||||
|
let path = local_root.join(rel_to_path(rel));
|
||||||
|
let conflict = preserve_conflict_copy(&path, now_secs())
|
||||||
|
.map_err(|e| format!("set aside conflict copy for {rel}: {e}"))?;
|
||||||
|
let name = conflict
|
||||||
|
.file_name()
|
||||||
|
.map(|n| n.to_string_lossy().into_owned())
|
||||||
|
.ok_or_else(|| format!("conflict copy for {rel} has no name"))?;
|
||||||
|
let conflict_rel = join_rel(parent_rel(rel), &name);
|
||||||
|
self.upload_new(folder_id, local_root, &conflict_rel, parent)
|
||||||
|
.await?;
|
||||||
|
info!(rel, "sync: uploaded local changes as a conflict copy");
|
||||||
|
Ok(Applied::Conflict)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set the local copy aside (it re-uploads as a new file next pass), then
|
||||||
|
/// take the remote version as the shared truth.
|
||||||
|
pub(super) async fn take_remote_keeping_local(
|
||||||
|
&self,
|
||||||
|
folder_id: i64,
|
||||||
|
local_root: &Path,
|
||||||
|
rel: &str,
|
||||||
|
uid: &NodeUid,
|
||||||
|
seen: &RemoteSeen,
|
||||||
|
) -> Result<Applied, String> {
|
||||||
|
let path = local_root.join(rel_to_path(rel));
|
||||||
|
if path.exists() {
|
||||||
|
preserve_conflict_copy(&path, now_secs())
|
||||||
|
.map_err(|e| format!("set aside conflict copy for {rel}: {e}"))?;
|
||||||
|
info!(rel, "sync: kept local changes as a conflict copy");
|
||||||
|
}
|
||||||
|
// The local copy has just been moved aside, so the state this
|
||||||
|
// download expects to find at the path is "nothing" — anything
|
||||||
|
// that appears while it runs is a *new* racing write, and gets
|
||||||
|
// its own conflict copy rather than being overwritten (B39).
|
||||||
|
self.download_file(folder_id, local_root, rel, uid, seen, None)
|
||||||
|
.await?;
|
||||||
|
Ok(Applied::Conflict)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Upload a brand-new local file to its remote parent, then record baseline.
|
||||||
|
pub(super) async fn upload_new(
|
||||||
|
&self,
|
||||||
|
folder_id: i64,
|
||||||
|
local_root: &Path,
|
||||||
|
rel: &str,
|
||||||
|
parent: &NodeUid,
|
||||||
|
) -> Result<Applied, String> {
|
||||||
|
let path = local_root.join(rel_to_path(rel));
|
||||||
|
let name = base_name(rel);
|
||||||
|
let Some(file) = open_to_upload(&path, rel)? else {
|
||||||
|
return Ok(Applied::Vanished);
|
||||||
|
};
|
||||||
|
let meta = file.metadata().map_err(|e| format!("stat {rel}: {e}"))?;
|
||||||
|
let mtime = system_mtime(&meta);
|
||||||
|
// Taken from the descriptor being streamed, so it names the content that
|
||||||
|
// actually goes up rather than whatever is at the path when we finish.
|
||||||
|
let streamed = LocalSig::from(&meta);
|
||||||
|
let thumbnails = self
|
||||||
|
.thumbnails_for_upload(path.clone(), name.to_string())
|
||||||
|
.await;
|
||||||
|
// Count the bytes as they are read, so this upload shows up in
|
||||||
|
// `GetQueueStatus` next to a manual one. The uid isn't known until the
|
||||||
|
// draft is sealed, so the transfer registers without one.
|
||||||
|
let (reader, sent) = Sha1Tap::new(OwnedCountingReader::new(
|
||||||
|
file,
|
||||||
|
self.transfers
|
||||||
|
.begin(name, "", TransferDirection::Upload, meta.len()),
|
||||||
|
));
|
||||||
|
let uid = self
|
||||||
|
.drive
|
||||||
|
// Mirror push: the local file is authoritative. If a prior attempt was
|
||||||
|
// interrupted mid-upload it left an unsealed draft of this name; recover
|
||||||
|
// it even across a daemon restart (which rotates our client uid), so the
|
||||||
|
// folder can reach idle instead of `AlreadyExists`-looping forever.
|
||||||
|
.upload_file_replacing_draft_from(
|
||||||
|
parent,
|
||||||
|
name,
|
||||||
|
pdfs_drive::media_type_for(name),
|
||||||
|
reader,
|
||||||
|
meta.len() as i64,
|
||||||
|
thumbnails,
|
||||||
|
Some(mtime),
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("upload {rel}: {e}"))?;
|
||||||
|
// The parent has gained a child that no cached listing of it knows
|
||||||
|
// about. Without this, a folder later switched to on-demand serves a
|
||||||
|
// snapshot that predates this upload (B86).
|
||||||
|
self.invalidate_children_of(parent);
|
||||||
|
warn_if_torn(rel, &path, streamed);
|
||||||
|
let remote = self
|
||||||
|
.landed_as_sent(rel, &uid, &sent.digest(), streamed)
|
||||||
|
.await?;
|
||||||
|
self.record_file_baseline(folder_id, rel, Some(streamed), &uid, &remote)?;
|
||||||
|
Ok(Applied::Uploaded)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Upload a changed local file as a new revision of an existing remote node.
|
||||||
|
///
|
||||||
|
/// The revision supersedes whatever is current on Drive, and the plan comes
|
||||||
|
/// from a walk that may be minutes old. Another computer syncing the same
|
||||||
|
/// folder may have committed a revision since, and uploading over it would
|
||||||
|
/// leave that edit only in the revision history. So Drive is asked first,
|
||||||
|
/// and a file that moved on is left for the next pass, which keeps the
|
||||||
|
/// local edit as a conflict copy (B249). A revision committed between this
|
||||||
|
/// check and the upload's own draft is not caught here; the read-back after
|
||||||
|
/// the upload catches one committed after it.
|
||||||
|
pub(super) async fn upload_revision(
|
||||||
|
&self,
|
||||||
|
folder_id: i64,
|
||||||
|
local_root: &Path,
|
||||||
|
rel: &str,
|
||||||
|
uid: &NodeUid,
|
||||||
|
seen: &RemoteSeen,
|
||||||
|
) -> Result<Applied, String> {
|
||||||
|
let path = local_root.join(rel_to_path(rel));
|
||||||
|
let Some(file) = open_to_upload(&path, rel)? else {
|
||||||
|
return Ok(Applied::Vanished);
|
||||||
|
};
|
||||||
|
let current = self
|
||||||
|
.drive
|
||||||
|
.enumerate_nodes(std::slice::from_ref(uid))
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("check {rel} on Drive: {e}"))?;
|
||||||
|
match current.first() {
|
||||||
|
Some(node) if !node.trashed && seen.still_current(node) => {}
|
||||||
|
Some(node) if !node.trashed => {
|
||||||
|
return Err(format!(
|
||||||
|
"{rel} changed on Drive since this pass looked; it is compared again on the next pass"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
return Err(format!(
|
||||||
|
"{rel} is no longer on Drive where this pass saw it; it is compared again on the next pass"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let meta = file.metadata().map_err(|e| format!("stat {rel}: {e}"))?;
|
||||||
|
let mtime = system_mtime(&meta);
|
||||||
|
let streamed = LocalSig::from(&meta);
|
||||||
|
let thumbnails = self
|
||||||
|
.thumbnails_for_upload(path.clone(), base_name(rel).to_string())
|
||||||
|
.await;
|
||||||
|
let (reader, sent) = Sha1Tap::new(OwnedCountingReader::new(
|
||||||
|
file,
|
||||||
|
self.transfers.begin(
|
||||||
|
base_name(rel),
|
||||||
|
uid.to_string(),
|
||||||
|
TransferDirection::Upload,
|
||||||
|
meta.len(),
|
||||||
|
),
|
||||||
|
));
|
||||||
|
self.drive
|
||||||
|
.upload_new_revision_from(uid, reader, meta.len() as i64, thumbnails, Some(mtime))
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("upload revision {rel}: {e}"))?;
|
||||||
|
warn_if_torn(rel, &path, streamed);
|
||||||
|
let remote = self
|
||||||
|
.landed_as_sent(rel, uid, &sent.digest(), streamed)
|
||||||
|
.await?;
|
||||||
|
self.record_file_baseline(folder_id, rel, Some(streamed), uid, &remote)?;
|
||||||
|
Ok(Applied::Uploaded)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Download a remote file to its local path (atomically via a temp file),
|
||||||
|
/// stamp the local mtime to match the remote, then record baseline.
|
||||||
|
///
|
||||||
|
/// `expected_local` is the identity planning saw at the destination. The
|
||||||
|
/// rename below is the destructive step, and the download in between can run
|
||||||
|
/// for minutes, so the destination is re-examined right before it: a local
|
||||||
|
/// file that no longer matches the plan is set aside as a conflict copy
|
||||||
|
/// instead of being replaced (`docs/BUGS.md` B39).
|
||||||
|
///
|
||||||
|
/// The baseline records `seen`, the revision the pass planned to download,
|
||||||
|
/// and not a read of the node afterwards. Another computer may commit a
|
||||||
|
/// revision while the download runs, and a read-back would record that
|
||||||
|
/// revision as synced while the disk holds the older one, so its edit would
|
||||||
|
/// never arrive (B250). If the download did fetch the newer revision, the
|
||||||
|
/// next pass fetches it once more, which costs a transfer and loses nothing.
|
||||||
|
pub(super) async fn download_file(
|
||||||
|
&self,
|
||||||
|
folder_id: i64,
|
||||||
|
local_root: &Path,
|
||||||
|
rel: &str,
|
||||||
|
uid: &NodeUid,
|
||||||
|
seen: &RemoteSeen,
|
||||||
|
expected_local: Option<LocalSig>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let (mtime, size) = (seen.mtime, seen.size);
|
||||||
|
let path = local_root.join(rel_to_path(rel));
|
||||||
|
if let Some(parent) = path.parent() {
|
||||||
|
std::fs::create_dir_all(parent).map_err(|e| format!("mkdir for {rel}: {e}"))?;
|
||||||
|
}
|
||||||
|
let tmp = staging_path(&path);
|
||||||
|
// A file an on-demand mount already read, say one just moved here from
|
||||||
|
// it, is in the content cache under the same revision key.
|
||||||
|
let seeded = size > 0 && self.cache.copy_cached_to(uid, mtime, size as u64, &tmp);
|
||||||
|
if seeded {
|
||||||
|
std::fs::File::open(&tmp)
|
||||||
|
.and_then(|f| f.sync_all())
|
||||||
|
.map_err(|e| {
|
||||||
|
let _ = std::fs::remove_file(&tmp);
|
||||||
|
format!("sync tmp {rel}: {e}")
|
||||||
|
})?;
|
||||||
|
debug!(
|
||||||
|
rel,
|
||||||
|
"sync: placed from the content cache instead of downloading"
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
let out = std::fs::File::create(&tmp).map_err(|e| format!("create tmp {rel}: {e}"))?;
|
||||||
|
// Count the bytes as they land, so the download reports progress like
|
||||||
|
// an on-demand hydration does.
|
||||||
|
let guard = self.transfers.begin(
|
||||||
|
base_name(rel),
|
||||||
|
uid.to_string(),
|
||||||
|
TransferDirection::Download,
|
||||||
|
size.max(0) as u64,
|
||||||
|
);
|
||||||
|
let mut out = CountingWriter::new(out, &guard);
|
||||||
|
self.drive
|
||||||
|
.download_file_to(uid, &mut out)
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
let _ = std::fs::remove_file(&tmp);
|
||||||
|
format!("download {rel}: {e}")
|
||||||
|
})?;
|
||||||
|
let mut out = out.into_inner();
|
||||||
|
out.flush().map_err(|e| format!("flush tmp {rel}: {e}"))?;
|
||||||
|
out.sync_all().map_err(|e| format!("sync tmp {rel}: {e}"))?;
|
||||||
|
}
|
||||||
|
place_download(&tmp, &path, expected_local, mtime, rel)?;
|
||||||
|
// Here the file on disk *is* the transferred content: it was published
|
||||||
|
// by a rename and stamped just above, so its stat is the identity.
|
||||||
|
self.record_file_baseline(folder_id, rel, local_sig(&path), uid, seen)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What Drive holds for `uid` after this daemon uploaded content with SHA-1
|
||||||
|
/// `sent` and identity `streamed` to it, as the baseline should record it.
|
||||||
|
///
|
||||||
|
/// Read back so the stored signature is exactly what a walk reports next
|
||||||
|
/// time. A digest on Drive that is not `sent` means another computer
|
||||||
|
/// committed a revision right after this upload. Recording that revision
|
||||||
|
/// as synced would hide it, and the edit here would be lost to it on the
|
||||||
|
/// next download. So the baseline is left as it was, and the next pass sees
|
||||||
|
/// both sides changed and keeps a conflict copy (B250).
|
||||||
|
pub(super) async fn landed_as_sent(
|
||||||
|
&self,
|
||||||
|
rel: &str,
|
||||||
|
uid: &NodeUid,
|
||||||
|
sent: &str,
|
||||||
|
streamed: LocalSig,
|
||||||
|
) -> Result<RemoteSeen, String> {
|
||||||
|
let node = match self.drive.enumerate_nodes(std::slice::from_ref(uid)).await {
|
||||||
|
Ok(nodes) => nodes.into_iter().next(),
|
||||||
|
Err(e) => {
|
||||||
|
warn!(rel, error = %e, "sync: baseline refetch failed; using local mtime");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let Some(node) = node else {
|
||||||
|
// Drive does not list a node it has just made at once. The upload
|
||||||
|
// stamped it with the local modification time, so that and the
|
||||||
|
// size sent are what a walk reports.
|
||||||
|
return Ok(RemoteSeen {
|
||||||
|
mtime: streamed.mtime,
|
||||||
|
size: streamed.size,
|
||||||
|
revision: None,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
if let Some(digest) = pdfs_drive::node_content_sha1(&node)
|
||||||
|
&& !digest.eq_ignore_ascii_case(sent)
|
||||||
|
{
|
||||||
|
return Err(format!(
|
||||||
|
"{rel} was changed on Drive by another client right after this upload; it is compared again on the next pass"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let (mtime, size) = remote_file_sig(&node);
|
||||||
|
Ok(RemoteSeen {
|
||||||
|
mtime,
|
||||||
|
size,
|
||||||
|
revision: pdfs_drive::node_revision_id(&node),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Record a file's baseline: the local identity these bytes came from and
|
||||||
|
/// the remote revision they were synced with. Called after every
|
||||||
|
/// upload/download so the very next reconcile sees the path as unchanged.
|
||||||
|
///
|
||||||
|
/// `local` is the identity the *transferred content* corresponds to, which
|
||||||
|
/// is not always the file's current stat. An upload streams the live file,
|
||||||
|
/// so it passes the identity it read the first byte at: if a writer changed
|
||||||
|
/// the file mid-stream, the remote now holds a torn revision, and recording
|
||||||
|
/// the pre-upload identity is what makes the next pass see the path as
|
||||||
|
/// locally changed and upload a whole, clean revision over it. Recording the
|
||||||
|
/// post-upload stat instead declared the torn revision synchronized and left
|
||||||
|
/// it as the file's content on Drive (`docs/BUGS.md` B40).
|
||||||
|
pub(super) fn record_file_baseline(
|
||||||
|
&self,
|
||||||
|
folder_id: i64,
|
||||||
|
rel: &str,
|
||||||
|
local: Option<LocalSig>,
|
||||||
|
uid: &NodeUid,
|
||||||
|
remote: &RemoteSeen,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let Some(local) = local else {
|
||||||
|
return Err(format!("stat {rel}: no local identity to baseline"));
|
||||||
|
};
|
||||||
|
self.store
|
||||||
|
.sync_entry_upsert(
|
||||||
|
folder_id,
|
||||||
|
&StoredSyncEntry {
|
||||||
|
rel_path: rel.to_string(),
|
||||||
|
remote_uid: Some(uid.to_string()),
|
||||||
|
local_mtime: local.mtime,
|
||||||
|
local_mtime_ns: local.mtime_ns,
|
||||||
|
local_size: local.size,
|
||||||
|
remote_rev: Some(remote.mtime.to_string()),
|
||||||
|
remote_hash: Some(remote.size.to_string()),
|
||||||
|
remote_revision_id: remote.revision.clone(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map_err(|e| format!("baseline {rel}: {e:?}"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,350 @@
|
|||||||
|
//! The push pass: sending local changes to Drive between full passes.
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
impl Syncer {
|
||||||
|
/// Get every local change up to Drive, and nothing else — the pass run for a
|
||||||
|
/// folder waiting to go on-demand, whose local copy is about to be evicted.
|
||||||
|
///
|
||||||
|
/// This exists because a full [`do_reconcile`](Self::do_reconcile) is both too
|
||||||
|
/// slow and too wasteful to stand between the user and the switch they asked
|
||||||
|
/// for. It walks the whole remote tree (the minutes-long part of a pass over a
|
||||||
|
/// large folder) to answer a question the switch makes irrelevant — what the
|
||||||
|
/// remote side has that we don't — and then downloads those files onto a disk
|
||||||
|
/// we are about to clear. A push pass answers only "is anything here not on
|
||||||
|
/// Drive yet?", which the local tree and the baseline already know, so it needs
|
||||||
|
/// no remote walk at all and finishes in the time the local walk takes.
|
||||||
|
///
|
||||||
|
/// The remote is consulted for exactly one thing: the files whose local copy
|
||||||
|
/// changed. Those, and only those, could be a two-sided edit, so their nodes are
|
||||||
|
/// fetched (cheaply, in one batch) to check whether the remote moved too. If it
|
||||||
|
/// did, the local copy goes up under a conflict name rather than overwriting the
|
||||||
|
/// other side. Everything else — remote edits, remote deletions, remote-only
|
||||||
|
/// files — is left for the FUSE mount to show live once the switch lands.
|
||||||
|
///
|
||||||
|
/// Per-path failures are counted, never fatal, exactly as in `do_reconcile`; a
|
||||||
|
/// non-zero [`Outcome::errors`] leaves the folder out of `idle`, which keeps the
|
||||||
|
/// queued switch waiting rather than evicting a file that never made it up.
|
||||||
|
pub(super) fn push_pass(
|
||||||
|
&self,
|
||||||
|
folder_id: i64,
|
||||||
|
local_root: &Path,
|
||||||
|
remote_root: &NodeUid,
|
||||||
|
rules: &IgnoreRules,
|
||||||
|
) -> Result<Outcome, PassAbort> {
|
||||||
|
// This pass uploads without walking Drive, so a walk saved by an
|
||||||
|
// earlier pass would not know what it sent; see `do_reconcile`.
|
||||||
|
self.store
|
||||||
|
.sync_walk_clear(folder_id)
|
||||||
|
.map_err(|e| format!("drop the saved walk: {e:?}"))?;
|
||||||
|
let step = Instant::now();
|
||||||
|
let baseline = self
|
||||||
|
.store
|
||||||
|
.sync_entries(folder_id)
|
||||||
|
.map_err(|e| format!("load baseline: {e:?}"))?;
|
||||||
|
self.trace_phase(Phase::Baseline, step.elapsed());
|
||||||
|
// Only the local side is walked here, so each baseline path is checked once.
|
||||||
|
self.progress_scan_total(folder_id, baseline.len());
|
||||||
|
|
||||||
|
let mut local: HashMap<String, LocalItem> = HashMap::new();
|
||||||
|
let mut unscanned = Unscanned::default();
|
||||||
|
let step = Instant::now();
|
||||||
|
let writing = open_for_write_set(local_root);
|
||||||
|
self.walk_local(
|
||||||
|
folder_id,
|
||||||
|
local_root,
|
||||||
|
rules,
|
||||||
|
&writing,
|
||||||
|
&mut local,
|
||||||
|
&mut unscanned,
|
||||||
|
)?;
|
||||||
|
self.trace_phase(Phase::LocalWalk, step.elapsed());
|
||||||
|
self.trace_count(Count::LocalEntries, local.len());
|
||||||
|
// The guard compares against the paths this pass could still see: an
|
||||||
|
// ignored or unreadable path is absent from `local` by rule or by
|
||||||
|
// failure, not by loss, and counting those as missing would trip the
|
||||||
|
// guard on every pass — wedging the folder's sync permanently — the
|
||||||
|
// moment a rule covers the whole tree.
|
||||||
|
let tracked = tracked_baseline(&baseline, rules, &unscanned);
|
||||||
|
// A local copy that is gone in its entirety is not trashed on Drive,
|
||||||
|
// for the reason `guard_local_wipe` gives. A full pass stops there, but
|
||||||
|
// this one exists for a switch to on-demand, which needs nothing local
|
||||||
|
// and leaves Drive as it is: refusing the pass would only keep the
|
||||||
|
// folder out of `idle`, wedging the switch for good (#46). So the pass
|
||||||
|
// forgets those paths instead of trashing them, and the mount then
|
||||||
|
// shows everything Drive still has.
|
||||||
|
let local_gone = match guard_local_wipe(&tracked, &local) {
|
||||||
|
Ok(()) => false,
|
||||||
|
Err(reason) => {
|
||||||
|
warn!(id = folder_id, %reason, "sync: going on-demand without trashing anything on Drive");
|
||||||
|
true
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// The remote folder uids come from the baseline instead of a walk: every
|
||||||
|
// directory this device has synced recorded its uid there when it was
|
||||||
|
// created or first matched up.
|
||||||
|
let mut remote_dirs: HashMap<String, NodeUid> = HashMap::new();
|
||||||
|
remote_dirs.insert(String::new(), remote_root.clone());
|
||||||
|
for (rel, item) in &local {
|
||||||
|
if !item.is_dir {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(uid) = baseline
|
||||||
|
.get(rel)
|
||||||
|
.and_then(|e| e.remote_uid.as_deref())
|
||||||
|
.and_then(parse_uid)
|
||||||
|
{
|
||||||
|
remote_dirs.insert(rel.clone(), uid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A local directory the baseline has no uid for is either brand new or one
|
||||||
|
// whose first pass never finished — and those look identical from here.
|
||||||
|
// Creating it blindly would duplicate a remote folder we simply haven't
|
||||||
|
// looked at, so when any exist, the remote folder tree is walked for real.
|
||||||
|
// It costs one light listing per folder and no file keys, and a folder whose
|
||||||
|
// baseline is complete — the case this pass is written for — skips it
|
||||||
|
// entirely and touches the network only for the files it uploads.
|
||||||
|
if local
|
||||||
|
.iter()
|
||||||
|
.any(|(rel, item)| item.is_dir && !remote_dirs.contains_key(rel))
|
||||||
|
{
|
||||||
|
self.walk_remote_dirs(folder_id, remote_root, "", &mut remote_dirs)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Files whose local copy has moved since the baseline: the only ones with
|
||||||
|
// anything to push, and the only ones that could be a two-sided edit.
|
||||||
|
let changed: Vec<&String> = local
|
||||||
|
.iter()
|
||||||
|
.filter(|(_, item)| !item.is_dir && !item.open_for_write)
|
||||||
|
.filter(|(rel, item)| {
|
||||||
|
baseline
|
||||||
|
.get(*rel)
|
||||||
|
.is_none_or(|b| b.local_mtime != item.mtime || b.local_size != item.size)
|
||||||
|
})
|
||||||
|
.map(|(rel, _)| rel)
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// One light batch tells us which of those also changed remotely. A light
|
||||||
|
// node carries the modification time and the revision id without
|
||||||
|
// unlocking the node key, and those are what the baseline compares
|
||||||
|
// against.
|
||||||
|
let check: Vec<NodeUid> = changed
|
||||||
|
.iter()
|
||||||
|
.filter_map(|rel| baseline.get(*rel))
|
||||||
|
.filter_map(|e| e.remote_uid.as_deref())
|
||||||
|
.filter_map(parse_uid)
|
||||||
|
.collect();
|
||||||
|
let remote_now: HashMap<String, (i64, Option<String>)> = if check.is_empty() {
|
||||||
|
HashMap::new()
|
||||||
|
} else {
|
||||||
|
self.rt
|
||||||
|
.block_on(self.drive.enumerate_nodes_light(&check))
|
||||||
|
.map_err(|e| format!("resolve changed nodes: {e}"))?
|
||||||
|
.into_iter()
|
||||||
|
.filter(|n| !n.trashed)
|
||||||
|
.map(|n| {
|
||||||
|
let revision = pdfs_drive::node_revision_id(&n);
|
||||||
|
(n.uid.to_string(), (n.modification_time, revision))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
let changed: HashSet<&String> = changed.into_iter().collect();
|
||||||
|
|
||||||
|
let mut outcome = Outcome {
|
||||||
|
deferred: local.values().filter(|item| item.open_for_write).count(),
|
||||||
|
unscanned: unscanned.report(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let mut order: Vec<&String> = local.keys().collect();
|
||||||
|
order.sort_by_key(|p| p.matches('/').count());
|
||||||
|
|
||||||
|
// Same depth-ascending batching as `do_reconcile`: a folder is created
|
||||||
|
// remotely before the paths inside it are classified, so their parent uid is
|
||||||
|
// in `remote_dirs` by the time they need it.
|
||||||
|
let mut batch: Vec<Pending> = Vec::new();
|
||||||
|
let mut batch_depth = 0usize;
|
||||||
|
for rel in order {
|
||||||
|
let depth = rel.matches('/').count();
|
||||||
|
if depth > batch_depth {
|
||||||
|
self.flush_batch(
|
||||||
|
folder_id,
|
||||||
|
local_root,
|
||||||
|
&mut remote_dirs,
|
||||||
|
std::mem::take(&mut batch),
|
||||||
|
&mut outcome,
|
||||||
|
)?;
|
||||||
|
batch_depth = depth;
|
||||||
|
}
|
||||||
|
let item = &local[rel];
|
||||||
|
if item.is_dir {
|
||||||
|
// The folder is already on Drive, so only its children carry work —
|
||||||
|
// but if the walk above is what found it, record the uid now so the
|
||||||
|
// next pass over this folder needs no walk at all.
|
||||||
|
if let Some(uid) = remote_dirs.get(rel) {
|
||||||
|
if baseline
|
||||||
|
.get(rel)
|
||||||
|
.and_then(|e| e.remote_uid.as_deref())
|
||||||
|
.is_none()
|
||||||
|
&& let Err(e) = self.baseline_dir(folder_id, rel, uid)
|
||||||
|
{
|
||||||
|
warn!(rel, error = %e, "sync: folder step failed; continuing");
|
||||||
|
outcome.failed(&format!("{rel}: {e}"));
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match remote_dirs.get(parent_rel(rel)) {
|
||||||
|
Some(parent) => batch.push(Pending::CreateDir {
|
||||||
|
rel: rel.clone(),
|
||||||
|
parent: parent.clone(),
|
||||||
|
}),
|
||||||
|
None => {
|
||||||
|
warn!(rel, "sync: no remote parent for folder; continuing");
|
||||||
|
outcome.failed(&format!("{rel}: no remote parent for folder"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !changed.contains(rel) {
|
||||||
|
// Local copy matches the baseline, so it is already on Drive.
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let base = baseline.get(rel);
|
||||||
|
let uid = base
|
||||||
|
.and_then(|e| e.remote_uid.as_deref())
|
||||||
|
.and_then(parse_uid);
|
||||||
|
match uid {
|
||||||
|
// Never uploaded (or the remote node is gone): it goes up as a new file.
|
||||||
|
None => match remote_dirs.get(parent_rel(rel)) {
|
||||||
|
Some(parent) => batch.push(Pending::UploadNew {
|
||||||
|
rel: rel.clone(),
|
||||||
|
parent: parent.clone(),
|
||||||
|
}),
|
||||||
|
None => {
|
||||||
|
warn!(rel, "sync: no remote parent for file; continuing");
|
||||||
|
outcome.failed(&format!("{rel}: no remote parent for file"));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Some(uid) => {
|
||||||
|
let (remote_moved, seen) = match remote_now.get(&uid.to_string()) {
|
||||||
|
Some((mtime, revision)) => {
|
||||||
|
let recorded = base.and_then(remote_sig);
|
||||||
|
let moved = recorded.is_none_or(|(m, _)| m != *mtime)
|
||||||
|
|| revision_moved(base, revision.as_deref());
|
||||||
|
let seen = RemoteSeen {
|
||||||
|
mtime: *mtime,
|
||||||
|
size: recorded.map_or(0, |(_, size)| size),
|
||||||
|
revision: revision.clone(),
|
||||||
|
};
|
||||||
|
(moved, seen)
|
||||||
|
}
|
||||||
|
// Trashed or unreadable remotely — treat as gone and re-upload
|
||||||
|
// the local copy as a new file rather than losing it.
|
||||||
|
None => {
|
||||||
|
match remote_dirs.get(parent_rel(rel)) {
|
||||||
|
Some(parent) => batch.push(Pending::UploadNew {
|
||||||
|
rel: rel.clone(),
|
||||||
|
parent: parent.clone(),
|
||||||
|
}),
|
||||||
|
None => {
|
||||||
|
warn!(rel, "sync: no remote parent for file; continuing");
|
||||||
|
outcome.failed(&format!("{rel}: no remote parent for file"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if remote_moved {
|
||||||
|
match remote_dirs.get(parent_rel(rel)) {
|
||||||
|
Some(parent) => batch.push(Pending::PushConflict {
|
||||||
|
rel: rel.clone(),
|
||||||
|
parent: parent.clone(),
|
||||||
|
}),
|
||||||
|
None => {
|
||||||
|
warn!(rel, "sync: no remote parent for file; continuing");
|
||||||
|
outcome.failed(&format!("{rel}: no remote parent for file"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
batch.push(Pending::UploadRevision {
|
||||||
|
rel: rel.clone(),
|
||||||
|
uid,
|
||||||
|
seen,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.flush_batch(
|
||||||
|
folder_id,
|
||||||
|
local_root,
|
||||||
|
&mut remote_dirs,
|
||||||
|
std::mem::take(&mut batch),
|
||||||
|
&mut outcome,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
// Paths the baseline knows that are no longer on disk: the user deleted them
|
||||||
|
// locally, and the deletion has to reach Drive before the mount starts
|
||||||
|
// showing the folder's remote contents — otherwise everything they deleted
|
||||||
|
// comes back the moment the switch lands. Shallowest first, skipping anything
|
||||||
|
// under a folder already trashed (its children went with it).
|
||||||
|
let deletions = local_deletions(&tracked, &local);
|
||||||
|
if local_gone {
|
||||||
|
// Forgotten instead of trashed. A row left behind would read to
|
||||||
|
// the switch as a deletion not on Drive yet and withdraw it, and
|
||||||
|
// to a later full pass as a reason to stop again. Forgotten, a full
|
||||||
|
// pass downloads the paths again.
|
||||||
|
let mut forgotten: HashSet<&str> = HashSet::new();
|
||||||
|
for rel in &deletions {
|
||||||
|
let mut parent = parent_rel(rel);
|
||||||
|
while !parent.is_empty() && !forgotten.contains(parent) {
|
||||||
|
parent = parent_rel(parent);
|
||||||
|
}
|
||||||
|
if parent.is_empty() {
|
||||||
|
let _ = self.store.sync_entries_remove_subtree(folder_id, rel);
|
||||||
|
forgotten.insert(rel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Ok(outcome);
|
||||||
|
}
|
||||||
|
let mut trashed: Vec<String> = Vec::new();
|
||||||
|
for rel in &deletions {
|
||||||
|
if trashed
|
||||||
|
.iter()
|
||||||
|
.any(|dir| rel.starts_with(&format!("{dir}/")))
|
||||||
|
{
|
||||||
|
let _ = self.store.sync_entry_remove(folder_id, rel);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(uid) = baseline[rel].remote_uid.as_deref().and_then(parse_uid) else {
|
||||||
|
let _ = self.store.sync_entry_remove(folder_id, rel);
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if let Err(e) = self
|
||||||
|
.rt
|
||||||
|
.block_on(self.drive.trash_nodes(&[uid]))
|
||||||
|
.and_then(batch::into_unit)
|
||||||
|
{
|
||||||
|
warn!(rel, error = %e, "sync: trash remote failed");
|
||||||
|
self.log_activity(ActivityKind::Trash, base_name(rel), e.to_string(), false);
|
||||||
|
outcome.failed(&format!("{rel}: {e}"));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
trashed.push(rel.clone());
|
||||||
|
if let Some(parent) = parent_uid_of(rel, &remote_dirs, &baseline) {
|
||||||
|
self.invalidate_children_of(&parent);
|
||||||
|
}
|
||||||
|
let _ = self.store.sync_entry_remove(folder_id, rel);
|
||||||
|
self.log_activity(
|
||||||
|
ActivityKind::Trash,
|
||||||
|
base_name(rel),
|
||||||
|
"removed on Drive",
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
outcome.deleted += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(outcome)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,553 @@
|
|||||||
|
//! The walks of a pass: the local tree, Drive's folders (resumable, and only
|
||||||
|
//! the changed ones when the event feed can be trusted), and listing one.
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
impl Syncer {
|
||||||
|
/// Recursively walk a local tree into `out`, keyed by `/`-joined relative
|
||||||
|
/// path. Symlinks and other special files are skipped, and paths that cannot
|
||||||
|
/// be read go to `unscanned`. Reports each entry to the pass's scan progress.
|
||||||
|
pub(super) fn walk_local(
|
||||||
|
&self,
|
||||||
|
folder_id: i64,
|
||||||
|
root: &Path,
|
||||||
|
rules: &IgnoreRules,
|
||||||
|
writing: &HashSet<PathBuf>,
|
||||||
|
out: &mut HashMap<String, LocalItem>,
|
||||||
|
unscanned: &mut Unscanned,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
walk_local_tree(root, rules, writing, out, unscanned, &mut |rel| {
|
||||||
|
self.progress_scanned(folder_id, base_name(rel))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Map every remote folder under `folder` to its uid by rel path, ignoring
|
||||||
|
/// files. The cheap half of [`walk_remote`](Self::walk_remote): folders carry no
|
||||||
|
/// content signature, so a light listing answers this without unlocking a single
|
||||||
|
/// node key. Used by [`push_pass`](Self::push_pass) to tell a folder it must
|
||||||
|
/// create from one it just hasn't recorded yet.
|
||||||
|
pub(super) fn walk_remote_dirs(
|
||||||
|
&self,
|
||||||
|
folder_id: i64,
|
||||||
|
folder: &NodeUid,
|
||||||
|
prefix: &str,
|
||||||
|
dirs: &mut HashMap<String, NodeUid>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let uids = self
|
||||||
|
.rt
|
||||||
|
.block_on(self.drive.enumerate_folder_children_node_uids(folder))
|
||||||
|
.map_err(|e| format!("enumerate {folder}: {e}"))?;
|
||||||
|
if uids.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let nodes = self
|
||||||
|
.rt
|
||||||
|
.block_on(self.drive.enumerate_nodes_light(&uids))
|
||||||
|
.map_err(|e| format!("resolve nodes: {e}"))?;
|
||||||
|
for node in nodes {
|
||||||
|
if node.trashed || !node.is_folder() || !pdfs_drive::remote_name_is_safe(&node.name) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let rel = join_rel(prefix, &node.name);
|
||||||
|
self.progress_scanned(folder_id, base_name(&rel));
|
||||||
|
dirs.insert(rel.clone(), node.uid.clone());
|
||||||
|
self.walk_remote_dirs(folder_id, &node.uid, &rel, dirs)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Walk the remote tree of a mirror folder into `walk`, folder by folder,
|
||||||
|
/// recording every descendant's relative path, and mapping each subfolder's
|
||||||
|
/// rel path to its uid in `walk.dirs`.
|
||||||
|
///
|
||||||
|
/// A file's size comes from its extended attributes, which only its own node
|
||||||
|
/// key can decrypt — and unlocking that key costs an S2K derivation (tens of
|
||||||
|
/// milliseconds) *per file*, which is the bulk of a pass over a large folder.
|
||||||
|
/// So the walk enumerates cheaply ([`enumerate_nodes_light`]) and only pays
|
||||||
|
/// for the files whose modification time has moved away from `baseline`: an
|
||||||
|
/// unchanged mtime means the recorded size still stands.
|
||||||
|
///
|
||||||
|
/// [`enumerate_nodes_light`]: proton_drive_rs::ProtonDriveClient::enumerate_nodes_light
|
||||||
|
///
|
||||||
|
/// What the walk could not read goes to `walk.gaps`, never silently out of
|
||||||
|
/// the map: a missing path reads as deleted on Drive.
|
||||||
|
///
|
||||||
|
/// Each folder's listing is saved as it comes in. A walk cut short by a
|
||||||
|
/// stop resumes from what was saved and lists only the folders it had not
|
||||||
|
/// reached, where it used to start over and, on a folder large enough,
|
||||||
|
/// never finish (B294). The database drops a saved walk whenever the
|
||||||
|
/// folder's baseline changes, so a resumed walk never meets a baseline
|
||||||
|
/// newer than its listings; it is as old as a long walk's first listings
|
||||||
|
/// would be, and the apply step checks each file again before it acts.
|
||||||
|
pub(super) fn walk_remote(
|
||||||
|
&self,
|
||||||
|
folder_id: i64,
|
||||||
|
root: &NodeUid,
|
||||||
|
walk: &mut RemoteWalk<'_>,
|
||||||
|
baseline: &HashMap<String, StoredSyncEntry>,
|
||||||
|
) -> Result<(), PassAbort> {
|
||||||
|
let WalkStart {
|
||||||
|
mut todo,
|
||||||
|
mut children,
|
||||||
|
dirty_upto,
|
||||||
|
} = self.start_walk(folder_id, root, walk);
|
||||||
|
// Folders to list again next pass: their listing failed or came back
|
||||||
|
// short this time.
|
||||||
|
let mut again: Vec<String> = Vec::new();
|
||||||
|
let mut listed: HashSet<String> = HashSet::new();
|
||||||
|
while let Some(next) = todo.pop_front() {
|
||||||
|
// Checked per folder, not per pass: this walk is the long pole on a
|
||||||
|
// large tree, and a user who asks for on-demand three minutes into
|
||||||
|
// it should not wait out the rest of a survey of files they want
|
||||||
|
// deleted. Bailing out here is safe precisely because the walk has
|
||||||
|
// applied nothing — a *partial* remote map, on the other hand,
|
||||||
|
// would be read as "the remote deleted everything we haven't
|
||||||
|
// reached yet", so it must never reach the diff.
|
||||||
|
if self.shutdown.is_stopping() {
|
||||||
|
return Err(PassAbort::Stopped);
|
||||||
|
}
|
||||||
|
if self.pass_abandoned(folder_id) {
|
||||||
|
return Err(PassAbort::Abandoned);
|
||||||
|
}
|
||||||
|
if self.ondemand_queued(folder_id) {
|
||||||
|
return Err(PassAbort::Interrupted);
|
||||||
|
}
|
||||||
|
// Gone with a folder listed again before it, or listed already.
|
||||||
|
if walk.dirs.get(&next.prefix) != Some(&next.uid) || !listed.insert(next.prefix.clone())
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let prefix = next.prefix;
|
||||||
|
// What an earlier listing could not read is read again now.
|
||||||
|
walk.gaps.forget(&prefix);
|
||||||
|
let Some(listing) = self.list_remote(folder_id, &next.uid, &prefix, walk, baseline)?
|
||||||
|
else {
|
||||||
|
// What the saved walk holds of it is older than the change
|
||||||
|
// that marked it: its files are left out of this pass, as a
|
||||||
|
// folder a full walk could not list is.
|
||||||
|
if let Some(children) = &children {
|
||||||
|
for rel in children.of(&prefix) {
|
||||||
|
if !walk.dirs.contains_key(rel) {
|
||||||
|
walk.out.remove(rel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
again.push(prefix);
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if listing.short || !listing.unread.is_empty() {
|
||||||
|
again.push(prefix.clone());
|
||||||
|
}
|
||||||
|
let mut removed = Vec::new();
|
||||||
|
let mut kept: HashSet<String> = HashSet::new();
|
||||||
|
if let Some(children) = &mut children {
|
||||||
|
// Listed again: what it held before and no longer holds goes,
|
||||||
|
// with all under it. A folder still there under the same uid
|
||||||
|
// keeps what was saved under it.
|
||||||
|
let fresh: HashMap<&str, &RemoteItem> = listing
|
||||||
|
.items
|
||||||
|
.iter()
|
||||||
|
.map(|(rel, item)| (rel.as_str(), item))
|
||||||
|
.collect();
|
||||||
|
for old in children.take(&prefix) {
|
||||||
|
let same_folder = walk.dirs.get(&old).is_some_and(|uid| {
|
||||||
|
fresh
|
||||||
|
.get(old.as_str())
|
||||||
|
.is_some_and(|item| item.is_dir && &item.uid == uid)
|
||||||
|
});
|
||||||
|
if same_folder {
|
||||||
|
kept.insert(old);
|
||||||
|
} else {
|
||||||
|
children.remove_subtree(&old, walk, &mut removed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
children.add(
|
||||||
|
&prefix,
|
||||||
|
listing
|
||||||
|
.items
|
||||||
|
.iter()
|
||||||
|
.map(|(rel, _)| rel)
|
||||||
|
.chain(&listing.unread),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let mut saved = Vec::with_capacity(listing.items.len() + listing.unread.len());
|
||||||
|
for (rel, item) in listing.items {
|
||||||
|
self.progress_scanned(folder_id, base_name(&rel));
|
||||||
|
saved.push(SavedWalkItem {
|
||||||
|
rel_path: rel.clone(),
|
||||||
|
uid: Some(item.uid.to_string()),
|
||||||
|
is_dir: item.is_dir,
|
||||||
|
mtime: item.mtime,
|
||||||
|
size: item.size,
|
||||||
|
revision: item.revision.clone(),
|
||||||
|
sha1: item.sha1.clone(),
|
||||||
|
});
|
||||||
|
if item.is_dir {
|
||||||
|
walk.dirs.insert(rel.clone(), item.uid.clone());
|
||||||
|
if !kept.contains(&rel) {
|
||||||
|
todo.push_back(WalkNext {
|
||||||
|
prefix: rel.clone(),
|
||||||
|
uid: item.uid.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
walk.out.insert(rel, item);
|
||||||
|
}
|
||||||
|
for rel in listing.unread {
|
||||||
|
self.progress_scanned(folder_id, base_name(&rel));
|
||||||
|
saved.push(SavedWalkItem {
|
||||||
|
rel_path: rel.clone(),
|
||||||
|
uid: None,
|
||||||
|
is_dir: false,
|
||||||
|
mtime: 0,
|
||||||
|
size: 0,
|
||||||
|
revision: None,
|
||||||
|
sha1: None,
|
||||||
|
});
|
||||||
|
walk.gaps.unread(rel);
|
||||||
|
}
|
||||||
|
// A walk that cannot be saved still runs; it just starts over if
|
||||||
|
// it is cut short.
|
||||||
|
if let Err(e) =
|
||||||
|
self.store
|
||||||
|
.sync_walk_record(folder_id, &prefix, listing.short, &saved, &removed)
|
||||||
|
{
|
||||||
|
debug!(folder = prefix, error = ?e, "sync: cannot save the walk's progress");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A stop that came during the last listing still ends the pass here,
|
||||||
|
// and the next one resumes a walk with nothing left to list.
|
||||||
|
if self.shutdown.is_stopping() {
|
||||||
|
return Err(PassAbort::Stopped);
|
||||||
|
}
|
||||||
|
self.finish_walk(folder_id, dirty_upto, &again)
|
||||||
|
.map_err(|e| PassAbort::from(format!("save the walk of Drive: {e:?}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keep a walk that reached its end as the next pass's picture of Drive.
|
||||||
|
/// A walk that listed every folder drops the dirty marks it read past; a
|
||||||
|
/// walk of the dirty folders only drops the marks it read, up to
|
||||||
|
/// `dirty_upto`. Either way, the folders in `again` stay dirty, so the
|
||||||
|
/// next pass lists them again.
|
||||||
|
pub(super) fn finish_walk(
|
||||||
|
&self,
|
||||||
|
folder_id: i64,
|
||||||
|
dirty_upto: Option<i64>,
|
||||||
|
again: &[String],
|
||||||
|
) -> pdfs_core::Result<()> {
|
||||||
|
if !again.is_empty() {
|
||||||
|
self.store.sync_remote_mark(folder_id, again)?;
|
||||||
|
}
|
||||||
|
match dirty_upto {
|
||||||
|
Some(seq) => self.store.sync_remote_dirty_consume(folder_id, seq),
|
||||||
|
None => {
|
||||||
|
if !self.store.sync_walk_complete(folder_id)? {
|
||||||
|
debug!(
|
||||||
|
id = folder_id,
|
||||||
|
"sync: the walk of Drive was dropped before its end"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a walk of Drive starts.
|
||||||
|
///
|
||||||
|
/// - A complete walk, kept up to date by the event stream, is loaded into
|
||||||
|
/// `walk`, and only the folders marked dirty since are listed again.
|
||||||
|
/// - A walk an earlier pass did not finish is loaded and continues, when
|
||||||
|
/// it is recent enough.
|
||||||
|
/// - Otherwise a new walk starts at the root.
|
||||||
|
pub(super) fn start_walk(
|
||||||
|
&self,
|
||||||
|
folder_id: i64,
|
||||||
|
root: &NodeUid,
|
||||||
|
walk: &mut RemoteWalk<'_>,
|
||||||
|
) -> WalkStart {
|
||||||
|
let root_uid = root.to_string();
|
||||||
|
let saved = match self.store.sync_walk_load(folder_id) {
|
||||||
|
Ok(saved) => saved,
|
||||||
|
Err(e) => {
|
||||||
|
warn!(id = folder_id, error = ?e, "sync: cannot read the saved walk; starting over");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Some(saved) = saved
|
||||||
|
&& saved.root_uid == root_uid
|
||||||
|
{
|
||||||
|
let age = now_secs().saturating_sub(saved.started);
|
||||||
|
if saved.complete
|
||||||
|
&& age < AUDIT_INTERVAL.as_secs() as i64
|
||||||
|
&& self.events_trusted(root)
|
||||||
|
&& let Some(start) = self.walk_dirty(folder_id, &saved, walk)
|
||||||
|
{
|
||||||
|
return start;
|
||||||
|
}
|
||||||
|
if !saved.complete
|
||||||
|
&& age < WALK_MAX_AGE.as_secs() as i64
|
||||||
|
&& let Some(restored) = restore_walk(&saved, walk)
|
||||||
|
{
|
||||||
|
self.progress_scanned_many(folder_id, restored.items);
|
||||||
|
self.trace_count(Count::Resumed, restored.items);
|
||||||
|
info!(
|
||||||
|
id = folder_id,
|
||||||
|
restored = restored.items,
|
||||||
|
folders_left = restored.todo.len(),
|
||||||
|
age_s = age,
|
||||||
|
"sync: resuming the walk of Drive"
|
||||||
|
);
|
||||||
|
return WalkStart {
|
||||||
|
todo: restored.todo,
|
||||||
|
children: None,
|
||||||
|
dirty_upto: None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// Loaded into `walk`, and of no use: start from nothing.
|
||||||
|
walk.out.clear();
|
||||||
|
walk.dirs.retain(|rel, _| rel.is_empty());
|
||||||
|
*walk.gaps = RemoteGaps::default();
|
||||||
|
}
|
||||||
|
if let Err(e) = self.store.sync_walk_begin(folder_id, &root_uid, now_secs()) {
|
||||||
|
debug!(id = folder_id, error = ?e, "sync: cannot save the walk's progress");
|
||||||
|
}
|
||||||
|
WalkStart {
|
||||||
|
todo: VecDeque::from([WalkNext {
|
||||||
|
prefix: String::new(),
|
||||||
|
uid: root.clone(),
|
||||||
|
}]),
|
||||||
|
children: None,
|
||||||
|
dirty_upto: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start from a complete walk: load it into `walk`, and list again the
|
||||||
|
/// folders marked dirty since, plus any found since and not listed yet.
|
||||||
|
/// `None` when it cannot be read back.
|
||||||
|
pub(super) fn walk_dirty(
|
||||||
|
&self,
|
||||||
|
folder_id: i64,
|
||||||
|
saved: &SavedWalk,
|
||||||
|
walk: &mut RemoteWalk<'_>,
|
||||||
|
) -> Option<WalkStart> {
|
||||||
|
let dirty = match self.store.sync_remote_dirty(folder_id) {
|
||||||
|
Ok(dirty) => dirty,
|
||||||
|
Err(e) => {
|
||||||
|
warn!(id = folder_id, error = ?e, "sync: cannot read what changed on Drive");
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let restored = restore_walk(saved, walk)?;
|
||||||
|
let mut todo = restored.todo;
|
||||||
|
let mut dirs: Vec<&str> = dirty.iter().map(|(_, dir)| dir.as_str()).collect();
|
||||||
|
dirs.sort_by_key(|dir| (dir.matches('/').count(), *dir));
|
||||||
|
dirs.dedup();
|
||||||
|
// Shallowest first: a folder listed again may turn out new or gone,
|
||||||
|
// and is then listed whole or dropped with what is under it.
|
||||||
|
for dir in &dirs {
|
||||||
|
match walk.dirs.get(*dir) {
|
||||||
|
Some(uid) => todo.push_back(WalkNext {
|
||||||
|
prefix: dir.to_string(),
|
||||||
|
uid: uid.clone(),
|
||||||
|
}),
|
||||||
|
// Gone from Drive, or new and not listed yet: listing its
|
||||||
|
// parent, marked too, settles it.
|
||||||
|
None => debug!(id = folder_id, dir, "sync: a dirty folder is not on Drive"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.progress_scanned_many(folder_id, restored.items);
|
||||||
|
self.trace_count(Count::Reused, restored.items);
|
||||||
|
self.trace_count(Count::Dirty, dirs.len());
|
||||||
|
info!(
|
||||||
|
id = folder_id,
|
||||||
|
known = restored.items,
|
||||||
|
dirty = dirs.len(),
|
||||||
|
to_list = todo.len(),
|
||||||
|
"sync: listing only the folders changed on Drive"
|
||||||
|
);
|
||||||
|
Some(WalkStart {
|
||||||
|
todo,
|
||||||
|
children: Some(restored.children),
|
||||||
|
dirty_upto: Some(dirty.iter().map(|(seq, _)| *seq).max().unwrap_or(0)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether Drive's event stream for `root` is being followed, so a
|
||||||
|
/// change on Drive is marked dirty by the time a pass looks. The stream
|
||||||
|
/// covers the account's own volume only, and must have been read lately.
|
||||||
|
///
|
||||||
|
/// Right after a start, the stream has not been read yet: wait a little
|
||||||
|
/// for it rather than walk all of Drive again.
|
||||||
|
pub(super) fn events_trusted(&self, root: &NodeUid) -> bool {
|
||||||
|
if root.volume_id != self.primary_root_uid.volume_id {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let started = Instant::now();
|
||||||
|
while self.events_read_at.load(Ordering::Relaxed) == 0
|
||||||
|
&& started.elapsed() < EVENTS_FRESH
|
||||||
|
&& self.shutdown.sleep(Duration::from_millis(250))
|
||||||
|
{}
|
||||||
|
let read_at = self.events_read_at.load(Ordering::Relaxed);
|
||||||
|
read_at > 0 && now_secs().saturating_sub(read_at) < EVENTS_FRESH.as_secs() as i64
|
||||||
|
}
|
||||||
|
|
||||||
|
/// List one folder on Drive. `None` when the listing failed: that is
|
||||||
|
/// noted in `walk.gaps`, and the folder is not saved as listed, so a
|
||||||
|
/// resumed walk asks again. A failure at the root fails the pass.
|
||||||
|
pub(super) fn list_remote(
|
||||||
|
&self,
|
||||||
|
folder_id: i64,
|
||||||
|
folder: &NodeUid,
|
||||||
|
prefix: &str,
|
||||||
|
walk: &mut RemoteWalk<'_>,
|
||||||
|
baseline: &HashMap<String, StoredSyncEntry>,
|
||||||
|
) -> Result<Option<Listing>, PassAbort> {
|
||||||
|
let listing = Instant::now();
|
||||||
|
let step = Instant::now();
|
||||||
|
let uids = self
|
||||||
|
.rt
|
||||||
|
.block_on(self.drive.enumerate_folder_children_node_uids(folder))
|
||||||
|
.map_err(|e| format!("enumerate {folder}: {e}"));
|
||||||
|
self.trace_call(Call::ListChildren, step.elapsed());
|
||||||
|
self.trace_count(Count::RemoteFolders, 1);
|
||||||
|
let Some(uids) = unlisted_gap(walk, prefix, uids)? else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let mut out = Listing::default();
|
||||||
|
if uids.is_empty() {
|
||||||
|
return Ok(Some(out));
|
||||||
|
}
|
||||||
|
let step = Instant::now();
|
||||||
|
let nodes = self
|
||||||
|
.rt
|
||||||
|
.block_on(self.drive.enumerate_nodes_light(&uids))
|
||||||
|
.map_err(|e| format!("resolve nodes: {e}"));
|
||||||
|
self.trace_call(Call::ReadNodes, step.elapsed());
|
||||||
|
let Some(nodes) = unlisted_gap(walk, prefix, nodes)? else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
// The SDK leaves out a node it cannot decrypt, and says so only in its
|
||||||
|
// log. Its name went with it, so all this can record is the folder.
|
||||||
|
if nodes.len() < uids.len() {
|
||||||
|
warn!(
|
||||||
|
folder = prefix,
|
||||||
|
listed = uids.len(),
|
||||||
|
read = nodes.len(),
|
||||||
|
"sync: some nodes on Drive cannot be read; leaving them out"
|
||||||
|
);
|
||||||
|
walk.gaps.short_listing(prefix);
|
||||||
|
out.short = true;
|
||||||
|
}
|
||||||
|
let nodes: Vec<Node> = nodes
|
||||||
|
.into_iter()
|
||||||
|
.filter(|node| {
|
||||||
|
let safe = pdfs_drive::remote_name_is_safe(&node.name);
|
||||||
|
if !safe {
|
||||||
|
warn!(folder = prefix, uid = %node.uid, "sync: a name on Drive cannot be a local file name; leaving it out");
|
||||||
|
}
|
||||||
|
safe
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// Files whose recorded mtime no longer matches: their size has to be
|
||||||
|
// read for real, so these are the only node keys worth unlocking.
|
||||||
|
let stale: Vec<NodeUid> = nodes
|
||||||
|
.iter()
|
||||||
|
.filter(|n| !n.trashed && !n.is_folder())
|
||||||
|
.filter(|n| {
|
||||||
|
unchanged_remote_size(
|
||||||
|
baseline,
|
||||||
|
&join_rel(prefix, &n.name),
|
||||||
|
n.modification_time,
|
||||||
|
pdfs_drive::node_revision_id(n).as_deref(),
|
||||||
|
)
|
||||||
|
.is_none()
|
||||||
|
})
|
||||||
|
.map(|n| n.uid.clone())
|
||||||
|
.collect();
|
||||||
|
// The full enumeration also decrypts the content digest, which the
|
||||||
|
// first sync of a path compares against the local file (B248).
|
||||||
|
let sized: HashMap<String, (i64, Option<String>)> = if stale.is_empty() {
|
||||||
|
HashMap::new()
|
||||||
|
} else {
|
||||||
|
let step = Instant::now();
|
||||||
|
let full = self
|
||||||
|
.rt
|
||||||
|
.block_on(self.drive.enumerate_nodes(&stale))
|
||||||
|
.map_err(|e| format!("resolve nodes: {e}"));
|
||||||
|
self.trace_call(Call::ReadNodesFull, step.elapsed());
|
||||||
|
self.trace_count(Count::NodesFull, stale.len());
|
||||||
|
let Some(full) = unlisted_gap(walk, prefix, full)? else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
full.iter()
|
||||||
|
.map(|n| {
|
||||||
|
(
|
||||||
|
n.uid.to_string(),
|
||||||
|
(remote_file_sig(n).1, pdfs_drive::node_content_sha1(n)),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
let stale: HashSet<String> = stale.iter().map(|u| u.to_string()).collect();
|
||||||
|
self.record_revisions(folder_id, prefix, &nodes, &sized, baseline);
|
||||||
|
self.trace_count(Count::Nodes, nodes.len());
|
||||||
|
self.engine.trace(|t| t.listing(prefix, listing.elapsed()));
|
||||||
|
|
||||||
|
for node in nodes {
|
||||||
|
if node.trashed {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let rel = join_rel(prefix, &node.name);
|
||||||
|
if node.is_folder() {
|
||||||
|
out.items.push((
|
||||||
|
rel,
|
||||||
|
RemoteItem {
|
||||||
|
uid: node.uid,
|
||||||
|
is_dir: true,
|
||||||
|
mtime: 0,
|
||||||
|
size: 0,
|
||||||
|
revision: None,
|
||||||
|
sha1: None,
|
||||||
|
},
|
||||||
|
));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let (size, sha1) = if stale.contains(&node.uid.to_string()) {
|
||||||
|
match sized.get(&node.uid.to_string()) {
|
||||||
|
Some(sized) => sized.clone(),
|
||||||
|
// Its size was needed but could not be read (the full
|
||||||
|
// enumeration skipped it as undecryptable). Leave it out
|
||||||
|
// rather than record a stale size, and say so: missing,
|
||||||
|
// it would read as deleted on Drive.
|
||||||
|
None => {
|
||||||
|
out.unread.push(rel);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
match unchanged_remote_size(
|
||||||
|
baseline,
|
||||||
|
&rel,
|
||||||
|
node.modification_time,
|
||||||
|
pdfs_drive::node_revision_id(&node).as_deref(),
|
||||||
|
) {
|
||||||
|
Some(size) => (size, None),
|
||||||
|
None => continue,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
out.items.push((
|
||||||
|
rel,
|
||||||
|
RemoteItem {
|
||||||
|
revision: pdfs_drive::node_revision_id(&node),
|
||||||
|
uid: node.uid,
|
||||||
|
is_dir: false,
|
||||||
|
mtime: node.modification_time,
|
||||||
|
size,
|
||||||
|
sha1,
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(Some(out))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -50,7 +50,7 @@ graph TD
|
|||||||
| [`pdfs-core`](../crates/pdfs-core) | Authentication and keyring (`auth`), configuration and directories (`config`), the control protocol (`control`), search scoring, ignore rules, Google Takeout parsing, the machine profile, the transfer registry (`transfers`) and the shutdown signal (`shutdown`) |
|
| [`pdfs-core`](../crates/pdfs-core) | Authentication and keyring (`auth`), configuration and directories (`config`), the control protocol (`control`), search scoring, ignore rules, Google Takeout parsing, the machine profile, the transfer registry (`transfers`) and the shutdown signal (`shutdown`) |
|
||||||
| [`pdfs-store`](../crates/pdfs-store) | The SQLite schema and queries (`db/`), the content cache (`cache`) |
|
| [`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-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 and engine thread (`mirror`), with 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-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-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-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-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-cli`](../crates/pdfs-cli) | The `pdfs` binary. `pdfs daemon` runs `pdfs_daemon::run` in-process; every other command is a control-socket client |
|
||||||
@@ -485,6 +485,11 @@ order, up to one 10-second deadline, and names any that are still running at the
|
|||||||
`pdfs diagnostics` reports what each worker is doing and which services are still running. The
|
`pdfs diagnostics` reports what each worker is doing and which services are still running. The
|
||||||
supervisor warns once about a service that ended while the mount runs.
|
supervisor warns once about a service that ended while the mount runs.
|
||||||
|
|
||||||
|
Work a request starts and does not wait for (a cache check, `VACUUM`, an import, a folder pin, a
|
||||||
|
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. Jobs are not joined on stop.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 10. Threat model: what this client writes to disk in plaintext
|
## 10. Threat model: what this client writes to disk in plaintext
|
||||||
|
|||||||
+3
-1
@@ -17,7 +17,9 @@ kept, with a list of the folders that changed on Proton Drive since (49).
|
|||||||
### Added
|
### Added
|
||||||
- **`pdfs diagnostics` says which of the daemon's background services are running.** If one
|
- **`pdfs diagnostics` says which of the daemon's background services are running.** If one
|
||||||
ends while the drive is mounted, for example the sync engine after a crash, the journal says
|
ends while the drive is mounted, for example the sync engine after a crash, the journal says
|
||||||
so once, by name, instead of saying nothing until a restart.
|
so once, by name, instead of saying nothing until a restart. It also lists the jobs running
|
||||||
|
in the background, such as a cache check, an import or a folder being pinned, and how long
|
||||||
|
each has run.
|
||||||
- **`PDFS_INSTANCE` runs a second client next to your own.** With a name set, the client keeps
|
- **`PDFS_INSTANCE` runs a second client next to your own.** With a name set, the client keeps
|
||||||
its own directories, keyring entry, kernel keys and mountpoint, so a test account can run
|
its own directories, keyring entry, kernel keys and mountpoint, so a test account can run
|
||||||
alongside the account you use. `scripts/live-bench.py` uses it to time one edit, from the
|
alongside the account you use. `scripts/live-bench.py` uses it to time one edit, from the
|
||||||
|
|||||||
Reference in new issue
Block a user