mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-28 12:02:14 +01:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8881c79f15 | ||
|
|
f975d9cf17 | ||
|
|
deb15a3327 | ||
|
|
8c7a0a8a17 | ||
|
|
9533ebcdfc | ||
|
|
ccc679eef5 | ||
|
|
d1421a84b1 | ||
|
|
670ec7db31 | ||
|
|
30b20fc444 | ||
|
|
5c6360e6e7 | ||
|
|
42926b71a9 | ||
|
|
21e7c03460 |
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"
|
||||
|
||||
@@ -389,6 +389,15 @@ pub(super) fn cmd_diagnostics() -> Result<()> {
|
||||
);
|
||||
}
|
||||
}
|
||||
if d.upload_paths.iter().any(|stat| stat.count > 0) {
|
||||
println!("uploads since start, by path:");
|
||||
for stat in &d.upload_paths {
|
||||
println!(
|
||||
" {:<38} {:>7} files {:>5} failed {:>9} ms total {:>7} ms longest",
|
||||
stat.path, stat.count, stat.errors, stat.total_ms, stat.longest_ms,
|
||||
);
|
||||
}
|
||||
}
|
||||
if d.inflight.is_empty() {
|
||||
println!("in-flight requests: none");
|
||||
} else {
|
||||
|
||||
@@ -38,7 +38,6 @@ use proton_sdk::error::ProtonError;
|
||||
use proton_sdk::http::Tokens;
|
||||
use proton_sdk::login::{self, LoginError, Step};
|
||||
use proton_sdk::session::{PasswordMode, ProtonApiSession, ResumeParameters};
|
||||
use proton_sdk::telemetry::TracingTelemetry;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
@@ -771,7 +770,7 @@ async fn migrate_legacy(
|
||||
/// default.
|
||||
fn tune(client: ProtonDriveClient, passphrases: &KeyPassphrases) -> ProtonDriveClient {
|
||||
let client = client
|
||||
.with_telemetry(TracingTelemetry::shared())
|
||||
.with_telemetry(crate::uploads::telemetry())
|
||||
.with_small_file_upload(true);
|
||||
match AppDirs::new().and_then(|dirs| crate::sdkcache::SdkCache::shared(&dirs)) {
|
||||
Ok(cache) => {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -2374,6 +2374,11 @@ pub struct Diagnostics {
|
||||
/// field.
|
||||
#[serde(default)]
|
||||
pub drive_calls: Vec<DriveCallStat>,
|
||||
/// Uploads since start, by how the SDK sent their content: `small` in one
|
||||
/// request, `blocks` as a draft, its blocks and a commit. Empty from a
|
||||
/// daemon that predates the field.
|
||||
#[serde(default)]
|
||||
pub upload_paths: Vec<UploadPathStat>,
|
||||
/// The daemon's long-lived threads, in start order, and whether each is
|
||||
/// still running. Empty from a daemon that predates the field.
|
||||
#[serde(default)]
|
||||
@@ -2433,6 +2438,17 @@ pub struct DriveCallStat {
|
||||
pub longest_ms: u64,
|
||||
}
|
||||
|
||||
/// Uploads that took one path, in [`Diagnostics::upload_paths`].
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct UploadPathStat {
|
||||
/// `small` or `blocks`.
|
||||
pub path: String,
|
||||
pub count: u64,
|
||||
pub errors: u64,
|
||||
pub total_ms: u64,
|
||||
pub longest_ms: u64,
|
||||
}
|
||||
|
||||
/// What the folder-sync engine is doing, for [`Diagnostics`].
|
||||
///
|
||||
/// The engine is one thread that runs every synced folder's passes in turn.
|
||||
|
||||
@@ -30,6 +30,7 @@ pub mod timestamp;
|
||||
pub mod transfers;
|
||||
pub mod tray;
|
||||
pub mod update;
|
||||
pub mod uploads;
|
||||
|
||||
// Photo logic shared with Proton Gallery through the proton-rs crates.
|
||||
pub use proton_gallery_rs::{exiftime, places, similar, takeout};
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
//! How the SDK sent each upload's content, counted from its telemetry.
|
||||
//!
|
||||
//! A file whose encrypted size is under 128 KiB goes up in one request
|
||||
//! (`small`). Any other file goes up as a draft, its blocks and a commit
|
||||
//! (`blocks`). The SDK picks the path inside each upload call and reports it
|
||||
//! only as the `backend` attribute of the `upload_file` and
|
||||
//! `upload_new_revision` timers, so this module counts those events. If the
|
||||
//! share of small uploads drops to zero for small files, the one-request path
|
||||
//! is off or the server refuses it, and `pdfs diagnostics` shows that.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use proton_sdk::telemetry::{Outcome, Telemetry, TelemetryEvent, TracingTelemetry};
|
||||
|
||||
/// The counts of every upload of this process, by path.
|
||||
pub static UPLOAD_PATHS: UploadPaths = UploadPaths::new();
|
||||
|
||||
/// Upload counts for each path.
|
||||
#[derive(Debug)]
|
||||
pub struct UploadPaths {
|
||||
small: PathStat,
|
||||
blocks: PathStat,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PathStat {
|
||||
count: AtomicU64,
|
||||
errors: AtomicU64,
|
||||
total_ms: AtomicU64,
|
||||
longest_ms: AtomicU64,
|
||||
}
|
||||
|
||||
/// One path's counts at one moment.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UploadPathStat {
|
||||
/// `small` or `blocks`.
|
||||
pub path: &'static str,
|
||||
pub count: u64,
|
||||
pub errors: u64,
|
||||
pub total_ms: u64,
|
||||
pub longest_ms: u64,
|
||||
}
|
||||
|
||||
impl PathStat {
|
||||
const fn new() -> Self {
|
||||
Self {
|
||||
count: AtomicU64::new(0),
|
||||
errors: AtomicU64::new(0),
|
||||
total_ms: AtomicU64::new(0),
|
||||
longest_ms: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
fn add(&self, failed: bool, took: Duration) {
|
||||
let ms = u64::try_from(took.as_millis()).unwrap_or(u64::MAX);
|
||||
self.count.fetch_add(1, Ordering::Relaxed);
|
||||
if failed {
|
||||
self.errors.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
self.total_ms.fetch_add(ms, Ordering::Relaxed);
|
||||
self.longest_ms.fetch_max(ms, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn snapshot(&self, path: &'static str) -> UploadPathStat {
|
||||
UploadPathStat {
|
||||
path,
|
||||
count: self.count.load(Ordering::Relaxed),
|
||||
errors: self.errors.load(Ordering::Relaxed),
|
||||
total_ms: self.total_ms.load(Ordering::Relaxed),
|
||||
longest_ms: self.longest_ms.load(Ordering::Relaxed),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for UploadPaths {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl UploadPaths {
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
small: PathStat::new(),
|
||||
blocks: PathStat::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Count `event` if it is the end of an upload.
|
||||
pub fn record(&self, event: &TelemetryEvent) {
|
||||
if !matches!(event.operation, "upload_file" | "upload_new_revision") {
|
||||
return;
|
||||
}
|
||||
let backend = event
|
||||
.attributes
|
||||
.iter()
|
||||
.find_map(|(key, value)| (*key == "backend").then_some(value.as_str()));
|
||||
let stat = match backend {
|
||||
Some("small") => &self.small,
|
||||
Some("blocks") => &self.blocks,
|
||||
_ => return,
|
||||
};
|
||||
stat.add(event.outcome == Outcome::Failure, event.duration);
|
||||
}
|
||||
|
||||
/// The counts so far, small first.
|
||||
pub fn snapshot(&self) -> [UploadPathStat; 2] {
|
||||
[self.small.snapshot("small"), self.blocks.snapshot("blocks")]
|
||||
}
|
||||
}
|
||||
|
||||
/// The SDK's telemetry sink for this process: every event goes to `tracing`
|
||||
/// as before, and uploads are also counted in [`UPLOAD_PATHS`].
|
||||
pub fn telemetry() -> Arc<dyn Telemetry> {
|
||||
Arc::new(Counting {
|
||||
inner: TracingTelemetry::shared(),
|
||||
})
|
||||
}
|
||||
|
||||
struct Counting {
|
||||
inner: Arc<dyn Telemetry>,
|
||||
}
|
||||
|
||||
impl Telemetry for Counting {
|
||||
fn record(&self, event: &TelemetryEvent) {
|
||||
UPLOAD_PATHS.record(event);
|
||||
self.inner.record(event);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn event(operation: &'static str, backend: &str, outcome: Outcome, ms: u64) -> TelemetryEvent {
|
||||
TelemetryEvent {
|
||||
operation,
|
||||
outcome,
|
||||
duration: Duration::from_millis(ms),
|
||||
attributes: vec![
|
||||
("backend", backend.to_owned()),
|
||||
("aead", "false".to_owned()),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uploads_are_counted_by_the_path_the_sdk_took() {
|
||||
let paths = UploadPaths::new();
|
||||
paths.record(&event("upload_file", "small", Outcome::Success, 300));
|
||||
paths.record(&event(
|
||||
"upload_new_revision",
|
||||
"small",
|
||||
Outcome::Failure,
|
||||
500,
|
||||
));
|
||||
paths.record(&event("upload_file", "blocks", Outcome::Success, 2_000));
|
||||
|
||||
let [small, blocks] = paths.snapshot();
|
||||
assert_eq!(
|
||||
small,
|
||||
UploadPathStat {
|
||||
path: "small",
|
||||
count: 2,
|
||||
errors: 1,
|
||||
total_ms: 800,
|
||||
longest_ms: 500,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
(blocks.count, blocks.errors, blocks.longest_ms),
|
||||
(1, 0, 2_000)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_operations_and_events_without_a_backend_are_not_counted() {
|
||||
let paths = UploadPaths::new();
|
||||
paths.record(&event("http_request", "small", Outcome::Success, 10));
|
||||
paths.record(&TelemetryEvent {
|
||||
operation: "upload_file",
|
||||
outcome: Outcome::Success,
|
||||
duration: Duration::from_millis(10),
|
||||
attributes: Vec::new(),
|
||||
});
|
||||
|
||||
assert!(paths.snapshot().iter().all(|stat| stat.count == 0));
|
||||
}
|
||||
}
|
||||
@@ -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| {
|
||||
|
||||
@@ -19,7 +19,8 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use pdfs_core::control::{
|
||||
AdmissionLoad, Diagnostics, DriveCallStat, InflightRequest, ServiceState, WorkerState,
|
||||
AdmissionLoad, Diagnostics, DriveCallStat, InflightRequest, ServiceState, UploadPathStat,
|
||||
WorkerState,
|
||||
};
|
||||
|
||||
use pdfs_core::lifecycle::ServiceBoard;
|
||||
@@ -200,6 +201,17 @@ impl Core {
|
||||
longest_ms: u64::try_from(stat.longest.as_millis()).unwrap_or(u64::MAX),
|
||||
})
|
||||
.collect(),
|
||||
upload_paths: pdfs_core::uploads::UPLOAD_PATHS
|
||||
.snapshot()
|
||||
.into_iter()
|
||||
.map(|stat| UploadPathStat {
|
||||
path: stat.path.to_owned(),
|
||||
count: stat.count,
|
||||
errors: stat.errors,
|
||||
total_ms: stat.total_ms,
|
||||
longest_ms: stat.longest_ms,
|
||||
})
|
||||
.collect(),
|
||||
admission: self
|
||||
.sync
|
||||
.admission
|
||||
|
||||
@@ -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"
|
||||
)
|
||||
}
|
||||
@@ -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
|
||||
@@ -27,6 +35,11 @@ digest of what it sent (52).
|
||||
its own directories, keyring entry, kernel keys and mountpoint, so a test account can run
|
||||
alongside the account you use. `scripts/live-bench.py` uses it to time one edit, from the
|
||||
write to the new revision on Proton Drive.
|
||||
- **`pdfs diagnostics` says how many uploads went up in one request.** It counts the uploads
|
||||
since start that took the one-request path for small files and those that went up in blocks,
|
||||
with their failures and times. If small files stop taking the one-request path, because
|
||||
`small_uploads` is off or Proton Drive refuses it, this shows it. The JSON report has them as
|
||||
`upload_paths`.
|
||||
- **`pdfs diagnostics` counts every call the daemon makes to Proton Drive.** Per kind of call it
|
||||
shows how many were made since start, how many failed, and their total and longest time. The
|
||||
JSON report has them as `drive_calls`.
|
||||
@@ -47,6 +60,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
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
|
||||
+319
-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,288 @@ 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 upload_paths(pdfs: Pdfs) -> dict[str, int]:
|
||||
"""Uploads since the daemon started, by the path the SDK took (`small` or
|
||||
`blocks`), as `pdfs diagnostics` counts them. Empty from an older build."""
|
||||
value = pdfs.json("diagnostics")
|
||||
|
||||
def find(node: object) -> list | None:
|
||||
if isinstance(node, dict):
|
||||
if isinstance(node.get("upload_paths"), list):
|
||||
return node["upload_paths"]
|
||||
for child in node.values():
|
||||
found = find(child)
|
||||
if found is not None:
|
||||
return found
|
||||
return None
|
||||
|
||||
return {stat["path"]: stat["count"] for stat in find(value) or []}
|
||||
|
||||
|
||||
def since_then(now: dict[str, int], then: dict[str, int]) -> dict[str, int]:
|
||||
return {path: count - then.get(path, 0) for path, count in now.items()}
|
||||
|
||||
|
||||
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")
|
||||
paths_before = upload_paths(pdfs)
|
||||
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
|
||||
)
|
||||
paths_after = upload_paths(pdfs)
|
||||
first["upload_paths"] = since_then(paths_after, paths_before)
|
||||
|
||||
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
|
||||
)
|
||||
edit["upload_paths"] = since_then(upload_paths(pdfs), paths_after)
|
||||
# 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}")
|
||||
if r.get("upload_paths"):
|
||||
split = ", ".join(f"{k} {v}" for k, v in sorted(r["upload_paths"].items()))
|
||||
print(f" uploads by path: {split}")
|
||||
|
||||
|
||||
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 +649,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 +673,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 +688,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