mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-28 04:02:13 +01:00
Compare commits
15
Commits
fix/rewatch-pass
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f975d9cf17 | ||
|
|
deb15a3327 | ||
|
|
8c7a0a8a17 | ||
|
|
9533ebcdfc | ||
|
|
ccc679eef5 | ||
|
|
20603205d9 | ||
|
|
d1421a84b1 | ||
|
|
670ec7db31 | ||
|
|
30b20fc444 | ||
|
|
5c6360e6e7 | ||
|
|
42926b71a9 | ||
|
|
21e7c03460 | ||
|
|
9b541899ef | ||
|
|
8a5f3f9ae0 | ||
|
|
d0697b7fcc |
No files matched your search
@@ -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 \
|
||||
|
||||
@@ -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
@@ -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
@@ -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"
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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| {
|
||||
|
||||
@@ -2115,6 +2115,60 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// An effect a daemon sent and never heard back from is `unsure` at the
|
||||
/// next start. One the folder still needs is sent again, and settles; one
|
||||
/// it no longer needs is settled by the first pass that looks (`effect`).
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn an_effect_left_unsure_by_a_stop_is_sent_again_or_settled() {
|
||||
take_logged();
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("unsure-effect");
|
||||
let (daemon, folder, client) = start_mirror(&drive, &dir, &[("a.txt", b"one")]);
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
// What a daemon killed while it sent two uploads leaves: one landed
|
||||
// (a.txt is on Drive), the other never went out.
|
||||
let sent = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs() as i64
|
||||
- 10;
|
||||
let db = reopen(&dir);
|
||||
db.sync_intent_issue(folder, "a.txt", "upload", sent)
|
||||
.unwrap();
|
||||
db.sync_intent_issue(folder, "new.txt", "upload", sent)
|
||||
.unwrap();
|
||||
drop(db);
|
||||
std::fs::write(dir.join("local").join("new.txt"), b"new").unwrap();
|
||||
take_logged();
|
||||
let daemon = Daemon::start(&dir, client).unwrap();
|
||||
assert!(wait_until(Duration::from_secs(60), || drive
|
||||
.lookup("mirrored/new.txt")
|
||||
.is_some()));
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
let logged = take_logged();
|
||||
let has = |text: &str| logged.iter().any(|line| line.contains(text));
|
||||
assert!(
|
||||
has("effects=2") && has("did not hear back from"),
|
||||
"{logged:#?}"
|
||||
);
|
||||
assert!(
|
||||
has("sending again an effect a stopped daemon may have made"),
|
||||
"{logged:#?}"
|
||||
);
|
||||
assert!(
|
||||
has("an effect a stopped daemon may have made is no longer needed"),
|
||||
"{logged:#?}"
|
||||
);
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
assert!(
|
||||
reopen(&dir).sync_intents(Some(folder)).unwrap().is_empty(),
|
||||
"every intent settled"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A restart owes the disk a walk in full, since nothing watched it
|
||||
/// meanwhile, and owes Drive nothing: its event stream resumes from the
|
||||
/// cursor (`root`).
|
||||
@@ -2436,6 +2490,70 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_mirror_create_whose_reply_was_lost_is_adopted_after_a_restart_and_its_edit_lands() {
|
||||
// Drive made the file, but the answer never came back, and the daemon
|
||||
// stopped before it tried again. While it was stopped the file was
|
||||
// written again. A one-request small upload makes this the common way
|
||||
// a create goes unanswered: it leaves a whole file, never a draft. The
|
||||
// start must find that file, take it as this one, and put the newer
|
||||
// bytes on it: one file, no conflict copy.
|
||||
take_logged();
|
||||
let drive = FakeDrive::new();
|
||||
let dir = scratch("mirror-lost-create-restart");
|
||||
let (daemon, folder, client) = start_mirror(&drive, &dir, &[("a.txt", b"one")]);
|
||||
let local = dir.join("local");
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
|
||||
client.lose_reply_to_next_create();
|
||||
std::fs::write(local.join("new.txt"), b"first").unwrap();
|
||||
assert!(wait_until(Duration::from_secs(30), || {
|
||||
on_drive(&drive, "mirrored/new.txt").is_some_and(|bytes| bytes == b"first")
|
||||
}));
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
|
||||
std::fs::write(local.join("new.txt"), b"second, written while stopped").unwrap();
|
||||
let daemon = Daemon::start(&dir, client).unwrap();
|
||||
let landed = wait_until(Duration::from_secs(60), || {
|
||||
on_drive(&drive, "mirrored/new.txt")
|
||||
.is_some_and(|bytes| bytes == b"second, written while stopped")
|
||||
});
|
||||
let logged = take_logged();
|
||||
assert!(
|
||||
landed,
|
||||
"{:#?}\n{:#?}",
|
||||
drive.tree(),
|
||||
logged
|
||||
.iter()
|
||||
.filter(|l| l.contains("sync") || l.contains("new"))
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
|
||||
|
||||
assert!(conflict_copies(&local, "new").is_empty());
|
||||
let tree = drive.tree();
|
||||
assert!(
|
||||
!tree.keys().any(|k| k.contains("sync-conflict")),
|
||||
"{tree:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
tree.keys().filter(|k| k.contains("new")).count(),
|
||||
1,
|
||||
"{tree:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(local.join("new.txt")).unwrap(),
|
||||
b"second, written while stopped"
|
||||
);
|
||||
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
|
||||
assert!(
|
||||
reopen(&dir).sync_intents(Some(folder)).unwrap().is_empty(),
|
||||
"every intent settled"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
|
||||
fn a_revision_made_during_a_mirror_download_still_arrives() {
|
||||
|
||||
@@ -11,7 +11,7 @@ use super::Db;
|
||||
use pdfs_core::Result;
|
||||
|
||||
/// Current schema version. Bump on every forward migration added below.
|
||||
pub(super) const SCHEMA_VERSION: i64 = 50;
|
||||
pub(super) const SCHEMA_VERSION: i64 = 52;
|
||||
|
||||
impl Db {
|
||||
pub(super) fn migrate(&self) -> Result<()> {
|
||||
@@ -553,6 +553,31 @@ impl Db {
|
||||
tx.execute_batch(MIGRATION_V50)?;
|
||||
}
|
||||
}
|
||||
if current < 51 {
|
||||
let has_folders: bool = tx.query_row(
|
||||
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'sync_folder'",
|
||||
[],
|
||||
|row| row.get::<_, i64>(0).map(|n| n > 0),
|
||||
)?;
|
||||
if has_folders {
|
||||
tx.execute_batch(MIGRATION_V51)?;
|
||||
}
|
||||
}
|
||||
if current < 52 {
|
||||
let has_intents: bool = tx.query_row(
|
||||
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'sync_intent'",
|
||||
[],
|
||||
|row| row.get::<_, i64>(0).map(|n| n > 0),
|
||||
)?;
|
||||
let has_column: bool = tx.query_row(
|
||||
"SELECT COUNT(*) FROM pragma_table_info('sync_intent') WHERE name = 'sent_sha1s'",
|
||||
[],
|
||||
|row| row.get::<_, i64>(0).map(|n| n > 0),
|
||||
)?;
|
||||
if has_intents && !has_column {
|
||||
tx.execute_batch(MIGRATION_V52)?;
|
||||
}
|
||||
}
|
||||
tx.execute(
|
||||
"INSERT INTO sync_state (key, value) VALUES ('schema_version', ?1)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||||
@@ -1585,6 +1610,45 @@ BEGIN
|
||||
END;
|
||||
";
|
||||
|
||||
/// Schema v51: an intent for each effect a mirror pass sends, written before
|
||||
/// it is sent and removed once its result is in (`docs/SYNC_ENGINE.md`).
|
||||
///
|
||||
/// One row a folder, path and kind of effect. A row left `issued` was sent by
|
||||
/// a daemon that stopped before it heard back: the effect may or may not have
|
||||
/// happened. A change to what the folder is, or its removal, drops its rows.
|
||||
const MIGRATION_V51: &str = "
|
||||
CREATE TABLE IF NOT EXISTS sync_intent (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
folder_id INTEGER NOT NULL,
|
||||
rel_path TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
state TEXT NOT NULL,
|
||||
attempts INTEGER NOT NULL,
|
||||
issued_at INTEGER NOT NULL,
|
||||
last_error TEXT,
|
||||
UNIQUE (folder_id, rel_path, kind)
|
||||
);
|
||||
DROP TRIGGER IF EXISTS sync_intent_drop_on_folder_update;
|
||||
DROP TRIGGER IF EXISTS sync_intent_drop_on_folder_delete;
|
||||
CREATE TRIGGER sync_intent_drop_on_folder_update
|
||||
AFTER UPDATE OF local_path, remote_uid, mode ON sync_folder
|
||||
BEGIN
|
||||
DELETE FROM sync_intent WHERE folder_id = OLD.id;
|
||||
END;
|
||||
CREATE TRIGGER sync_intent_drop_on_folder_delete
|
||||
AFTER DELETE ON sync_folder
|
||||
BEGIN
|
||||
DELETE FROM sync_intent WHERE folder_id = OLD.id;
|
||||
END;
|
||||
";
|
||||
|
||||
/// v52: the SHA-1s of the bytes each unsettled mirror upload sent, space
|
||||
/// separated. A reply that never came may hide an upload that landed, and its
|
||||
/// digest is how a later pass knows the file on Drive for its own.
|
||||
const MIGRATION_V52: &str = "
|
||||
ALTER TABLE sync_intent ADD COLUMN sent_sha1s TEXT;
|
||||
";
|
||||
|
||||
/// See [`MIGRATION_V49_COLUMNS`].
|
||||
const MIGRATION_V49: &str = "
|
||||
CREATE TABLE IF NOT EXISTS sync_remote_dirty (
|
||||
|
||||
@@ -66,7 +66,8 @@ pub use photos::{StoredPhoto, StoredPlace, THUMB_HAVE, THUMB_NONE, THUMB_UNKNOWN
|
||||
pub use pins::PinRow;
|
||||
pub use replace::ReplaceIntent;
|
||||
pub use sync::{
|
||||
DeleteWindow, SavedWalk, SavedWalkDir, SavedWalkItem, StoredSyncEntry, StoredSyncFolder,
|
||||
DeleteWindow, SavedWalk, SavedWalkDir, SavedWalkItem, StoredIntent, StoredSyncEntry,
|
||||
StoredSyncFolder,
|
||||
};
|
||||
pub use trash::StoredTrash;
|
||||
|
||||
|
||||
@@ -19,6 +19,26 @@ pub struct DeleteWindow {
|
||||
pub deleted: u64,
|
||||
}
|
||||
|
||||
/// An effect a mirror pass sent, or is about to send, and has not settled.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StoredIntent {
|
||||
pub id: i64,
|
||||
pub folder_id: i64,
|
||||
pub rel_path: String,
|
||||
/// What the effect does, such as `upload` or `download`.
|
||||
pub kind: String,
|
||||
/// Where it stands, as the effect reducer names it.
|
||||
pub state: String,
|
||||
/// How many times it was sent, this time included.
|
||||
pub attempts: u32,
|
||||
/// When it was last sent, in seconds since the epoch.
|
||||
pub issued_at: i64,
|
||||
pub last_error: Option<String>,
|
||||
/// For an upload: the SHA-1s of the bytes its attempts streamed without
|
||||
/// hearing a success back, lowercase. One of them may have landed.
|
||||
pub sent_sha1s: Vec<String>,
|
||||
}
|
||||
|
||||
/// What a mirror pass has walked of Drive, saved so a pass cut short
|
||||
/// resumes the walk instead of listing every folder again (B294), and so a
|
||||
/// finished walk serves as the next pass's picture of Drive.
|
||||
@@ -828,6 +848,139 @@ impl Db {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record that an effect is about to be sent: a new intent in state
|
||||
/// `issued`, or the one already there for the same folder, path and kind,
|
||||
/// sent once more. Returns the intent as it is now, and the state it was
|
||||
/// in before, if there was one.
|
||||
pub fn sync_intent_issue(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rel_path: &str,
|
||||
kind: &str,
|
||||
now: i64,
|
||||
) -> Result<(StoredIntent, Option<String>)> {
|
||||
let mut conn = self.conn.lock();
|
||||
let tx = conn.transaction()?;
|
||||
let before: Option<String> = tx
|
||||
.query_row(
|
||||
"SELECT state FROM sync_intent WHERE folder_id = ?1 AND rel_path = ?2 AND kind = ?3",
|
||||
params![folder_id, rel_path, kind],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
tx.execute(
|
||||
"INSERT INTO sync_intent (folder_id, rel_path, kind, state, attempts, issued_at)
|
||||
VALUES (?1, ?2, ?3, 'issued', 1, ?4)
|
||||
ON CONFLICT(folder_id, rel_path, kind) DO UPDATE SET state = 'issued',
|
||||
attempts = attempts + 1, issued_at = excluded.issued_at",
|
||||
params![folder_id, rel_path, kind, now],
|
||||
)?;
|
||||
let intent = tx.query_row(
|
||||
&format!(
|
||||
"SELECT {INTENT_COLUMNS} FROM sync_intent
|
||||
WHERE folder_id = ?1 AND rel_path = ?2 AND kind = ?3"
|
||||
),
|
||||
params![folder_id, rel_path, kind],
|
||||
intent_row,
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok((intent, before))
|
||||
}
|
||||
|
||||
/// Settle an intent whose effect is done: the row goes.
|
||||
pub fn sync_intent_settle(&self, id: i64) -> Result<()> {
|
||||
let conn = self.conn.lock();
|
||||
conn.execute("DELETE FROM sync_intent WHERE id = ?1", params![id])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Move an intent to `state`, with the error that put it there.
|
||||
pub fn sync_intent_set(&self, id: i64, state: &str, error: Option<&str>) -> Result<()> {
|
||||
let conn = self.conn.lock();
|
||||
conn.execute(
|
||||
"UPDATE sync_intent SET state = ?2, last_error = ?3 WHERE id = ?1",
|
||||
params![id, state, error],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Note that the upload `kind` of `rel_path` streamed bytes with SHA-1
|
||||
/// `sha1` and heard no success back. Nothing happens without an intent for
|
||||
/// it. A digest already noted is not added again.
|
||||
pub fn sync_intent_sent(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rel_path: &str,
|
||||
kind: &str,
|
||||
sha1: &str,
|
||||
) -> Result<()> {
|
||||
let sha1 = sha1.to_ascii_lowercase();
|
||||
let conn = self.conn.lock();
|
||||
conn.execute(
|
||||
"UPDATE sync_intent SET sent_sha1s = CASE
|
||||
WHEN sent_sha1s IS NULL OR sent_sha1s = '' THEN ?4
|
||||
WHEN instr(' ' || sent_sha1s || ' ', ' ' || ?4 || ' ') > 0 THEN sent_sha1s
|
||||
ELSE sent_sha1s || ' ' || ?4 END
|
||||
WHERE folder_id = ?1 AND rel_path = ?2 AND kind = ?3",
|
||||
params![folder_id, rel_path, kind, sha1],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every intent not settled, oldest first; only `folder_id`'s when given.
|
||||
pub fn sync_intents(&self, folder_id: Option<i64>) -> Result<Vec<StoredIntent>> {
|
||||
let conn = self.read()?;
|
||||
let mut stmt = conn.prepare(&format!(
|
||||
"SELECT {INTENT_COLUMNS} FROM sync_intent
|
||||
WHERE ?1 IS NULL OR folder_id = ?1 ORDER BY id"
|
||||
))?;
|
||||
let rows = stmt
|
||||
.query_map(params![folder_id], intent_row)?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// Move every intent in state `from` to `to`, across all folders.
|
||||
/// Returns how many moved.
|
||||
pub fn sync_intents_move(&self, from: &str, to: &str) -> Result<usize> {
|
||||
let conn = self.conn.lock();
|
||||
Ok(conn.execute(
|
||||
"UPDATE sync_intent SET state = ?2 WHERE state = ?1",
|
||||
params![from, to],
|
||||
)?)
|
||||
}
|
||||
|
||||
/// Settle the intents of `folder_id` in one of `states` that were last
|
||||
/// sent before `before`: a pass that started after them looked at their
|
||||
/// paths and did not send them again. Returns the intents settled.
|
||||
pub fn sync_intents_settle_before(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
states: &[&str],
|
||||
before: i64,
|
||||
) -> Result<Vec<StoredIntent>> {
|
||||
let mut conn = self.conn.lock();
|
||||
let tx = conn.transaction()?;
|
||||
let mut settled = Vec::new();
|
||||
{
|
||||
let mut stmt = tx.prepare(&format!(
|
||||
"SELECT {INTENT_COLUMNS} FROM sync_intent
|
||||
WHERE folder_id = ?1 AND issued_at < ?2 ORDER BY id"
|
||||
))?;
|
||||
for row in stmt.query_map(params![folder_id, before], intent_row)? {
|
||||
let row = row?;
|
||||
if states.contains(&row.state.as_str()) {
|
||||
settled.push(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
for intent in &settled {
|
||||
tx.execute("DELETE FROM sync_intent WHERE id = ?1", params![intent.id])?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(settled)
|
||||
}
|
||||
|
||||
/// Drop the entire baseline for a folder. Used when flipping ondemand→mirror:
|
||||
/// the local tree was evicted, so the old baseline is stale and would make the
|
||||
/// next reconcile mistake "locally deleted" for "must re-download". Clearing it
|
||||
@@ -842,6 +995,26 @@ impl Db {
|
||||
}
|
||||
}
|
||||
|
||||
const INTENT_COLUMNS: &str =
|
||||
"id, folder_id, rel_path, kind, state, attempts, issued_at, last_error, sent_sha1s";
|
||||
|
||||
fn intent_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoredIntent> {
|
||||
Ok(StoredIntent {
|
||||
id: row.get(0)?,
|
||||
folder_id: row.get(1)?,
|
||||
rel_path: row.get(2)?,
|
||||
kind: row.get(3)?,
|
||||
state: row.get(4)?,
|
||||
attempts: u32::try_from(row.get::<_, i64>(5)?).unwrap_or(u32::MAX),
|
||||
issued_at: row.get(6)?,
|
||||
last_error: row.get(7)?,
|
||||
sent_sha1s: row
|
||||
.get::<_, Option<String>>(8)?
|
||||
.map(|s| s.split_whitespace().map(str::to_owned).collect())
|
||||
.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn clear_walk(tx: &rusqlite::Transaction<'_>, folder_id: i64) -> Result<()> {
|
||||
for table in [
|
||||
"sync_walk",
|
||||
|
||||
@@ -8452,3 +8452,78 @@ fn a_deletion_window_is_kept_per_folder_until_the_folder_changes() {
|
||||
db.sync_folder_remove(other).unwrap();
|
||||
assert_eq!(db.sync_delete_window(other).unwrap(), None);
|
||||
}
|
||||
|
||||
/// An intent is one row per folder, path and kind: sent again, it counts the
|
||||
/// attempt and says what state it was left in. It goes once settled, and with
|
||||
/// the folder.
|
||||
#[test]
|
||||
fn an_upload_notes_each_digest_it_sent_once() {
|
||||
let db = Db::open_in_memory().unwrap();
|
||||
let id = db.sync_folder_add("/home/me/Docs", "v~root", "s").unwrap();
|
||||
// Nothing to note without an intent.
|
||||
db.sync_intent_sent(id, "a.txt", "upload", "AA").unwrap();
|
||||
assert!(db.sync_intents(Some(id)).unwrap().is_empty());
|
||||
|
||||
db.sync_intent_issue(id, "a.txt", "upload", 10).unwrap();
|
||||
db.sync_intent_sent(id, "a.txt", "upload", "AA").unwrap();
|
||||
db.sync_intent_sent(id, "a.txt", "upload", "aa").unwrap();
|
||||
// Sent again with other bytes: both may have landed.
|
||||
db.sync_intent_issue(id, "a.txt", "upload", 20).unwrap();
|
||||
db.sync_intent_sent(id, "a.txt", "upload", "bb").unwrap();
|
||||
// Another kind of the same path keeps its own.
|
||||
db.sync_intent_issue(id, "a.txt", "upload-revision", 21)
|
||||
.unwrap();
|
||||
let intents = db.sync_intents(Some(id)).unwrap();
|
||||
let upload = intents.iter().find(|i| i.kind == "upload").unwrap();
|
||||
assert_eq!(upload.sent_sha1s, ["aa", "bb"]);
|
||||
let revision = intents
|
||||
.iter()
|
||||
.find(|i| i.kind == "upload-revision")
|
||||
.unwrap();
|
||||
assert!(revision.sent_sha1s.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_effect_intent_is_kept_until_it_is_settled_or_its_folder_changes() {
|
||||
let db = Db::open_in_memory().unwrap();
|
||||
let id = db.sync_folder_add("/home/me/Docs", "v~root", "s").unwrap();
|
||||
let other = db
|
||||
.sync_folder_add("/home/me/Other", "v~other", "s")
|
||||
.unwrap();
|
||||
let (first, before) = db.sync_intent_issue(id, "a.txt", "upload", 10).unwrap();
|
||||
assert_eq!(before, None);
|
||||
assert_eq!((first.state.as_str(), first.attempts), ("issued", 1));
|
||||
db.sync_intent_set(first.id, "retry", Some("timed out"))
|
||||
.unwrap();
|
||||
let (again, before) = db.sync_intent_issue(id, "a.txt", "upload", 20).unwrap();
|
||||
assert_eq!(before.as_deref(), Some("retry"));
|
||||
assert_eq!(again.id, first.id, "the same intent");
|
||||
assert_eq!((again.attempts, again.issued_at), (2, 20));
|
||||
assert_eq!(again.last_error.as_deref(), Some("timed out"));
|
||||
let (download, _) = db.sync_intent_issue(id, "a.txt", "download", 21).unwrap();
|
||||
db.sync_intent_issue(other, "b.txt", "upload", 5).unwrap();
|
||||
assert_eq!(db.sync_intents(Some(id)).unwrap().len(), 2);
|
||||
assert_eq!(db.sync_intents(None).unwrap().len(), 3);
|
||||
|
||||
db.sync_intent_settle(download.id).unwrap();
|
||||
assert_eq!(db.sync_intents(Some(id)).unwrap().len(), 1);
|
||||
|
||||
// A start finds what a stopped daemon left sent.
|
||||
assert_eq!(db.sync_intents_move("issued", "unsure").unwrap(), 2);
|
||||
assert_eq!(db.sync_intents_move("issued", "unsure").unwrap(), 0);
|
||||
// A pass that began after an intent was sent settles it.
|
||||
let settled = db
|
||||
.sync_intents_settle_before(other, &["unsure"], 6)
|
||||
.unwrap();
|
||||
assert_eq!(settled.len(), 1);
|
||||
assert!(db.sync_intents(Some(other)).unwrap().is_empty());
|
||||
assert!(
|
||||
db.sync_intents_settle_before(id, &["unsure"], 20)
|
||||
.unwrap()
|
||||
.is_empty(),
|
||||
"sent at 20, not before"
|
||||
);
|
||||
|
||||
db.sync_folder_set_mode(id, "ondemand").unwrap();
|
||||
assert!(db.sync_intents(Some(id)).unwrap().is_empty());
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
//! The effect reducer: where one effect a mirror pass sends stands, from the
|
||||
//! moment it is about to be sent until its result is in
|
||||
//! (`docs/SYNC_ENGINE.md`).
|
||||
//!
|
||||
//! An effect is an upload, a download, a folder made on Drive, and the other
|
||||
//! [`Pending`](crate::model::Pending) ops. Before one is sent, an intent for it
|
||||
//! is written to the database (`sync_intent`); when its result is in, the
|
||||
//! intent is settled or kept with the failure. An intent still `issued` when
|
||||
//! the daemon starts was sent by a daemon that stopped before it heard back,
|
||||
//! so the effect may or may not have happened: it is `unsure`.
|
||||
//!
|
||||
//! [`step`] is pure, as the root reducer is: the I/O results, the restart and
|
||||
//! the pass that looks again are inputs.
|
||||
//!
|
||||
//! For now the intents are kept in shadow: they record and log what happens,
|
||||
//! and nothing reads them to decide what to send. The apply step's own checks
|
||||
//! (a create that may have landed is looked up before it is sent again, B266;
|
||||
//! a download checks the disk before it replaces a file, B39) still do that.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// Failures in a row after which an effect is reported as blocked.
|
||||
pub const BLOCKED_AFTER: u32 = 5;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum EffectState {
|
||||
/// Sent, or about to be; no result yet.
|
||||
Issued,
|
||||
/// Found issued at a start: the daemon stopped before the result came,
|
||||
/// so the effect may or may not have happened.
|
||||
Unsure,
|
||||
/// It failed, and a later pass may send it again.
|
||||
Retry,
|
||||
/// It failed [`BLOCKED_AFTER`] times in a row.
|
||||
Blocked,
|
||||
/// Its result is in. The intent goes.
|
||||
Settled,
|
||||
}
|
||||
|
||||
impl EffectState {
|
||||
/// The name the database keeps.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
EffectState::Issued => "issued",
|
||||
EffectState::Unsure => "unsure",
|
||||
EffectState::Retry => "retry",
|
||||
EffectState::Blocked => "blocked",
|
||||
EffectState::Settled => "settled",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_name(name: &str) -> Option<EffectState> {
|
||||
Some(match name {
|
||||
"issued" => EffectState::Issued,
|
||||
"unsure" => EffectState::Unsure,
|
||||
"retry" => EffectState::Retry,
|
||||
"blocked" => EffectState::Blocked,
|
||||
"settled" => EffectState::Settled,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for EffectState {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(self.name())
|
||||
}
|
||||
}
|
||||
|
||||
/// Something that happened to an effect.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum EffectInput {
|
||||
/// It is sent (again); `attempts` counts this one.
|
||||
Issued { attempts: u32 },
|
||||
/// It did what it was sent to do.
|
||||
Succeeded,
|
||||
/// It failed.
|
||||
Failed,
|
||||
/// The daemon started.
|
||||
Restarted,
|
||||
/// A pass that began after it was sent looked at its path and did not
|
||||
/// send it again: what it was for has changed, or is done.
|
||||
Superseded,
|
||||
}
|
||||
|
||||
/// The state after `input`.
|
||||
pub fn step(state: EffectState, input: EffectInput) -> EffectState {
|
||||
use EffectState as S;
|
||||
match (state, input) {
|
||||
(S::Settled, _) => S::Settled,
|
||||
(_, EffectInput::Issued { .. }) => S::Issued,
|
||||
(_, EffectInput::Succeeded | EffectInput::Superseded) => S::Settled,
|
||||
(S::Issued, EffectInput::Restarted) => S::Unsure,
|
||||
(state, EffectInput::Restarted) => state,
|
||||
(_, EffectInput::Failed) => S::Retry,
|
||||
}
|
||||
}
|
||||
|
||||
/// The state after a failure on the `attempts`th send. Counts are kept
|
||||
/// outside [`step`], with the intent.
|
||||
pub fn failed(attempts: u32) -> EffectState {
|
||||
if attempts >= BLOCKED_AFTER {
|
||||
EffectState::Blocked
|
||||
} else {
|
||||
step(EffectState::Issued, EffectInput::Failed)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use EffectInput as I;
|
||||
use EffectState as S;
|
||||
|
||||
#[test]
|
||||
fn an_effect_settles_once_it_succeeds() {
|
||||
let sent = step(S::Retry, I::Issued { attempts: 2 });
|
||||
assert_eq!(sent, S::Issued);
|
||||
assert_eq!(step(sent, I::Succeeded), S::Settled);
|
||||
assert_eq!(step(S::Settled, I::Failed), S::Settled, "settled stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_effect_sent_before_a_stop_is_unsure_after_the_start() {
|
||||
assert_eq!(step(S::Issued, I::Restarted), S::Unsure);
|
||||
// Only one that was sent: a failure is known, and stays one.
|
||||
assert_eq!(step(S::Retry, I::Restarted), S::Retry);
|
||||
assert_eq!(step(S::Blocked, I::Restarted), S::Blocked);
|
||||
// Sent again, or found needless by a later pass.
|
||||
assert_eq!(step(S::Unsure, I::Issued { attempts: 2 }), S::Issued);
|
||||
assert_eq!(step(S::Unsure, I::Superseded), S::Settled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_effect_that_keeps_failing_is_blocked() {
|
||||
assert_eq!(failed(1), S::Retry);
|
||||
assert_eq!(failed(BLOCKED_AFTER - 1), S::Retry);
|
||||
assert_eq!(failed(BLOCKED_AFTER), S::Blocked);
|
||||
assert_eq!(step(S::Blocked, I::Superseded), S::Settled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_state_reads_back_by_its_name() {
|
||||
for state in [S::Issued, S::Unsure, S::Retry, S::Blocked, S::Settled] {
|
||||
assert_eq!(EffectState::from_name(state.name()), Some(state));
|
||||
}
|
||||
assert_eq!(EffectState::from_name("planned"), None);
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ use pdfs_store::db::{DeleteWindow, StoredSyncEntry};
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use proton_drive_rs::{Node, NodeKind};
|
||||
|
||||
pub mod effect;
|
||||
pub mod evidence;
|
||||
pub mod local_dirty;
|
||||
pub mod mirror;
|
||||
|
||||
@@ -38,6 +38,7 @@ use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
use sha1::{Digest as _, Sha1};
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use crate::effect::{self, EffectState};
|
||||
use crate::evidence::{Evidence, RemoteEvidence, Side};
|
||||
use crate::local_dirty::{Claim, LocalWalk, root_id};
|
||||
use crate::planner::HasKind;
|
||||
@@ -48,7 +49,9 @@ use pdfs_core::syncignore::IgnoreRules;
|
||||
use pdfs_core::timestamp::now_secs;
|
||||
use pdfs_core::transfers::{CountingWriter, OwnedCountingReader};
|
||||
use pdfs_drive::parse_uid;
|
||||
use pdfs_store::db::{DeleteWindow, SavedWalk, SavedWalkItem, StoredSyncEntry, StoredSyncFolder};
|
||||
use pdfs_store::db::{
|
||||
DeleteWindow, SavedWalk, SavedWalkItem, StoredIntent, StoredSyncEntry, StoredSyncFolder,
|
||||
};
|
||||
|
||||
mod apply;
|
||||
mod engine;
|
||||
@@ -532,6 +535,9 @@ impl Syncer {
|
||||
remote_root: &NodeUid,
|
||||
rules: &IgnoreRules,
|
||||
) -> Result<Outcome, PassAbort> {
|
||||
// Intents sent before this moment that the pass does not send again
|
||||
// are settled at its end (`effect`).
|
||||
let pass_began = now_secs();
|
||||
// Loaded before the walks: the remote one uses it to tell which files are
|
||||
// unchanged and so can skip decrypting their claimed size, and its size is
|
||||
// the only estimate available of how much this pass has to check — the walks
|
||||
@@ -846,6 +852,18 @@ impl Syncer {
|
||||
}
|
||||
FilePlan::Conflict => {
|
||||
let remote = r.expect("conflict requires a remote file");
|
||||
if self.landed_unanswered(folder_id, rel, remote.sha1.as_deref()) {
|
||||
info!(
|
||||
rel,
|
||||
"sync: the file on Drive is an upload of ours that went unanswered; sending the newer local bytes as a revision of it"
|
||||
);
|
||||
batch.push(Pending::UploadRevision {
|
||||
rel: rel.clone(),
|
||||
uid: remote.uid.clone(),
|
||||
seen: RemoteSeen::from(remote),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
batch.push(Pending::Conflict {
|
||||
rel: rel.clone(),
|
||||
uid: remote.uid.clone(),
|
||||
@@ -1043,6 +1061,11 @@ impl Syncer {
|
||||
}
|
||||
self.trace_phase(Phase::Cleanup, cleanup.elapsed());
|
||||
self.settle_deletions(folder_id, window, outcome.deleted);
|
||||
// Every path was looked at and planned: what an earlier pass left
|
||||
// unsettled and this one did not send again is no longer owed.
|
||||
if outcome.unscanned.is_empty() && outcome.deferred == 0 {
|
||||
self.supersede_intents(folder_id, pass_began);
|
||||
}
|
||||
// A change the pass could not apply stays dirty for the next one.
|
||||
self.local_dirty.looked(
|
||||
folder_id,
|
||||
|
||||
@@ -134,6 +134,146 @@ impl Syncer {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write the intent of `op` before it is sent (`effect`). In shadow: a
|
||||
/// failure to write it is logged, and the op is sent anyway.
|
||||
fn issue_intent(&self, folder_id: i64, op: &Pending) -> Option<StoredIntent> {
|
||||
let (intent, before) = match self.store.sync_intent_issue(
|
||||
folder_id,
|
||||
op.rel(),
|
||||
op.intent(),
|
||||
now_secs(),
|
||||
) {
|
||||
Ok(issued) => issued,
|
||||
Err(e) => {
|
||||
debug!(id = folder_id, rel = op.rel(), error = ?e, "sync: cannot record an intent");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
match before.as_deref().and_then(EffectState::from_name) {
|
||||
// Sent by a daemon that stopped before it heard back. The apply
|
||||
// step's own checks tell whether it landed (B266, B39).
|
||||
Some(EffectState::Unsure) => {
|
||||
self.trace_count(Count::UnsureResent, 1);
|
||||
info!(
|
||||
id = folder_id,
|
||||
rel = op.rel(),
|
||||
kind = op.intent(),
|
||||
attempts = intent.attempts,
|
||||
"sync: sending again an effect a stopped daemon may have made"
|
||||
);
|
||||
}
|
||||
Some(EffectState::Retry | EffectState::Blocked) => {
|
||||
self.trace_count(Count::Retried, 1);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Some(intent)
|
||||
}
|
||||
|
||||
/// Settle or keep `intent` by how its op ended.
|
||||
fn settle_intent(&self, intent: &StoredIntent, op: &Pending, result: &Result<Applied, String>) {
|
||||
let written = match result {
|
||||
Ok(_) => self.store.sync_intent_settle(intent.id),
|
||||
Err(e) => {
|
||||
let state = effect::failed(intent.attempts);
|
||||
if state == EffectState::Blocked && intent.state != EffectState::Blocked.name() {
|
||||
warn!(
|
||||
id = intent.folder_id,
|
||||
rel = op.rel(),
|
||||
kind = op.intent(),
|
||||
attempts = intent.attempts,
|
||||
error = %e,
|
||||
"sync: an effect keeps failing"
|
||||
);
|
||||
}
|
||||
self.store.sync_intent_set(intent.id, state.name(), Some(e))
|
||||
}
|
||||
};
|
||||
if let Err(e) = written {
|
||||
debug!(id = intent.folder_id, rel = op.rel(), error = ?e, "sync: cannot settle an intent");
|
||||
}
|
||||
}
|
||||
|
||||
/// Note that an upload of `rel` streamed bytes with SHA-1 `sha1` and did
|
||||
/// not hear a success back. They may have landed all the same.
|
||||
fn note_sent(&self, folder_id: i64, rel: &str, kind: &str, sha1: &str) {
|
||||
if let Err(error) = self.store.sync_intent_sent(folder_id, rel, kind, sha1) {
|
||||
debug!(rel, error = ?error, "sync: cannot note what an upload sent");
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the file Drive holds at `rel`, with SHA-1 `remote_sha1`, is one
|
||||
/// of this daemon's own uploads whose answer never came: an upload of
|
||||
/// `rel` not yet settled streamed exactly those bytes.
|
||||
///
|
||||
/// Then the file is ours, not another computer's, and a newer local edit
|
||||
/// is not a conflict with it: it goes up as a revision. A file that only
|
||||
/// happens to hold the same bytes loses nothing by that either.
|
||||
pub(super) fn landed_unanswered(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rel: &str,
|
||||
remote_sha1: Option<&str>,
|
||||
) -> bool {
|
||||
let Some(remote_sha1) = remote_sha1 else {
|
||||
return false;
|
||||
};
|
||||
let intents = match self.store.sync_intents(Some(folder_id)) {
|
||||
Ok(intents) => intents,
|
||||
Err(error) => {
|
||||
debug!(rel, error = ?error, "sync: cannot read the effect intents");
|
||||
return false;
|
||||
}
|
||||
};
|
||||
intents.iter().any(|intent| {
|
||||
intent.rel_path == rel
|
||||
&& matches!(intent.kind.as_str(), "upload" | "upload-revision")
|
||||
&& intent
|
||||
.sent_sha1s
|
||||
.iter()
|
||||
.any(|sent| sent.eq_ignore_ascii_case(remote_sha1))
|
||||
})
|
||||
}
|
||||
|
||||
/// Settle the intents of `folder_id` that a pass begun at `began` did
|
||||
/// not send again, though it looked at every path: what they were for has
|
||||
/// changed, or is done.
|
||||
pub(super) fn supersede_intents(&self, folder_id: i64, began: i64) {
|
||||
let states = [
|
||||
EffectState::Unsure.name(),
|
||||
EffectState::Retry.name(),
|
||||
EffectState::Blocked.name(),
|
||||
];
|
||||
match self
|
||||
.store
|
||||
.sync_intents_settle_before(folder_id, &states, began)
|
||||
{
|
||||
Ok(settled) => {
|
||||
self.trace_count(Count::Superseded, settled.len());
|
||||
for intent in settled {
|
||||
let level_info = intent.state == EffectState::Unsure.name();
|
||||
if level_info {
|
||||
info!(
|
||||
id = folder_id,
|
||||
rel = %intent.rel_path,
|
||||
kind = %intent.kind,
|
||||
"sync: an effect a stopped daemon may have made is no longer needed"
|
||||
);
|
||||
} else {
|
||||
debug!(
|
||||
id = folder_id,
|
||||
rel = %intent.rel_path,
|
||||
kind = %intent.kind,
|
||||
state = %intent.state,
|
||||
"sync: an effect is no longer needed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => debug!(id = folder_id, error = ?e, "sync: cannot settle intents"),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)
|
||||
@@ -150,9 +290,13 @@ impl Syncer {
|
||||
op: Pending,
|
||||
) -> Result<Applied, String> {
|
||||
self.progress_started(folder_id, base_name(op.rel()));
|
||||
let intent = self.issue_intent(folder_id, &op);
|
||||
let step = Instant::now();
|
||||
let result = self.apply_one(folder_id, local_root, &op).await;
|
||||
self.trace_call(op.call(), step.elapsed());
|
||||
if let Some(intent) = intent {
|
||||
self.settle_intent(&intent, &op, &result);
|
||||
}
|
||||
self.progress_finished(folder_id);
|
||||
let name = base_name(op.rel());
|
||||
match &result {
|
||||
@@ -220,6 +364,15 @@ impl Syncer {
|
||||
return Ok(Applied::Vanished);
|
||||
}
|
||||
if !digest.eq_ignore_ascii_case(sha1) {
|
||||
if self.landed_unanswered(folder_id, rel, Some(sha1)) {
|
||||
info!(
|
||||
rel,
|
||||
"sync: the file on Drive is an upload of ours that went unanswered; sending the newer local bytes as a revision of it"
|
||||
);
|
||||
return self
|
||||
.upload_revision(folder_id, local_root, rel, uid, remote)
|
||||
.await;
|
||||
}
|
||||
info!(
|
||||
rel,
|
||||
"sync: same size as on Drive but different content; keeping a conflict copy"
|
||||
@@ -341,8 +494,14 @@ impl Syncer {
|
||||
Some(mtime),
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| format!("upload {rel}: {e}"))?;
|
||||
.await;
|
||||
let uid = match uid {
|
||||
Ok(uid) => uid,
|
||||
Err(e) => {
|
||||
self.note_sent(folder_id, rel, "upload", &sent.digest());
|
||||
return Err(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).
|
||||
@@ -362,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,
|
||||
@@ -377,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}"))?;
|
||||
@@ -410,10 +567,28 @@ impl Syncer {
|
||||
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}"))?;
|
||||
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
|
||||
.landed_as_sent(rel, uid, &sent.digest(), streamed)
|
||||
@@ -582,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"
|
||||
)
|
||||
}
|
||||
@@ -242,6 +242,19 @@ pub fn run(core: Syncer, rx: Receiver<SyncMsg>) {
|
||||
),
|
||||
Err(e) => warn!(error = ?e, "sync: cannot reset folders left syncing"),
|
||||
}
|
||||
// An effect still `issued` was sent by a daemon that stopped before it
|
||||
// heard back: it may or may not have happened (`effect`).
|
||||
match core.store.sync_intents_move(
|
||||
effect::EffectState::Issued.name(),
|
||||
effect::EffectState::Unsure.name(),
|
||||
) {
|
||||
Ok(0) => {}
|
||||
Ok(n) => info!(
|
||||
effects = n,
|
||||
"sync: effects the last run sent and did not hear back from"
|
||||
),
|
||||
Err(e) => warn!(error = ?e, "sync: cannot read the effects the last run sent"),
|
||||
}
|
||||
// Paths the watcher currently covers, mapped to their folder id, so an event
|
||||
// path can be resolved back to the folder it belongs to.
|
||||
let watched: Arc<Mutex<Vec<(PathBuf, i64)>>> = Arc::new(Mutex::new(Vec::new()));
|
||||
|
||||
@@ -307,6 +307,19 @@ impl Pending {
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind of effect its intent records (`effect`).
|
||||
pub fn intent(&self) -> &'static str {
|
||||
match self {
|
||||
Pending::CreateDir { .. } => "create-folder",
|
||||
Pending::UploadNew { .. } => "upload",
|
||||
Pending::UploadRevision { .. } => "upload-revision",
|
||||
Pending::Download { .. } => "download",
|
||||
Pending::Adopt { .. } => "adopt",
|
||||
Pending::Conflict { .. } => "conflict",
|
||||
Pending::PushConflict { .. } => "push-conflict",
|
||||
}
|
||||
}
|
||||
|
||||
/// The activity line's detail, which distinguishes ops that share a kind.
|
||||
pub fn detail(&self) -> &'static str {
|
||||
match self {
|
||||
|
||||
@@ -13,7 +13,7 @@ use std::collections::HashMap;
|
||||
|
||||
use pdfs_core::Result;
|
||||
use pdfs_store::db::{
|
||||
Db, DeleteWindow, SavedWalk, SavedWalkItem, StoredSyncEntry, StoredSyncFolder,
|
||||
Db, DeleteWindow, SavedWalk, SavedWalkItem, StoredIntent, StoredSyncEntry, StoredSyncFolder,
|
||||
};
|
||||
|
||||
/// The sync tables, as the mirror engine uses them.
|
||||
@@ -80,6 +80,43 @@ pub trait SyncStore: Send + Sync {
|
||||
fn sync_delete_window(&self, folder_id: i64) -> Result<Option<DeleteWindow>>;
|
||||
/// Record the folder's deletion window.
|
||||
fn sync_delete_window_set(&self, folder_id: i64, window: &DeleteWindow) -> Result<()>;
|
||||
|
||||
// The intent of each effect sent (`effect`).
|
||||
|
||||
/// Record that an effect is about to be sent; returns the intent and the
|
||||
/// state it was in before, if any.
|
||||
fn sync_intent_issue(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rel_path: &str,
|
||||
kind: &str,
|
||||
now: i64,
|
||||
) -> Result<(StoredIntent, Option<String>)>;
|
||||
/// Drop a settled intent.
|
||||
fn sync_intent_settle(&self, id: i64) -> Result<()>;
|
||||
/// Move an intent to `state`, with the error that put it there.
|
||||
fn sync_intent_set(&self, id: i64, state: &str, error: Option<&str>) -> Result<()>;
|
||||
/// Note that upload `kind` of `rel_path` streamed bytes with SHA-1 `sha1`
|
||||
/// and heard no success back.
|
||||
fn sync_intent_sent(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rel_path: &str,
|
||||
kind: &str,
|
||||
sha1: &str,
|
||||
) -> Result<()>;
|
||||
/// Every intent not settled; only `folder_id`'s when given.
|
||||
fn sync_intents(&self, folder_id: Option<i64>) -> Result<Vec<StoredIntent>>;
|
||||
/// Move every intent in state `from` to `to`.
|
||||
fn sync_intents_move(&self, from: &str, to: &str) -> Result<usize>;
|
||||
/// Settle the intents of `folder_id` in one of `states` last sent before
|
||||
/// `before`.
|
||||
fn sync_intents_settle_before(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
states: &[&str],
|
||||
before: i64,
|
||||
) -> Result<Vec<StoredIntent>>;
|
||||
}
|
||||
|
||||
impl SyncStore for Db {
|
||||
@@ -154,6 +191,44 @@ impl SyncStore for Db {
|
||||
fn sync_delete_window_set(&self, folder_id: i64, window: &DeleteWindow) -> Result<()> {
|
||||
Db::sync_delete_window_set(self, folder_id, window)
|
||||
}
|
||||
fn sync_intent_issue(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rel_path: &str,
|
||||
kind: &str,
|
||||
now: i64,
|
||||
) -> Result<(StoredIntent, Option<String>)> {
|
||||
Db::sync_intent_issue(self, folder_id, rel_path, kind, now)
|
||||
}
|
||||
fn sync_intent_settle(&self, id: i64) -> Result<()> {
|
||||
Db::sync_intent_settle(self, id)
|
||||
}
|
||||
fn sync_intent_set(&self, id: i64, state: &str, error: Option<&str>) -> Result<()> {
|
||||
Db::sync_intent_set(self, id, state, error)
|
||||
}
|
||||
fn sync_intent_sent(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
rel_path: &str,
|
||||
kind: &str,
|
||||
sha1: &str,
|
||||
) -> Result<()> {
|
||||
Db::sync_intent_sent(self, folder_id, rel_path, kind, sha1)
|
||||
}
|
||||
fn sync_intents(&self, folder_id: Option<i64>) -> Result<Vec<StoredIntent>> {
|
||||
Db::sync_intents(self, folder_id)
|
||||
}
|
||||
fn sync_intents_move(&self, from: &str, to: &str) -> Result<usize> {
|
||||
Db::sync_intents_move(self, from, to)
|
||||
}
|
||||
fn sync_intents_settle_before(
|
||||
&self,
|
||||
folder_id: i64,
|
||||
states: &[&str],
|
||||
before: i64,
|
||||
) -> Result<Vec<StoredIntent>> {
|
||||
Db::sync_intents_settle_before(self, folder_id, states, before)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -216,5 +291,20 @@ mod tests {
|
||||
);
|
||||
store.sync_remote_dirty_consume(id, dirty[0].0).unwrap();
|
||||
assert!(store.sync_remote_dirty(id).unwrap().is_empty());
|
||||
|
||||
let (intent, _) = store.sync_intent_issue(id, "a.txt", "upload", 1).unwrap();
|
||||
store.sync_intent_set(intent.id, "retry", None).unwrap();
|
||||
assert_eq!(store.sync_intents(Some(id)).unwrap()[0].state, "retry");
|
||||
assert_eq!(store.sync_intents_move("retry", "blocked").unwrap(), 1);
|
||||
assert_eq!(
|
||||
store
|
||||
.sync_intents_settle_before(id, &["blocked"], 2)
|
||||
.unwrap()
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
let (intent, _) = store.sync_intent_issue(id, "a.txt", "upload", 3).unwrap();
|
||||
store.sync_intent_settle(intent.id).unwrap();
|
||||
assert!(store.sync_intents(None).unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -148,10 +148,18 @@ pub enum Count {
|
||||
/// Paths on disk taken from the last pass's walk, which a trusted claim
|
||||
/// of the local dirty set keeps up to date, instead of walked again.
|
||||
LocalReused,
|
||||
/// Effects sent again that a stopped daemon had sent and not heard back
|
||||
/// from: each may have happened already (`effect`).
|
||||
UnsureResent,
|
||||
/// Effects sent again after they failed.
|
||||
Retried,
|
||||
/// Unsettled effects of earlier passes that this pass looked at and no
|
||||
/// longer sent.
|
||||
Superseded,
|
||||
}
|
||||
|
||||
impl Count {
|
||||
const ALL: [Count; 14] = [
|
||||
const ALL: [Count; 17] = [
|
||||
Count::LocalEntries,
|
||||
Count::RemoteFolders,
|
||||
Count::Nodes,
|
||||
@@ -166,6 +174,9 @@ impl Count {
|
||||
Count::LocalUntrusted,
|
||||
Count::MissedLocal,
|
||||
Count::LocalReused,
|
||||
Count::UnsureResent,
|
||||
Count::Retried,
|
||||
Count::Superseded,
|
||||
];
|
||||
|
||||
fn name(self) -> &'static str {
|
||||
@@ -184,6 +195,9 @@ impl Count {
|
||||
Count::LocalUntrusted => "local dirty untrusted",
|
||||
Count::MissedLocal => "missed local changes",
|
||||
Count::LocalReused => "local reused",
|
||||
Count::UnsureResent => "unsure resent",
|
||||
Count::Retried => "retried",
|
||||
Count::Superseded => "superseded",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,6 +108,7 @@ a live account since.
|
||||
|
||||
| Entry | Title |
|
||||
|---|---|
|
||||
| [B305](#b305--a-mirrored-file-whose-upload-went-unanswered-gets-a-conflict-copy-of-its-own-edit) | A mirrored file whose upload went unanswered gets a conflict copy of its own edit |
|
||||
| [B304](#b304--a-write-released-while-its-files-create-lands-is-kept-as-a-conflict-copy) | A write released while its file's create lands is kept as a conflict copy |
|
||||
| [B303](#b303--a-file-made-where-a-withdrawn-create-was-listed-refuses-every-write) | A file made where a withdrawn create was listed refuses every write |
|
||||
| [B302](#b302--a-stop-during-a-replacing-rename-leaves-the-replaced-file-in-the-trash) | A stop during a replacing rename leaves the replaced file in the trash |
|
||||
@@ -407,6 +408,36 @@ a live account since.
|
||||
|
||||
Newest first.
|
||||
|
||||
### B305 — A mirrored file whose upload went unanswered gets a conflict copy of its own edit
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
**Found:** 2026-11-27, writing the simulation for the case the effect reducer is meant to handle
|
||||
(`FURTHER_IMPROVEMENTS.md`): a create accepted by Drive, the reply lost, a restart, and a newer
|
||||
local edit. The simulation failed on the first run. Drive held `new.txt` with the first bytes and
|
||||
`new (sync-conflict …).txt` with the edit.
|
||||
**Where:** the `FilePlan::Conflict` arm of the plan in `crates/pdfs-sync/src/mirror.rs`, and
|
||||
`Pending::Adopt` in `crates/pdfs-sync/src/mirror/apply.rs`
|
||||
|
||||
**Repro:** In a mirror folder, write a new file. Lose the answer to its upload after Drive has
|
||||
made the file. Stop the daemon, write the file again, and start the daemon.
|
||||
|
||||
**Cause.** The upload failed as far as the daemon knew, so no baseline was recorded. The next pass
|
||||
found the path on both sides with no baseline and different bytes, which is what two computers
|
||||
writing one new file look like, so it kept the local copy as a conflict copy. The edit itself is
|
||||
not lost. The one-request small upload makes this ending of a lost reply the usual one: it
|
||||
leaves a whole file, never a draft for the next attempt to replace.
|
||||
|
||||
**Fix.** An upload that hears no success back notes the SHA-1 of the bytes it streamed in its
|
||||
effect intent (`sent_sha1s`, schema 52). Before keeping a conflict copy, the plan checks the
|
||||
intents. If Drive's file holds exactly bytes an unsettled upload of that path sent, the file is
|
||||
this daemon's own. The local bytes then go up as a revision of it. A first-sync adopt of a
|
||||
same-size file with other bytes does the same. A file that holds those bytes by chance loses
|
||||
nothing either: they are what this computer sent.
|
||||
|
||||
**Verified:** `a_mirror_create_whose_reply_was_lost_is_adopted_after_a_restart_and_its_edit_lands`
|
||||
fails without the fix and passes with it. `an_upload_notes_each_digest_it_sent_once` covers the
|
||||
store.
|
||||
|
||||
### B304 — A write released while its file's create lands is kept as a conflict copy
|
||||
|
||||
**Status:** Fixed (unverified)
|
||||
|
||||
+23
-2
@@ -11,11 +11,21 @@ scratch (user data in `staging/` and `recovery/` is never touched by this).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
Schema: **50**. New tables save a mirror folder's walk of Proton Drive (48). A finished walk is
|
||||
Schema: **52**. New tables save a mirror folder's walk of Proton Drive (48). A finished walk is
|
||||
kept, with a list of the folders that changed on Proton Drive since (49). Each mirror folder
|
||||
counts the deletions it made in the last day (50).
|
||||
counts the deletions it made in the last day (50). Each upload, download or folder a mirror pass
|
||||
sends is recorded until its result is in (51), and an upload that heard no answer keeps the
|
||||
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
|
||||
@@ -45,6 +55,11 @@ counts the deletions it made in the last day (50).
|
||||
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
|
||||
@@ -71,6 +86,12 @@ counts the deletions it made in the last day (50).
|
||||
first pass, and whenever the change feed lost track (#53).
|
||||
|
||||
### Fixed
|
||||
- **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
|
||||
files under one name. It kept this computer's newer edit as a conflict copy next to its own
|
||||
first upload. Now an upload that hears no answer keeps the digest of the bytes it sent. When
|
||||
Proton Drive holds exactly those bytes, the newer edit goes up as a new version of that file.
|
||||
- **A stop ends the loops that follow Proton Drive's change feed before the daemon exits.**
|
||||
The loops that read the Drive and photos event streams, and the gallery refresh, kept
|
||||
running after every other service had stopped, and could still write to the database while
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -258,6 +258,63 @@ disk and reuses the picture of Drive), and `a_root_made_again_is_watched_again`
|
||||
`a_root_replaced_between_passes_is_watched_again` (sims: a file written in a root moved away and
|
||||
made again reaches Drive within a minute; the second fails without the inode check).
|
||||
|
||||
## Effect intents as built
|
||||
|
||||
The second reducer, `pdfs_sync::effect`, follows one effect a mirror pass sends: a folder made on
|
||||
Drive, an upload, a new revision, a download, an adopted file or a conflict copy (the `Pending`
|
||||
ops). Before an op is sent, its intent is written to `sync_intent` (schema 51): one row per
|
||||
folder, path and kind, with the number of attempts and the time it was last sent. Its result
|
||||
decides what happens next:
|
||||
|
||||
| State | Meaning |
|
||||
|---|---|
|
||||
| issued | Sent, or about to be; no result yet. |
|
||||
| unsure | Found `issued` at a start: the daemon stopped before the result came, so the effect may or may not have happened. |
|
||||
| retry | It failed, and a later pass may send it again. |
|
||||
| blocked | It failed five times in a row. The journal says `sync: an effect keeps failing` once. |
|
||||
| settled | Its result is in. The row goes. |
|
||||
|
||||
- A start moves every `issued` row to `unsure`, and says how many in the journal.
|
||||
- An op sent again keeps its row and counts the attempt. When the row was `unsure`, the journal
|
||||
says `sync: sending again an effect a stopped daemon may have made`.
|
||||
- A pass that looked at every path (none unscanned or deferred) settles the rows from before it
|
||||
began that it did not send again: what they were for has changed, or is done. An `unsure` one
|
||||
is logged at info.
|
||||
- A change to what the folder is, or its removal, drops its rows.
|
||||
|
||||
The intents decide one thing so far: whether a file on Drive is an upload of this daemon's
|
||||
that went unanswered.
|
||||
- An upload that does not hear a success back notes the SHA-1 of the bytes it streamed in its
|
||||
intent (`sent_sha1s`, schema 52). Each attempt adds its digest.
|
||||
- When a later pass would keep a conflict copy, it checks the intent first. The path may be new
|
||||
on both sides, or changed on both sides since the baseline. If Drive's file holds exactly
|
||||
bytes an unsettled upload of that path sent, the file is ours. The newer local bytes then go up
|
||||
as a revision of it, with no conflict copy. The same holds for a first-sync adopt of a
|
||||
same-size file whose bytes differ.
|
||||
- This is the usual end of a lost reply to a one-request small upload. Such an upload leaves a
|
||||
whole file, never a draft. If the file was written again before the next pass, for example
|
||||
while the daemon was stopped, the next pass used to see two different files and fork a
|
||||
conflict copy of this computer's own edit.
|
||||
- A file that only happens to hold the same bytes loses nothing either: its content is what
|
||||
this computer sent.
|
||||
- A daemon killed in the middle of an upload notes no digest, so that case still ends in a
|
||||
conflict copy when the file is edited before the next pass. It is kept, and nothing is lost.
|
||||
|
||||
Otherwise nothing reads the intents to decide what to send. The apply step's own checks still
|
||||
decide whether an effect that may have landed is sent again (B266 for a create, B39 for a
|
||||
download). Deletions on either side are not recorded yet. Trace counts: `unsure resent`,
|
||||
`retried`, `superseded`.
|
||||
|
||||
**Tests:**
|
||||
- the `effect::tests` unit tests;
|
||||
- DB: `an_effect_intent_is_kept_until_it_is_settled_or_its_folder_changes`, and
|
||||
`an_upload_notes_each_digest_it_sent_once`;
|
||||
- sim `an_effect_left_unsure_by_a_stop_is_sent_again_or_settled`: of two uploads a stopped daemon
|
||||
left unsure, the one still needed is sent again and the other is settled;
|
||||
- sim `a_mirror_create_whose_reply_was_lost_is_adopted_after_a_restart_and_its_edit_lands`:
|
||||
Drive makes the file and the answer is lost, then the daemon stops and the file is written
|
||||
again. After the start there is one file, holding the newer bytes, and no conflict copy.
|
||||
|
||||
## Plan of work (separate PRs)
|
||||
|
||||
1. **Frontier checkpoint.**
|
||||
|
||||
+26
-3
@@ -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
|
||||
|
||||
|
||||
@@ -327,6 +327,11 @@ What the parts mean:
|
||||
A `sync: root state` line in the journal says when a folder's state changes, for example
|
||||
`from=following to=auditing (local: Overflow)`: the side named is walked in full by the next
|
||||
pass, which takes the folder back to `following`.
|
||||
**`unsure resent`** counts effects sent again that a daemon stopped before it heard back
|
||||
from; the apply step checks whether each already landed before it sends it. **`retried`**
|
||||
counts effects sent again after a failure, and **`superseded`** counts unsettled effects of
|
||||
earlier passes that were no longer needed. A `sync: an effect keeps failing` line names an
|
||||
upload, download or folder that failed five times in a row.
|
||||
|
||||
Please include these lines when you report a slow folder.
|
||||
|
||||
|
||||
+290
-6
@@ -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))
|
||||
|
||||
Reference in new issue
Block a user