Compare commits

..
Author SHA1 Message Date
nvrl fe9528ce29 Merge branch 'docs/bugs-sim-flakes' into fix/sim-fail-fast 2026-11-26 01:37:51 +01:00
nvrl c2f5537bd7 fix(sim): run one simulation's daemons at a time, and abort a mount that will not stop (B297)
Daemon::start takes a turn: a daemon started on one test thread waits
while another test thread still has one, so plain cargo test no longer
runs the simulations side by side. A stop that does not end within 60 s,
or a daemon alive after 20 minutes, aborts the mount's FUSE connection,
which the mounting user may do, so a mount that stops answering fails the
test instead of hanging the run.
2026-11-26 01:29:54 +01:00
nvrl 23a961d020 Merge branch 'main' into docs/bugs-sim-flakes 2026-11-26 01:10:26 +01:00
nvrl d84b35c039 Merge pull request #135 from narrrl/feat/db-read-no-writer-fallback
fix(core,fuse): fail a read rather than wait on the writer, and keep one diagnostics probe
2026-11-26 01:09:55 +01:00
nvrl bf7d26ce23 docs(bugs): list B295 in the index 2026-11-26 01:04:33 +01:00
nvrl 62ae18efbf docs(bugs): B297 is the simulations run in parallel
The local runs behind the first version left out --test-threads=1, which
CI and TESTING.md use. Run serially, the same branches pass in CI.
2026-11-26 00:34:34 +01:00
nvrl 7cffeb924d docs(bugs): B297, the simulations fail or hang about one run in two
Twelve local runs of the full suite on three branches based on main:
five passed, six failed and one hung. CI on main fails too. Records
which tests fail, with what, and the hang's stuck FUSE request.
2026-11-26 00:34:34 +01:00
69 changed files with 730 additions and 715 deletions

No files matched your search

+1 -1
View File
@@ -48,7 +48,7 @@ runs are destructive: use a dedicated test account, never one holding data you c
- **Keep shared logic in `pdfs-core`.** The CLI and GUI never touch the database or the network;
they speak the control protocol to the daemon.
- **The SQLite schema is forward-only.** Never edit a shipped migration — add a new one and bump
`SCHEMA_VERSION` in `crates/pdfs-store/src/db/migrations.rs`.
`SCHEMA_VERSION` in `crates/pdfs-core/src/db/migrations.rs`.
- **Typed errors and `?` over panics** on runtime paths. Blocking filesystem, keyring, or
control-socket work stays off GTK's main thread.
- **`staging/` and `recovery/` may hold the only copy of user data.** Nothing may clear or purge
Generated
-46
View File
@@ -3641,7 +3641,6 @@ dependencies = [
"clap_complete",
"pdfs-core",
"pdfs-fuse",
"pdfs-store",
"rpassword",
"serde_json",
"tokio",
@@ -3680,21 +3679,6 @@ dependencies = [
"zeroize",
]
[[package]]
name = "pdfs-drive"
version = "3.10.0"
dependencies = [
"async-trait",
"futures",
"parking_lot 0.13.0",
"pdfs-core",
"pdfs-store",
"proton-drive-rs",
"sha1 0.11.0",
"tokio",
"tracing",
]
[[package]]
name = "pdfs-fuse"
version = "3.10.0"
@@ -3713,9 +3697,6 @@ dependencies = [
"notify",
"parking_lot 0.13.0",
"pdfs-core",
"pdfs-drive",
"pdfs-store",
"pdfs-sync",
"proton-drive-rs",
"proton-gallery-app-rs",
"proton-gallery-rs",
@@ -3756,33 +3737,6 @@ dependencies = [
"webkit6",
]
[[package]]
name = "pdfs-store"
version = "3.10.0"
dependencies = [
"libc",
"parking_lot 0.13.0",
"pdfs-core",
"proton-drive-rs",
"proton-gallery-rs",
"rusqlite",
"serde",
"serde_json",
"sha2 0.11.1",
"tracing",
]
[[package]]
name = "pdfs-sync"
version = "3.10.0"
dependencies = [
"pdfs-core",
"pdfs-drive",
"pdfs-store",
"proton-drive-rs",
"tracing",
]
[[package]]
name = "pem-rfc7468"
version = "0.7.0"
+1 -4
View File
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["crates/pdfs-core", "crates/pdfs-store", "crates/pdfs-drive", "crates/pdfs-sync", "crates/pdfs-fuse", "crates/pdfs-cli", "crates/pdfs-gui"]
members = ["crates/pdfs-core", "crates/pdfs-fuse", "crates/pdfs-cli", "crates/pdfs-gui"]
[workspace.package]
version = "3.10.0"
@@ -24,9 +24,6 @@ chrono = { version = "0.4", default-features = false, features = ["std"] }
# Internal crates.
pdfs-core = { path = "crates/pdfs-core" }
pdfs-store = { path = "crates/pdfs-store" }
pdfs-drive = { path = "crates/pdfs-drive" }
pdfs-sync = { path = "crates/pdfs-sync" }
pdfs-fuse = { path = "crates/pdfs-fuse" }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "fs", "io-util", "time", "signal"] }
-1
View File
@@ -15,7 +15,6 @@ path = "src/main.rs"
[dependencies]
pdfs-core.workspace = true
pdfs-store.workspace = true
pdfs-fuse.workspace = true
tokio.workspace = true
anyhow.workspace = true
+2 -2
View File
@@ -11,15 +11,15 @@ use anyhow::{Context, Result, anyhow, bail};
use clap::{Parser, Subcommand, ValueHint};
use clap_complete::engine::{ArgValueCandidates, ArgValueCompleter};
use pdfs_core::auth;
use pdfs_core::cache::ContentCache;
use pdfs_core::config::AppDirs;
use pdfs_core::control::{
ConflictKeep, ErrorKind, LinkChange, MountKind, RefreshScope, Request as CtlRequest,
Response as CtlResponse, RestoreItem as CtlRestoreItem, ShareEntryKind, SyncFolderInfo,
SyncIssue, SyncPhase, daemon_outdated, pending_summary,
};
use pdfs_core::db::Db;
use pdfs_core::service;
use pdfs_store::cache::ContentCache;
use pdfs_store::db::Db;
mod complete;
mod journal;
+1 -1
View File
@@ -26,8 +26,8 @@ use std::sync::Arc;
use std::time::Duration;
use chrono::{Datelike, Local, TimeZone};
use pdfs_core::cache::Pin;
use pdfs_core::config::{AppDirs, KEYRING_SERVICE};
use pdfs_core::control::Pin;
use pdfs_core::control::{
ActivityEntry, ActivityKind, AlbumInfo, DeviceInfo, DirEntry, Event, LocalHit, PhotoItem,
PhotoKind, PhotoLocation, PhotoMonth, PhotoThumb, PlaceInfo, Request, Response, SearchHit,
+2 -2
View File
@@ -16,7 +16,7 @@ impl Access {
matches!(self, Self::Owner | Self::Editor)
}
pub fn as_db_str(self) -> &'static str {
pub(crate) fn as_db_str(self) -> &'static str {
match self {
Self::Owner => "owner",
Self::Editor => "editor",
@@ -25,7 +25,7 @@ impl Access {
}
}
pub fn from_db_str(value: &str) -> Option<Self> {
pub(crate) fn from_db_str(value: &str) -> Option<Self> {
match value {
"owner" => Some(Self::Owner),
"editor" => Some(Self::Editor),
@@ -13,7 +13,7 @@
//! the mtime, so a stale blob is detected and ignored (and the event poller
//! evicts it eagerly anyway).
//!
//! [`AppDirs::cache_dir`]: pdfs_core::config::AppDirs::cache_dir
//! [`AppDirs::cache_dir`]: crate::config::AppDirs::cache_dir
//! [`Node`]: proton_drive_rs::Node
use std::collections::{BTreeMap, HashMap, HashSet};
@@ -33,8 +33,7 @@ use tracing::debug;
use parking_lot::Mutex;
use crate::db::{CacheEntryInput, Db};
pub use pdfs_core::control::Pin;
use pdfs_core::error::{Error, Result};
use crate::error::{Error, Result};
/// `cache_entries.kind` tag for whole-file content blobs.
const KIND_BLOB: &str = "blob";
@@ -277,6 +276,34 @@ struct GeometryMeta {
sizes: Vec<u64>,
}
/// One pin, as carried over the control socket and listed in `status`.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Pin {
/// Node uid in `volume~link` display form.
pub uid: String,
/// Last path the node was pinned under, for display in `status`. Advisory
/// only — the uid is the identity.
pub path: String,
/// A folder pin whose whole subtree is kept on disk. `false` for a single
/// file. Defaulted so a legacy `pins.json` (file pins only) still parses.
#[serde(default)]
pub recursive: bool,
/// Whether the pinned node is a folder, when the node cache knows.
///
/// `recursive` is pin *policy*, not node kind: a folder pinned
/// non-recursively has `recursive: false`, and a front-end reading it as
/// "this is a file" draws a file icon and sends an invalid `OpenFile`. This
/// is resolved from the `nodes` row at list time, so it is `None` for a pin
/// whose node is not cached — and absent from an older daemon's reply,
/// which is why it is defaulted.
#[serde(default)]
pub is_dir: Option<bool>,
/// A pinned file whose content is on disk right now. The daemon fills it
/// in when it answers `ListPins`; folders and older daemons say `false`.
#[serde(default)]
pub cached: bool,
}
/// The legacy JSON pin registry, kept only to import a pre-P5 `pins.json` into
/// the DB once on open. Live pins are owned by the `pins` table.
#[derive(Serialize, Deserialize, Default)]
+1 -1
View File
@@ -30,7 +30,7 @@ const LEGACY_USER_AGENT: &str = "proton-drive-linux/0.1.0";
pub const KEYRING_SERVICE: &str = "proton-drive-linux";
/// Default soft cap on the on-disk content cache (5 GiB). LRU-evicts unpinned
/// blobs back under this; pinned files are exempt. See `pdfs_store::cache`.
/// blobs back under this; pinned files are exempt. See [`crate::cache`].
pub const DEFAULT_CACHE_BUDGET_BYTES: u64 = 5 * 1024 * 1024 * 1024;
/// Environment override for [`AppConfig::resolved_conflict_sweep`]. Exists so a
+2 -29
View File
@@ -12,37 +12,10 @@ use std::time::Duration;
use serde::{Deserialize, Serialize};
use crate::cache::Pin;
use crate::error::Result;
pub use crate::mounts::{MountAccess, MountKind, MountMode, MountSpec};
/// One pin, as carried over the control socket and listed in `status`.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Pin {
/// Node uid in `volume~link` display form.
pub uid: String,
/// Last path the node was pinned under, for display in `status`. Advisory
/// only — the uid is the identity.
pub path: String,
/// A folder pin whose whole subtree is kept on disk. `false` for a single
/// file. Defaulted so a legacy `pins.json` (file pins only) still parses.
#[serde(default)]
pub recursive: bool,
/// Whether the pinned node is a folder, when the node cache knows.
///
/// `recursive` is pin *policy*, not node kind: a folder pinned
/// non-recursively has `recursive: false`, and a front-end reading it as
/// "this is a file" draws a file icon and sends an invalid `OpenFile`. This
/// is resolved from the `nodes` row at list time, so it is `None` for a pin
/// whose node is not cached — and absent from an older daemon's reply,
/// which is why it is defaulted.
#[serde(default)]
pub is_dir: Option<bool>,
/// A pinned file whose content is on disk right now. The daemon fills it
/// in when it answers `ListPins`; folders and older daemons say `false`.
#[serde(default)]
pub cached: bool,
}
/// Cap on the *write* half of a round-trip. A crashed daemon can leave its
/// listening socket in the kernel (e.g. as a `<defunct>` zombie): `connect`
/// then succeeds but no one ever replies. A short write bound trips fast when
@@ -2506,7 +2479,7 @@ pub enum Response {
username: String,
mountpoint: String,
pinned: usize,
/// Bytes of cached content blobs (see `pdfs_store::cache::ContentCache::usage`).
/// Bytes of cached content blobs (see [`crate::cache::ContentCache::usage`]).
used: u64,
/// Configured soft byte cap (`0` = unlimited).
budget: u64,
@@ -3,8 +3,8 @@
use rusqlite::params;
use super::Db;
use pdfs_core::Result;
use pdfs_core::control::{ActivityEntry, ActivityKind};
use crate::Result;
use crate::control::{ActivityEntry, ActivityKind};
/// How many activity rows to keep. Older rows are pruned on insert, so the feed
/// stays a bounded "recent history" rather than growing without limit.
@@ -12,7 +12,7 @@ use rusqlite::params;
use std::collections::HashMap;
use super::{Db, StoredPhoto, THUMB_UNKNOWN};
use pdfs_core::Result;
use crate::Result;
/// One album of the persisted listing, ordered newest-activity-first in `seq`.
#[derive(Clone, Debug, PartialEq)]
@@ -199,7 +199,7 @@ impl Db {
let name = name.clone().or(learned_name);
let media_type = media_type.clone().or(learned_media);
let kind =
pdfs_core::control::PhotoKind::classify(name.as_deref(), media_type.as_deref());
crate::control::PhotoKind::classify(name.as_deref(), media_type.as_deref());
stmt.execute(params![
album_uid,
uid,
@@ -271,7 +271,7 @@ impl Db {
name: r.get(2)?,
ratio: r.get(3)?,
thumb_state: r.get(4)?,
kind: pdfs_core::control::PhotoKind::from_i64(r.get(5)?),
kind: crate::control::PhotoKind::from_i64(r.get(5)?),
// Album rows have no favorite state of their own: an album
// photo on someone else's volume is not in our timeline, and
// favouriting one is not supported yet anyway.
@@ -335,7 +335,7 @@ impl Db {
name: r.get(2)?,
ratio: r.get(3)?,
thumb_state: r.get(4)?,
kind: pdfs_core::control::PhotoKind::from_i64(r.get(5)?),
kind: crate::control::PhotoKind::from_i64(r.get(5)?),
// Album rows have no favorite state of their own: an album
// photo on someone else's volume is not in our timeline, and
// favouriting one is not supported yet anyway.
@@ -4,7 +4,7 @@
use rusqlite::params;
use super::Db;
use pdfs_core::Result;
use crate::Result;
pub struct CacheEntryInput<'a> {
/// On-disk filename of the blob or block.
@@ -3,7 +3,7 @@
use rusqlite::{OptionalExtension, params};
use super::Db;
use pdfs_core::Result;
use crate::Result;
pub struct StoredDevice {
pub uid: String,
@@ -4,8 +4,8 @@
use rusqlite::{OptionalExtension, params};
use super::Db;
use pdfs_core::Result;
use pdfs_core::localindex::LocalEntry;
use crate::Result;
use crate::localindex::LocalEntry;
use super::nodes::candidate_trigrams;
use super::utils::{TRIGRAM_MIN, like_escape};
@@ -10,7 +10,7 @@
use rusqlite::OptionalExtension;
use super::Db;
use pdfs_core::Result;
use crate::Result;
/// A point-in-time picture of the database's size and contents.
///
@@ -8,7 +8,7 @@
use rusqlite::OptionalExtension;
use super::Db;
use pdfs_core::Result;
use crate::Result;
/// Current schema version. Bump on every forward migration added below.
pub(super) const SCHEMA_VERSION: i64 = 49;
@@ -34,7 +34,7 @@ impl Db {
.unwrap_or(0);
if current > SCHEMA_VERSION {
return Err(pdfs_core::Error::Other(format!(
return Err(crate::Error::Other(format!(
"database schema {current} is newer than this build supports ({SCHEMA_VERSION}); refusing to open it to avoid corrupting user data"
)));
}
@@ -788,7 +788,7 @@ CREATE INDEX pending_op_parent ON pending_op(parent_uid);
/// Schema v13: photos record their media type and a derived `kind` so the
/// timeline can be split into Photos / Videos / Raw tabs. `media_type` is
/// nullable — it is filled once the daemon resolves a photo's node — while
/// `kind` (see [`pdfs_core::control::PhotoKind`]) defaults to `0` (still photo), the
/// `kind` (see [`crate::control::PhotoKind`]) defaults to `0` (still photo), the
/// classification anything unresolved falls back to. Existing rows are
/// reclassified for free on the next timeline refresh, so no backfill is needed.
const MIGRATION_V13: &str = "
@@ -1237,7 +1237,7 @@ const MIGRATION_V32: &str = "UPDATE {table} SET thumb_state = 0 WHERE kind = 1 A
///
/// `latitude` and `longitude` come from the location other clients write into
/// a photo's extended attributes; `place_id` is the GeoNames id of the nearest
/// town (see `pdfs_core::places`), so the Places view is a plain `GROUP BY`.
/// town (see `crate::places`), so the Places view is a plain `GROUP BY`.
///
/// Every photo is marked unresolved, so the next refresh reads the location of
/// the whole library once. That is the backfill: the metadata is on the node
@@ -1253,7 +1253,7 @@ UPDATE photos SET resolved_at = NULL;
/// Schema v34: what each photo looks like, for finding similar ones.
///
/// `similar_hash` is a 64-bit difference hash of the photo's thumbnail (see
/// `pdfs_core::similar`): resized and re-encoded copies of one picture land a few
/// `crate::similar`): resized and re-encoded copies of one picture land a few
/// bits apart, where the server's `content_hash` only matches byte-identical
/// files. `NULL` until the daemon has hashed the thumbnail, which it does as
/// thumbnails arrive and when the similar-photo finder asks for the rest.
@@ -26,7 +26,7 @@
use parking_lot::Mutex;
use rusqlite::Connection;
use pdfs_core::{Error, Result};
use crate::{Error, Result};
use std::fs::File;
use std::os::fd::AsRawFd;
use std::path::{Path, PathBuf};
@@ -7,8 +7,8 @@
use rusqlite::params;
use super::Db;
use pdfs_core::mounts::{MountAccess, MountKind, MountMode, MountSpec};
use pdfs_core::{Error, Result};
use crate::mounts::{MountAccess, MountKind, MountMode, MountSpec};
use crate::{Error, Result};
impl Db {
/// Project the configured primary mount into the presentation table.
@@ -8,7 +8,7 @@ use rusqlite::{OptionalExtension, Transaction, params};
use super::Db;
use super::ops::{OP_CREATE, OP_MKDIR, OP_RENAME, local_lid, local_uid, wake_ops_waiting_for_tx};
use pdfs_core::{Access, Result};
use crate::{Access, Result};
use proton_drive_rs::proton_sdk::ids::{LinkId, NodeUid, VolumeId};
use proton_drive_rs::{Node, NodeKind};
@@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize};
use super::Db;
use super::nodes::{adopt_placeholder_row_tx, node_lid};
use pdfs_core::Result;
use crate::Result;
/// The `kind` of a [`PendingOp`] that uploads a staged file as a new revision.
pub const OP_REVISION: &str = "revision";
@@ -8,7 +8,7 @@ use std::collections::{HashMap, HashSet};
use proton_gallery_rs::grouping::{Grouped, group_photos, name_stem};
use super::Db;
use pdfs_core::Result;
use crate::Result;
/// A photo whose thumbnail state is not known yet: it has never been asked for.
pub const THUMB_UNKNOWN: i64 = 0;
@@ -33,7 +33,7 @@ pub struct StoredPhoto {
pub thumb_state: i64,
/// Which Photos-page tab this entry belongs to, derived from its name and
/// media type when the timeline was last replaced.
pub kind: pdfs_core::control::PhotoKind,
pub kind: crate::control::PhotoKind,
/// Whether the photo carries Proton's `Favorite` tag.
pub favorite: bool,
/// How many photos this photo's group holds — one shot taken as RAW+JPEG is
@@ -46,7 +46,7 @@ pub struct StoredPhoto {
pub place_id: Option<u32>,
}
/// A town photos were taken in: its GeoNames id (see [`pdfs_core::places`]), how
/// A town photos were taken in: its GeoNames id (see [`crate::places`]), how
/// many photos it holds, and the newest of them.
#[derive(Clone, Debug, PartialEq)]
pub struct StoredPlace {
@@ -102,7 +102,7 @@ struct Learned {
content_hash: Option<String>,
main_uid: Option<String>,
location: Option<(f64, f64)>,
/// What its thumbnail looks like (see [`pdfs_core::similar`]).
/// What its thumbnail looks like (see [`crate::similar`]).
similar_hash: Option<i64>,
/// When this photo's node was last resolved, kept so a refresh that skips it
/// does not make it look unresolved again.
@@ -143,7 +143,7 @@ fn stored_photo(r: &rusqlite::Row<'_>) -> rusqlite::Result<StoredPhoto> {
name: r.get(2)?,
ratio: r.get(3)?,
thumb_state: r.get(4)?,
kind: pdfs_core::control::PhotoKind::from_i64(r.get(5)?),
kind: crate::control::PhotoKind::from_i64(r.get(5)?),
favorite: r.get::<_, i64>(6)? != 0,
group_size: r.get::<_, i64>(7)?.max(1) as usize,
has_raw: r.get::<_, i64>(8)? != 0,
@@ -324,7 +324,7 @@ impl Db {
resolved_at=?11 WHERE uid=?1",
)?;
for row in rows.iter().filter(|row| row.resolved_at.is_some()) {
let kind = pdfs_core::control::PhotoKind::classify(
let kind = crate::control::PhotoKind::classify(
row.name.as_deref(),
row.media_type.as_deref(),
);
@@ -339,7 +339,7 @@ impl Db {
row.location.map(|p| p.0),
row.location.map(|p| p.1),
row.location
.and_then(|(lat, lon)| pdfs_core::places::nearest(lat, lon))
.and_then(|(lat, lon)| crate::places::nearest(lat, lon))
.map(|city| city.id),
row.resolved_at
])?;
@@ -356,8 +356,8 @@ impl Db {
Ok((
Grouped {
uid: r.get(0)?,
raw: pdfs_core::control::PhotoKind::from_i64(r.get(1)?)
== pdfs_core::control::PhotoKind::Raw,
raw: crate::control::PhotoKind::from_i64(r.get(1)?)
== crate::control::PhotoKind::Raw,
main_uid: r.get(2)?,
day: r.get(3)?,
stem: name_stem(name.as_deref()),
@@ -467,7 +467,7 @@ impl Db {
};
// Everything the insert and the grouping need, resolved once per photo.
let resolved: Vec<(&TimelineRow, Learned, pdfs_core::control::PhotoKind)> = items
let resolved: Vec<(&TimelineRow, Learned, crate::control::PhotoKind)> = items
.iter()
.filter(|row| !tombstones.contains(&row.uid))
.map(|row| {
@@ -502,7 +502,7 @@ impl Db {
// The tab this photo lands in is derived here, once, so a page or
// count query is a plain indexed `WHERE kind = ?` rather than a
// reclassification of every row.
let kind = pdfs_core::control::PhotoKind::classify(
let kind = crate::control::PhotoKind::classify(
carried.name.as_deref(),
carried.media_type.as_deref(),
);
@@ -514,7 +514,7 @@ impl Db {
.iter()
.map(|(row, carried, kind)| Grouped {
uid: row.uid.clone(),
raw: *kind == pdfs_core::control::PhotoKind::Raw,
raw: *kind == crate::control::PhotoKind::Raw,
main_uid: carried.main_uid.clone(),
day: capture_day(&tx, row.capture_time),
stem: name_stem(carried.name.as_deref()),
@@ -553,7 +553,7 @@ impl Db {
carried.location.map(|(_, lon)| lon),
carried
.location
.and_then(|(lat, lon)| pdfs_core::places::nearest(lat, lon))
.and_then(|(lat, lon)| crate::places::nearest(lat, lon))
.map(|city| city.id),
carried.similar_hash,
])?;
@@ -652,7 +652,7 @@ impl Db {
&self,
offset: usize,
limit: usize,
kind: Option<pdfs_core::control::PhotoKind>,
kind: Option<crate::control::PhotoKind>,
range: Option<(i64, i64)>,
favorites: bool,
not_in_album: bool,
@@ -665,7 +665,7 @@ impl Db {
&self,
offset: usize,
limit: usize,
kind: Option<pdfs_core::control::PhotoKind>,
kind: Option<crate::control::PhotoKind>,
range: Option<(i64, i64)>,
favorites: bool,
not_in_album: bool,
@@ -681,7 +681,7 @@ impl Db {
binds.push(excluded.to_owned().into());
conds.push("p.uid NOT IN (SELECT value FROM json_each(?1))".to_owned());
}
if kind != Some(pdfs_core::control::PhotoKind::Raw) {
if kind != Some(crate::control::PhotoKind::Raw) {
conds.push("p.uid = COALESCE(p.group_key, p.uid)".to_string());
}
if let Some(k) = kind {
@@ -780,21 +780,21 @@ impl Db {
/// scopes the counts to one tab when set.
pub fn photos_months(
&self,
kind: Option<pdfs_core::control::PhotoKind>,
kind: Option<crate::control::PhotoKind>,
) -> Result<Vec<(i32, i32, usize)>> {
self.photos_months_visible(kind, "[]")
}
pub fn photos_months_visible(
&self,
kind: Option<pdfs_core::control::PhotoKind>,
kind: Option<crate::control::PhotoKind>,
excluded: &str,
) -> Result<Vec<(i32, i32, usize)>> {
let conn = self.read()?;
// The scrubber has to agree with the page it scrubs, so it counts what
// the page shows: groups everywhere except on the Raw tab.
let filter = match kind {
Some(pdfs_core::control::PhotoKind::Raw) => "kind = ?2",
Some(crate::control::PhotoKind::Raw) => "kind = ?2",
Some(_) => "uid = COALESCE(group_key, uid) AND kind = ?2",
None => "uid = COALESCE(group_key, uid) AND ?2 IS NULL",
};
@@ -1018,7 +1018,7 @@ impl Db {
)?;
stmt.query_map(
params![
pdfs_core::control::PhotoKind::Video.as_i64(),
crate::control::PhotoKind::Video.as_i64(),
THUMB_NONE,
limit as i64
],
@@ -1030,7 +1030,7 @@ impl Db {
}
/// Record the look of photo `uid`: its difference hash, or
/// [`pdfs_core::similar::NO_HASH`] when its thumbnail gave none.
/// [`crate::similar::NO_HASH`] when its thumbnail gave none.
pub fn photo_set_similar_hash(&self, uid: &str, hash: u64) -> Result<()> {
let conn = self.conn.lock();
conn.execute(
@@ -1049,13 +1049,13 @@ impl Db {
GROUP BY COALESCE(group_key, uid) \
HAVING MAX(similar_hash) IS NOT NULL \
OR MAX(kind != ?1 AND thumb_state != ?2))",
params![pdfs_core::control::PhotoKind::Video.as_i64(), THUMB_NONE],
params![crate::control::PhotoKind::Video.as_i64(), THUMB_NONE],
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
Ok((hashed.max(0) as usize, total.max(0) as usize))
}
/// Sets of shots that look alike (see [`pdfs_core::similar`]), one photo per
/// Sets of shots that look alike (see [`crate::similar`]), one photo per
/// shot in capture order, and the sets newest first. A set whose photos
/// are all byte-identical copies is left to [`Self::photo_duplicates`].
pub fn photo_similar(&self) -> Result<Vec<Vec<StoredPhoto>>> {
@@ -1067,13 +1067,13 @@ impl Db {
FROM photos GROUP BY k \
HAVING MAX(similar_hash) IS NOT NULL AND MAX(similar_hash) != ?1",
)?;
stmt.query_map(params![pdfs_core::similar::NO_HASH as i64], |r| {
stmt.query_map(params![crate::similar::NO_HASH as i64], |r| {
Ok((r.get(0)?, r.get::<_, i64>(1)? as u64, r.get(2)?))
})?
.collect::<rusqlite::Result<_>>()?
};
let hashes: Vec<u64> = rows.iter().map(|(_, hash, _)| *hash).collect();
let found: Vec<Vec<usize>> = pdfs_core::similar::sets(&hashes)
let found: Vec<Vec<usize>> = crate::similar::sets(&hashes)
.into_iter()
.filter(|set| {
let first = &rows[set[0]].2;
@@ -1108,7 +1108,7 @@ impl Db {
}
pub fn photos_counts_visible(&self, excluded: &str) -> Result<(usize, usize, usize)> {
use pdfs_core::control::PhotoKind;
use crate::control::PhotoKind;
let conn = self.read()?;
// Photos and Videos count groups — one shot is one entry, however many
// files it was stored as. Raw counts files, because the Raw tab lists
@@ -5,7 +5,7 @@ use rusqlite::{OptionalExtension, params};
use super::Db;
use super::utils::MAX_PATH_DEPTH;
use pdfs_core::Result;
use crate::Result;
/// One row of [`Db::pin_list`]. `recursive` is pin *policy* — whether the whole
/// subtree is kept — while `is_dir` is the node's kind as the node cache knows
@@ -6,7 +6,7 @@ use proton_drive_rs::proton_sdk::ids::{LinkId, NodeUid, VolumeId};
use rusqlite::{OptionalExtension, params};
use super::Db;
use pdfs_core::{Access, Error, Result};
use crate::{Access, Error, Result};
impl Db {
/// Load the complete, deliberately small shared-root authority map.
@@ -4,7 +4,7 @@
use rusqlite::{OptionalExtension, params};
use super::Db;
use pdfs_core::Result;
use crate::Result;
impl Db {
pub fn get_event_cursor(&self) -> Result<Option<String>> {
@@ -4,7 +4,7 @@
use rusqlite::{OptionalExtension, params};
use super::Db;
use pdfs_core::Result;
use crate::Result;
use std::collections::HashMap;
/// What a mirror pass has walked of Drive, saved so a pass cut short
@@ -1,8 +1,8 @@
use super::activity::ACTIVITY_KEEP;
use super::migrations::SCHEMA_VERSION;
use super::*;
use pdfs_core::control::{ActivityEntry, ActivityKind};
use pdfs_core::localindex::LocalEntry;
use crate::control::{ActivityEntry, ActivityKind};
use crate::localindex::LocalEntry;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use proton_drive_rs::{Node, NodeKind};
use serde_json::json;
@@ -157,7 +157,7 @@ fn photos_replace_keeps_what_was_learned_and_drops_what_left() {
// Media type is learned-and-kept like the ratio: p1 keeps the video type
// it was first seen with even though the later refresh carried `None`, so
// it stays classified as a video.
assert_eq!(page[1].kind, pdfs_core::control::PhotoKind::Video);
assert_eq!(page[1].kind, crate::control::PhotoKind::Video);
assert_eq!(db.photos_count().unwrap(), 3);
// The counts break down by tab, and a filtered page returns only its tab.
@@ -166,7 +166,7 @@ fn photos_replace_keeps_what_was_learned_and_drops_what_left() {
.photos_page(
0,
10,
Some(pdfs_core::control::PhotoKind::Video),
Some(crate::control::PhotoKind::Video),
None,
false,
false,
@@ -193,7 +193,7 @@ fn photos_replace_keeps_what_was_learned_and_drops_what_left() {
.photos_page(
0,
10,
Some(pdfs_core::control::PhotoKind::Video),
Some(crate::control::PhotoKind::Video),
Some((150, 350)),
false,
false,
@@ -324,7 +324,7 @@ fn places_group_photos_by_the_nearest_town() {
let summary: Vec<(&str, usize, &str)> = places
.iter()
.map(|place| {
let city = pdfs_core::places::city(place.id).expect("a known town");
let city = crate::places::city(place.id).expect("a known town");
(city.name, place.count, place.cover.uid.as_str())
})
.collect();
@@ -448,7 +448,7 @@ fn similar_photos_group_by_look_and_skip_exact_copies() {
db.photo_set_similar_hash("copy2", !look).unwrap();
db.photo_set_similar_hash("other", look ^ 0xffff_ffff)
.unwrap();
db.photo_set_similar_hash("flat", pdfs_core::similar::NO_HASH)
db.photo_set_similar_hash("flat", crate::similar::NO_HASH)
.unwrap();
let sets = db.photo_similar().unwrap();
@@ -925,7 +925,7 @@ fn shared_root_replacement_tombstones_without_losing_work_or_authority() {
let child = foreign_folder("foreign", "child", shared.uid.clone(), "Secret");
db.upsert_nodes(&[own_root, virtual_root, shared.clone(), child.clone()])
.unwrap();
db.set_share_access(&shared.uid, pdfs_core::Access::Editor)
db.set_share_access(&shared.uid, crate::Access::Editor)
.unwrap();
db.enqueue_op(&PendingOp {
id: 0,
@@ -962,7 +962,7 @@ fn shared_root_replacement_tombstones_without_losing_work_or_authority() {
assert_eq!(db.pending_ops().unwrap().len(), 1);
assert_eq!(
db.share_access(&shared.uid).unwrap(),
Some(pdfs_core::Access::Viewer)
Some(crate::Access::Viewer)
);
let mut reappeared = shared.clone();
@@ -973,7 +973,7 @@ fn shared_root_replacement_tombstones_without_losing_work_or_authority() {
std::slice::from_ref(&shared.uid),
&[PublishedSharedRoot {
node: reappeared,
access: pdfs_core::Access::Viewer,
access: crate::Access::Viewer,
}],
)
.unwrap()
@@ -993,7 +993,7 @@ fn shared_root_replacement_tombstones_without_losing_work_or_authority() {
assert_eq!(db.pending_ops().unwrap().len(), 1);
assert_eq!(
db.share_access(&shared.uid).unwrap(),
Some(pdfs_core::Access::Viewer),
Some(crate::Access::Viewer),
"reappearance stays fail-closed until an observed role refresh"
);
}
@@ -1012,7 +1012,7 @@ fn shared_root_node_and_authority_publication_roll_back_together() {
let shared = foreign_folder("foreign", "share", virtual_uid.clone(), "Before");
db.upsert_nodes(&[own_root, virtual_root, shared.clone()])
.unwrap();
db.set_share_access(&shared.uid, pdfs_core::Access::Viewer)
db.set_share_access(&shared.uid, crate::Access::Viewer)
.unwrap();
db.set_listed(&virtual_uid, false).unwrap();
db.with_conn(|conn| {
@@ -1033,7 +1033,7 @@ fn shared_root_node_and_authority_publication_roll_back_together() {
std::slice::from_ref(&shared.uid),
&[PublishedSharedRoot {
node: changed,
access: pdfs_core::Access::Editor,
access: crate::Access::Editor,
}],
);
assert!(result.is_err());
@@ -1046,7 +1046,7 @@ fn shared_root_node_and_authority_publication_roll_back_together() {
);
assert_eq!(
db.share_access(&shared.uid).unwrap(),
Some(pdfs_core::Access::Viewer)
Some(crate::Access::Viewer)
);
assert!(db.children_if_listed(&virtual_uid).unwrap().is_none());
}
@@ -1065,7 +1065,7 @@ fn accepted_but_unmaterialized_shared_root_keeps_its_snapshot() {
let shared = foreign_folder("foreign", "share", virtual_uid.clone(), "Retained");
db.upsert_nodes(&[own_root, virtual_root, shared.clone()])
.unwrap();
db.set_share_access(&shared.uid, pdfs_core::Access::Editor)
db.set_share_access(&shared.uid, crate::Access::Editor)
.unwrap();
db.enqueue_op(&PendingOp {
id: 0,
@@ -1090,7 +1090,7 @@ fn accepted_but_unmaterialized_shared_root_keeps_its_snapshot() {
assert_eq!(db.pending_ops().unwrap().len(), 1);
assert_eq!(
db.share_access(&shared.uid).unwrap(),
Some(pdfs_core::Access::Viewer),
Some(crate::Access::Viewer),
"an accepted root without verified materialized membership fails closed"
);
}
@@ -1178,7 +1178,7 @@ fn foreign_delete_tombstones_the_subtree_without_losing_pending_work() {
deep.clone(),
])
.unwrap();
db.set_share_access(&deleted.uid, pdfs_core::Access::Editor)
db.set_share_access(&deleted.uid, crate::Access::Editor)
.unwrap();
db.enqueue_op(&PendingOp {
id: 0,
@@ -1205,7 +1205,7 @@ fn foreign_delete_tombstones_the_subtree_without_losing_pending_work() {
assert_eq!(db.pending_ops().unwrap().len(), 1);
assert_eq!(
db.share_access(&deleted.uid).unwrap(),
Some(pdfs_core::Access::Viewer)
Some(crate::Access::Viewer)
);
}
@@ -2027,10 +2027,10 @@ fn share_access_round_trips_updates_and_deletes() {
assert_eq!(db.share_access(&root).unwrap(), None);
for access in [
pdfs_core::Access::Owner,
pdfs_core::Access::Editor,
pdfs_core::Access::Viewer,
pdfs_core::Access::Unknown,
crate::Access::Owner,
crate::Access::Editor,
crate::Access::Viewer,
crate::Access::Unknown,
] {
db.set_share_access(&root, access).unwrap();
assert_eq!(db.share_access(&root).unwrap(), Some(access));
@@ -2051,16 +2051,16 @@ fn effective_node_access_inherits_from_the_persisted_share_root() {
.unwrap();
db.upsert_node(&file("child", "nested", "child.txt", 1))
.unwrap();
db.set_share_access(&uid("shared"), pdfs_core::Access::Viewer)
db.set_share_access(&uid("shared"), crate::Access::Viewer)
.unwrap();
assert_eq!(
db.effective_node_access(&uid("child")).unwrap(),
Some(pdfs_core::Access::Viewer)
Some(crate::Access::Viewer)
);
assert_eq!(
db.effective_node_access(&uid("root")).unwrap(),
Some(pdfs_core::Access::Owner)
Some(crate::Access::Owner)
);
assert_eq!(db.effective_node_access(&uid("missing")).unwrap(), None);
}
@@ -2075,14 +2075,14 @@ fn effective_node_access_uses_the_nearest_nested_share_root() {
.unwrap();
db.upsert_node(&file("child", "inner", "child.txt", 1))
.unwrap();
db.set_share_access(&uid("outer"), pdfs_core::Access::Editor)
db.set_share_access(&uid("outer"), crate::Access::Editor)
.unwrap();
db.set_share_access(&uid("inner"), pdfs_core::Access::Viewer)
db.set_share_access(&uid("inner"), crate::Access::Viewer)
.unwrap();
assert_eq!(
db.effective_node_access(&uid("child")).unwrap(),
Some(pdfs_core::Access::Viewer)
Some(crate::Access::Viewer)
);
}
@@ -2096,13 +2096,13 @@ fn effective_node_access_keeps_a_missing_share_root_tombstone_authoritative() {
.unwrap();
db.upsert_node(&file("child", "nested", "child.txt", 1))
.unwrap();
db.set_share_access(&uid("shared"), pdfs_core::Access::Viewer)
db.set_share_access(&uid("shared"), crate::Access::Viewer)
.unwrap();
db.delete_node(&uid("shared")).unwrap();
assert_eq!(
db.effective_node_access(&uid("child")).unwrap(),
Some(pdfs_core::Access::Viewer)
Some(crate::Access::Viewer)
);
}
@@ -2112,17 +2112,17 @@ fn downgrade_all_share_access_leaves_unrecorded_owned_nodes_owned() {
db.upsert_node(&folder("root", None, "My Files")).unwrap();
db.upsert_node(&folder("shared", Some("root"), "Shared"))
.unwrap();
db.set_share_access(&uid("shared"), pdfs_core::Access::Editor)
db.set_share_access(&uid("shared"), crate::Access::Editor)
.unwrap();
assert_eq!(db.downgrade_all_share_access().unwrap(), 1);
assert_eq!(
db.effective_node_access(&uid("shared")).unwrap(),
Some(pdfs_core::Access::Viewer)
Some(crate::Access::Viewer)
);
assert_eq!(
db.effective_node_access(&uid("root")).unwrap(),
Some(pdfs_core::Access::Owner)
Some(crate::Access::Owner)
);
}
@@ -2168,12 +2168,8 @@ fn migration_v17_adds_share_access_to_a_v16_fixture() {
Some("survives")
);
let root = uid("offline-share");
db.set_share_access(&root, pdfs_core::Access::Viewer)
.unwrap();
assert_eq!(
db.share_access(&root).unwrap(),
Some(pdfs_core::Access::Viewer)
);
db.set_share_access(&root, crate::Access::Viewer).unwrap();
assert_eq!(db.share_access(&root).unwrap(), Some(crate::Access::Viewer));
// Migrating an old fixture always lands on head, whatever head is today.
assert_eq!(
db.state_str("schema_version").unwrap().as_deref(),
@@ -2255,12 +2251,12 @@ fn migration_v18_projects_v17_sync_folders_and_cascades_deletes() {
let projected = &locations[0];
assert!(matches!(
projected.kind,
pdfs_core::mounts::MountKind::Device {
crate::mounts::MountKind::Device {
sync_folder_id
} if sync_folder_id == existing
));
assert_eq!(projected.local_path, "/home/me/Existing");
assert_eq!(projected.mode, pdfs_core::mounts::MountMode::OnDemand);
assert_eq!(projected.mode, crate::mounts::MountMode::OnDemand);
assert_eq!(projected.state, "syncing");
assert_eq!(projected.last_sync, 123);
assert_eq!(
@@ -2307,7 +2303,7 @@ fn my_files_projection_retains_share_id_only_for_the_same_root() {
assert_eq!(locations.len(), 1);
assert!(matches!(
locations[0].kind,
pdfs_core::mounts::MountKind::MyFiles
crate::mounts::MountKind::MyFiles
));
assert_eq!(locations[0].local_path, "/mnt/proton");
assert_eq!(locations[0].root_uid, "vol~root-new");
@@ -3704,7 +3700,7 @@ fn a_stand_in_keeps_its_access_once_its_create_has_landed() {
.unwrap();
assert_eq!(
db.effective_node_access(&stand_in).unwrap(),
Some(pdfs_core::Access::Owner)
Some(crate::Access::Owner)
);
db.claim_next_due_op(1).unwrap().unwrap();
db.finish_create(
@@ -3718,11 +3714,11 @@ fn a_stand_in_keeps_its_access_once_its_create_has_landed() {
// The tree still names the file by its stand-in for a moment.
assert_eq!(
db.effective_node_access(&stand_in).unwrap(),
Some(pdfs_core::Access::Owner)
Some(crate::Access::Owner)
);
assert_eq!(
db.effective_node_access(&uid("real")).unwrap(),
Some(pdfs_core::Access::Owner)
Some(crate::Access::Owner)
);
}
@@ -3912,7 +3908,7 @@ fn a_landed_folder_keeps_a_row_until_the_server_copy_replaces_it() {
assert_eq!(landed.name, "New folder");
assert_eq!(
db.effective_node_access(&uid("child")).unwrap(),
Some(pdfs_core::Access::Owner),
Some(crate::Access::Owner),
"the child's authority resolves without a network re-read"
);
let names: Vec<_> = db
@@ -4514,7 +4510,7 @@ fn a_node_keeps_its_lid_across_updates_and_a_new_one_never_reuses_it() {
fn a_lid_handed_out_before_the_node_is_stored_reads_as_no_node() {
let db = Db::open_in_memory().unwrap();
db.upsert_node(&folder("root", None, "My Files")).unwrap();
db.set_share_access(&uid("root"), pdfs_core::Access::Owner)
db.set_share_access(&uid("root"), crate::Access::Owner)
.unwrap();
let stub = file("stub", "root", "stub.txt", 1);
let [lid] = db.lids_for(&[&stub]).unwrap()[..] else {
@@ -6421,7 +6417,7 @@ fn album_photos_replace_keeps_what_was_learned() {
assert_eq!(page[2].thumb_state, THUMB_NONE);
// The media type is learned-and-kept, so p1 stays classified as a video even
// though the second refresh carried none.
assert_eq!(page[1].kind, pdfs_core::control::PhotoKind::Video);
assert_eq!(page[1].kind, crate::control::PhotoKind::Video);
assert_eq!(page[0].thumb_state, THUMB_UNKNOWN);
// Paging is relative to the album, and the shared flag round-trips.
@@ -7201,7 +7197,7 @@ fn a_raw_and_its_jpeg_are_one_entry_in_the_grid() {
.photos_page(
0,
10,
Some(pdfs_core::control::PhotoKind::Raw),
Some(crate::control::PhotoKind::Raw),
None,
false,
false,
@@ -7861,7 +7857,7 @@ fn a_queued_op_stops_existing_once_the_node_is_deleted() {
#[test]
fn attachments_have_their_own_location_and_cannot_evict_local_files() {
use pdfs_core::mounts::MountKind;
use crate::mounts::MountKind;
let db = Db::open_in_memory().unwrap();
let id = db
.sync_folder_attach("/work", "vol~work", "myfiles-share")
@@ -5,7 +5,7 @@ use std::collections::{HashMap, HashSet};
use rusqlite::params;
use super::Db;
use pdfs_core::Result;
use crate::Result;
pub struct StoredTrash {
pub uid: String,
@@ -2,7 +2,7 @@
use rusqlite::{Connection, OptionalExtension, params};
use pdfs_core::Result;
use crate::Result;
/// Below this length the trigram tokenizer indexes nothing (it needs 3-char
/// grams), so short queries fall back to a `LIKE` scan over `nodes.name`.
+2
View File
@@ -5,8 +5,10 @@
pub mod access;
pub mod auth;
pub mod batch;
pub mod cache;
pub mod config;
pub mod control;
pub mod db;
pub mod error;
pub mod kernelkey;
pub mod keycheck;
+1 -1
View File
@@ -4,7 +4,7 @@
//! side. Drive names come from the `nodes` FTS index; local names come from the
//! `local_files` index this module feeds. The daemon runs [`scan`] on a
//! background thread — never on a FUSE or control-socket thread — and streams
//! batches into `pdfs_store::db::Db::local_upsert_batch`.
//! batches into [`crate::db::Db::local_upsert_batch`].
//!
//! Walking is deliberately shallow on cost: we stat each entry once (the walker
//! already has the `DirEntry` metadata) and skip the directories that dominate a
+1 -1
View File
@@ -526,7 +526,7 @@ mod tests {
use super::*;
/// A unique temp directory removed on drop; avoids a dev-dependency, as in
/// `pdfs_store::cache`'s tests.
/// [`crate::cache`]'s tests.
struct TempDir(std::path::PathBuf);
impl TempDir {
fn new() -> Self {
-28
View File
@@ -1,28 +0,0 @@
[package]
name = "pdfs-drive"
version.workspace = true
edition.workspace = true
license.workspace = true
authors.workspace = true
rust-version.workspace = true
repository.workspace = true
homepage.workspace = true
description = "The Proton Drive calls the Linux client makes, behind a trait"
[features]
# FakeDrive and the simulation RNG, for tests in this and other crates.
sim = ["dep:parking_lot", "dep:sha1", "dep:tokio", "dep:pdfs-store"]
[dependencies]
pdfs-core.workspace = true
proton-drive-rs.workspace = true
tracing.workspace = true
pdfs-store = { workspace = true, optional = true }
async-trait.workspace = true
futures.workspace = true
parking_lot = { workspace = true, optional = true }
sha1 = { workspace = true, optional = true }
tokio = { workspace = true, optional = true }
[dev-dependencies]
tokio.workspace = true
-6
View File
@@ -1,6 +0,0 @@
//! What the simulation tests need from Drive: [`fake_drive::FakeDrive`], an
//! in-memory Drive that injects Drive's known faults, and the seeded
//! [`rng::Rng`] that makes a run replayable.
pub mod fake_drive;
pub mod rng;
-4
View File
@@ -11,9 +11,6 @@ description = "FUSE on-demand filesystem for Proton Drive"
[dependencies]
pdfs-core.workspace = true
pdfs-drive.workspace = true
pdfs-sync.workspace = true
pdfs-store.workspace = true
zip.workspace = true
sha1.workspace = true
proton-drive-rs.workspace = true
@@ -41,6 +38,5 @@ notify = "8"
parking_lot.workspace = true
[dev-dependencies]
pdfs-drive = { workspace = true, features = ["sim"] }
tracing-subscriber.workspace = true
tokio = { workspace = true, features = ["test-util"] }
+1 -1
View File
@@ -16,8 +16,8 @@ use std::collections::HashSet;
use std::sync::atomic::Ordering;
use pdfs_core::control::{AlbumInfo, PhotoItem, Topic};
use pdfs_core::db::StoredAlbum;
use pdfs_core::{CoreError, CoreResult};
use pdfs_store::db::StoredAlbum;
use proton_drive_rs::NodeKind;
use proton_drive_rs::proton_sdk::ids::NodeUid;
+1 -1
View File
@@ -4,8 +4,8 @@
//! The existing three-way engine performs the initial, non-destructive union.
use super::{Core, parse_uid, sync};
use pdfs_core::db::StoredSyncFolder;
use pdfs_core::{CoreError, CoreResult};
use pdfs_store::db::StoredSyncFolder;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use std::collections::HashSet;
use std::path::{Component, Path, PathBuf};
+2 -2
View File
@@ -17,10 +17,10 @@ use pdfs_core::control::{
ActivityKind, DeviceInfo, JobItem, MountKind, MountSpec, SyncFolderInfo, SyncPhase,
SyncProgress,
};
use pdfs_core::db::{StoredDevice, StoredSyncFolder};
use pdfs_core::mounts::MountMode;
use pdfs_core::profile::PROFILE_DIR_NAME;
use pdfs_core::{CoreError, CoreResult};
use pdfs_store::db::{StoredDevice, StoredSyncFolder};
use proton_drive_rs::proton_sdk::ids::{DeviceUid, NodeUid};
use proton_drive_rs::{DeviceType, Node};
use std::sync::OnceLock;
@@ -1346,7 +1346,7 @@ impl Core {
#[cfg(test)]
mod tests {
use pdfs_store::db::StoredSyncFolder;
use pdfs_core::db::StoredSyncFolder;
use super::{
ApplicableMountMode, commit_after_teardown, migrated_name, pending_intent_matches,
+8 -8
View File
@@ -30,9 +30,9 @@ use std::time::{Duration, Instant};
use parking_lot::Mutex;
use pdfs_core::batch;
use pdfs_core::cache::{Baseline, StagedWrite};
use pdfs_core::control::{ActivityKind, SyncIssue, TransferDirection};
use pdfs_store::cache::{Baseline, StagedWrite};
use pdfs_store::db::{
use pdfs_core::db::{
CreateLanding, CreateRetired, OP_CREATE, OP_MKDIR, OP_RENAME, OP_REVISION, OP_TRASH,
PARK_EXPIRY_MS, PendingOp, RenameMeta,
};
@@ -93,8 +93,8 @@ const DRAIN_ACCESS_RECHECK: Duration = Duration::from_secs(5);
/// recheck records a failure, so the op enters the ordinary backoff and, at
/// [`FAILING_ATTEMPTS`], is counted and named by `Response::Status`.
///
/// [`Db::effective_node_access`]: pdfs_store::db::Db::effective_node_access
/// [`FAILING_ATTEMPTS`]: pdfs_store::db::FAILING_ATTEMPTS
/// [`Db::effective_node_access`]: pdfs_core::db::Db::effective_node_access
/// [`FAILING_ATTEMPTS`]: pdfs_core::db::FAILING_ATTEMPTS
const DRAIN_ACCESS_DEFER_LIMIT: Duration = Duration::from_secs(300);
/// A registered cancellation flag for one in-flight upload, deregistered when
@@ -315,7 +315,7 @@ impl Core {
/// worker would just multiply them.
///
/// [`DRAIN_WORKERS`]: super::DRAIN_WORKERS
/// [`Db::claim_next_due_op`]: pdfs_store::db::Db::claim_next_due_op
/// [`Db::claim_next_due_op`]: pdfs_core::db::Db::claim_next_due_op
pub(crate) fn run_pending_drain(&self, primary: bool) {
loop {
// Between ops, never inside one: an op that has started is either
@@ -476,8 +476,8 @@ impl Core {
/// where they are either way; this changes only whether the user can see
/// them.
///
/// [`Db::record_op_failure`]: pdfs_store::db::Db::record_op_failure
/// [`FAILING_ATTEMPTS`]: pdfs_store::db::FAILING_ATTEMPTS
/// [`Db::record_op_failure`]: pdfs_core::db::Db::record_op_failure
/// [`FAILING_ATTEMPTS`]: pdfs_core::db::FAILING_ATTEMPTS
fn defer_for_access(&self, op: &PendingOp, reason: AccessDeferral) {
let now = now_millis();
let next_attempt_at = now + DRAIN_ACCESS_RECHECK.as_millis() as i64;
@@ -2968,7 +2968,7 @@ mod tests {
use super::*;
use crate::state::WriteHandle;
use pdfs_core::Access;
use pdfs_store::db::Db;
use pdfs_core::db::Db;
use proton_drive_rs::NodeKind;
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
use std::cell::Cell;
@@ -25,23 +25,22 @@ use async_trait::async_trait;
use futures::StreamExt as _;
use futures::stream::BoxStream;
use proton_drive_rs::proton_sdk::account::Quota;
use proton_drive_rs::proton_sdk::api::ResponseCode;
use proton_drive_rs::proton_sdk::error::{ProtonError, Result};
use proton_drive_rs::proton_sdk::error::Result;
use proton_drive_rs::proton_sdk::ids::{DriveEventId, NodeUid, ShareId};
use proton_drive_rs::{
AvailableNameTarget, Device, DeviceType, DriveEvent, DriveEventScopeId, Node, NodeKind,
NodeMoveItem, ProtonDriveClient, RevisionReader, Thumbnail, ThumbnailType, TrashedNode,
AvailableNameTarget, Device, DeviceType, DriveEvent, DriveEventScopeId, Node, NodeMoveItem,
ProtonDriveClient, RevisionReader, Thumbnail, ThumbnailType, TrashedNode,
};
/// One outcome per node of a batch request; see [`ProtonDriveClient::trash_nodes`].
pub type NodeOutcomes = Vec<(NodeUid, Result<()>)>;
pub(crate) type NodeOutcomes = Vec<(NodeUid, Result<()>)>;
/// The outcomes of a streaming batch request, one item per node as it lands.
pub type OutcomeStream<'a> = BoxStream<'a, Result<(NodeUid, Result<()>)>>;
pub(crate) type OutcomeStream<'a> = BoxStream<'a, Result<(NodeUid, Result<()>)>>;
/// Drive as the sync core sees it. See the module documentation.
#[async_trait]
pub trait DriveApi: Send + Sync {
pub(crate) trait DriveApi: Send + Sync {
async fn get_my_files_folder(&self) -> Result<Node>;
async fn context_share_id(&self, uid: &NodeUid) -> Result<ShareId>;
@@ -211,13 +210,14 @@ pub trait DriveApi: Send + Sync {
/// `uid` that landed, or retired the create that made `uid`, before the
/// tree has the node, so a simulation can hold it there. Blocks the drain
/// worker it is called on.
#[cfg(test)]
fn landing(&self, _uid: &NodeUid) {}
}
/// The generic signatures of the client, over the object-safe ones above.
impl dyn DriveApi {
#[allow(clippy::too_many_arguments)]
pub async fn upload_file_from<R: Read + Send>(
pub(crate) async fn upload_file_from<R: Read + Send>(
&self,
parent_uid: &NodeUid,
name: &str,
@@ -242,7 +242,7 @@ impl dyn DriveApi {
}
#[allow(clippy::too_many_arguments)]
pub async fn upload_file_replacing_draft_from<R: Read + Send>(
pub(crate) async fn upload_file_replacing_draft_from<R: Read + Send>(
&self,
parent_uid: &NodeUid,
name: &str,
@@ -266,7 +266,7 @@ impl dyn DriveApi {
.await
}
pub async fn upload_new_revision_from<R: Read + Send>(
pub(crate) async fn upload_new_revision_from<R: Read + Send>(
&self,
file_uid: &NodeUid,
mut reader: R,
@@ -284,7 +284,7 @@ impl dyn DriveApi {
.await
}
pub async fn download_file_to<W: Write + Send>(
pub(crate) async fn download_file_to<W: Write + Send>(
&self,
uid: &NodeUid,
output: &mut W,
@@ -292,7 +292,7 @@ impl dyn DriveApi {
self.download_file_to_dyn(uid, output).await
}
pub async fn download_revision_to<W: Write + Send>(
pub(crate) async fn download_revision_to<W: Write + Send>(
&self,
file_uid: &NodeUid,
revision_id: &str,
@@ -305,7 +305,7 @@ impl dyn DriveApi {
/// An open revision that block reads are served from; see [`RevisionReader`].
#[async_trait]
pub trait RevisionRead: Send + Sync {
pub(crate) trait RevisionRead: Send + Sync {
/// Plaintext size of the revision.
fn size(&self) -> u64;
@@ -575,38 +575,3 @@ impl DriveApi for ProtonDriveClient {
ProtonDriveClient::create_device(self, name, device_type).await
}
}
/// Whether a failed call failed because Proton could not be reached, rather
/// than because it answered and refused.
///
/// A transport error is the network. So is a request timeout: the SDK reports
/// Proton's own "try again" codes that way, and the daemon's `no_answer` reports its
/// deadline that way. Anything else Proton actually said, and says again on a
/// retry, so it must reach the caller rather than be queued.
pub fn is_network_error(e: &ProtonError) -> bool {
match e {
ProtonError::Transport(_) => true,
ProtonError::Api(api) => {
matches!(
api.code,
ResponseCode::RequestTimeout | ResponseCode::Timeout
)
}
_ => false,
}
}
/// The server revision id of a node's active revision, if it is a file that has
/// one. The stable identity the drain conflict-checks against (see `Baseline` in pdfs-store).
pub fn node_revision_id(node: &Node) -> Option<String> {
match &node.kind {
NodeKind::Folder => None,
NodeKind::File {
active_revision_id, ..
} => active_revision_id.clone(),
}
}
/// An in-memory Drive and the seeded randomness the simulations share.
#[cfg(feature = "sim")]
pub mod sim;
+1 -1
View File
@@ -15,7 +15,7 @@
use std::process::{Child, Command, Stdio};
use std::time::Duration;
use pdfs_store::db::PendingCounts;
use pdfs_core::db::PendingCounts;
use tracing::{debug, warn};
use super::Core;
+100 -21
View File
@@ -55,23 +55,21 @@ use fuser::{
};
use futures::StreamExt as _;
use pdfs_core::batch;
use pdfs_core::cache::{BLOCK_SIZE, Baseline, BlockGeometry, BlockSpan, ContentCache, StagedWrite};
use pdfs_core::config::{AppDirs, SweepMode};
use pdfs_core::control::{
ActivityEntry, ActivityKind, DirEntry, ErrorKind, LocalHit, PhotoKind, PublicLinkInfo,
SearchFilters, SearchHit, SearchSource, SyncFolderInfo, SyncIssue, SyncPhase, SyncProgress,
ThumbnailBuildStatus, Topic, TransferDirection,
};
use pdfs_core::db::{
Db, LOCAL_VOLUME, OP_CREATE, OP_MKDIR, OP_RENAME, OP_REVISION, OP_TRASH, PARK_UNTIL, PendingOp,
PublishedSharedRoot, RenameMeta, StoredNode, StoredSyncFolder, StoredTrash,
};
use pdfs_core::localindex;
use pdfs_core::search::relevance_score;
use pdfs_core::syncignore::is_transient_name;
use pdfs_core::{Access, CoreError, CoreResult, access_for, perm_bits};
use pdfs_store::cache::{
BLOCK_SIZE, Baseline, BlockGeometry, BlockSpan, ContentCache, StagedWrite,
};
use pdfs_store::db::{
Db, LOCAL_VOLUME, OP_CREATE, OP_MKDIR, OP_RENAME, OP_REVISION, OP_TRASH, PARK_UNTIL, PendingOp,
PublishedSharedRoot, RenameMeta, StoredNode, StoredSyncFolder, StoredTrash,
};
use proton_drive_rs::proton_sdk::api::ResponseCode;
use proton_drive_rs::proton_sdk::error::ProtonError;
use proton_drive_rs::proton_sdk::ids::{DriveEventId, LinkId, NodeUid, ShareId, VolumeId};
@@ -89,12 +87,8 @@ use control::run_control_socket;
mod devices;
mod diagnostics;
mod drain;
mod drive;
use drive::{DriveApi, RevisionRead};
use pdfs_drive as drive;
use pdfs_drive::node_revision_id;
#[cfg(test)]
use pdfs_sync::naming::{conflict_label, conflict_label_of, conflict_name_as};
use pdfs_sync::naming::{conflict_name, this_hostname};
mod events;
mod filesystem;
mod gallery;
@@ -3356,7 +3350,7 @@ impl Core {
/// [`Core::landed_row_uid`] for a node known by its stand-in `uid`.
pub(crate) fn landed_stand_in_uid(&self, uid: &NodeUid) -> Option<NodeUid> {
pdfs_store::db::local_lid(&uid.to_string()).and_then(|lid| self.landed_lid_uid(lid))
pdfs_core::db::local_lid(&uid.to_string()).and_then(|lid| self.landed_lid_uid(lid))
}
fn landed_lid_uid(&self, lid: i64) -> Option<NodeUid> {
@@ -4688,7 +4682,7 @@ impl Core {
/// Every pin, with `cached` saying whether a pinned file's content is on
/// disk, so a front-end listing pins can badge them without a round-trip
/// per file.
fn list_pins(&self) -> Vec<pdfs_core::control::Pin> {
fn list_pins(&self) -> Vec<pdfs_core::cache::Pin> {
let mut pins = self.cache.list_pins();
for pin in pins.iter_mut().filter(|pin| pin.is_dir == Some(false)) {
if let Ok(Some(node)) = self.db.node_by_uid(&pin.uid) {
@@ -6416,7 +6410,7 @@ fn parse_node_uid(s: &str) -> Option<NodeUid> {
/// The uid a node made on this machine goes by until it lands, so it can be
/// interned, listed and written to before the server has ever heard of it:
/// its row's local id, as [`pdfs_store::db::local_uid`]
/// its row's local id, as [`pdfs_core::db::local_uid`]
/// has it.
fn local_node_uid(lid: i64) -> NodeUid {
NodeUid::new(VolumeId::from(LOCAL_VOLUME), LinkId::from(lid.to_string()))
@@ -6507,6 +6501,70 @@ fn is_gone(e: &(dyn std::error::Error + 'static)) -> bool {
api_code(e) == Some(ResponseCode::DoesNotExist)
}
/// A variant of `name` to fall back on when the remote already has that name.
///
/// Deliberately the same shape the sync engine uses for its conflict copies
/// (`sync.rs`, `conflict_path`), so the two halves of the product name the same
/// situation the same way and a user only has to learn it once.
fn conflict_name(name: &str, stamp: i64) -> String {
conflict_name_as(name, conflict_label(), stamp)
}
/// [`conflict_name`] with the machine's label given.
fn conflict_name_as(name: &str, label: &str, stamp: i64) -> String {
let path = Path::new(name);
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or(name);
let tag = conflict_tag(label, stamp, 0);
match path.extension().and_then(|s| s.to_str()) {
Some(ext) => format!("{stem} (sync-conflict {tag}).{ext}"),
None => format!("{stem} (sync-conflict {tag})"),
}
}
/// This machine's name as its conflict copies carry it (`docs/BUGS.md` B251).
///
/// Two computers syncing one folder that each keep a copy of the same file in
/// the same second would otherwise make the same name on Drive, and nobody
/// could tell which computer a copy came from. Read once, from the hostname.
fn conflict_label() -> &'static str {
static LABEL: OnceLock<String> = OnceLock::new();
LABEL.get_or_init(|| conflict_label_of(&this_hostname()))
}
/// `host` as one token: anything but ASCII letters, digits, `-`, `_` and `.`
/// becomes `-`, so the label holds no space for `conflict_base_name` to trip
/// on and no `/` or `)` to break the name.
fn conflict_label_of(host: &str) -> String {
let label: String = host
.chars()
.take(32)
.map(|c| {
if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {
c
} else {
'-'
}
})
.collect();
label.trim_matches('-').to_string()
}
/// The inside of a conflict copy's marker: `<label> <stamp>`, with `-<n>`
/// when an earlier copy already holds that name. Without a label it is the
/// bare stamp that copies had before B251.
fn conflict_tag(label: &str, stamp: i64, suffix: u32) -> String {
let suffix = if suffix == 0 {
String::new()
} else {
format!("-{suffix}")
};
if label.is_empty() {
format!("{stamp}{suffix}")
} else {
format!("{label} {stamp}{suffix}")
}
}
/// Fabricate the node the server would have returned, for a `create`/`mkdir`
/// that could not reach it. Everything the kernel asks about a fresh node —
/// name, kind, size, times — is knowable locally; the uid is the only invention,
@@ -6548,6 +6606,16 @@ fn local_node(uid: NodeUid, parent_uid: NodeUid, name: String, is_dir: bool) ->
}
}
/// This machine's hostname, used to name (and later recover) its Proton Drive
/// Device. Reads the live kernel hostname, falling back to a generic label.
fn this_hostname() -> String {
std::fs::read_to_string("/proc/sys/kernel/hostname")
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "Linux device".to_string())
}
/// Whether `dir` has no entries.
fn dir_is_empty(dir: &Path) -> std::io::Result<bool> {
Ok(std::fs::read_dir(dir)?.next().is_none())
@@ -7059,6 +7127,17 @@ fn expand_restore(
waves
}
/// The server revision id of a node's active revision, if it is a file that has
/// one. The stable identity the drain conflict-checks against (see [`Baseline`]).
fn node_revision_id(node: &Node) -> Option<String> {
match &node.kind {
NodeKind::Folder => None,
NodeKind::File {
active_revision_id, ..
} => active_revision_id.clone(),
}
}
/// The plaintext content SHA-1 of a file node, if its active revision carried one.
/// A download-free content fingerprint the conflict sweep uses to prove two files
/// hold identical bytes before it removes one.
@@ -7238,7 +7317,7 @@ fn unix_secs(secs: i64) -> SystemTime {
#[cfg(test)]
mod merge_over_pending_tests {
use super::{PendingRevision, merge_over_pending};
use pdfs_store::cache::{Baseline, StagedWrite};
use pdfs_core::cache::{Baseline, StagedWrite};
use std::io::Write as _;
use std::path::PathBuf;
@@ -7743,13 +7822,13 @@ mod local_uid_tests {
let uid = local_node_uid(42);
assert!(is_local_uid(&uid));
assert!(is_local_uid_str(&uid.to_string()));
assert_eq!(uid.to_string(), pdfs_store::db::local_uid(42));
assert_eq!(uid.to_string(), pdfs_core::db::local_uid(42));
// It has to survive the trip through `pending_op.uid` as text, like any
// other uid does, and give back the row it stands for.
let parsed = parse_node_uid(&uid.to_string()).expect("parses back");
assert_eq!(parsed, uid);
assert_eq!(pdfs_store::db::local_lid(&uid.to_string()), Some(42));
assert_eq!(pdfs_core::db::local_lid(&uid.to_string()), Some(42));
}
#[test]
@@ -8071,8 +8150,8 @@ mod tests {
}
}
use crate::filesystem::access_allowed;
use pdfs_store::cache::{Baseline, StagedWrite};
use pdfs_store::db::{OP_REVISION, OP_TRASH, PendingOp};
use pdfs_core::cache::{Baseline, StagedWrite};
use pdfs_core::db::{OP_REVISION, OP_TRASH, PendingOp};
fn session_flag(live: bool) -> std::sync::Arc<std::sync::atomic::AtomicBool> {
std::sync::Arc::new(std::sync::atomic::AtomicBool::new(live))
@@ -9885,7 +9964,7 @@ mod tests {
N.fetch_add(1, Ordering::Relaxed)
));
std::fs::create_dir_all(&dir_path).unwrap();
let db = pdfs_store::db::Db::open(&dir_path.join("cache.db")).unwrap();
let db = pdfs_core::db::Db::open(&dir_path.join("cache.db")).unwrap();
let share_access = db.all_share_access().unwrap();
let st = crate::state::State::new(std::sync::Arc::new(db), share_access);
(st, TestDir(dir_path))
+19 -1
View File
@@ -84,7 +84,25 @@ impl Link {
}
}
pub(crate) use pdfs_drive::is_network_error;
/// Whether a failed call failed because Proton could not be reached, rather
/// than because it answered and refused.
///
/// A transport error is the network. So is a request timeout: the SDK reports
/// Proton's own "try again" codes that way, and [`no_answer`] reports our
/// deadline that way. Anything else Proton actually said, and says again on a
/// retry, so it must reach the caller rather than be queued.
pub(crate) fn is_network_error(e: &ProtonError) -> bool {
match e {
ProtonError::Transport(_) => true,
ProtonError::Api(api) => {
matches!(
api.code,
ResponseCode::RequestTimeout | ResponseCode::Timeout
)
}
_ => false,
}
}
/// The error a call reports when it runs past `after` without an answer.
pub(crate) fn no_answer(after: Duration) -> ProtonError {
+2 -2
View File
@@ -1,7 +1,7 @@
//! The photos timeline and its thumbnails.
//!
//! The timeline is a flat, newest-first projection of the photo share, persisted
//! by [`pdfs_store::db`] so the gallery opens instantly and refreshes behind the
//! by [`pdfs_core::db`] so the gallery opens instantly and refreshes behind the
//! user. Thumbnails the server has none for (anything a camera wrote rather than
//! a phone) are generated locally and stored as if the server had served them.
@@ -22,8 +22,8 @@ use pdfs_core::control::{
ThumbnailBuildStatus, Topic, is_audio_file_name, is_raw_image_name, is_thumbnail_image_name,
is_thumbnail_media_name,
};
use pdfs_core::db::{self, StoredPhoto};
use pdfs_core::{CoreError, CoreResult};
use pdfs_store::db::{self, StoredPhoto};
use proton_drive_rs::proton_sdk::error::Result as DriveResult;
use proton_drive_rs::proton_sdk::ids::NodeUid;
+2 -2
View File
@@ -479,7 +479,7 @@ impl Core {
}
/// Only device backups belong in the device's cross-machine profile.
fn profile_folders(folders: Vec<pdfs_store::db::StoredSyncFolder>) -> Vec<ProfileFolder> {
fn profile_folders(folders: Vec<pdfs_core::db::StoredSyncFolder>) -> Vec<ProfileFolder> {
folders
.into_iter()
.filter(|f| f.kind == "device")
@@ -556,7 +556,7 @@ mod tests {
#[test]
fn attached_my_files_folders_are_not_in_the_device_profile() {
let dir = crate::sim::daemon::scratch("profile-folder-kinds");
let db = pdfs_store::db::Db::open(&dir.join("cache.db")).unwrap();
let db = pdfs_core::db::Db::open(&dir.join("cache.db")).unwrap();
db.sync_folder_add("/backup", "vol~backup", "device-share")
.unwrap();
db.sync_folder_attach("/work", "vol~work", "my-files-share")
+1 -1
View File
@@ -11,7 +11,7 @@ use super::*;
use std::io::Write;
use pdfs_core::control::{PendingOpInfo, SyncIssue};
use pdfs_store::db::{FAILING_ATTEMPTS, PARK_UNTIL};
use pdfs_core::db::{FAILING_ATTEMPTS, PARK_UNTIL};
impl Core {
/// Every queued op, oldest first, with a path a person can read.
+1 -1
View File
@@ -19,8 +19,8 @@ use std::sync::Arc;
use std::time::Duration;
use parking_lot::Mutex;
use pdfs_core::db::{StoredSyncEntry, StoredSyncFolder};
use pdfs_core::{CoreError, CoreResult};
use pdfs_store::db::{StoredSyncEntry, StoredSyncFolder};
use proton_drive_rs::NodeKind;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use tracing::{info, warn};
+143 -2
View File
@@ -13,10 +13,10 @@ use std::sync::mpsc::SyncSender;
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use pdfs_core::cache::ContentCache;
use pdfs_core::config::AppConfig;
use pdfs_core::control::{self, PendingOpInfo, Request, Response};
use pdfs_store::cache::ContentCache;
use pdfs_store::db::Db;
use pdfs_core::db::Db;
use proton_drive_rs::ProtonDriveClient;
use proton_drive_rs::proton_sdk::config::ProtonClientConfiguration;
use proton_drive_rs::proton_sdk::session::{PasswordMode, ProtonApiSession, ResumeParameters};
@@ -30,6 +30,16 @@ const MOUNT_DEADLINE: Duration = Duration::from_secs(20);
/// How long a restart may wait for the last run to let go of its database.
const LAST_RUN_DEADLINE: Duration = Duration::from_secs(30);
/// How long a stop may wait for the mount to end before it aborts the FUSE
/// connection. A mount that stops answering otherwise hangs the test, and the
/// whole run with it (`docs/BUGS.md` B297).
const STOP_DEADLINE: Duration = Duration::from_secs(60);
/// How long one daemon may live. Past this, its FUSE connection is aborted, so
/// a test blocked on a request the mount never answers fails with `ENOTCONN`
/// instead of hanging the run. The whole suite takes about 15 minutes in CI.
const LIFETIME_LIMIT: Duration = Duration::from_secs(20 * 60);
pub(crate) struct Daemon {
pub(crate) client: FakeClient,
pub(crate) mountpoint: PathBuf,
@@ -38,6 +48,13 @@ pub(crate) struct Daemon {
stop: SyncSender<()>,
mount: Option<JoinHandle<io::Result<MountOutcome>>>,
rt: Option<tokio::runtime::Runtime>,
/// The mount's FUSE connection, as `/sys/fs/fuse/connections` names it.
connection: u64,
/// Dropped with the daemon, which ends the thread enforcing
/// [`LIFETIME_LIMIT`].
_alive: std::sync::mpsc::Sender<()>,
/// Dropped after `shut_down`, so the next simulation waits for this one.
_turn: Turn,
}
impl Daemon {
@@ -45,6 +62,7 @@ impl Daemon {
/// A later start on the same `dir` is a restart: it finds the queue, the
/// cache and the database the last run left.
pub(crate) fn start(dir: &Path, client: FakeClient) -> io::Result<Self> {
let turn = Turn::take();
log_to_test_output();
isolate_from_the_developer();
let mountpoint = dir.join("mnt");
@@ -112,6 +130,27 @@ impl Daemon {
}
std::thread::sleep(Duration::from_millis(20));
}
let connection = {
use std::os::unix::fs::MetadataExt;
u64::from(libc::minor(std::fs::metadata(&mountpoint)?.dev()))
};
let (alive, dropped) = std::sync::mpsc::channel::<()>();
{
let mountpoint = mountpoint.clone();
std::thread::Builder::new()
.name("sim-lifetime".into())
.spawn(move || {
if let Err(std::sync::mpsc::RecvTimeoutError::Timeout) =
dropped.recv_timeout(LIFETIME_LIMIT)
{
eprintln!(
"{}: the daemon outlived {LIFETIME_LIMIT:?}; aborting its FUSE connection",
mountpoint.display()
);
abort_connection(connection);
}
})?;
}
Ok(Self {
client,
mountpoint,
@@ -120,6 +159,9 @@ impl Daemon {
stop,
mount: Some(mount),
rt: Some(rt),
connection,
_alive: alive,
_turn: turn,
})
}
@@ -215,6 +257,21 @@ impl Daemon {
return Ok(MountOutcome::Shutdown);
};
let _ = self.stop.try_send(());
if !wait_until(STOP_DEADLINE, || mount.is_finished()) {
abort_connection(self.connection);
let _ = wait_until(STOP_DEADLINE, || mount.is_finished());
if !mount.is_finished() {
// Joining would hang the run; leak the thread instead.
return Err(io::Error::other(format!(
"{}: the mount did not end after its FUSE connection was aborted",
self.mountpoint.display()
)));
}
return Err(io::Error::other(format!(
"{}: the mount did not stop within {STOP_DEADLINE:?}, so its FUSE connection was aborted",
self.mountpoint.display()
)));
}
let outcome = mount
.join()
.unwrap_or_else(|_| Err(io::Error::other("mount thread panicked")));
@@ -231,6 +288,61 @@ impl Drop for Daemon {
}
}
/// Abort FUSE connection `connection`: every request waiting on it fails with
/// `ENOTCONN`, and the mount's session ends. The connection belongs to the
/// user who mounted it, so this needs no privileges.
fn abort_connection(connection: u64) {
let path = format!("/sys/fs/fuse/connections/{connection}/abort");
if let Err(error) = std::fs::write(&path, "1") {
eprintln!("could not abort {path}: {error}");
}
}
/// One simulation's turn to run daemons. The simulations share the process:
/// its environment (see [`isolate_from_the_developer`]), its cores and its
/// mounts. Run side by side, as plain `cargo test` does, they miss their
/// deadlines and can hang (`docs/BUGS.md` B297). So a daemon started on one
/// test thread waits while another test thread still has one.
struct Turn;
/// The test thread whose daemons run now, and how many it has.
static TURN: parking_lot::Mutex<Option<(std::thread::ThreadId, usize)>> =
parking_lot::Mutex::new(None);
static TURN_FREE: parking_lot::Condvar = parking_lot::Condvar::new();
impl Turn {
fn take() -> Self {
let me = std::thread::current().id();
let mut turn = TURN.lock();
loop {
match turn.as_mut() {
None => {
*turn = Some((me, 1));
return Turn;
}
Some((owner, count)) if *owner == me => {
*count += 1;
return Turn;
}
Some(_) => TURN_FREE.wait(&mut turn),
}
}
}
}
impl Drop for Turn {
fn drop(&mut self) {
let mut turn = TURN.lock();
if let Some((_, count)) = turn.as_mut() {
*count -= 1;
if *count == 0 {
*turn = None;
TURN_FREE.notify_all();
}
}
}
}
/// Whether a file system is mounted at `path`: it sits on another device than
/// its parent.
fn is_mounted(path: &Path) -> bool {
@@ -369,6 +481,35 @@ mod tests {
use pdfs_core::control::{RefreshScope, SyncIssue};
use std::collections::BTreeMap;
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_simulation_on_another_thread_waits_for_this_ones_daemons() {
// Side by side, the simulations missed their deadlines and could hang
// on a mount (B297).
let drive = FakeDrive::new();
let first = Daemon::start(&scratch("turn-first"), drive.client(1, Faults::lan())).unwrap();
let second_up = Arc::new(std::sync::atomic::AtomicBool::new(false));
let other = {
let drive = drive.clone();
let second_up = second_up.clone();
std::thread::spawn(move || {
let second =
Daemon::start(&scratch("turn-second"), drive.client(2, Faults::lan())).unwrap();
second_up.store(true, std::sync::atomic::Ordering::SeqCst);
second.stop().unwrap();
})
};
std::thread::sleep(Duration::from_secs(2));
assert!(!second_up.load(std::sync::atomic::Ordering::SeqCst));
// A second daemon on this thread does not wait for the first.
let restarted = first.restart().unwrap();
assert!(!second_up.load(std::sync::atomic::Ordering::SeqCst));
restarted.stop().unwrap();
other.join().unwrap();
assert!(second_up.load(std::sync::atomic::Ordering::SeqCst));
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_daemon_on_the_fake_drive_syncs_both_ways() {
@@ -67,10 +67,10 @@ use proton_drive_rs::{
use sha1::{Digest as _, Sha1};
use super::rng::Rng;
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
use crate::drive::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
/// The volume every fake node lives on.
pub const VOLUME: &str = "simvol";
pub(crate) const VOLUME: &str = "simvol";
/// How long superseded versions of a node are kept for lagging reads. Longer
/// than any lag a test sets.
@@ -350,19 +350,19 @@ impl Server {
/// An in-memory Drive shared by every simulated client. See the module
/// documentation.
pub struct FakeDrive {
pub(crate) struct FakeDrive {
server: Mutex<Server>,
}
/// A node of [`FakeDrive::tree`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Entry {
pub(crate) enum Entry {
Folder,
File(Arc<Vec<u8>>),
}
impl FakeDrive {
pub fn new() -> Arc<Self> {
pub(crate) fn new() -> Arc<Self> {
let root = uid("root");
let mut server = Server {
root: root.clone(),
@@ -370,7 +370,7 @@ impl FakeDrive {
next_link: 0,
next_revision: 0,
events: Vec::new(),
block_pattern: vec![pdfs_store::cache::BLOCK_SIZE],
block_pattern: vec![pdfs_core::cache::BLOCK_SIZE],
max_space: 1 << 40,
devices: Vec::new(),
};
@@ -395,7 +395,7 @@ impl FakeDrive {
}
/// A connection to this Drive for one simulated daemon.
pub fn client(self: &Arc<Self>, seed: u64, faults: Faults) -> FakeClient {
pub(crate) fn client(self: &Arc<Self>, seed: u64, faults: Faults) -> FakeClient {
FakeClient(Arc::new(ClientInner {
drive: self.clone(),
faults: Mutex::new(faults),
@@ -426,24 +426,24 @@ impl FakeDrive {
/// Plaintext block sizes for content uploaded from now on, cycled with the
/// last one repeating: `[1 MiB, 4 MiB]` makes a short first block.
pub fn set_block_pattern(&self, pattern: Vec<u64>) {
pub(crate) fn set_block_pattern(&self, pattern: Vec<u64>) {
assert!(!pattern.is_empty() && pattern.iter().all(|&size| size > 0));
self.server.lock().block_pattern = pattern;
}
/// The account's storage limit; a limit below what is stored refuses every
/// upload until something is deleted.
pub fn set_quota(&self, max_space: i64) {
pub(crate) fn set_quota(&self, max_space: i64) {
self.server.lock().max_space = max_space;
}
pub fn root(&self) -> NodeUid {
pub(crate) fn root(&self) -> NodeUid {
self.server.lock().root.clone()
}
/// The live tree as Drive has it now, by path below the root: every node
/// that is neither trashed nor below a trashed folder.
pub fn tree(&self) -> BTreeMap<String, Entry> {
pub(crate) fn tree(&self) -> BTreeMap<String, Entry> {
let server = self.server.lock();
let mut tree = BTreeMap::new();
for uid in server.nodes.keys() {
@@ -483,7 +483,7 @@ impl FakeDrive {
/// Every name a node has had in the root, trashed or not, as far back as
/// Drive keeps its versions.
pub fn names_ever_in_root(&self) -> Vec<String> {
pub(crate) fn names_ever_in_root(&self) -> Vec<String> {
let server = self.server.lock();
let mut names: Vec<String> = server
.nodes
@@ -499,7 +499,7 @@ impl FakeDrive {
}
/// The uid at `path` below the root, as Drive has it now.
pub fn lookup(&self, path: &str) -> Option<NodeUid> {
pub(crate) fn lookup(&self, path: &str) -> Option<NodeUid> {
let server = self.server.lock();
let mut at = server.root.clone();
for name in path.split('/').filter(|name| !name.is_empty()) {
@@ -509,23 +509,23 @@ impl FakeDrive {
}
/// Every change Drive has logged, oldest first.
pub fn event_count(&self) -> usize {
pub(crate) fn event_count(&self) -> usize {
self.server.lock().events.len()
}
/// Changes made by another device, straight on the server: what a second
/// client would do, without the daemon that client would need.
pub fn device(&self) -> Device<'_> {
pub(crate) fn device(&self) -> Device<'_> {
Device(self)
}
}
/// See [`FakeDrive::device`].
pub struct Device<'a>(&'a FakeDrive);
pub(crate) struct Device<'a>(&'a FakeDrive);
impl Device<'_> {
/// Write `content` at `path`, as a new file or a new revision of one.
pub fn write(&self, path: &str, content: &[u8]) -> NodeUid {
pub(crate) fn write(&self, path: &str, content: &[u8]) -> NodeUid {
let (parent, name) = split_path(path);
let parent = self
.0
@@ -560,7 +560,7 @@ impl Device<'_> {
}
/// Make a folder at `path`.
pub fn mkdir(&self, path: &str) -> NodeUid {
pub(crate) fn mkdir(&self, path: &str) -> NodeUid {
let (parent, name) = split_path(path);
let parent = self
.0
@@ -585,7 +585,7 @@ impl Device<'_> {
}
/// Move the node at `path` to the trash.
pub fn trash(&self, path: &str) {
pub(crate) fn trash(&self, path: &str) {
let uid = self.0.lookup(path).expect("device trash of a missing node");
let mut server = self.0.server.lock();
let mut remote = server.current(&uid).cloned().expect("live node");
@@ -594,7 +594,7 @@ impl Device<'_> {
}
/// Rename the node at `path` in place.
pub fn rename(&self, path: &str, new_name: &str) {
pub(crate) fn rename(&self, path: &str, new_name: &str) {
let uid = self
.0
.lookup(path)
@@ -616,35 +616,35 @@ struct Lag {
/// The faults and timing of one connection. See the module documentation.
#[derive(Clone, Debug)]
pub struct Faults {
pub(crate) struct Faults {
/// Each request takes a time drawn from this range, in milliseconds.
pub latency_ms: (u64, u64),
pub(crate) latency_ms: (u64, u64),
/// How far behind the present reads are about a node appearing or going
/// to the trash.
pub listing_lag: Duration,
pub(crate) listing_lag: Duration,
/// How far behind the present reads are about a live node's name, folder
/// or revision.
pub update_lag: Duration,
pub(crate) update_lag: Duration,
/// How long a change takes to reach the event feed.
pub event_delay: Duration,
pub(crate) event_delay: Duration,
/// Chance that an event is delivered twice.
pub duplicate_events: f64,
pub(crate) duplicate_events: f64,
/// Chance that two neighbouring events of a page swap places.
pub reorder_events: f64,
pub(crate) reorder_events: f64,
/// Chance that a request never reaches Drive.
pub fail: f64,
pub(crate) fail: f64,
/// Chance that a change Drive made loses its reply.
pub drop_reply: f64,
pub(crate) drop_reply: f64,
/// Chance that a request stalls for [`Faults::stall_for`] and then fails.
pub stall: f64,
pub stall_for: Duration,
pub(crate) stall: f64,
pub(crate) stall_for: Duration,
/// Whether renames and moves send the entity cache's name, as the SDK does.
pub stale_name_cache: bool,
pub(crate) stale_name_cache: bool,
}
impl Faults {
/// No latency and no faults beyond the SDK's own stale name cache.
pub fn none() -> Self {
pub(crate) fn none() -> Self {
Self {
latency_ms: (0, 0),
listing_lag: Duration::ZERO,
@@ -661,7 +661,7 @@ impl Faults {
}
/// A good link: a few milliseconds a request, listings barely behind.
pub fn lan() -> Self {
pub(crate) fn lan() -> Self {
Self {
latency_ms: (2, 15),
listing_lag: Duration::from_millis(50),
@@ -672,7 +672,7 @@ impl Faults {
/// A good link whose event feed is slow and untidy: every echo of our own
/// changes comes late, often twice, often out of order.
pub fn echoes() -> Self {
pub(crate) fn echoes() -> Self {
Self {
event_delay: Duration::from_secs(1),
duplicate_events: 0.3,
@@ -683,7 +683,7 @@ impl Faults {
/// The Wi-Fi of the 2026-10 account runs: slow and lossy, with listings
/// and events well behind.
pub fn wifi() -> Self {
pub(crate) fn wifi() -> Self {
Self {
latency_ms: (60, 400),
listing_lag: Duration::from_millis(800),
@@ -787,11 +787,11 @@ async fn wait_until_released(state: &HoldState) {
/// A call held on its way to or from Drive, from [`FakeClient::hold_next_read`]
/// or [`FakeClient::hold_reply_to_next_create`]. It goes on when this is
/// dropped.
pub struct Held(Arc<HoldState>);
pub(crate) struct Held(Arc<HoldState>);
impl Held {
/// Whether the read has come and is being held.
pub fn reached(&self) -> bool {
pub(crate) fn reached(&self) -> bool {
self.0.reached.load(Ordering::SeqCst)
}
}
@@ -805,32 +805,32 @@ impl Drop for Held {
/// One daemon's connection to a [`FakeDrive`]. Cheap to clone; clones share
/// the link, the faults and the entity cache.
#[derive(Clone)]
pub struct FakeClient(Arc<ClientInner>);
pub(crate) struct FakeClient(Arc<ClientInner>);
impl FakeClient {
pub fn set_online(&self, online: bool) {
pub(crate) fn set_online(&self, online: bool) {
self.0.online.store(online, Ordering::SeqCst);
}
pub fn set_faults(&self, faults: Faults) {
pub(crate) fn set_faults(&self, faults: Faults) {
*self.0.faults.lock() = faults;
}
/// Take the link down as soon as the next file create has been answered,
/// so whatever the daemon asks next goes unanswered.
pub fn drop_link_after_next_create(&self) {
pub(crate) fn drop_link_after_next_create(&self) {
self.0.drop_after_create.store(true, Ordering::SeqCst);
}
/// Make the next file create on Drive and lose its answer, as a link that
/// drops it on the way back does.
pub fn lose_reply_to_next_create(&self) {
pub(crate) fn lose_reply_to_next_create(&self) {
self.0.lose_create_reply.store(true, Ordering::SeqCst);
}
/// Hold the next read of `uid` alone, before it reaches Drive, until the
/// answer is dropped. Only one read is held at a time.
pub fn hold_next_read(&self, uid: &NodeUid) -> Held {
pub(crate) fn hold_next_read(&self, uid: &NodeUid) -> Held {
let state = Arc::new(HoldState {
uid: uid.clone(),
reached: AtomicBool::new(false),
@@ -843,7 +843,7 @@ impl FakeClient {
/// Answer the next read of `uid` alone with what Drive holds now, then
/// hold the answer until it is dropped, as a slow link does. Only one
/// answer is held at a time.
pub fn hold_answer_to_next_read(&self, uid: &NodeUid) -> Held {
pub(crate) fn hold_answer_to_next_read(&self, uid: &NodeUid) -> Held {
let state = Arc::new(HoldState {
uid: uid.clone(),
reached: AtomicBool::new(false),
@@ -855,7 +855,7 @@ impl FakeClient {
/// Hold the next listing of the children of `folder`, before it reaches
/// Drive, until the answer is dropped.
pub fn hold_next_children_of(&self, folder: &NodeUid) -> Held {
pub(crate) fn hold_next_children_of(&self, folder: &NodeUid) -> Held {
let state = Arc::new(HoldState {
uid: folder.clone(),
reached: AtomicBool::new(false),
@@ -867,7 +867,7 @@ impl FakeClient {
/// Hold the next trash of `uid` alone, before it reaches Drive, until the
/// answer is dropped.
pub fn hold_next_trash(&self, uid: &NodeUid) -> Held {
pub(crate) fn hold_next_trash(&self, uid: &NodeUid) -> Held {
let state = Arc::new(HoldState {
uid: uid.clone(),
reached: AtomicBool::new(false),
@@ -880,16 +880,16 @@ impl FakeClient {
/// Hold the next download of `uid`'s content once Drive has answered it,
/// before the bytes reach the daemon, until the answer is dropped.
/// Give `uid` a server thumbnail, as an upload that carried one would.
pub fn set_thumbnail(&self, uid: &NodeUid, bytes: Vec<u8>) {
pub(crate) fn set_thumbnail(&self, uid: &NodeUid, bytes: Vec<u8>) {
self.0.thumbnails.lock().insert(uid.clone(), bytes);
}
/// File content bytes served so far, by whole downloads and ranged reads.
pub fn content_read(&self) -> u64 {
pub(crate) fn content_read(&self) -> u64 {
self.0.content_read.load(Ordering::SeqCst)
}
pub fn hold_next_download(&self, uid: &NodeUid) -> Held {
pub(crate) fn hold_next_download(&self, uid: &NodeUid) -> Held {
let state = Arc::new(HoldState {
uid: uid.clone(),
reached: AtomicBool::new(false),
@@ -902,7 +902,7 @@ impl FakeClient {
/// Hold the drain once the next upload to `uid` has landed and its blob
/// is let go of, before the tree has the node (`DriveApi::landing`), until
/// the answer is dropped.
pub fn hold_next_landing(&self, uid: &NodeUid) -> Held {
pub(crate) fn hold_next_landing(&self, uid: &NodeUid) -> Held {
let state = Arc::new(HoldState {
uid: uid.clone(),
reached: AtomicBool::new(false),
@@ -914,7 +914,7 @@ impl FakeClient {
/// [`FakeClient::hold_next_landing`] for whichever node lands next, such
/// as a new file, whose uid Drive has not minted yet.
pub fn hold_next_landing_of_any(&self) -> Held {
pub(crate) fn hold_next_landing_of_any(&self) -> Held {
let held = self.hold_next_landing(&uid("*"));
self.0.hold_any_landing.store(true, Ordering::SeqCst);
held
@@ -922,7 +922,7 @@ impl FakeClient {
/// Make the next file create on Drive, then hold its answer until the
/// answer is dropped, as a slow link does.
pub fn hold_reply_to_next_create(&self) -> Held {
pub(crate) fn hold_reply_to_next_create(&self) -> Held {
let state = Arc::new(HoldState {
uid: self.0.drive.root(),
reached: AtomicBool::new(false),
@@ -934,7 +934,7 @@ impl FakeClient {
/// Hold the next file create before it reaches Drive, until the answer
/// is dropped.
pub fn hold_next_create(&self) -> Held {
pub(crate) fn hold_next_create(&self) -> Held {
let state = Arc::new(HoldState {
uid: self.0.drive.root(),
reached: AtomicBool::new(false),
@@ -945,28 +945,32 @@ impl FakeClient {
}
/// Make the next revision of a file on Drive and lose its answer.
pub fn lose_reply_to_next_revision(&self) {
pub(crate) fn lose_reply_to_next_revision(&self) {
self.0.lose_revision_reply.store(true, Ordering::SeqCst);
}
/// Make the next revision of a file on Drive and answer it, then lose the
/// answer to the next read of that file alone, as the read-back after an
/// upload meets on a link that drops it.
pub fn lose_read_back_of_next_revision(&self) {
pub(crate) fn lose_read_back_of_next_revision(&self) {
self.0.lose_revision_read_back.store(true, Ordering::SeqCst);
}
/// Answer the next `reads` reads of file `uid` alone that find it as Drive
/// lists a file whose create it has not committed yet: no active revision,
/// no size.
pub fn answer_reads_unrevised(&self, uid: &NodeUid, reads: usize) {
pub(crate) fn answer_reads_unrevised(&self, uid: &NodeUid, reads: usize) {
*self.0.unrevised_reads.lock() = Some((uid.clone(), reads));
}
/// Answer the next listing of `folder`'s nodes with what Drive holds now,
/// `unrevised` in it as Drive lists a file whose create it has not
/// committed yet, then hold the answer until it is dropped.
pub fn hold_answer_to_next_listing(&self, folder: &NodeUid, unrevised: &NodeUid) -> Held {
pub(crate) fn hold_answer_to_next_listing(
&self,
folder: &NodeUid,
unrevised: &NodeUid,
) -> Held {
let state = Arc::new(HoldState {
uid: folder.clone(),
reached: AtomicBool::new(false),
@@ -990,7 +994,7 @@ impl FakeClient {
}
/// Requests made through this client so far.
pub fn requests(&self) -> u64 {
pub(crate) fn requests(&self) -> u64 {
self.0.requests.load(Ordering::SeqCst)
}
@@ -1845,7 +1849,7 @@ impl RevisionRead for FakeRevision {
}
/// A uid on the fake volume.
pub fn uid(link: &str) -> NodeUid {
pub(crate) fn uid(link: &str) -> NodeUid {
NodeUid::new(VolumeId::from(VOLUME), LinkId::from(link))
}
@@ -1925,7 +1929,7 @@ fn api(code: ResponseCode, message: &str) -> ProtonError {
}
/// What a request that never got an answer reports; the daemon reads it as
/// the network (see [`crate::is_network_error`]).
/// the network (see `link::is_network_error`).
fn no_answer() -> ProtonError {
ProtonError::Api(ProtonApiError {
code: ResponseCode::RequestTimeout,
@@ -1945,7 +1949,7 @@ fn now_secs() -> i64 {
#[cfg(test)]
mod tests {
use super::*;
use crate::is_network_error;
use crate::link::is_network_error;
fn code(error: &ProtonError) -> Option<ResponseCode> {
match error {
+2 -2
View File
@@ -2,8 +2,8 @@
//! the faults the real one has, and the tools to drive daemons against it.
pub(crate) mod daemon;
pub(crate) use pdfs_drive::sim::fake_drive;
pub(crate) mod fake_drive;
pub(crate) mod model;
pub(crate) use pdfs_drive::sim::rng;
pub(crate) mod rng;
pub(crate) mod run;
pub(crate) mod watchdog;
@@ -3,14 +3,14 @@
//! and faults, and no dependency.
#[derive(Clone, Debug)]
pub struct Rng(u64);
pub(crate) struct Rng(u64);
impl Rng {
pub fn new(seed: u64) -> Self {
pub(crate) fn new(seed: u64) -> Self {
Self(seed)
}
pub fn next_u64(&mut self) -> u64 {
pub(crate) fn next_u64(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
@@ -19,26 +19,26 @@ impl Rng {
}
/// A value in `0..n`; `0` when `n` is `0`.
pub fn below(&mut self, n: u64) -> u64 {
pub(crate) fn below(&mut self, n: u64) -> u64 {
if n == 0 { 0 } else { self.next_u64() % n }
}
/// A value in `lo..=hi`.
pub fn between(&mut self, lo: u64, hi: u64) -> u64 {
pub(crate) fn between(&mut self, lo: u64, hi: u64) -> u64 {
lo + self.below(hi.saturating_sub(lo) + 1)
}
/// True with probability `p`.
pub fn chance(&mut self, p: f64) -> bool {
pub(crate) fn chance(&mut self, p: f64) -> bool {
p > 0.0 && (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64 <= p
}
pub fn pick<'a, T>(&mut self, items: &'a [T]) -> Option<&'a T> {
pub(crate) fn pick<'a, T>(&mut self, items: &'a [T]) -> Option<&'a T> {
items.get(self.below(items.len() as u64) as usize)
}
/// A child generator, so one consumer's draws do not shift another's.
pub fn fork(&mut self) -> Self {
pub(crate) fn fork(&mut self) -> Self {
Self::new(self.next_u64())
}
}
+4 -4
View File
@@ -7,9 +7,9 @@ use std::fs::File;
use std::path::PathBuf;
use std::sync::Arc;
use pdfs_core::cache::StagedWrite;
use pdfs_core::db::Db;
use pdfs_core::{Access, access_for};
use pdfs_store::cache::StagedWrite;
use pdfs_store::db::Db;
#[cfg(test)]
use proton_drive_rs::MemberRole;
use proton_drive_rs::proton_sdk::ids::NodeUid;
@@ -1770,9 +1770,9 @@ mod tests {
node("shared-child", "shared", "pending.txt", false),
);
st.flushed_db()
.enqueue_op(&pdfs_store::db::PendingOp {
.enqueue_op(&pdfs_core::db::PendingOp {
id: 0,
kind: pdfs_store::db::OP_RENAME.to_string(),
kind: pdfs_core::db::OP_RENAME.to_string(),
uid: uid("shared-child").to_string(),
parent_uid: Some(shared.uid.to_string()),
name: Some("pending-renamed.txt".to_string()),
+61 -6
View File
@@ -33,8 +33,8 @@ use std::sync::mpsc::{Receiver, RecvTimeoutError};
use std::time::{Duration, Instant, SystemTime};
use notify::{RecursiveMode, Watcher};
use proton_drive_rs::Node;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use proton_drive_rs::{Node, NodeKind};
use sha1::{Digest as _, Sha1};
use tracing::{debug, info, warn};
@@ -42,11 +42,14 @@ use crate::transfers::{CountingWriter, OwnedCountingReader};
use crate::{Core, now_secs, parse_uid};
use pdfs_core::batch;
use pdfs_core::control::{ActivityKind, TransferDirection};
use pdfs_core::db::{SavedWalk, SavedWalkItem, StoredSyncEntry, StoredSyncFolder};
use pdfs_core::syncignore::IgnoreRules;
use pdfs_store::db::{SavedWalk, SavedWalkItem, StoredSyncEntry, StoredSyncFolder};
mod engine;
mod local_scan;
mod model;
mod planner;
mod trace;
pub(crate) use engine::SYNC_CONCURRENCY;
pub(crate) use engine::{EngineHealth, SyncMsg, spawn};
#[cfg(test)]
@@ -56,11 +59,7 @@ use engine::{classify, event_target, settle_with};
#[cfg(test)]
use local_scan::is_write_mode;
use local_scan::open_for_write_set;
use model::{Applied, remote_file_sig, system_mtime, system_mtime_ns};
use model::{LocalItem, LocalSig, Outcome, PassAbort, Pending, RemoteItem, RemoteSeen};
use pdfs_sync::model;
use pdfs_sync::planner;
use pdfs_sync::trace;
pub(crate) use planner::base_name;
#[cfg(test)]
use planner::conflict_path;
@@ -78,6 +77,25 @@ use trace::{Call, Count, Phase};
/// nothing, so the journal says where a slow engine spends its time.
const SLOW_PASS: Duration = Duration::from_secs(30);
/// What a [`Pending`] op did, so the reconcile can update shared state on the
/// engine thread (never inside a task).
enum Applied {
/// A folder was created; register `uid` in `remote_dirs` for its children.
Dir(String, NodeUid),
/// A local file was uploaded (new file or new revision).
Uploaded,
/// A remote file was downloaded.
Downloaded,
/// A conflict copy was kept.
Conflict,
/// A path already the same on both sides got its first baseline. Nothing
/// moved, so it is neither counted nor logged.
Adopted,
/// The local file to upload was deleted after the scan planned it. There is
/// nothing left to send, and the next pass sees the deletion (B108).
Vanished,
}
impl Core {
/// Reconcile one synced folder, then apply any mode switch queued while it was
/// busy. Both halves live here because the switch has to happen with the pass
@@ -3087,6 +3105,43 @@ fn sync_parent_dir(path: &Path) -> std::io::Result<()> {
// ---- helpers --------------------------------------------------------------
/// A remote node's `(mtime, size)` change signature. Size prefers the plaintext
/// `claimed_size`; otherwise the encrypted storage size (stable either way, and
/// only ever compared against the same node's own baseline).
fn remote_file_sig(node: &Node) -> (i64, i64) {
let size = match &node.kind {
NodeKind::File {
claimed_size,
total_size_on_storage,
..
} => claimed_size.unwrap_or(*total_size_on_storage),
NodeKind::Folder => 0,
};
(node.modification_time, size)
}
/// A file's modification time as epoch seconds (0 if unavailable).
fn system_mtime(meta: &std::fs::Metadata) -> i64 {
meta.modified()
.ok()
.and_then(|t| t.duration_since(SystemTime::UNIX_EPOCH).ok())
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
/// The same modification time in nanoseconds, when the filesystem reports one.
///
/// Whole seconds cannot distinguish an edit made in the same second as the last
/// sync from no edit at all, and if the size did not change either, that file
/// was never uploaded (`docs/BUGS.md` B25). `None` for a clock or filesystem that
/// cannot answer, which falls the comparison back to seconds rather than
/// asserting an mtime of zero.
fn system_mtime_ns(meta: &std::fs::Metadata) -> Option<i64> {
meta.modified()
.ok()
.and_then(|t| t.duration_since(SystemTime::UNIX_EPOCH).ok())
.and_then(|d| i64::try_from(d.as_nanos()).ok())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -6,12 +6,12 @@ use super::*;
/// recognise the same content again, and no more.
///
/// `mtime_ns` is the whole reason this is a struct rather than a pair — see
/// [`StoredSyncEntry::local_mtime_ns`](pdfs_store::db::StoredSyncEntry).
/// [`StoredSyncEntry::local_mtime_ns`](pdfs_core::db::StoredSyncEntry).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LocalSig {
pub mtime: i64,
pub mtime_ns: Option<i64>,
pub size: i64,
pub(super) struct LocalSig {
pub(super) mtime: i64,
pub(super) mtime_ns: Option<i64>,
pub(super) size: i64,
}
impl LocalSig {
@@ -21,7 +21,7 @@ impl LocalSig {
/// falls back to whole seconds, which is what a baseline row written before
/// schema 28 — or a filesystem that reports no sub-second time — can support
/// (`docs/BUGS.md` B25).
pub fn same_content(&self, other: &Self) -> bool {
pub(super) fn same_content(&self, other: &Self) -> bool {
if self.size != other.size {
return false;
}
@@ -63,52 +63,52 @@ impl From<&StoredSyncEntry> for LocalSig {
}
}
pub struct LocalItem {
pub is_dir: bool,
pub mtime: i64,
pub(super) struct LocalItem {
pub(super) is_dir: bool,
pub(super) mtime: i64,
/// [`LocalItem::mtime`] to nanosecond precision, when the filesystem
/// reports one.
pub mtime_ns: Option<i64>,
pub size: i64,
pub(super) mtime_ns: Option<i64>,
pub(super) size: i64,
/// True when another process holds this file open for writing (detected via
/// `/proc/*/fd`). An open-for-write file is kept in the map — so it is not
/// misread as a deletion — but treated as unchanged for upload purposes,
/// deferring the upload until the writer closes the file.
pub open_for_write: bool,
pub(super) open_for_write: bool,
}
/// One item found while walking a remote tree.
pub struct RemoteItem {
pub uid: NodeUid,
pub is_dir: bool,
pub mtime: i64,
pub size: i64,
pub(super) struct RemoteItem {
pub(super) uid: NodeUid,
pub(super) is_dir: bool,
pub(super) mtime: i64,
pub(super) size: i64,
/// The active revision's id. The light walk carries it for every file, so
/// it is the signal that tells another client's new revision from a link
/// merely re-stamped.
pub revision: Option<String>,
pub(super) revision: Option<String>,
/// The active revision's content SHA-1, read only for files the walk
/// enumerated in full (no baseline, or a moved mtime). `None` is never
/// proof of anything.
pub sha1: Option<String>,
pub(super) sha1: Option<String>,
}
/// What a pass saw of a remote file: the signature its baseline records once
/// the file is synced, and what an upload checks Drive still holds before it
/// supersedes it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RemoteSeen {
pub mtime: i64,
pub size: i64,
pub revision: Option<String>,
pub(super) struct RemoteSeen {
pub(super) mtime: i64,
pub(super) size: i64,
pub(super) revision: Option<String>,
}
impl RemoteSeen {
/// Whether `node` is still the revision this was taken from. The revision
/// id decides it when both sides have one; otherwise the modification time
/// and size, which is all a baseline row from before schema 44 holds.
pub fn still_current(&self, node: &Node) -> bool {
match (&self.revision, pdfs_drive::node_revision_id(node)) {
pub(super) fn still_current(&self, node: &Node) -> bool {
match (&self.revision, crate::node_revision_id(node)) {
(Some(seen), Some(now)) => *seen == now,
_ => (self.mtime, self.size) == remote_file_sig(node),
}
@@ -129,28 +129,28 @@ impl From<&RemoteItem> for RemoteSeen {
/// conflict copies, and how many failed to apply (and so still need another
/// pass). The counts drive both the folder's state and its activity summary.
#[derive(Default)]
pub struct Outcome {
pub uploaded: usize,
pub downloaded: usize,
pub created: usize,
pub deleted: usize,
pub conflicts: usize,
pub errors: usize,
pub(super) struct Outcome {
pub(super) uploaded: usize,
pub(super) downloaded: usize,
pub(super) created: usize,
pub(super) deleted: usize,
pub(super) conflicts: usize,
pub(super) errors: usize,
/// Files skipped because another process held them open for writing.
pub deferred: usize,
pub(super) deferred: usize,
/// Paths the local scan could not read, left out of the pass. Not part of
/// [`is_empty`](Self::is_empty) or the summary: an unreadable folder stays
/// unreadable from one poll to the next, so the pass reports it once, when
/// the set changes, rather than on every poll.
pub unscanned: Vec<String>,
pub(super) unscanned: Vec<String>,
/// The first step that failed in this pass, so the line that ends a pass
/// in `error` says why without a search back through the journal.
pub first_error: Option<String>,
pub(super) first_error: Option<String>,
}
impl Outcome {
/// Count one failed step, keeping the first one's message.
pub fn failed(&mut self, error: &str) {
pub(super) fn failed(&mut self, error: &str) {
self.errors += 1;
if self.first_error.is_none() {
self.first_error = Some(error.to_string());
@@ -158,7 +158,7 @@ impl Outcome {
}
/// Fold in one applied op.
pub fn record(&mut self, applied: &Applied) {
pub(super) fn record(&mut self, applied: &Applied) {
match applied {
Applied::Dir(..) => self.created += 1,
Applied::Uploaded => self.uploaded += 1,
@@ -170,7 +170,7 @@ impl Outcome {
/// Whether the pass moved nothing at all — the common case on a poll of an
/// unchanged folder, which should not add a line to the activity feed.
pub fn is_empty(&self) -> bool {
pub(super) fn is_empty(&self) -> bool {
self.uploaded == 0
&& self.downloaded == 0
&& self.created == 0
@@ -181,7 +181,7 @@ impl Outcome {
}
/// A human summary of the pass: "3 uploaded, 1 downloaded, 2 failed".
pub fn summary(&self) -> String {
pub(super) fn summary(&self) -> String {
let mut parts = Vec::new();
for (n, label) in [
(self.uploaded, "uploaded"),
@@ -203,7 +203,7 @@ impl Outcome {
/// A network operation queued during classification and run concurrently in a
/// per-depth batch. Parent uids are resolved up front (the parent folder is one
/// depth shallower and already created), so tasks share nothing mutable.
pub enum Pending {
pub(super) enum Pending {
/// Create a new remote folder under `parent`.
CreateDir { rel: String, parent: NodeUid },
/// Upload a brand-new local file into `parent`.
@@ -255,7 +255,7 @@ pub enum Pending {
impl Pending {
/// The path this op acts on, relative to the folder root.
pub fn rel(&self) -> &str {
pub(super) fn rel(&self) -> &str {
match self {
Pending::CreateDir { rel, .. }
| Pending::UploadNew { rel, .. }
@@ -268,7 +268,7 @@ impl Pending {
}
/// Which call of the pass's trace this op counts as.
pub fn call(&self) -> Call {
pub(super) fn call(&self) -> Call {
match self {
Pending::CreateDir { .. } => Call::CreateFolder,
Pending::UploadNew { .. } | Pending::PushConflict { .. } => Call::Upload,
@@ -280,7 +280,7 @@ impl Pending {
}
/// How this op reads in the activity feed.
pub fn kind(&self) -> ActivityKind {
pub(super) fn kind(&self) -> ActivityKind {
match self {
Pending::CreateDir { .. } => ActivityKind::CreateFolder,
Pending::UploadNew { .. }
@@ -293,7 +293,7 @@ impl Pending {
}
/// The activity line's detail, which distinguishes ops that share a kind.
pub fn detail(&self) -> &'static str {
pub(super) fn detail(&self) -> &'static str {
match self {
Pending::CreateDir { .. } => "on Drive",
Pending::UploadNew { .. } => "new file",
@@ -307,7 +307,7 @@ impl Pending {
}
/// Why a full reconcile pass stopped without a result.
pub enum PassAbort {
pub(super) enum PassAbort {
/// An on-demand switch was queued while the pass was running. Everything left
/// to do is work on a local copy about to be evicted, so the pass gives up its
/// remaining work to a [`push pass`](Core::push_pass) instead. Not a failure —
@@ -329,60 +329,3 @@ impl From<String> for PassAbort {
PassAbort::Failed(e)
}
}
/// What a [`Pending`] op did, so the reconcile can update shared state on the
/// engine thread (never inside a task).
pub enum Applied {
/// A folder was created; register `uid` in `remote_dirs` for its children.
Dir(String, NodeUid),
/// A local file was uploaded (new file or new revision).
Uploaded,
/// A remote file was downloaded.
Downloaded,
/// A conflict copy was kept.
Conflict,
/// A path already the same on both sides got its first baseline. Nothing
/// moved, so it is neither counted nor logged.
Adopted,
/// The local file to upload was deleted after the scan planned it. There is
/// nothing left to send, and the next pass sees the deletion (B108).
Vanished,
}
/// A remote node's `(mtime, size)` change signature. Size prefers the plaintext
/// `claimed_size`; otherwise the encrypted storage size (stable either way, and
/// only ever compared against the same node's own baseline).
pub fn remote_file_sig(node: &Node) -> (i64, i64) {
let size = match &node.kind {
NodeKind::File {
claimed_size,
total_size_on_storage,
..
} => claimed_size.unwrap_or(*total_size_on_storage),
NodeKind::Folder => 0,
};
(node.modification_time, size)
}
/// A file's modification time as epoch seconds (0 if unavailable).
pub fn system_mtime(meta: &std::fs::Metadata) -> i64 {
meta.modified()
.ok()
.and_then(|t| t.duration_since(SystemTime::UNIX_EPOCH).ok())
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
/// The same modification time in nanoseconds, when the filesystem reports one.
///
/// Whole seconds cannot distinguish an edit made in the same second as the last
/// sync from no edit at all, and if the size did not change either, that file
/// was never uploaded (`docs/BUGS.md` B25). `None` for a clock or filesystem that
/// cannot answer, which falls the comparison back to seconds rather than
/// asserting an mtime of zero.
pub fn system_mtime_ns(meta: &std::fs::Metadata) -> Option<i64> {
meta.modified()
.ok()
.and_then(|t| t.duration_since(SystemTime::UNIX_EPOCH).ok())
.and_then(|d| i64::try_from(d.as_nanos()).ok())
}
@@ -16,7 +16,7 @@ use super::*;
/// Ignored baseline rows are deliberately left in the database rather than
/// removed: with the row intact, un-ignoring the path later re-adopts the
/// existing remote file instead of reading as a brand-new local one.
pub fn classification_order<L, R, B>(
pub(super) fn classification_order<L, R, B>(
local: &HashMap<String, L>,
remote: &HashMap<String, R>,
baseline: &HashMap<String, B>,
@@ -52,7 +52,7 @@ where
/// Lets [`classification_order`] ask either walk's item whether it is a
/// directory without knowing which walk it came from.
pub trait HasKind {
pub(super) trait HasKind {
fn is_dir(&self) -> bool;
}
@@ -79,7 +79,7 @@ impl HasKind for RemoteItem {
/// counts as ignored if it matches as either. Erring towards "ignored" only ever
/// shrinks the set the guard checks, which weakens a safety net rather than
/// causing a deletion — the wrong direction to be wrong in is the other one.
pub fn filter_baseline<'a, B>(
pub(super) fn filter_baseline<'a, B>(
baseline: &'a HashMap<String, B>,
rules: &IgnoreRules,
) -> HashMap<String, &'a B> {
@@ -101,7 +101,7 @@ pub fn filter_baseline<'a, B>(
/// the whole pass instead is what B55 did, and it left one root-owned folder
/// stopping every other file in the tree from syncing (B196).
#[derive(Default)]
pub struct Unscanned {
pub(super) struct Unscanned {
covered: HashSet<String>,
/// The subset worth telling the user about, with why: an entry that only
/// vanished mid-scan is not, since the next pass sees it settled.
@@ -110,18 +110,18 @@ pub struct Unscanned {
impl Unscanned {
/// Leave out `rel`, which vanished while the scan looked at it.
pub fn vanished(&mut self, rel: String) {
pub(super) fn vanished(&mut self, rel: String) {
self.covered.insert(rel);
}
/// Leave out `rel`, which cannot be read for `reason`.
pub fn unreadable(&mut self, rel: String, reason: &str) {
pub(super) fn unreadable(&mut self, rel: String, reason: &str) {
self.unreadable.push(format!("{rel} ({reason})"));
self.covered.insert(rel);
}
/// Whether `rel` is a left-out path or lies under one.
pub fn covers(&self, rel: &str) -> bool {
pub(super) fn covers(&self, rel: &str) -> bool {
if self.covered.is_empty() {
return false;
}
@@ -138,7 +138,7 @@ impl Unscanned {
}
/// The unreadable paths with their reasons, sorted, for the activity feed.
pub fn report(&self) -> Vec<String> {
pub(super) fn report(&self) -> Vec<String> {
let mut lines = self.unreadable.clone();
lines.sort_unstable();
lines
@@ -149,7 +149,7 @@ impl Unscanned {
/// under a path the scan could not read. This is the set [`guard_local_wipe`]
/// checks and the set a push pass reads deletions from, since a path outside
/// it is absent from the local walk by rule or by failure, never by loss.
pub fn tracked_baseline<'a, B>(
pub(super) fn tracked_baseline<'a, B>(
baseline: &'a HashMap<String, B>,
rules: &IgnoreRules,
unscanned: &Unscanned,
@@ -167,7 +167,7 @@ pub fn tracked_baseline<'a, B>(
/// it raw trashed every synced path that later became ignored, because the walk
/// skips those, and the switch to on-demand that the push pass runs for then
/// deleted the local copy too (B197).
pub fn local_deletions<B, L>(
pub(super) fn local_deletions<B, L>(
tracked: &HashMap<String, &B>,
local: &HashMap<String, L>,
) -> Vec<String> {
@@ -205,7 +205,7 @@ fn looks_like_a_wipe(missing: usize, total: usize) -> bool {
/// When the synced paths are all or nearly all absent locally, the likely
/// cause is an unavailable mount or unreadable folder rather than a deliberate
/// deletion of the whole tree.
pub fn guard_local_wipe<B, L>(
pub(super) fn guard_local_wipe<B, L>(
baseline: &HashMap<String, B>,
local: &HashMap<String, L>,
) -> Result<(), String> {
@@ -231,7 +231,7 @@ pub fn guard_local_wipe<B, L>(
/// everything", which a pass answers by deleting the local copies. When all or
/// nearly all synced paths are gone from Drive at once, a failed listing is far
/// likelier than a deliberate wipe of the folder, so the pass stops instead.
pub fn guard_remote_wipe<B, R>(
pub(super) fn guard_remote_wipe<B, R>(
baseline: &HashMap<String, B>,
remote: &HashMap<String, R>,
) -> Result<(), String> {
@@ -259,7 +259,7 @@ pub fn guard_remote_wipe<B, R>(
/// every path under that folder that the walk did not return is then left out,
/// as [`Unscanned`] leaves out what the local scan could not read.
#[derive(Default)]
pub struct RemoteGaps {
pub(super) struct RemoteGaps {
/// Folders whose listing came back with fewer nodes than it named.
short: HashSet<String>,
/// Paths seen, but whose entry could not be read.
@@ -271,35 +271,35 @@ pub struct RemoteGaps {
impl RemoteGaps {
/// The listing of `folder` named nodes that did not come back.
pub fn short_listing(&mut self, folder: &str) {
pub(super) fn short_listing(&mut self, folder: &str) {
self.short.insert(folder.to_string());
}
/// `rel` is on Drive, but the walk could not read what it needs of it.
pub fn unread(&mut self, rel: String) {
pub(super) fn unread(&mut self, rel: String) {
self.unread.insert(rel);
}
/// The listing of `folder` failed, so nothing under it was walked.
pub fn unlisted(&mut self, folder: &str) {
pub(super) fn unlisted(&mut self, folder: &str) {
self.unlisted.insert(folder.to_string());
}
/// `rel` is no longer on Drive, or is about to be read again: whatever
/// was noted of it goes.
pub fn forget(&mut self, rel: &str) {
pub(super) fn forget(&mut self, rel: &str) {
self.short.remove(rel);
self.unread.remove(rel);
self.unlisted.remove(rel);
}
pub fn is_empty(&self) -> bool {
pub(super) fn is_empty(&self) -> bool {
self.short.is_empty() && self.unread.is_empty() && self.unlisted.is_empty()
}
/// Whether `rel` may be missing from `remote` only because the walk could
/// not read it. A path the walk returned is never hidden.
pub fn hides<R>(
pub(super) fn hides<R>(
&self,
rel: &str,
remote: &HashMap<String, R>,
@@ -326,7 +326,7 @@ impl RemoteGaps {
}
/// The folders to name to the user, sorted.
pub fn report(&self) -> Vec<String> {
pub(super) fn report(&self) -> Vec<String> {
let mut lines: Vec<String> = self
.short
.iter()
@@ -355,7 +355,7 @@ impl RemoteGaps {
/// Trashing the folder would take that work with it, and the next pass would
/// then delete the copy this pass just downloaded. `None` when everything under
/// it is exactly what the baseline recorded.
pub fn remote_subtree_changed(
pub(super) fn remote_subtree_changed(
rel: &str,
remote: &HashMap<String, RemoteItem>,
baseline: &HashMap<String, StoredSyncEntry>,
@@ -389,7 +389,7 @@ pub fn remote_subtree_changed(
/// Another computer's revision in the same second as that upload kept the
/// modification time, and only the size could show it (B254). The pass then
/// records the id on the row, so this costs one read per row.
pub fn unchanged_remote_size(
pub(super) fn unchanged_remote_size(
baseline: &HashMap<String, StoredSyncEntry>,
rel: &str,
mtime: i64,
@@ -410,12 +410,12 @@ pub fn unchanged_remote_size(
/// Whether a baseline row without a revision id can take the one Drive now
/// reports: the file's modification time and the size just read for real are
/// the ones the row recorded, so the revision is the one it was synced at.
pub fn revision_confirms_baseline(base: &StoredSyncEntry, mtime: i64, size: i64) -> bool {
pub(super) fn revision_confirms_baseline(base: &StoredSyncEntry, mtime: i64, size: i64) -> bool {
base.remote_revision_id.is_none() && remote_sig(base) == Some((mtime, size))
}
/// Join a child `name` onto a walk's `prefix`, giving a rel path.
pub fn join_rel(prefix: &str, name: &str) -> String {
pub(super) fn join_rel(prefix: &str, name: &str) -> String {
if prefix.is_empty() {
name.to_string()
} else {
@@ -427,7 +427,7 @@ pub fn join_rel(prefix: &str, name: &str) -> String {
/// synced at. Only a revision id on both sides can say so; a row from before
/// schema 44, or a node read without one, leaves it to the modification time
/// and size.
pub fn revision_moved(base: Option<&StoredSyncEntry>, now: Option<&str>) -> bool {
pub(super) fn revision_moved(base: Option<&StoredSyncEntry>, now: Option<&str>) -> bool {
match (base.and_then(|b| b.remote_revision_id.as_deref()), now) {
(Some(recorded), Some(now)) => recorded != now,
_ => false,
@@ -435,7 +435,7 @@ pub fn revision_moved(base: Option<&StoredSyncEntry>, now: Option<&str>) -> bool
}
/// The stored remote signature of a baseline row, if it has one.
pub fn remote_sig(e: &StoredSyncEntry) -> Option<(i64, i64)> {
pub(super) fn remote_sig(e: &StoredSyncEntry) -> Option<(i64, i64)> {
match (&e.remote_rev, &e.remote_hash) {
(Some(m), Some(s)) => Some((m.parse().ok()?, s.parse().ok()?)),
_ => None,
@@ -443,7 +443,7 @@ pub fn remote_sig(e: &StoredSyncEntry) -> Option<(i64, i64)> {
}
/// The parent of a `/`-joined relative path (`""` for a top-level entry).
pub fn parent_rel(rel: &str) -> &str {
pub(super) fn parent_rel(rel: &str) -> &str {
match rel.rfind('/') {
Some(i) => &rel[..i],
None => "",
@@ -451,7 +451,7 @@ pub fn parent_rel(rel: &str) -> &str {
}
/// The final component of a `/`-joined relative path.
pub fn base_name(rel: &str) -> &str {
pub(crate) fn base_name(rel: &str) -> &str {
match rel.rfind('/') {
Some(i) => &rel[i + 1..],
None => rel,
@@ -460,27 +460,28 @@ pub fn base_name(rel: &str) -> &str {
/// Turn a `/`-joined relative path into an OS path (`/` is already the separator
/// on Linux, this keeps the intent explicit).
pub fn rel_to_path(rel: &str) -> PathBuf {
pub(super) fn rel_to_path(rel: &str) -> PathBuf {
rel.split('/').collect()
}
/// The name for a conflict copy of `path`, e.g.
/// `notes (sync-conflict laptop 1700000000).txt`.
pub fn conflict_path(path: &Path, stamp: i64) -> PathBuf {
#[cfg(test)]
pub(super) fn conflict_path(path: &Path, stamp: i64) -> PathBuf {
conflict_path_with_suffix(path, stamp, 0)
}
/// As [`conflict_path`], with a deterministic suffix used when that name already
/// exists. This keeps conflict preservation from ever replacing an older copy.
pub fn conflict_path_with_suffix(path: &Path, stamp: i64, suffix: u32) -> PathBuf {
conflict_path_as(path, crate::naming::conflict_label(), stamp, suffix)
pub(super) fn conflict_path_with_suffix(path: &Path, stamp: i64, suffix: u32) -> PathBuf {
conflict_path_as(path, crate::conflict_label(), stamp, suffix)
}
/// [`conflict_path_with_suffix`] with the machine's label given.
pub fn conflict_path_as(path: &Path, label: &str, stamp: i64, suffix: u32) -> PathBuf {
pub(super) fn conflict_path_as(path: &Path, label: &str, stamp: i64, suffix: u32) -> PathBuf {
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("file");
let ext = path.extension().and_then(|s| s.to_str());
let tag = crate::naming::conflict_tag(label, stamp, suffix);
let tag = crate::conflict_tag(label, stamp, suffix);
let name = match ext {
Some(ext) => format!("{stem} (sync-conflict {tag}).{ext}"),
None => format!("{stem} (sync-conflict {tag})"),
@@ -494,7 +495,7 @@ pub fn conflict_path_as(path: &Path, label: &str, stamp: i64, suffix: u32) -> Pa
/// A pure decision for one file-shaped path. Transfer identities and filesystem
/// effects are attached by the executor after this classification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilePlan {
pub(super) enum FilePlan {
Unchanged,
Deferred,
UploadNew,
@@ -515,7 +516,7 @@ pub enum FilePlan {
AdoptBaseline,
}
pub fn plan_file(
pub(super) fn plan_file(
local: Option<&LocalItem>,
remote: Option<&RemoteItem>,
baseline: Option<&StoredSyncEntry>,
@@ -15,7 +15,7 @@ use super::*;
/// A stage of a pass. A pass runs them in this order, except that planning
/// and applying alternate, one folder depth at a time.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Phase {
pub(crate) enum Phase {
/// Waiting for the folder's lock, held by a mode switch or a relocation.
LockWait,
/// Reading the stored baseline from the database.
@@ -57,7 +57,7 @@ impl Phase {
/// A kind of call to Drive, or of work applied for one path.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Call {
pub(crate) enum Call {
/// The child uids of one folder.
ListChildren,
/// Names and kinds of one folder's children, without unlocking file keys.
@@ -107,7 +107,7 @@ impl Call {
/// Something a pass counts.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Count {
pub(crate) enum Count {
/// Files and folders the local walk found.
LocalEntries,
/// Folders on Drive the remote walk listed.
@@ -184,7 +184,7 @@ impl Stat {
/// The timings and counts of one pass.
#[derive(Clone, Debug)]
pub struct PassTrace {
pub(crate) struct PassTrace {
folder_id: i64,
started: Instant,
/// How the pass ended and how long it ran; `None` while it runs.
@@ -196,7 +196,7 @@ pub struct PassTrace {
}
impl PassTrace {
pub fn new(folder_id: i64) -> Self {
pub(crate) fn new(folder_id: i64) -> Self {
Self {
folder_id,
started: Instant::now(),
@@ -208,28 +208,28 @@ impl PassTrace {
}
}
pub fn folder_id(&self) -> i64 {
pub(crate) fn folder_id(&self) -> i64 {
self.folder_id
}
pub fn is_ended(&self) -> bool {
pub(crate) fn is_ended(&self) -> bool {
self.ended.is_some()
}
pub fn phase(&mut self, phase: Phase, took: Duration) {
pub(crate) fn phase(&mut self, phase: Phase, took: Duration) {
self.phases[phase as usize].add(took);
}
pub fn call(&mut self, call: Call, took: Duration) {
pub(crate) fn call(&mut self, call: Call, took: Duration) {
self.calls[call as usize].add(took);
}
pub fn count(&mut self, count: Count, n: usize) {
pub(crate) fn count(&mut self, count: Count, n: usize) {
self.counts[count as usize] += n as u64;
}
/// Note how long listing the Drive folder at `rel` took, keeping the slowest.
pub fn listing(&mut self, rel: &str, took: Duration) {
pub(crate) fn listing(&mut self, rel: &str, took: Duration) {
if self
.slowest_listing
.as_ref()
@@ -239,7 +239,7 @@ impl PassTrace {
}
}
pub fn end(&mut self, how: &'static str) {
pub(crate) fn end(&mut self, how: &'static str) {
if self.ended.is_none() {
self.ended = Some((how, self.started.elapsed()));
}
@@ -252,7 +252,7 @@ impl PassTrace {
/// The trace as `pdfs diagnostics` reports it. Stages and calls that
/// never happened are left out.
pub fn summary(&self) -> SyncPassTrace {
pub(crate) fn summary(&self) -> SyncPassTrace {
SyncPassTrace {
folder_id: self.folder_id,
ended: self
+1 -1
View File
@@ -1672,7 +1672,7 @@ pub(crate) fn clock_time(unix: i64) -> String {
/// the set is unchanged (the common case on the 2s tick) it only flips the unpin
/// buttons' `sensitive` flag, avoiding the rebuild that used to flicker the list
/// and drop scroll/selection every tick.
pub(crate) fn repaint_pins(ui: &Rc<Ui>, pins: &[pdfs_core::control::Pin], mounted: bool) {
pub(crate) fn repaint_pins(ui: &Rc<Ui>, pins: &[pdfs_core::cache::Pin], mounted: bool) {
let desired: Vec<String> = pins.iter().map(|p| p.path.clone()).collect();
if ui.status.pins_state.borrow().as_ref() == Some(&desired) {
for r in ui.status.pin_rows.borrow().iter() {
-22
View File
@@ -1,22 +0,0 @@
[package]
name = "pdfs-store"
version.workspace = true
edition.workspace = true
license.workspace = true
authors.workspace = true
rust-version.workspace = true
repository.workspace = true
homepage.workspace = true
description = "SQLite metadata and the content cache for the Proton Drive Linux client"
[dependencies]
pdfs-core.workspace = true
proton-drive-rs.workspace = true
proton-gallery-rs.workspace = true
rusqlite.workspace = true
serde.workspace = true
serde_json.workspace = true
tracing.workspace = true
parking_lot.workspace = true
sha2.workspace = true
libc.workspace = true
-9
View File
@@ -1,9 +0,0 @@
//! The daemon's local state: the SQLite metadata database and the content
//! cache of file blocks on disk.
//!
//! Split out of `pdfs-core`, which keeps configuration, the control protocol and
//! the types every front end shares. Front ends that only talk to the daemon do
//! not depend on this crate.
pub mod cache;
pub mod db;
-17
View File
@@ -1,17 +0,0 @@
[package]
name = "pdfs-sync"
version.workspace = true
edition.workspace = true
license.workspace = true
authors.workspace = true
rust-version.workspace = true
repository.workspace = true
homepage.workspace = true
description = "The mirror engine's planner and pass model for the Proton Drive Linux client"
[dependencies]
pdfs-core.workspace = true
pdfs-drive.workspace = true
pdfs-store.workspace = true
proton-drive-rs.workspace = true
tracing.workspace = true
-24
View File
@@ -1,24 +0,0 @@
//! The mirror engine's decisions, apart from the I/O that feeds and applies them.
//!
//! [`model`] is what a pass knows about each path, [`planner`] decides what to
//! do with it and refuses what looks like a wipe, [`trace`] records where a pass
//! spent its time, and [`naming`] names conflict copies. None of it touches the
//! disk, the database or Drive, so all of it is tested without a daemon.
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant, SystemTime};
use pdfs_core::control::ActivityKind;
use pdfs_core::syncignore::IgnoreRules;
use pdfs_store::db::StoredSyncEntry;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use proton_drive_rs::{Node, NodeKind};
pub mod model;
pub mod naming;
pub mod planner;
pub mod trace;
use model::{LocalItem, LocalSig, RemoteItem};
use trace::Call;
-78
View File
@@ -1,78 +0,0 @@
//! How conflict copies are named, here and on Drive.
use std::path::Path;
use std::sync::OnceLock;
/// A variant of `name` to fall back on when the remote already has that name.
///
/// Deliberately the same shape the sync engine uses for its conflict copies
/// (`sync.rs`, `conflict_path`), so the two halves of the product name the same
/// situation the same way and a user only has to learn it once.
pub fn conflict_name(name: &str, stamp: i64) -> String {
conflict_name_as(name, conflict_label(), stamp)
}
/// [`conflict_name`] with the machine's label given.
pub fn conflict_name_as(name: &str, label: &str, stamp: i64) -> String {
let path = Path::new(name);
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or(name);
let tag = conflict_tag(label, stamp, 0);
match path.extension().and_then(|s| s.to_str()) {
Some(ext) => format!("{stem} (sync-conflict {tag}).{ext}"),
None => format!("{stem} (sync-conflict {tag})"),
}
}
/// This machine's name as its conflict copies carry it (`docs/BUGS.md` B251).
///
/// Two computers syncing one folder that each keep a copy of the same file in
/// the same second would otherwise make the same name on Drive, and nobody
/// could tell which computer a copy came from. Read once, from the hostname.
pub fn conflict_label() -> &'static str {
static LABEL: OnceLock<String> = OnceLock::new();
LABEL.get_or_init(|| conflict_label_of(&this_hostname()))
}
/// `host` as one token: anything but ASCII letters, digits, `-`, `_` and `.`
/// becomes `-`, so the label holds no space for `conflict_base_name` to trip
/// on and no `/` or `)` to break the name.
pub fn conflict_label_of(host: &str) -> String {
let label: String = host
.chars()
.take(32)
.map(|c| {
if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {
c
} else {
'-'
}
})
.collect();
label.trim_matches('-').to_string()
}
/// The inside of a conflict copy's marker: `<label> <stamp>`, with `-<n>`
/// when an earlier copy already holds that name. Without a label it is the
/// bare stamp that copies had before B251.
pub fn conflict_tag(label: &str, stamp: i64, suffix: u32) -> String {
let suffix = if suffix == 0 {
String::new()
} else {
format!("-{suffix}")
};
if label.is_empty() {
format!("{stamp}{suffix}")
} else {
format!("{label} {stamp}{suffix}")
}
}
/// This machine's hostname, used to name (and later recover) its Proton Drive
/// Device. Reads the live kernel hostname, falling back to a generic label.
pub fn this_hostname() -> String {
std::fs::read_to_string("/proc/sys/kernel/hostname")
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "Linux device".to_string())
}
+1 -1
View File
@@ -625,7 +625,7 @@ Features whose code is shaped by a constraint that the code alone does not expla
### Photos
`pdfs-fuse/src/photos.rs`, `pdfs-store/src/db/photos.rs`, `pdfs-gui/src/app/pages/photos.rs`.
`pdfs-fuse/src/photos.rs`, `pdfs-core/src/db/photos.rs`, `pdfs-gui/src/app/pages/photos.rs`.
- **Favorites** use the SDK's photo tags. Favoriting a photo that is not on the account's own
photos volume (shared, or only in an album) is refused: it would need re-encryption the SDK does
+49
View File
@@ -108,6 +108,7 @@ a live account since.
| Entry | Title |
|---|---|
| [B297](#b297--the-simulations-fail-and-hang-when-run-in-parallel-and-nothing-stops-that) | The simulations fail and hang when run in parallel, and nothing stops that |
| [B296](#b296--a-busy-database-stalls-reads-and-piles-up-diagnostics-threads) | A busy database stalls reads, and piles up diagnostics threads |
| [B294](#b294--a-mirror-folder-too-large-to-finish-in-one-run-never-syncs-and-holds-back-the-others) | A mirror folder too large to finish in one run never syncs, and holds back the others |
| [B66](#b66--local-only-pending-data-is-not-protected-at-shutdown-high-21) | Local-only pending data is not protected at shutdown (HIGH-21) |
@@ -308,6 +309,7 @@ a live account since.
| Entry | Title |
|---|---|
| [B295](#b295--a-resize-the-scratch-file-refused-still-succeeded) | A resize the scratch file refused still succeeded |
| [B293](#b293--a-large-trash-never-lists-and-empty-trash-never-empties-it) | A large trash never lists, and Empty Trash never empties it |
| [B292](#b292--two-programs-changing-settings-at-once-lose-one-of-the-changes) | Two programs changing settings at once lose one of the changes |
| [B290](#b290--reopening-the-database-right-after-closing-it-can-be-refused-as-another-daemon) | Reopening the database right after closing it can be refused as another daemon |
@@ -398,6 +400,53 @@ a live account since.
Newest first.
### B297 — The simulations fail and hang when run in parallel, and nothing stops that
**Status:** Fixed (unverified)
**Found:** 2026-11-25, while running the full simulation suite several times each for #134, #135
and the 4.0 crate moves, with `cargo test -p pdfs-fuse --lib -- --ignored sim::`. That command
leaves out `--test-threads=1`, which CI and [TESTING.md](TESTING.md) use, so libtest ran up to
eight simulations at once in one process.
**Where:** `crates/pdfs-fuse/src/sim/daemon.rs`, `Daemon::start` and `Daemon::shut_down`
**Repro:** Run the suite without `--test-threads=1`. Of 18 such runs on three branches based on
main, 6 passed, 10 failed and 2 hung until a 900 s timeout. The failures were timing asserts
in many tests, among them `a_write_that_failed_on_a_short_outage_goes_out_soon_after_the_link_returns`,
`three_clients_one_writer_each` and `one_client_with_stale_hashes_and_reordered_echoes`.
Each passes when run alone.
In a hung run, one test thread stayed in state D in `request_wait_answer`, waiting on a FUSE
request to a mount its own process serves. Killing the process left it a zombie and left its
mounts in place until their connections were aborted through
`/sys/fs/fuse/connections/<n>/abort`.
Run serially, the same branches pass in CI (#133 to #137).
**Cause.** The simulations share process-wide state: `isolate_from_the_developer` sets the XDG
variables once, which is sound only while no other test reads the environment, and every
daemon runs drain workers, a sync engine and a runtime on the same few cores. In parallel the
timing asserts miss their deadlines, and the harness has no way out of a mount that stops
answering.
**Fix.** `Daemon::start` takes a turn: a daemon started on one test thread waits while
another test thread still has one, so plain `cargo test` runs the simulations one after the
other. A daemon on the same thread, as in a restart or the multi-client runs, does not wait.
`--test-threads=1` stays the documented way, because it also keeps the parts of a test
before its first daemon apart.
A mount that does not stop within 60 s has its FUSE connection aborted through
`/sys/fs/fuse/connections/<n>/abort`, which the mounting user may write, and the stop fails
with that message. A daemon alive after 20 minutes gets the same, so a test blocked on a
request the mount never answers fails with `ENOTCONN` instead of hanging the run.
**Verified:** `a_simulation_on_another_thread_waits_for_this_ones_daemons`, which fails
without the turn.
Separately, CI on main (`0b9e849`) failed `a_move_blocked_by_trash_can_be_retried_after_restore`
once, serially ([run](https://github.com/narrrl/proton-drive-linux/actions/runs/45694939718)):
the assert at `daemon.rs:2209` found an empty list. It has not failed since.
---
### B296 — A busy database stalls reads, and piles up diagnostics threads
**Status:** Fixed (unverified)
+1 -1
View File
@@ -4,7 +4,7 @@ All notable changes to the Linux client since the 1.0.0 release. Format follows
[Keep a Changelog](https://keepachangelog.com/1.1.0/); versions follow semver, and every
release is tagged `vX.Y.Z` with `Cargo.toml` and `packaging/PKGBUILD` in agreement.
`Schema:` lines record the SQLite `SCHEMA_VERSION` (`pdfs-store/src/db/migrations.rs`) a
`Schema:` lines record the SQLite `SCHEMA_VERSION` (`pdfs-core/src/db/migrations.rs`) a
release ships. Migrations are forward-only — a database written by a newer client is a hard
refuse-to-open, not a downgrade, so rolling back a release means restoring the cache from
scratch (user data in `staging/` and `recovery/` is never touched by this).
+2 -2
View File
@@ -126,8 +126,8 @@ release may still be running when a new front end starts, so treat an error repl
request as "not supported".
**A schema change.** Migrations are forward-only. Add a new step to
`crates/pdfs-store/src/db/migrations.rs` and bump `SCHEMA_VERSION`; never edit a shipped step. Add
a test in `crates/pdfs-store/src/db/tests.rs` that migrates from the previous version.
`crates/pdfs-core/src/db/migrations.rs` and bump `SCHEMA_VERSION`; never edit a shipped step. Add
a test in `crates/pdfs-core/src/db/tests.rs` that migrates from the previous version.
**A GUI string.** Wrap it in the helpers from `crates/pdfs-gui/src/i18n.rs`, add any new source
file to `po/POTFILES.in`, run `po/update.sh`, and translate the new entries in every catalog. See
+1 -1
View File
@@ -25,7 +25,7 @@ The daemon already knows what changed:
`NodeUpdated { node_uid, parent_node_uid }` and `NodeDeleted { node_uid }` name the exact nodes.
Today only the FUSE cache uses these events.
The pass trace (`crates/pdfs-sync/src/trace.rs`) is how we measure this design against the current one. Get
The pass trace (`sync/trace.rs`) is how we measure this design against the current one. Get
traces from #53 and from a local 100k-file test folder before Phase 2, so the work goes where the
time goes.
+2 -2
View File
@@ -16,7 +16,7 @@ cargo clippy --workspace --all-targets -- -D warnings
```
Tests sit in `#[cfg(test)]` modules next to the code. Database tests are in
`crates/pdfs-store/src/db/tests.rs`; a schema change adds one that migrates from the previous
`crates/pdfs-core/src/db/tests.rs`; a schema change adds one that migrates from the previous
version.
To check the migrations against a real database, point `PDFS_MIGRATE_DB` at it and run the
@@ -24,7 +24,7 @@ ignored test. It migrates a copy taken with `VACUUM INTO` and never writes the d
```bash
PDFS_MIGRATE_DB=~/.local/state/proton-drive-linux/cache.db \
cargo test -p pdfs-store a_copy_of_a_real_database -- --ignored
cargo test -p pdfs-core a_copy_of_a_real_database -- --ignored
```
## Simulation runs