Compare commits

...
Author SHA1 Message Date
nvrl 7e12c747a0 fix(gui,fuse): name the deletion when stopping a sync deletes the Drive folder
With "Also delete from Proton Drive" on, the stop-sync dialog kept its
routine heading, button and toast, although the action also moves the
folder in Proton Drive to the trash, and for an online-only folder that
is the only copy. The heading and button now change with the switch, and
the toast names the deletion.

The daemon dropped the folder from the sync set first and then only
logged a failed trash, so a removal while offline answered "removed
synced folder" and the copy in Proton Drive stayed without a word. It
now answers with an error that says the folder stopped syncing but its
Drive folder was not moved to the trash.

New sim: stopping_sync_says_so_when_its_drive_folder_could_not_be_deleted.
The catalogs are regenerated with po/update.sh, which also marks one
string that main no longer uses as obsolete.
2026-11-28 03:25:59 +01:00
nvrl f975d9cf17 Merge pull request #198 from narrrl/perf/revision-over
perf(sync): check an edit's base revision through the upload's own read
2026-11-28 02:11:30 +01:00
nvrl deb15a3327 Merge pull request #197 from narrrl/feat/sdk-0.12.7
build(deps): proton-sdk and proton-drive-rs 0.12.7
2026-11-28 01:23:57 +01:00
nvrl 8c7a0a8a17 perf(sync): check an edit's base revision through the upload's own read
A mirror edit read the file's node before each upload to make sure no
other client had committed a revision since the pass looked (B249). The
SDK then read the same link again for the content key and the revision
id. proton-drive-rs 0.12.8 adds upload_new_revision_over, which makes
that check with its own read and creates the revision over the expected
one. The mirror now uses it whenever it knows the revision it saw, and
keeps the separate read only for rows without one.

0.12.8 also caches a folder's hash key, so a second upload into the same
folder reads none of its keys again.

The fake drive answers upload_new_revision_over with Moved, Trashed or
Sealed, and honors hold_next_read, so the B249 sim still covers the race.
2026-11-28 01:21:56 +01:00
nvrl 9533ebcdfc build(deps): proton-sdk and proton-drive-rs 0.12.7
The new SDK sends a file whose encrypted size is under 128 KiB, and a new
revision of one, in a single request instead of a draft, its block and a
commit. Synced folders and the drive mount both stream their uploads, so both
take the one-request path. The small_uploads switch turns it off.
2026-11-28 00:33:48 +01:00
nvrl ccc679eef5 Merge pull request #196 from narrrl/feat/small-uploads
fix(sync): take an unanswered upload's file on Drive as our own, not a conflict
2026-11-28 00:30:10 +01:00
nvrl d1421a84b1 Merge pull request #195 from narrrl/feat/small-upload-switch
feat(config): switch for the one-request small upload
2026-11-28 00:16:50 +01:00
nvrl 670ec7db31 Merge pull request #194 from narrrl/fix/ci-apt-microsoft
ci: drop the runner's Microsoft apt source before the update
2026-11-28 00:16:36 +01:00
nvrl 30b20fc444 Merge pull request #193 from narrrl/feat/bench-small-files
test(bench): time many small files and count the requests they take
2026-11-28 00:16:23 +01:00
nvrl 5c6360e6e7 feat(config): switch for the one-request small upload
small_uploads in config.json, on when absent, decides whether the daemon's Drive client sends a small file in one request. It lets the path be turned off without a new build while it is new.
2026-11-28 00:09:40 +01:00
nvrl 42926b71a9 ci: drop the runner's Microsoft apt source before the update
packages.microsoft.com answered 403 on a main run, and apt-get update failed the release-cache job. Nothing here installs from it.
2026-11-27 23:32:42 +01:00
nvrl 21e7c03460 test(bench): time many small files and count the requests they take
live-bench.py gets a small scenario: a tree of small random files and a few images with thumbnails, a first sync, then a batch of edits. Each phase reports wall time, files per second, the daemon's CPU time and the requests it sent, counted from the SDK's telemetry. This is the baseline for the one-request small upload.
2026-11-27 23:26:07 +01:00
27 changed files with 4532 additions and 3693 deletions

No files matched your search

+9
View File
@@ -17,6 +17,9 @@ jobs:
- name: Install native dependencies
run: |
# The runner image lists Microsoft's apt repository, which nothing here
# needs and which at times answers 403 and fails the update.
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
sudo apt-get update
sudo apt-get install -y \
pkg-config \
@@ -80,6 +83,9 @@ jobs:
- name: Install native dependencies
run: |
# The runner image lists Microsoft's apt repository, which nothing here
# needs and which at times answers 403 and fails the update.
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
sudo apt-get update
sudo apt-get install -y \
pkg-config \
@@ -129,6 +135,9 @@ jobs:
- name: Install native dependencies
run: |
# The runner image lists Microsoft's apt repository, which nothing here
# needs and which at times answers 403 and fails the update.
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
sudo apt-get update
sudo apt-get install -y \
pkg-config \
+6
View File
@@ -20,6 +20,9 @@ jobs:
- name: Install system dependencies
run: |
# The runner image lists Microsoft's apt repository, which nothing here
# needs and which at times answers 403 and fails the update.
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
sudo apt-get update
sudo apt-get install -y \
pkg-config \
@@ -75,6 +78,9 @@ jobs:
- name: Install system dependencies
run: |
# The runner image lists Microsoft's apt repository, which nothing here
# needs and which at times answers 403 and fails the update.
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
sudo apt-get update
sudo apt-get install -y \
pkg-config \
Generated
+4 -4
View File
@@ -4071,9 +4071,9 @@ dependencies = [
[[package]]
name = "proton-drive-rs"
version = "0.12.6"
version = "0.12.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b1a71d0e737a9bd6cff07105218e7bef3bddcfd9d6651646d7302cdbba71961"
checksum = "11c09c245784d7253072b751e43b1919140fdbc8641c5328a7e2801889c86041"
dependencies = [
"async-trait",
"base64 0.23.1",
@@ -4191,9 +4191,9 @@ dependencies = [
[[package]]
name = "proton-sdk"
version = "0.12.6"
version = "0.12.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81edef2b4b174e936a3537793ee901b92dd7c0484eb7fed09ad69432f407f86b"
checksum = "7a6ed261fbcabf35abe67ebf8c8aff85b01fc43aef5b298380a6e6f7d3dd31d3"
dependencies = [
"aes-gcm 0.11.1",
"async-trait",
+2 -2
View File
@@ -15,8 +15,8 @@ keywords = ["proton", "drive", "fuse", "sync", "linux"]
categories = ["filesystem", "command-line-utilities"]
[workspace.dependencies]
proton-sdk = { version = "0.12.6" }
proton-drive-rs = { version = "0.12.6" }
proton-sdk = { version = "0.12.8" }
proton-drive-rs = { version = "0.12.8" }
proton-gallery-app-rs = "0.1.0"
proton-gallery-rs = "0.1.5"
proton-map-rs = "0.1.0"
+8
View File
@@ -278,6 +278,12 @@ pub struct AppConfig {
/// the field.
#[serde(default)]
pub local_first: Option<bool>,
/// Send a file small enough, with its thumbnails, to fit 128 KiB in one
/// request instead of three or more. `None` means on. `false` uploads
/// every file in blocks, the way all files went before. Defaulted for
/// configs predating the field.
#[serde(default)]
pub small_uploads: Option<bool>,
/// Ask GitHub once a day whether a newer release is out, and say so in the
/// desktop app. Off by default: GitHub then sees the address and version
/// asking. Never used where a package manager installs updates (see
@@ -1077,6 +1083,7 @@ mod tests {
language: Some("de".to_string()),
online_map: true,
local_first: Some(false),
small_uploads: Some(false),
update_check: true,
update_last_checked: Some(1_760_000_000),
update_latest: Some("3.6.0".to_string()),
@@ -1096,6 +1103,7 @@ mod tests {
assert_eq!(decoded.update_latest.as_deref(), Some("3.6.0"));
assert_eq!(decoded.language.as_deref(), Some("de"));
assert_eq!(decoded.upload_limit, Some(500_000));
assert_eq!(decoded.small_uploads, Some(false));
assert_eq!(decoded.download_limit, None);
assert_eq!(decoded.files_view, config.files_view);
assert_eq!(decoded.photos_view, config.photos_view);
+7
View File
@@ -241,6 +241,13 @@ pub fn mount_once(mountpoint: Option<PathBuf>) -> Result<pdfs_fuse::MountOutcome
let (client, session) = rt
.block_on(auth::resume_client())
.context("resume session (run `pdfs login` first)")?;
// On unless the config turns it off: the one-request upload for small
// files is new, and this lets it be switched off without a new build.
let small_uploads = config.small_uploads.unwrap_or(true);
if !small_uploads {
tracing::info!("small files are uploaded in blocks: small_uploads is off in the config");
}
let client = client.with_small_file_upload(small_uploads);
// Token updates are persisted automatically in real-time. The SDK session has
// a token refresh callback registered during `resume_client` that writes updated
+25 -1
View File
@@ -23,7 +23,7 @@ use proton_drive_rs::{
Thumbnail, ThumbnailType, TrashedNode,
};
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead, RevisionUpload};
/// Every kind of call [`DriveApi`] makes, one per method.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -393,6 +393,30 @@ impl DriveApi for Counted {
.await
}
async fn upload_new_revision_over_dyn(
&self,
file_uid: &NodeUid,
expected: &str,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
) -> Result<RevisionUpload> {
// Counted with the other revision uploads: it is one, with its check.
self.timed(
DriveCall::UploadNewRevision,
self.inner.upload_new_revision_over_dyn(
file_uid,
expected,
reader,
intended_size,
thumbnails,
last_modification_time,
),
)
.await
}
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
self.timed(DriveCall::OpenRevision, self.inner.open_revision(uid))
.await
+55
View File
@@ -33,6 +33,8 @@ use proton_drive_rs::{
NodeMoveItem, ProtonDriveClient, RevisionReader, Thumbnail, ThumbnailType, TrashedNode,
};
pub use proton_drive_rs::{RevisionUpload, SealedUpload};
pub mod counted;
pub mod digest;
@@ -120,6 +122,18 @@ pub trait DriveApi: Send + Sync {
last_modification_time: Option<i64>,
) -> Result<()>;
/// A new revision of `file_uid`, only over the revision `expected`. See
/// [`ProtonDriveClient::upload_new_revision_over`].
async fn upload_new_revision_over_dyn(
&self,
file_uid: &NodeUid,
expected: &str,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
) -> Result<RevisionUpload>;
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>>;
/// The file's thumbnail of `thumbnail_type`, or `None` when its revision
@@ -287,6 +301,26 @@ impl dyn DriveApi {
.await
}
pub async fn upload_new_revision_over<R: Read + Send>(
&self,
file_uid: &NodeUid,
expected: &str,
mut reader: R,
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
) -> Result<RevisionUpload> {
self.upload_new_revision_over_dyn(
file_uid,
expected,
&mut reader,
intended_size,
thumbnails,
last_modification_time,
)
.await
}
pub async fn download_file_to<W: Write + Send>(
&self,
uid: &NodeUid,
@@ -468,6 +502,27 @@ impl DriveApi for ProtonDriveClient {
.await
}
async fn upload_new_revision_over_dyn(
&self,
file_uid: &NodeUid,
expected: &str,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
) -> Result<RevisionUpload> {
ProtonDriveClient::upload_new_revision_over(
self,
file_uid,
expected,
reader,
intended_size,
thumbnails,
last_modification_time.and_then(pdfs_core::timestamp::modification_time),
)
.await
}
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
let reader = ProtonDriveClient::open_revision(self, uid).await?;
Ok(Arc::new(reader))
+52 -1
View File
@@ -67,7 +67,7 @@ use proton_drive_rs::{
use sha1::{Digest as _, Sha1};
use super::rng::Rng;
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead, RevisionUpload, SealedUpload};
/// The volume every fake node lives on.
pub const VOLUME: &str = "simvol";
@@ -1531,6 +1531,57 @@ impl DriveApi for FakeClient {
Ok(())
}
async fn upload_new_revision_over_dyn(
&self,
file_uid: &NodeUid,
expected: &str,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
) -> Result<RevisionUpload> {
// The SDK reads the file's link for its keys and checks the revision
// on that read, so it is held, lags and counts like any other read.
self.wait_if_held(&self.0.hold, std::slice::from_ref(file_uid))
.await;
let lag = self.lag();
let seen = self
.request(false, |server| {
Ok(server
.visible(file_uid, lag, Instant::now())
.map(|remote| (remote.trashed, remote.file.map(|file| file.revision))))
})
.await?;
match seen {
None => return Err(api(ResponseCode::DoesNotExist, "file not found")),
Some((true, _)) => return Ok(RevisionUpload::Trashed),
Some((false, revision)) if revision.as_deref() != Some(expected) => {
return Ok(RevisionUpload::Moved);
}
Some(_) => {}
}
self.upload_new_revision_from_dyn(
file_uid,
reader,
intended_size,
thumbnails,
last_modification_time,
)
.await?;
let revision_id = self
.0
.drive
.server
.lock()
.current(file_uid)
.and_then(|remote| remote.file.as_ref().map(|file| file.revision.clone()))
.unwrap_or_default();
Ok(RevisionUpload::Sealed(SealedUpload {
node_uid: file_uid.clone(),
revision_id,
}))
}
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
let file = self
.request(false, |server| {
+16 -2
View File
@@ -130,12 +130,26 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
},
CtlRequest::RemoveSyncFolder { id, delete_remote } => {
match core.remove_sync_folder(id, delete_remote) {
Ok(()) => {
Ok(None) => {
core.profile().touch_profile();
CtlResponse::Ok {
message: "removed synced folder".to_string(),
message: if delete_remote {
"removed synced folder and moved its folder in Proton Drive to the trash"
} else {
"removed synced folder"
}
.to_string(),
}
}
// The folder no longer syncs, but its copy in Proton Drive is
// still there. That is not what was asked, so it is an error,
// and the message says which half happened.
Ok(Some(trash_error)) => {
core.profile().touch_profile();
CtlResponse::error(CoreError::remote(format!(
"stopped syncing the folder, but its folder in Proton Drive was not moved to the trash: {trash_error}"
)))
}
Err(e) => CtlResponse::error(e),
}
}
+28 -11
View File
@@ -765,9 +765,18 @@ impl Core {
jobs
}
/// Remove a synced folder from the sync set. `delete_remote` also deletes its
/// folder under the device root; otherwise the cloud copy is left in place.
pub(crate) fn remove_sync_folder(&self, id: i64, delete_remote: bool) -> CoreResult<()> {
/// Remove a synced folder from the sync set. `delete_remote` also moves its
/// folder under the device root to the trash; otherwise the cloud copy is
/// left in place.
///
/// The folder is out of the sync set before the trash is asked, so a trash
/// that fails does not fail the removal. It comes back as `Some(error)`,
/// for the caller to say that the cloud copy is still there.
pub(crate) fn remove_sync_folder(
&self,
id: i64,
delete_remote: bool,
) -> CoreResult<Option<String>> {
let lock = self.sync.lock(id);
// A pass holds the lock for as long as it runs, hours on a large
// folder. Ask it to stop at its next checkpoint rather than wait it
@@ -823,16 +832,24 @@ impl Core {
self.clear_sync_folder_paused(id);
// Stop watching the folder we just dropped.
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
if delete_remote
&& let Some(uid) = parse_uid(&folder.remote_uid)
&& let Err(e) = self
.rt
.block_on(self.drive.trash_nodes(&[uid]))
.and_then(batch::into_unit)
if !delete_remote {
return Ok(None);
}
let Some(uid) = parse_uid(&folder.remote_uid) else {
warn!(id, remote = %folder.remote_uid, "delete remote device folder: bad uid");
return Ok(Some(format!("bad folder id {}", folder.remote_uid)));
};
match self
.rt
.block_on(self.drive.trash_nodes(&[uid]))
.and_then(batch::into_unit)
{
warn!(id, error = %e, "delete remote device folder failed");
Ok(()) => Ok(None),
Err(e) => {
warn!(id, error = %e, "delete remote device folder failed");
Ok(Some(e.to_string()))
}
}
Ok(())
}
/// Trigger a reconcile: one folder by id, or every folder when `id` is `None`.
+51
View File
@@ -4485,6 +4485,57 @@ mod tests {
id
}
/// Stop syncing with "Also delete from Proton Drive" on, while Drive cannot
/// be reached. The folder stops syncing, but its copy in Proton Drive
/// stays. The reply was a plain success, so the app said "Stopped syncing
/// folder" and nothing told the user the cloud copy was still there.
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn stopping_sync_says_so_when_its_drive_folder_could_not_be_deleted() {
let drive = FakeDrive::new();
let dir = scratch("stop-sync-delete-offline");
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
let local = dir.join("docs");
let id = sync_folder(&daemon, &local, "mirror");
std::fs::write(local.join("keep.txt"), b"keep").unwrap();
daemon.request(&Request::SyncNow { id: Some(id) }).unwrap();
let on_drive = || {
drive.tree().iter().any(|(path, entry)| {
path.ends_with("docs/keep.txt") && *entry == Entry::File(Arc::new(b"keep".to_vec()))
})
};
assert!(
wait_until(Duration::from_secs(30), || on_drive()
&& listed_folder(&daemon, id).is_some_and(|f| f.state == "idle")),
"the folder synced: {:?}",
listed_folder(&daemon, id)
);
daemon.client.set_online(false);
let error = daemon
.request(&Request::RemoveSyncFolder {
id,
delete_remote: true,
})
.unwrap_err()
.to_string();
daemon.client.set_online(true);
assert!(
error.contains("stopped syncing the folder")
&& error.contains("was not moved to the trash"),
"{error}"
);
assert!(
listed_folder(&daemon, id).is_none(),
"the folder still syncs"
);
assert!(on_drive(), "the copy in Proton Drive is gone after all");
assert_eq!(std::fs::read(local.join("keep.txt")).unwrap(), b"keep");
daemon.stop().unwrap();
let _ = std::fs::remove_dir_all(dir);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_move_out_of_an_on_demand_folder_refuses_a_file_still_open_for_writing() {
+44 -10
View File
@@ -1007,20 +1007,54 @@ pub(crate) fn prompt_remove_sync_folder(
dialog.set_response_appearance("remove", adw::ResponseAppearance::Destructive);
dialog.set_default_response(Some("cancel"));
dialog.set_close_response("cancel");
let ui = ui.clone();
dialog.connect_response(None, move |_, resp| {
if resp == "remove" {
run_devices_mutation(
&ui,
Request::RemoveSyncFolder {
id,
delete_remote: !attached && delete_remote.is_active(),
// With the switch on, the button does more than stop syncing, so it says
// so: the heading, the button and the outcome all name the deletion.
delete_remote.connect_active_notify({
let dialog = dialog.clone();
move |row| {
let deleting = row.is_active();
dialog.set_heading(Some(&if deleting {
gettext("Stop Syncing and Delete Folder?")
} else {
gettext("Stop Syncing Folder?")
}));
dialog.set_response_label(
"remove",
&if deleting {
gettext("Stop Syncing and Delete")
} else {
gettext("Stop Syncing")
},
&gettext("Stopped syncing folder"),
&gettext("Couldn't stop syncing the folder"),
);
}
});
let ui = ui.clone();
dialog.connect_response(None, move |_, resp| {
if resp != "remove" {
return;
}
let deleting = !attached && delete_remote.is_active();
let (done, failed) = if deleting {
(
gettext("Stopped syncing and moved the folder in Proton Drive to the trash"),
gettext("Couldn't stop syncing and delete the folder"),
)
} else {
(
gettext("Stopped syncing folder"),
gettext("Couldn't stop syncing the folder"),
)
};
run_devices_mutation(
&ui,
Request::RemoveSyncFolder {
id,
delete_remote: deleting,
},
&done,
&failed,
);
});
dialog.present(win.as_ref());
}
+51 -26
View File
@@ -521,9 +521,13 @@ impl Syncer {
/// 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.
/// local edit as a conflict copy (B249). A revision committed after the
/// upload is caught by the read-back.
///
/// When the pass knows the revision id, the check rides on the read of the
/// file the upload makes for its keys (`upload_new_revision_over`), and the
/// revision is created over that id, so Drive refuses one committed in
/// between. A baseline without an id still reads the node first.
pub(super) async fn upload_revision(
&self,
folder_id: i64,
@@ -536,22 +540,16 @@ impl Syncer {
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"
));
if seen.revision.is_none() {
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(moved_on_drive(rel)),
_ => return Err(gone_from_drive(rel)),
}
}
let meta = file.metadata().map_err(|e| format!("stat {rel}: {e}"))?;
@@ -569,13 +567,27 @@ impl Syncer {
meta.len(),
),
));
if let Err(e) = self
.drive
.upload_new_revision_from(uid, reader, meta.len() as i64, thumbnails, Some(mtime))
.await
{
self.note_sent(folder_id, rel, "upload-revision", &sent.digest());
return Err(format!("upload revision {rel}: {e}"));
let size = meta.len() as i64;
let uploaded = match seen.revision.as_deref() {
Some(expected) => self
.drive
.upload_new_revision_over(uid, expected, reader, size, thumbnails, Some(mtime))
.await
.map(Some),
None => self
.drive
.upload_new_revision_from(uid, reader, size, thumbnails, Some(mtime))
.await
.map(|()| None),
};
match uploaded {
Ok(None | Some(pdfs_drive::RevisionUpload::Sealed(_))) => {}
Ok(Some(pdfs_drive::RevisionUpload::Moved)) => return Err(moved_on_drive(rel)),
Ok(Some(pdfs_drive::RevisionUpload::Trashed)) => return Err(gone_from_drive(rel)),
Err(e) => {
self.note_sent(folder_id, rel, "upload-revision", &sent.digest());
return Err(format!("upload revision {rel}: {e}"));
}
}
warn_if_torn(rel, &path, streamed);
let remote = self
@@ -745,3 +757,16 @@ impl Syncer {
.map_err(|e| format!("baseline {rel}: {e:?}"))
}
}
/// Why a revision was not sent: Drive's file moved on since the pass looked.
fn moved_on_drive(rel: &str) -> String {
format!("{rel} changed on Drive since this pass looked; it is compared again on the next pass")
}
/// Why a revision was not sent: the file is no longer on Drive where the pass
/// saw it.
fn gone_from_drive(rel: &str) -> String {
format!(
"{rel} is no longer on Drive where this pass saw it; it is compared again on the next pass"
)
}
+19
View File
@@ -18,6 +18,14 @@ sends is recorded until its result is in (51), and an upload that heard no answe
digest of what it sent (52).
### Added
- **Small files go up to Proton Drive in one request.** A file whose encrypted size is under
128 KiB, and a new revision of one, is now sent in a single request instead of a draft, its
block and a commit. This covers synced folders and the drive mount. On a test account, a first
sync of 200 small files ran 58% faster, and 50 edits of them 97% faster. Larger files go up in
blocks as before. `proton-sdk` and `proton-drive-rs` are now 0.12.7.
- **`small_uploads` in `config.json` turns off the one-request upload for small files.** It is
on by default. Set it to `false` to send every file as a draft, its blocks and a commit, as
before. The service reads it at start. See [Configuration](CONFIGURATION.md#small_uploads).
- **`pdfs diagnostics` says which of the daemon's background services are running.** If one
ends while the drive is mounted, for example the sync engine after a crash, the journal says
so once, by name, instead of saying nothing until a restart. It also lists the jobs running
@@ -47,6 +55,11 @@ digest of what it sent (52).
any more.
### Changed
- **An upload into a folder and an edit of a synced file make fewer requests.** The key that
hashes a folder's file names is now read once per folder, not once per upload. A synced
folder no longer reads a file again before it sends an edit. It checks that nobody else
changed the file through the read the upload already makes, and it still sends nothing over
a revision it has not seen. `proton-sdk` and `proton-drive-rs` are now 0.12.8.
- **A sync pass over a quiet folder no longer reads the whole folder on disk.** While the
filesystem watcher has been running without a break, a pass reads again only the folders and
files it reported changed, and takes the rest from the pass before. The whole folder is still
@@ -73,6 +86,12 @@ digest of what it sent (52).
first pass, and whenever the change feed lost track (#53).
### Fixed
- **Stopping a sync with "Also delete from Proton Drive" says that it deletes, and says so when
the deletion failed.** With the switch on, the dialog now reads "Stop Syncing and Delete
Folder?" and its button "Stop Syncing and Delete". If the folder stopped syncing but its folder
in Proton Drive could not be moved to the trash, for example while offline, the app and
`pdfs sync rm --delete-remote` now report an error that says so. Before, they reported plain
success, and the copy in Proton Drive stayed without a word.
- **A mirrored file whose upload went unanswered no longer gets a conflict copy of its own
edit.** Proton Drive can make a file and lose the answer. If the file was then written again
before the next sync, for example while the daemon was stopped, that sync saw two different
+11
View File
@@ -88,6 +88,7 @@ fix it.
| `device_uid` | string | none | Computers → Continue This Backup Here… or Sync With This Computer… | The computer this machine syncs into. Unset means "match by hostname" |
| `conflict_sweep` | `off` / `report` / `enforce` | `report` | Sync → Conflict Copies | See [`conflict_sweep`](#conflict_sweep) |
| `local_first` | bool | `true` | — | See [`local_first`](#local_first) |
| `small_uploads` | bool | `true` | — | See [`small_uploads`](#small_uploads) |
| `language` | gettext code | system | General → Appearance | Language of the app, tray and prompt, such as `de` or `pt_BR` |
| `proton_theme` | bool | follow system | General → Appearance | Proton's colours instead of the system theme |
| `online_map` | bool | `false` | General → Appearance | Street map for Places from OpenFreeMap |
@@ -145,6 +146,16 @@ call returns at once. The change goes to Drive from the queue, the same way it d
Set it to `false` to have these calls wait for Drive again, as before 3.0.0. The switch is there
for one release, in case the queued path misbehaves for you; please report it if it does.
### `small_uploads`
A file that fits in 128 KiB with its thumbnails goes to Proton Drive in one request. A larger one
goes as a draft, its blocks, and a commit, which takes three requests or more. Most synced files
are small, so this is what decides how fast a folder of many small files syncs.
Set it to `false` to upload every file in blocks again. The setting is read when the service
starts. The journal says `small files are uploaded in blocks` while it is off. Please report it if
you need to turn it off.
### `open_with`
Decides how files picked in the search launcher or the app are opened. Rules are tried in order;
+26 -3
View File
@@ -307,9 +307,32 @@ instance's keyring entry so the next run does not sign in again; `--logout` forg
Proton asks for a CAPTCHA, sign in once by hand with `PDFS_INSTANCE=bench pdfs login`.
The script refuses a `pdfs` built without `PDFS_INSTANCE`, which would act on your own account.
A new folder's first sync uploads about one small file every four seconds, so with a 500-file
tree the edit is timed about 35 minutes in. A run that is cut short leaves its folder behind; the
next run removes it.
A new folder's first sync uploads about two small files a second (eight at a time), so with a
500-file tree the edit is timed a few minutes in. A run that is cut short leaves its folder behind;
the next run removes it.
### The small-file benchmark
`--scenario small` times many small files instead, the case that the API's one-request small
upload is for. For each tree size (200 by default) it makes files of `--small-size` random bytes
(4096 by default), plus `--images` noise PNGs that get thumbnails (10 by default). It then:
- times the first sync, until every file is uploaded and the folder is quiet
- rewrites `--edits` of the files at once (50 by default) and times until all are uploaded again
For each phase it reports wall time, files per second, the daemon's CPU time, and the requests
the daemon sent. The requests are API calls by method, plus storage uploads. It counts them from
the SDK's telemetry: the daemon runs with `RUST_LOG=info,pgp=error,proton_sdk::telemetry=debug`,
and its log goes to the work directory. If the SDK tags each request with its endpoint, the JSON
output also counts requests per endpoint.
```bash
scripts/live-bench.py --account-env path/to/.env --pdfs target/release/pdfs --scenario small \
--json small.json
```
Wall time varies by 2x between runs against the live service. Compare medians of three runs,
and treat the request counts as the stable measure.
## Before a release
+426 -403
View File
File diff suppressed because it is too large. Load diff
+426 -403
View File
File diff suppressed because it is too large. Load diff
+426 -403
View File
File diff suppressed because it is too large. Load diff
+426 -403
View File
File diff suppressed because it is too large. Load diff
+426 -403
View File
File diff suppressed because it is too large. Load diff
+426 -403
View File
File diff suppressed because it is too large. Load diff
+420 -403
View File
File diff suppressed because it is too large. Load diff
+426 -403
View File
File diff suppressed because it is too large. Load diff
+426 -403
View File
File diff suppressed because it is too large. Load diff
+290 -6
View File
@@ -2,7 +2,10 @@
"""Time one edit in a synced folder, from the write to the new revision on Drive.
Runs against a real account on a separate instance (`PDFS_INSTANCE`), so the
user's own daemon and session are never touched. For each tree size it:
user's own daemon and session are never touched. There are two scenarios,
picked with `--scenario`.
`edit` (the default) times one edit. For each tree size it:
1. makes a disposable folder in My files and a local tree of that many files,
2. attaches the local tree to it and waits for the first sync to finish,
@@ -12,6 +15,19 @@ user's own daemon and session are never touched. For each tree size it:
- verify: the pass end until `pdfs versions list` shows the new revision,
4. detaches the folder and trashes the remote copy.
`small` times many small files, the case Proton's one-request small upload is
for. For each tree size it:
1. makes a tree of files of `--small-size` random bytes, plus `--images` noise
PNGs that get thumbnails, and attaches it,
2. times the first sync until every file is uploaded and the folder is quiet,
3. rewrites `--edits` of the files at once and times until all of them are
uploaded again,
4. reports, for each phase, the wall time, files per second, the daemon's CPU
time and the requests it sent: API calls by method, and storage uploads.
The requests come from the SDK's telemetry, so the daemon runs with
`proton_sdk::telemetry=debug`.
The account comes from an env file with `username=`, `password=` and, for an
account with two-factor sign-in, `PROTON_TOTP_SECRET=`. It is read here and
typed into `pdfs login` over a pseudo-terminal; it is never printed or written
@@ -33,6 +49,8 @@ import hashlib
import hmac
import json
import os
import random
import re
import pty
import select
import shutil
@@ -43,6 +61,7 @@ import sys
import tempfile
import time
import uuid
import zlib
from pathlib import Path
POLL = 0.1
@@ -300,6 +319,259 @@ def bench_one(
shutil.rmtree(local, ignore_errors=True)
ANSI = re.compile(r"\x1b\[[0-9;]*m")
OPERATION = re.compile(r"operation=\W*(\w+)")
METHOD = re.compile(r"method=(\w+)")
ENDPOINT = re.compile(r"endpoint=(\S+)")
SDK_LOG = "info,pgp=error,proton_sdk::telemetry=debug"
# Slower than `POLL`: each poll is a diagnostics request to the daemon, and the
# small-file scenario measures the daemon's CPU time.
SMALL_POLL = 0.5
class Requests:
"""Counts the requests the daemon logs through the SDK's telemetry, from a
byte offset of its log on."""
def __init__(self, log: Path) -> None:
self.log = log
self.offset = log.stat().st_size
def take(self) -> dict[str, int]:
with self.log.open("rb") as file:
file.seek(self.offset)
chunk = file.read()
self.offset = file.tell()
counts: dict[str, int] = {}
for line in ANSI.sub("", chunk.decode(errors="replace")).splitlines():
if "proton_sdk::telemetry" not in line:
continue
found = OPERATION.search(line)
if not found:
continue
operation = found.group(1)
if operation == "http_request":
method = METHOD.search(line)
key = f"api {method.group(1) if method else '?'}"
# SDKs that tag the endpoint also get a count per endpoint.
route = ENDPOINT.search(line)
if route:
detail = f"endpoint {method.group(1) if method else '?'} {route.group(1)}"
counts[detail] = counts.get(detail, 0) + 1
elif operation.startswith("storage_"):
key = operation.replace("_", " ")
else:
key = f"op {operation}"
counts[key] = counts.get(key, 0) + 1
return counts
def cpu_seconds(pid: int) -> float:
"""User and system CPU time of `pid` so far."""
fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()
return (int(fields[11]) + int(fields[12])) / os.sysconf("SC_CLK_TCK")
def noise_png(path: Path, side: int, rng: random.Random) -> None:
"""A PNG of random pixels: it does not compress, so its size is known, and
the daemon makes thumbnails for it."""
def chunk(kind: bytes, data: bytes) -> bytes:
body = kind + data
return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body))
rows = b"".join(b"\x00" + rng.randbytes(side * 3) for _ in range(side))
path.write_bytes(
b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", struct.pack(">IIBBBBB", side, side, 8, 2, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(rows, 1))
+ chunk(b"IEND", b"")
)
def make_small_tree(
root: Path, files: int, size: int, images: int, rng: random.Random, per_dir: int = 50
) -> list[Path]:
paths = []
for index in range(files):
directory = root / f"d{index // per_dir:04d}"
directory.mkdir(parents=True, exist_ok=True)
path = directory / f"f{index:06d}.bin"
path.write_bytes(rng.randbytes(size))
paths.append(path)
if images:
(root / "pictures").mkdir()
for index in range(images):
noise_png(root / "pictures" / f"p{index:04d}.png", 120, rng)
return paths
class Passes:
"""The passes over one folder that ended, as the diagnostics show them.
They keep only the last one, so poll often enough to see each."""
def __init__(self, pdfs: Pdfs, folder_id: int, stale: set[str]) -> None:
self.pdfs = pdfs
self.folder_id = folder_id
self.stale = stale
self.last: str | None = None
self.ended: list[dict] = []
def poll(self) -> dict:
state = sync_state(self.pdfs)
trace = trace_for(state, self.folder_id)
if trace and trace.get("ended") and state.get("pass_folder") != self.folder_id:
key = json.dumps(trace, sort_keys=True)
if key != self.last and key not in self.stale:
self.last = key
self.ended.append(trace)
return state
def calls(self, name: str, since: int = 0) -> int:
return sum(
call["count"]
for trace in self.ended[since:]
for call in trace.get("calls", [])
if call["name"] == name
)
def totals(self, since: int = 0) -> dict[str, dict[str, int]]:
totals: dict[str, dict[str, int]] = {}
for trace in self.ended[since:]:
for kind in ("phases", "calls"):
for stat in trace.get(kind, []):
entry = totals.setdefault(f"{kind[:-1]} {stat['name']}", {"count": 0, "ms": 0})
entry["count"] += stat["count"]
entry["ms"] += stat["total_ms"]
return totals
def wait_for(
self, what: str, name: str, at_least: int, since: int, quiet: float, timeout: float
) -> float:
"""Wait until the passes since `since` made `at_least` calls of `name`,
then until no pass ran for `quiet` seconds. Returns when the last pass
that did work was seen to end."""
deadline = time.monotonic() + timeout
while self.calls(name, since) < at_least:
if time.monotonic() > deadline:
raise TimeoutError(
f"timed out waiting for {what}: {self.calls(name, since)} of {at_least}"
)
self.poll()
time.sleep(SMALL_POLL)
done = time.monotonic()
seen = len(self.ended)
while time.monotonic() - done < quiet:
if time.monotonic() > deadline:
raise TimeoutError(f"the folder did not go quiet after {what}")
state = self.poll()
if state.get("pass_folder") == self.folder_id or len(self.ended) != seen:
seen = len(self.ended)
done = time.monotonic()
time.sleep(SMALL_POLL)
return done
def phase_result(
files: int, wall: float, cpu: float, requests: dict[str, int], passes: Passes, since: int
) -> dict:
sent = sum(n for key, n in requests.items() if key.startswith(("api ", "storage upload")))
return {
"files": files,
"wall_s": round(wall, 2),
"files_per_s": round(files / wall, 3) if wall else None,
"cpu_s": round(cpu, 2),
"cpu_ms_per_file": round(cpu * 1000 / files) if files else None,
"requests": requests,
"requests_per_file": round(sent / files, 2) if files else None,
"passes": len(passes.ended) - since,
"totals": passes.totals(since),
}
def bench_small(
pdfs: Pdfs, daemon_pid: int, mount: Path, work: Path, files: int, args: argparse.Namespace
) -> dict:
rng = random.Random(files)
name = f"pdfs-bench-small-{files}-{uuid.uuid4().hex[:8]}"
local = work / name
local.mkdir()
paths = make_small_tree(local, files, args.small_size, args.images, rng)
uploads = files + args.images
pdfs.run("mkdir", str(mount), name)
folder_id = None
try:
stale = {json.dumps(t, sort_keys=True) for t in sync_state(pdfs).get("traces", [])}
requests = Requests(work / "daemon.log")
cpu = cpu_seconds(daemon_pid)
started = time.monotonic()
pdfs.run("sync", "attach", "--to", name, str(local))
folder = next(
item
for item in pdfs.json("sync", "list")["items"]
if Path(item["local_path"]).resolve() == local.resolve()
)
folder_id = folder["id"]
passes = Passes(pdfs, folder_id, stale)
done = passes.wait_for("the first sync", "upload", uploads, 0, args.quiet, args.timeout)
first = phase_result(
uploads, done - started, cpu_seconds(daemon_pid) - cpu, requests.take(), passes, 0
)
edits = min(args.edits, files)
edited = rng.sample(paths, edits)
since = len(passes.ended)
cpu = cpu_seconds(daemon_pid)
started = time.monotonic()
for path in edited:
path.write_bytes(rng.randbytes(args.small_size))
done = passes.wait_for(
"the edits", "upload revision", edits, since, args.quiet, args.timeout
)
edit = phase_result(
edits, done - started, cpu_seconds(daemon_pid) - cpu, requests.take(), passes, since
)
# The counts say the edits were sent; a few read back say they landed.
for path in edited[:3]:
remote_path = f"{name}/{path.relative_to(local)}"
wait("the edit on Drive", lambda p=remote_path: revisions(pdfs, p) >= 2, args.timeout)
return {
"scenario": "small",
"files": files,
"images": args.images,
"size": args.small_size,
"first_sync": first,
"edits": edit,
}
finally:
if folder_id is not None:
for _ in range(20):
try:
pdfs.run("sync", "rm", str(folder_id))
break
except Exception as error: # noqa: BLE001
print(f" sync rm: {error}; retrying", file=sys.stderr)
time.sleep(6)
with contextlib.suppress(Exception):
pdfs.run("rm", f"{mount}/{name}")
shutil.rmtree(local, ignore_errors=True)
def print_small(result: dict) -> None:
print(f"{result['files']:>6} files of {result['size']} B and {result['images']} images:")
for phase in ("first_sync", "edits"):
r = result[phase]
sent = ", ".join(
f"{k} {v}" for k, v in sorted(r["requests"].items()) if not k.startswith(("op ", "endpoint "))
)
print(
f" {phase}: {r['files']} files in {r['wall_s']} s ({r['files_per_s']}/s), "
f"CPU {r['cpu_s']} s ({r['cpu_ms_per_file']} ms/file), "
f"{r['requests_per_file']} requests/file over {r['passes']} passes"
)
print(f" requests: {sent}")
def refuse_without_instances(binary: str) -> None:
"""Stop unless `binary` honours PDFS_INSTANCE. One built before it existed
ignores the variable and would sign in, attach and delete on the default
@@ -348,7 +620,11 @@ def main() -> int:
parser.add_argument("--account-env", type=Path, required=True, help="env file with the test account")
parser.add_argument("--pdfs", default="pdfs", help="the pdfs CLI to run")
parser.add_argument("--instance", default="bench", help="PDFS_INSTANCE to run under")
parser.add_argument("--sizes", default="20,500", help="tree sizes, comma-separated")
parser.add_argument("--scenario", choices=("edit", "small"), default="edit", help="what to time")
parser.add_argument("--sizes", help="tree sizes, comma-separated (default 20,500; 200 for small)")
parser.add_argument("--small-size", type=int, default=4096, help="bytes per file (small)")
parser.add_argument("--images", type=int, default=10, help="noise PNGs with thumbnails (small)")
parser.add_argument("--edits", type=int, default=50, help="files rewritten at once (small)")
parser.add_argument("--timeout", type=float, default=3600, help="seconds per wait")
parser.add_argument(
"--quiet", type=float, default=15, help="seconds without a pass before the edit"
@@ -368,8 +644,11 @@ def main() -> int:
work = args.work or Path(tempfile.mkdtemp(prefix="pdfs-bench-"))
work.mkdir(parents=True, exist_ok=True)
log = (work / "daemon.log").open("w")
daemon_env = dict(pdfs.env)
if args.scenario == "small":
daemon_env["RUST_LOG"] = SDK_LOG
daemon = subprocess.Popen(
[args.pdfs, "daemon"], env=pdfs.env, stdin=subprocess.DEVNULL, stdout=log, stderr=log
[args.pdfs, "daemon"], env=daemon_env, stdin=subprocess.DEVNULL, stdout=log, stderr=log
)
results = []
try:
@@ -380,9 +659,14 @@ def main() -> int:
)
mount = Path(status["mount"].get("mountpoint") or Path.home() / f"ProtonDrive-{args.instance}")
remove_leftovers(pdfs, mount)
for size in (int(s) for s in args.sizes.split(",")):
result = bench_one(pdfs, mount, work, size, args.timeout, args.quiet)
print_result(result)
sizes = args.sizes or ("200" if args.scenario == "small" else "20,500")
for size in (int(s) for s in sizes.split(",")):
if args.scenario == "small":
result = bench_small(pdfs, daemon.pid, mount, work, size, args)
print_small(result)
else:
result = bench_one(pdfs, mount, work, size, args.timeout, args.quiet)
print_result(result)
results.append(result)
if args.json:
args.json.write_text(json.dumps(results, indent=2))