Compare commits

...
Author SHA1 Message Date
nvrl 6ecf713d3a Merge pull request #141 from narrrl/feat/drive-call-stats
feat(drive,fuse,cli): count and time every call to Drive in pdfs diagnostics
2026-11-26 01:58:28 +01:00
nvrl 8e3e048005 feat(drive,fuse,cli): count and time every call to Drive in pdfs diagnostics
pdfs_drive::counted::Counted wraps any DriveApi and records, per method,
how many calls were made, how many failed, and their total and longest
time. The mount wraps its Drive in it before the first call, so the root
lookup counts too. Diagnostics gains drive_calls (serde default, so an
older CLI or daemon still reads the report), and pdfs diagnostics prints
it. A streaming batch call is counted when it starts, untimed.
2026-11-26 01:37:04 +01:00
nvrl f34ed62f27 refactor: move the sync planner, pass model and trace into pdfs-sync
Third crate seam of 4.0. `sync/model.rs`, `sync/planner.rs` and
`sync/trace.rs` decide and record without doing I/O, so they move into a
new `pdfs-sync` crate that depends only on pdfs-core, pdfs-drive,
pdfs-store and the SDK's node types. The naming of conflict copies moves
with them as `pdfs_sync::naming`. `Applied` and the mtime and size
signature helpers move from `sync.rs` into the model, which uses them.
`node_revision_id` moves to pdfs-drive.

`sync.rs` and `sync/engine.rs` stay in pdfs-fuse until the store and
local-filesystem ports exist. `conflict_path` loses its `cfg(test)`,
which does not reach another crate's tests. No behaviour change.
2026-11-26 01:03:05 +01:00
nvrl 19cfbf0ae0 refactor: move the Drive seam and FakeDrive into pdfs-drive
Second crate seam of 4.0. `DriveApi`, `RevisionRead` and the forwarding
impl for the real client move from `pdfs-fuse/src/drive.rs` to the root of a
new `pdfs-drive` crate. The in-memory `FakeDrive` and the simulation RNG
move under its `sim` feature, which `pdfs-fuse` enables for its tests.

- `is_network_error` classifies Drive's errors and moves with them;
  `link` re-exports it.
- `DriveApi::landing`, the drain's test hook, is no longer `cfg(test)`:
  a cfg on a trait method does not cross crates. Its default is a no-op and
  the drain still calls it only in tests.
- `pdfs-fuse` keeps its paths (`crate::drive`, `crate::sim::fake_drive`)
  through re-exports, so no call site changes.

Test counts are unchanged: pdfs-fuse 448 plus pdfs-drive 18 is the 466
pdfs-fuse had before.
2026-11-26 00:57:08 +01:00
nvrl 5e3e242db8 refactor: move the database and the content cache into pdfs-store
First crate seam of 4.0. `pdfs-core/src/db` and `cache.rs` move unchanged
into a new `pdfs-store` crate; `pdfs-core` keeps configuration, the control
protocol and the shared types, and no longer opens SQLite itself.

- `Pin` is a control-protocol type, so it moves to `pdfs_core::control`;
  `pdfs_store::cache` re-exports it. The GUI still depends on core alone.
- `Access::as_db_str`/`from_db_str` become public for the store.
- `pdfs-fuse` and `pdfs-cli` depend on `pdfs-store`; imports change from
  `pdfs_core::{db,cache}` to `pdfs_store::{db,cache}`.

Test counts are unchanged: pdfs-core 208 plus pdfs-store 277 is the 485
pdfs-core had before.
2026-11-26 00:47:53 +01:00
nvrl 580bbacec3 fix(core,fuse): fail a read rather than wait on the writer, and keep one diagnostics probe
`Db::read` fell back to the write connection when it could not open a
read-only one, so a read waited behind whatever transaction the writer was
in. It now returns an error; only an in-memory database, which has no
read-only connections, still reads through the writer.

The diagnostics report counted queued operations on a new thread per report
and left it behind after half a second. The supervisor asks every tick, so a
database that did not answer gained a thread per tick. A probe now starts
only when the previous one has returned, and the count is reported as
unknown instead of 0 when it does not come back (B296).
2026-11-26 00:47:49 +01:00
nvrl b85c2bf786 Merge pull request #134 from narrrl/feat/sync-remote-dirty
feat(fuse,core): list only the folders that changed on Drive in a mirror pass (#53)
2026-11-26 00:26:26 +01:00
nvrl 2d9fb03d8b Merge pull request #133 from narrrl/fix/resize-scratch-refused
fix(fuse): fail a resize the scratch file refuses instead of recording it (B295)
2026-11-26 00:25:51 +01:00
nvrl 293fda9177 fix(fuse): fail a resize the scratch file refuses instead of recording it (B295)
A resize through an open handle recorded the new length and claimed the
grown tail as written before calling set_len on the scratch file, and
ignored its result. A refused grow (full disk) then succeeded, and the
handle described bytes the scratch file never held.

WriteHandle::resize now resizes the scratch file first and records the
length and ranges only on success; setattr answers its error.
2026-11-25 21:47:09 +01:00
74 changed files with 1741 additions and 701 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-core/src/db/migrations.rs`.
`SCHEMA_VERSION` in `crates/pdfs-store/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,6 +3641,7 @@ dependencies = [
"clap_complete",
"pdfs-core",
"pdfs-fuse",
"pdfs-store",
"rpassword",
"serde_json",
"tokio",
@@ -3679,6 +3680,21 @@ 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"
@@ -3697,6 +3713,9 @@ 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",
@@ -3737,6 +3756,33 @@ 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"
+4 -1
View File
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["crates/pdfs-core", "crates/pdfs-fuse", "crates/pdfs-cli", "crates/pdfs-gui"]
members = ["crates/pdfs-core", "crates/pdfs-store", "crates/pdfs-drive", "crates/pdfs-sync", "crates/pdfs-fuse", "crates/pdfs-cli", "crates/pdfs-gui"]
[workspace.package]
version = "3.10.0"
@@ -24,6 +24,9 @@ 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,6 +15,7 @@ path = "src/main.rs"
[dependencies]
pdfs-core.workspace = true
pdfs-store.workspace = true
pdfs-fuse.workspace = true
tokio.workspace = true
anyhow.workspace = true
+13 -3
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;
@@ -3606,7 +3606,8 @@ fn cmd_diagnostics() -> Result<()> {
"uptime {} rss {} pending ops {}",
human_secs(d.uptime_secs),
human_bytes(d.rss_bytes),
d.pending_ops,
d.pending_ops
.map_or_else(|| "unknown (database busy)".to_owned(), |n| n.to_string()),
);
println!(
"control handlers {}/{}",
@@ -3645,6 +3646,15 @@ fn cmd_diagnostics() -> Result<()> {
);
}
}
if !d.drive_calls.is_empty() {
println!("calls to Drive since start:");
for call in &d.drive_calls {
println!(
" {:<38} {:>7} calls {:>5} failed {:>9} ms total {:>7} ms longest",
call.call, call.count, call.errors, call.total_ms, call.longest_ms,
);
}
}
if d.inflight.is_empty() {
println!("in-flight requests: none");
} else {
+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(crate) fn as_db_str(self) -> &'static str {
pub fn as_db_str(self) -> &'static str {
match self {
Self::Owner => "owner",
Self::Editor => "editor",
@@ -25,7 +25,7 @@ impl Access {
}
}
pub(crate) fn from_db_str(value: &str) -> Option<Self> {
pub fn from_db_str(value: &str) -> Option<Self> {
match value {
"owner" => Some(Self::Owner),
"editor" => Some(Self::Editor),
+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 [`crate::cache`].
/// blobs back under this; pinned files are exempt. See `pdfs_store::cache`.
pub const DEFAULT_CACHE_BUDGET_BYTES: u64 = 5 * 1024 * 1024 * 1024;
/// Environment override for [`AppConfig::resolved_conflict_sweep`]. Exists so a
+49 -4
View File
@@ -12,10 +12,37 @@ 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
@@ -2335,11 +2362,29 @@ pub struct Diagnostics {
/// from the CLI.
pub control_handlers: usize,
pub control_handler_limit: usize,
/// Queued mutations not yet drained.
pub pending_ops: u64,
/// Queued mutations not yet drained. `None` when the database did not
/// answer in time, which is itself the thing to look at.
#[serde(default)]
pub pending_ops: Option<u64>,
/// The folder-sync engine. `None` from a daemon that predates the field.
#[serde(default)]
pub sync: Option<SyncEngineState>,
/// Every kind of call made to Drive since start: how many, how many
/// failed, and how long they took. Empty from a daemon that predates the
/// field.
#[serde(default)]
pub drive_calls: Vec<DriveCallStat>,
}
/// One kind of call to Drive, in [`Diagnostics::drive_calls`].
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct DriveCallStat {
/// The client method, such as `enumerate_folder_children_node_uids`.
pub call: String,
pub count: u64,
pub errors: u64,
pub total_ms: u64,
pub longest_ms: u64,
}
/// What the folder-sync engine is doing, for [`Diagnostics`].
@@ -2477,7 +2522,7 @@ pub enum Response {
username: String,
mountpoint: String,
pinned: usize,
/// Bytes of cached content blobs (see [`crate::cache::ContentCache::usage`]).
/// Bytes of cached content blobs (see `pdfs_store::cache::ContentCache::usage`).
used: u64,
/// Configured soft byte cap (`0` = unlimited).
budget: u64,
-2
View File
@@ -5,10 +5,8 @@
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 [`crate::db::Db::local_upsert_batch`].
//! batches into `pdfs_store::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
/// [`crate::cache`]'s tests.
/// `pdfs_store::cache`'s tests.
struct TempDir(std::path::PathBuf);
impl TempDir {
fn new() -> Self {
+28
View File
@@ -0,0 +1,28 @@
[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
+597
View File
@@ -0,0 +1,597 @@
//! A [`DriveApi`] that counts and times every call it forwards.
//!
//! Wrapping the client in [`Counted`] answers "what is the daemon asking Drive,
//! and how long does Drive take" without a debugger or a log at debug level:
//! [`CallStats::snapshot`] gives, per kind of call, how many were made, how
//! many failed, and their total and longest time. The diagnostics report shows
//! it.
//!
//! A streaming call (a batch move, restore or delete) is counted once when it
//! starts. Its time is not measured, because the stream outlives the call.
use std::io::{Read, Write};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use async_trait::async_trait;
use proton_drive_rs::proton_sdk::account::Quota;
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, NodeMoveItem,
Thumbnail, ThumbnailType, TrashedNode,
};
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
/// Every kind of call [`DriveApi`] makes, one per method.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DriveCall {
GetMyFilesFolder,
ContextShareId,
GetNode,
EnumerateNodes,
EnumerateNodesLight,
EnumerateChildren,
EnumerateEvents,
InvalidateCaches,
CreateFolder,
UploadFile,
UploadFileFrom,
UploadFileReplacingDraft,
UploadNewRevision,
OpenRevision,
DownloadThumbnail,
DownloadFile,
DownloadRevision,
RenameNode,
MoveNode,
CopyNode,
GetAvailableName,
MoveNodes,
TrashNodes,
RestoreNodes,
RestoreNodesStreaming,
DeleteNodes,
EnumerateTrash,
EmptyTrash,
EnumerateTrashedNodes,
Quota,
EnumerateDevices,
CreateDevice,
}
impl DriveCall {
pub const ALL: [DriveCall; 32] = [
DriveCall::GetMyFilesFolder,
DriveCall::ContextShareId,
DriveCall::GetNode,
DriveCall::EnumerateNodes,
DriveCall::EnumerateNodesLight,
DriveCall::EnumerateChildren,
DriveCall::EnumerateEvents,
DriveCall::InvalidateCaches,
DriveCall::CreateFolder,
DriveCall::UploadFile,
DriveCall::UploadFileFrom,
DriveCall::UploadFileReplacingDraft,
DriveCall::UploadNewRevision,
DriveCall::OpenRevision,
DriveCall::DownloadThumbnail,
DriveCall::DownloadFile,
DriveCall::DownloadRevision,
DriveCall::RenameNode,
DriveCall::MoveNode,
DriveCall::CopyNode,
DriveCall::GetAvailableName,
DriveCall::MoveNodes,
DriveCall::TrashNodes,
DriveCall::RestoreNodes,
DriveCall::RestoreNodesStreaming,
DriveCall::DeleteNodes,
DriveCall::EnumerateTrash,
DriveCall::EmptyTrash,
DriveCall::EnumerateTrashedNodes,
DriveCall::Quota,
DriveCall::EnumerateDevices,
DriveCall::CreateDevice,
];
/// The name the diagnostics report shows: the client method's own.
pub fn name(self) -> &'static str {
match self {
DriveCall::GetMyFilesFolder => "get_my_files_folder",
DriveCall::ContextShareId => "context_share_id",
DriveCall::GetNode => "get_node",
DriveCall::EnumerateNodes => "enumerate_nodes",
DriveCall::EnumerateNodesLight => "enumerate_nodes_light",
DriveCall::EnumerateChildren => "enumerate_folder_children_node_uids",
DriveCall::EnumerateEvents => "enumerate_events",
DriveCall::InvalidateCaches => "invalidate_caches_for_event",
DriveCall::CreateFolder => "create_folder",
DriveCall::UploadFile => "upload_file",
DriveCall::UploadFileFrom => "upload_file_from",
DriveCall::UploadFileReplacingDraft => "upload_file_replacing_draft_from",
DriveCall::UploadNewRevision => "upload_new_revision_from",
DriveCall::OpenRevision => "open_revision",
DriveCall::DownloadThumbnail => "download_thumbnail",
DriveCall::DownloadFile => "download_file_to",
DriveCall::DownloadRevision => "download_revision_to",
DriveCall::RenameNode => "rename_node",
DriveCall::MoveNode => "move_node",
DriveCall::CopyNode => "copy_node",
DriveCall::GetAvailableName => "get_available_name",
DriveCall::MoveNodes => "move_nodes_streaming",
DriveCall::TrashNodes => "trash_nodes",
DriveCall::RestoreNodes => "restore_nodes",
DriveCall::RestoreNodesStreaming => "restore_nodes_streaming",
DriveCall::DeleteNodes => "delete_nodes_streaming",
DriveCall::EnumerateTrash => "enumerate_trash_node_uids",
DriveCall::EmptyTrash => "empty_trash",
DriveCall::EnumerateTrashedNodes => "enumerate_trashed_nodes_light",
DriveCall::Quota => "quota",
DriveCall::EnumerateDevices => "enumerate_devices",
DriveCall::CreateDevice => "create_device",
}
}
}
/// One kind of call, as [`CallStats::snapshot`] reports it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CallStat {
pub call: DriveCall,
pub count: u64,
pub errors: u64,
pub total: Duration,
pub longest: Duration,
}
#[derive(Default)]
struct Counter {
count: AtomicU64,
errors: AtomicU64,
total_us: AtomicU64,
longest_us: AtomicU64,
}
/// The counts behind a [`Counted`] drive, shared with whoever reports them.
pub struct CallStats {
counters: [Counter; DriveCall::ALL.len()],
}
impl Default for CallStats {
fn default() -> Self {
Self {
counters: std::array::from_fn(|_| Counter::default()),
}
}
}
impl CallStats {
fn record(&self, call: DriveCall, failed: bool, took: Option<Duration>) {
let counter = &self.counters[call as usize];
counter.count.fetch_add(1, Ordering::Relaxed);
if failed {
counter.errors.fetch_add(1, Ordering::Relaxed);
}
if let Some(took) = took {
let us = u64::try_from(took.as_micros()).unwrap_or(u64::MAX);
counter.total_us.fetch_add(us, Ordering::Relaxed);
counter.longest_us.fetch_max(us, Ordering::Relaxed);
}
}
/// Every kind of call made at least once, in [`DriveCall::ALL`] order.
pub fn snapshot(&self) -> Vec<CallStat> {
DriveCall::ALL
.iter()
.filter_map(|&call| {
let counter = &self.counters[call as usize];
let count = counter.count.load(Ordering::Relaxed);
(count > 0).then(|| CallStat {
call,
count,
errors: counter.errors.load(Ordering::Relaxed),
total: Duration::from_micros(counter.total_us.load(Ordering::Relaxed)),
longest: Duration::from_micros(counter.longest_us.load(Ordering::Relaxed)),
})
})
.collect()
}
}
/// A [`DriveApi`] that forwards to `inner` and records every call in `stats`.
pub struct Counted {
inner: Arc<dyn DriveApi>,
stats: Arc<CallStats>,
}
impl Counted {
pub fn new(inner: Arc<dyn DriveApi>, stats: Arc<CallStats>) -> Self {
Self { inner, stats }
}
async fn timed<T>(
&self,
call: DriveCall,
future: impl std::future::Future<Output = Result<T>>,
) -> Result<T> {
let started = Instant::now();
let result = future.await;
self.stats
.record(call, result.is_err(), Some(started.elapsed()));
result
}
}
#[async_trait]
impl DriveApi for Counted {
async fn get_my_files_folder(&self) -> Result<Node> {
self.timed(
DriveCall::GetMyFilesFolder,
self.inner.get_my_files_folder(),
)
.await
}
async fn context_share_id(&self, uid: &NodeUid) -> Result<ShareId> {
self.timed(DriveCall::ContextShareId, self.inner.context_share_id(uid))
.await
}
async fn get_node(&self, uid: &NodeUid) -> Result<Option<Node>> {
self.timed(DriveCall::GetNode, self.inner.get_node(uid))
.await
}
async fn enumerate_nodes(&self, uids: &[NodeUid]) -> Result<Vec<Node>> {
self.timed(DriveCall::EnumerateNodes, self.inner.enumerate_nodes(uids))
.await
}
async fn enumerate_nodes_light(&self, uids: &[NodeUid]) -> Result<Vec<Node>> {
self.timed(
DriveCall::EnumerateNodesLight,
self.inner.enumerate_nodes_light(uids),
)
.await
}
async fn enumerate_folder_children_node_uids(
&self,
folder_uid: &NodeUid,
) -> Result<Vec<NodeUid>> {
self.timed(
DriveCall::EnumerateChildren,
self.inner.enumerate_folder_children_node_uids(folder_uid),
)
.await
}
async fn enumerate_events(
&self,
scope: &DriveEventScopeId,
cursor: Option<&DriveEventId>,
) -> Result<Vec<DriveEvent>> {
self.timed(
DriveCall::EnumerateEvents,
self.inner.enumerate_events(scope, cursor),
)
.await
}
async fn invalidate_caches_for_event(&self, event: &DriveEvent) -> Result<()> {
self.timed(
DriveCall::InvalidateCaches,
self.inner.invalidate_caches_for_event(event),
)
.await
}
async fn create_folder(
&self,
parent_uid: &NodeUid,
name: &str,
last_modification_time: Option<i64>,
) -> Result<NodeUid> {
self.timed(
DriveCall::CreateFolder,
self.inner
.create_folder(parent_uid, name, last_modification_time),
)
.await
}
async fn upload_file(
&self,
parent_uid: &NodeUid,
name: &str,
media_type: &str,
contents: &[u8],
) -> Result<NodeUid> {
self.timed(
DriveCall::UploadFile,
self.inner
.upload_file(parent_uid, name, media_type, contents),
)
.await
}
async fn upload_file_from_dyn(
&self,
parent_uid: &NodeUid,
name: &str,
media_type: &str,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
aead: bool,
) -> Result<NodeUid> {
self.timed(
DriveCall::UploadFileFrom,
self.inner.upload_file_from_dyn(
parent_uid,
name,
media_type,
reader,
intended_size,
thumbnails,
last_modification_time,
aead,
),
)
.await
}
async fn upload_file_replacing_draft_from_dyn(
&self,
parent_uid: &NodeUid,
name: &str,
media_type: &str,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
aead: bool,
) -> Result<NodeUid> {
self.timed(
DriveCall::UploadFileReplacingDraft,
self.inner.upload_file_replacing_draft_from_dyn(
parent_uid,
name,
media_type,
reader,
intended_size,
thumbnails,
last_modification_time,
aead,
),
)
.await
}
async fn upload_new_revision_from_dyn(
&self,
file_uid: &NodeUid,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
) -> Result<()> {
self.timed(
DriveCall::UploadNewRevision,
self.inner.upload_new_revision_from_dyn(
file_uid,
reader,
intended_size,
thumbnails,
last_modification_time,
),
)
.await
}
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
self.timed(DriveCall::OpenRevision, self.inner.open_revision(uid))
.await
}
async fn download_thumbnail(
&self,
uid: &NodeUid,
thumbnail_type: ThumbnailType,
) -> Result<Option<Vec<u8>>> {
self.timed(
DriveCall::DownloadThumbnail,
self.inner.download_thumbnail(uid, thumbnail_type),
)
.await
}
async fn download_file_to_dyn(
&self,
uid: &NodeUid,
output: &mut (dyn Write + Send),
) -> Result<()> {
self.timed(
DriveCall::DownloadFile,
self.inner.download_file_to_dyn(uid, output),
)
.await
}
async fn download_revision_to_dyn(
&self,
file_uid: &NodeUid,
revision_id: &str,
writer: &mut (dyn Write + Send),
) -> Result<()> {
self.timed(
DriveCall::DownloadRevision,
self.inner
.download_revision_to_dyn(file_uid, revision_id, writer),
)
.await
}
async fn rename_node(
&self,
uid: &NodeUid,
new_name: &str,
new_media_type: Option<&str>,
) -> Result<()> {
self.timed(
DriveCall::RenameNode,
self.inner.rename_node(uid, new_name, new_media_type),
)
.await
}
async fn move_node(&self, uid: &NodeUid, new_parent: &NodeUid) -> Result<()> {
self.timed(DriveCall::MoveNode, self.inner.move_node(uid, new_parent))
.await
}
async fn copy_node(
&self,
uid: &NodeUid,
new_parent: &NodeUid,
name: Option<&str>,
) -> Result<NodeUid> {
self.timed(
DriveCall::CopyNode,
self.inner.copy_node(uid, new_parent, name),
)
.await
}
async fn get_available_name(
&self,
parent_uid: &NodeUid,
name: &str,
target: AvailableNameTarget,
) -> Result<String> {
self.timed(
DriveCall::GetAvailableName,
self.inner.get_available_name(parent_uid, name, target),
)
.await
}
fn move_nodes_streaming<'a>(
&'a self,
items: Vec<NodeMoveItem>,
new_parent: NodeUid,
) -> OutcomeStream<'a> {
self.stats.record(DriveCall::MoveNodes, false, None);
self.inner.move_nodes_streaming(items, new_parent)
}
async fn trash_nodes(&self, uids: &[NodeUid]) -> Result<NodeOutcomes> {
self.timed(DriveCall::TrashNodes, self.inner.trash_nodes(uids))
.await
}
async fn restore_nodes(&self, uids: &[NodeUid]) -> Result<NodeOutcomes> {
self.timed(DriveCall::RestoreNodes, self.inner.restore_nodes(uids))
.await
}
fn restore_nodes_streaming<'a>(&'a self, uids: &[NodeUid]) -> OutcomeStream<'a> {
self.stats
.record(DriveCall::RestoreNodesStreaming, false, None);
self.inner.restore_nodes_streaming(uids)
}
fn delete_nodes_streaming<'a>(&'a self, uids: &[NodeUid]) -> OutcomeStream<'a> {
self.stats.record(DriveCall::DeleteNodes, false, None);
self.inner.delete_nodes_streaming(uids)
}
async fn enumerate_trash_node_uids(&self) -> Result<Vec<NodeUid>> {
self.timed(
DriveCall::EnumerateTrash,
self.inner.enumerate_trash_node_uids(),
)
.await
}
async fn empty_trash(&self) -> Result<()> {
self.timed(DriveCall::EmptyTrash, self.inner.empty_trash())
.await
}
async fn enumerate_trashed_nodes_light(&self, uids: &[NodeUid]) -> Result<Vec<TrashedNode>> {
self.timed(
DriveCall::EnumerateTrashedNodes,
self.inner.enumerate_trashed_nodes_light(uids),
)
.await
}
async fn quota(&self) -> Result<Quota> {
self.timed(DriveCall::Quota, self.inner.quota()).await
}
async fn enumerate_devices(&self) -> Result<Vec<Device>> {
self.timed(DriveCall::EnumerateDevices, self.inner.enumerate_devices())
.await
}
async fn create_device(&self, name: &str, device_type: DeviceType) -> Result<Device> {
self.timed(
DriveCall::CreateDevice,
self.inner.create_device(name, device_type),
)
.await
}
fn landing(&self, uid: &NodeUid) {
self.inner.landing(uid);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_call_has_its_own_counter() {
for (index, call) in DriveCall::ALL.iter().enumerate() {
assert_eq!(*call as usize, index, "{} is out of order", call.name());
}
let names: std::collections::HashSet<_> =
DriveCall::ALL.iter().map(|call| call.name()).collect();
assert_eq!(names.len(), DriveCall::ALL.len());
}
#[test]
fn a_call_is_counted_with_its_failures_and_time() {
let stats = CallStats::default();
stats.record(DriveCall::GetNode, false, Some(Duration::from_millis(30)));
stats.record(DriveCall::GetNode, true, Some(Duration::from_millis(10)));
stats.record(DriveCall::DeleteNodes, false, None);
assert_eq!(
stats.snapshot(),
vec![
CallStat {
call: DriveCall::GetNode,
count: 2,
errors: 1,
total: Duration::from_millis(40),
longest: Duration::from_millis(30),
},
CallStat {
call: DriveCall::DeleteNodes,
count: 1,
errors: 0,
total: Duration::ZERO,
longest: Duration::ZERO,
},
]
);
}
}
@@ -25,22 +25,25 @@ 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::error::Result;
use proton_drive_rs::proton_sdk::api::ResponseCode;
use proton_drive_rs::proton_sdk::error::{ProtonError, Result};
use proton_drive_rs::proton_sdk::ids::{DriveEventId, NodeUid, ShareId};
use proton_drive_rs::{
AvailableNameTarget, Device, DeviceType, DriveEvent, DriveEventScopeId, Node, NodeMoveItem,
ProtonDriveClient, RevisionReader, Thumbnail, ThumbnailType, TrashedNode,
AvailableNameTarget, Device, DeviceType, DriveEvent, DriveEventScopeId, Node, NodeKind,
NodeMoveItem, ProtonDriveClient, RevisionReader, Thumbnail, ThumbnailType, TrashedNode,
};
pub mod counted;
/// One outcome per node of a batch request; see [`ProtonDriveClient::trash_nodes`].
pub(crate) type NodeOutcomes = Vec<(NodeUid, Result<()>)>;
pub type NodeOutcomes = Vec<(NodeUid, Result<()>)>;
/// The outcomes of a streaming batch request, one item per node as it lands.
pub(crate) type OutcomeStream<'a> = BoxStream<'a, Result<(NodeUid, Result<()>)>>;
pub type OutcomeStream<'a> = BoxStream<'a, Result<(NodeUid, Result<()>)>>;
/// Drive as the sync core sees it. See the module documentation.
#[async_trait]
pub(crate) trait DriveApi: Send + Sync {
pub trait DriveApi: Send + Sync {
async fn get_my_files_folder(&self) -> Result<Node>;
async fn context_share_id(&self, uid: &NodeUid) -> Result<ShareId>;
@@ -210,14 +213,13 @@ pub(crate) 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(crate) async fn upload_file_from<R: Read + Send>(
pub async fn upload_file_from<R: Read + Send>(
&self,
parent_uid: &NodeUid,
name: &str,
@@ -242,7 +244,7 @@ impl dyn DriveApi {
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn upload_file_replacing_draft_from<R: Read + Send>(
pub async fn upload_file_replacing_draft_from<R: Read + Send>(
&self,
parent_uid: &NodeUid,
name: &str,
@@ -266,7 +268,7 @@ impl dyn DriveApi {
.await
}
pub(crate) async fn upload_new_revision_from<R: Read + Send>(
pub async fn upload_new_revision_from<R: Read + Send>(
&self,
file_uid: &NodeUid,
mut reader: R,
@@ -284,7 +286,7 @@ impl dyn DriveApi {
.await
}
pub(crate) async fn download_file_to<W: Write + Send>(
pub async fn download_file_to<W: Write + Send>(
&self,
uid: &NodeUid,
output: &mut W,
@@ -292,7 +294,7 @@ impl dyn DriveApi {
self.download_file_to_dyn(uid, output).await
}
pub(crate) async fn download_revision_to<W: Write + Send>(
pub async fn download_revision_to<W: Write + Send>(
&self,
file_uid: &NodeUid,
revision_id: &str,
@@ -305,7 +307,7 @@ impl dyn DriveApi {
/// An open revision that block reads are served from; see [`RevisionReader`].
#[async_trait]
pub(crate) trait RevisionRead: Send + Sync {
pub trait RevisionRead: Send + Sync {
/// Plaintext size of the revision.
fn size(&self) -> u64;
@@ -575,3 +577,38 @@ 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;
@@ -67,10 +67,10 @@ use proton_drive_rs::{
use sha1::{Digest as _, Sha1};
use super::rng::Rng;
use crate::drive::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
/// The volume every fake node lives on.
pub(crate) const VOLUME: &str = "simvol";
pub 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(crate) struct FakeDrive {
pub struct FakeDrive {
server: Mutex<Server>,
}
/// A node of [`FakeDrive::tree`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Entry {
pub enum Entry {
Folder,
File(Arc<Vec<u8>>),
}
impl FakeDrive {
pub(crate) fn new() -> Arc<Self> {
pub 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_core::cache::BLOCK_SIZE],
block_pattern: vec![pdfs_store::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(crate) fn client(self: &Arc<Self>, seed: u64, faults: Faults) -> FakeClient {
pub 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(crate) fn set_block_pattern(&self, pattern: Vec<u64>) {
pub 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(crate) fn set_quota(&self, max_space: i64) {
pub fn set_quota(&self, max_space: i64) {
self.server.lock().max_space = max_space;
}
pub(crate) fn root(&self) -> NodeUid {
pub 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(crate) fn tree(&self) -> BTreeMap<String, Entry> {
pub 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(crate) fn names_ever_in_root(&self) -> Vec<String> {
pub 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(crate) fn lookup(&self, path: &str) -> Option<NodeUid> {
pub 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(crate) fn event_count(&self) -> usize {
pub 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(crate) fn device(&self) -> Device<'_> {
pub fn device(&self) -> Device<'_> {
Device(self)
}
}
/// See [`FakeDrive::device`].
pub(crate) struct Device<'a>(&'a FakeDrive);
pub struct Device<'a>(&'a FakeDrive);
impl Device<'_> {
/// Write `content` at `path`, as a new file or a new revision of one.
pub(crate) fn write(&self, path: &str, content: &[u8]) -> NodeUid {
pub 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(crate) fn mkdir(&self, path: &str) -> NodeUid {
pub 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(crate) fn trash(&self, path: &str) {
pub 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(crate) fn rename(&self, path: &str, new_name: &str) {
pub 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(crate) struct Faults {
pub struct Faults {
/// Each request takes a time drawn from this range, in milliseconds.
pub(crate) latency_ms: (u64, u64),
pub latency_ms: (u64, u64),
/// How far behind the present reads are about a node appearing or going
/// to the trash.
pub(crate) listing_lag: Duration,
pub listing_lag: Duration,
/// How far behind the present reads are about a live node's name, folder
/// or revision.
pub(crate) update_lag: Duration,
pub update_lag: Duration,
/// How long a change takes to reach the event feed.
pub(crate) event_delay: Duration,
pub event_delay: Duration,
/// Chance that an event is delivered twice.
pub(crate) duplicate_events: f64,
pub duplicate_events: f64,
/// Chance that two neighbouring events of a page swap places.
pub(crate) reorder_events: f64,
pub reorder_events: f64,
/// Chance that a request never reaches Drive.
pub(crate) fail: f64,
pub fail: f64,
/// Chance that a change Drive made loses its reply.
pub(crate) drop_reply: f64,
pub drop_reply: f64,
/// Chance that a request stalls for [`Faults::stall_for`] and then fails.
pub(crate) stall: f64,
pub(crate) stall_for: Duration,
pub stall: f64,
pub stall_for: Duration,
/// Whether renames and moves send the entity cache's name, as the SDK does.
pub(crate) stale_name_cache: bool,
pub stale_name_cache: bool,
}
impl Faults {
/// No latency and no faults beyond the SDK's own stale name cache.
pub(crate) fn none() -> Self {
pub 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(crate) fn lan() -> Self {
pub 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(crate) fn echoes() -> Self {
pub 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(crate) fn wifi() -> Self {
pub 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(crate) struct Held(Arc<HoldState>);
pub struct Held(Arc<HoldState>);
impl Held {
/// Whether the read has come and is being held.
pub(crate) fn reached(&self) -> bool {
pub 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(crate) struct FakeClient(Arc<ClientInner>);
pub struct FakeClient(Arc<ClientInner>);
impl FakeClient {
pub(crate) fn set_online(&self, online: bool) {
pub fn set_online(&self, online: bool) {
self.0.online.store(online, Ordering::SeqCst);
}
pub(crate) fn set_faults(&self, faults: Faults) {
pub 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(crate) fn drop_link_after_next_create(&self) {
pub 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(crate) fn lose_reply_to_next_create(&self) {
pub 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(crate) fn hold_next_read(&self, uid: &NodeUid) -> Held {
pub 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(crate) fn hold_answer_to_next_read(&self, uid: &NodeUid) -> Held {
pub 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(crate) fn hold_next_children_of(&self, folder: &NodeUid) -> Held {
pub 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(crate) fn hold_next_trash(&self, uid: &NodeUid) -> Held {
pub 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(crate) fn set_thumbnail(&self, uid: &NodeUid, bytes: Vec<u8>) {
pub 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(crate) fn content_read(&self) -> u64 {
pub fn content_read(&self) -> u64 {
self.0.content_read.load(Ordering::SeqCst)
}
pub(crate) fn hold_next_download(&self, uid: &NodeUid) -> Held {
pub 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(crate) fn hold_next_landing(&self, uid: &NodeUid) -> Held {
pub 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(crate) fn hold_next_landing_of_any(&self) -> Held {
pub 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(crate) fn hold_reply_to_next_create(&self) -> Held {
pub 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(crate) fn hold_next_create(&self) -> Held {
pub fn hold_next_create(&self) -> Held {
let state = Arc::new(HoldState {
uid: self.0.drive.root(),
reached: AtomicBool::new(false),
@@ -945,32 +945,28 @@ impl FakeClient {
}
/// Make the next revision of a file on Drive and lose its answer.
pub(crate) fn lose_reply_to_next_revision(&self) {
pub 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(crate) fn lose_read_back_of_next_revision(&self) {
pub 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(crate) fn answer_reads_unrevised(&self, uid: &NodeUid, reads: usize) {
pub 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(crate) fn hold_answer_to_next_listing(
&self,
folder: &NodeUid,
unrevised: &NodeUid,
) -> Held {
pub fn hold_answer_to_next_listing(&self, folder: &NodeUid, unrevised: &NodeUid) -> Held {
let state = Arc::new(HoldState {
uid: folder.clone(),
reached: AtomicBool::new(false),
@@ -994,7 +990,7 @@ impl FakeClient {
}
/// Requests made through this client so far.
pub(crate) fn requests(&self) -> u64 {
pub fn requests(&self) -> u64 {
self.0.requests.load(Ordering::SeqCst)
}
@@ -1849,7 +1845,7 @@ impl RevisionRead for FakeRevision {
}
/// A uid on the fake volume.
pub(crate) fn uid(link: &str) -> NodeUid {
pub fn uid(link: &str) -> NodeUid {
NodeUid::new(VolumeId::from(VOLUME), LinkId::from(link))
}
@@ -1929,7 +1925,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 `link::is_network_error`).
/// the network (see [`crate::is_network_error`]).
fn no_answer() -> ProtonError {
ProtonError::Api(ProtonApiError {
code: ResponseCode::RequestTimeout,
@@ -1949,7 +1945,7 @@ fn now_secs() -> i64 {
#[cfg(test)]
mod tests {
use super::*;
use crate::link::is_network_error;
use crate::is_network_error;
fn code(error: &ProtonError) -> Option<ResponseCode> {
match error {
+6
View File
@@ -0,0 +1,6 @@
//! 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;
@@ -3,14 +3,14 @@
//! and faults, and no dependency.
#[derive(Clone, Debug)]
pub(crate) struct Rng(u64);
pub struct Rng(u64);
impl Rng {
pub(crate) fn new(seed: u64) -> Self {
pub fn new(seed: u64) -> Self {
Self(seed)
}
pub(crate) fn next_u64(&mut self) -> u64 {
pub 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(crate) fn below(&mut self, n: u64) -> u64 {
pub fn below(&mut self, n: u64) -> u64 {
if n == 0 { 0 } else { self.next_u64() % n }
}
/// A value in `lo..=hi`.
pub(crate) fn between(&mut self, lo: u64, hi: u64) -> u64 {
pub fn between(&mut self, lo: u64, hi: u64) -> u64 {
lo + self.below(hi.saturating_sub(lo) + 1)
}
/// True with probability `p`.
pub(crate) fn chance(&mut self, p: f64) -> bool {
pub fn chance(&mut self, p: f64) -> bool {
p > 0.0 && (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64 <= p
}
pub(crate) fn pick<'a, T>(&mut self, items: &'a [T]) -> Option<&'a T> {
pub 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(crate) fn fork(&mut self) -> Self {
pub fn fork(&mut self) -> Self {
Self::new(self.next_u64())
}
}
+4
View File
@@ -11,6 +11,9 @@ 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
@@ -38,5 +41,6 @@ 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_core::db::StoredSyncFolder;
use pdfs_store::db::StoredSyncFolder;
use super::{
ApplicableMountMode, commit_after_teardown, migrated_name, pending_intent_matches,
+92 -21
View File
@@ -13,12 +13,12 @@
//! diagnostic that blocks on the hang it is diagnosing reports nothing at
//! exactly the moment it matters.
use std::sync::LazyLock;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Instant;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, LazyLock};
use std::time::{Duration, Instant};
use parking_lot::Mutex;
use pdfs_core::control::{Diagnostics, InflightRequest, WorkerState};
use pdfs_core::control::{Diagnostics, DriveCallStat, InflightRequest, WorkerState};
use super::Core;
@@ -164,31 +164,66 @@ impl Core {
control_handler_limit: super::control::handler_limit(),
pending_ops: self.pending_ops_quickly(),
sync: Some(self.sync_engine.report()),
drive_calls: self
.drive_calls
.snapshot()
.into_iter()
.map(|stat| DriveCallStat {
call: stat.call.name().to_owned(),
count: stat.count,
errors: stat.errors,
total_ms: u64::try_from(stat.total.as_millis()).unwrap_or(u64::MAX),
longest_ms: u64::try_from(stat.longest.as_millis()).unwrap_or(u64::MAX),
})
.collect(),
}
}
/// Queued mutations, or `0` if the database did not answer within
/// [`PENDING_COUNT_DEADLINE`].
fn pending_ops_quickly(&self) -> u64 {
/// Queued mutations, or `None` when the database did not answer within
/// [`PENDING_COUNT_DEADLINE`] or an earlier probe is still waiting on it.
///
/// The supervisor asks for a report every tick. One thread per report
/// would pile up behind a database that never answers, so a second probe
/// is not started until the first one has returned.
fn pending_ops_quickly(&self) -> Option<u64> {
let db = self.db.clone();
let (tx, rx) = std::sync::mpsc::channel();
if std::thread::Builder::new()
.name("pdfs-diagnostics".into())
.spawn(move || {
let counts = db.pending_op_counts().unwrap_or_default();
let total = counts.uploads.max(0) as u64 + counts.changes.max(0) as u64;
let _ = tx.send(total);
})
.is_err()
{
return 0;
}
rx.recv_timeout(PENDING_COUNT_DEADLINE).unwrap_or(0)
probe_once(&self.pending_probe, PENDING_COUNT_DEADLINE, move || {
let counts = db.pending_op_counts().ok()?;
Some(counts.uploads.max(0) as u64 + counts.changes.max(0) as u64)
})
}
}
/// Run `probe` on a thread of its own and wait up to `deadline` for it.
///
/// `None` when it did not answer in time, or when the previous probe sharing
/// `busy` has not returned yet: then no new thread is started at all.
fn probe_once<T: Send + 'static>(
busy: &Arc<AtomicBool>,
deadline: Duration,
probe: impl FnOnce() -> Option<T> + Send + 'static,
) -> Option<T> {
if busy.swap(true, Ordering::AcqRel) {
return None;
}
let done = Arc::clone(busy);
let (tx, rx) = std::sync::mpsc::channel();
let spawned = std::thread::Builder::new()
.name("pdfs-diagnostics".into())
.spawn(move || {
let answer = probe();
done.store(false, Ordering::Release);
let _ = tx.send(answer);
});
if spawned.is_err() {
busy.store(false, Ordering::Release);
return None;
}
rx.recv_timeout(deadline).ok().flatten()
}
/// How long the report waits for the database before reporting without it.
const PENDING_COUNT_DEADLINE: std::time::Duration = std::time::Duration::from_millis(500);
const PENDING_COUNT_DEADLINE: Duration = Duration::from_millis(500);
#[cfg(test)]
mod tests {
@@ -252,4 +287,40 @@ mod tests {
);
assert_eq!(parse_vm_rss("VmPeak:\t 100 kB\n"), 0);
}
#[test]
fn a_stuck_probe_is_not_started_again() {
let busy = Arc::new(AtomicBool::new(false));
let (release, wait) = std::sync::mpsc::channel::<()>();
let short = Duration::from_millis(50);
let stuck = probe_once(&busy, short, move || {
let _ = wait.recv();
Some(1)
});
assert_eq!(stuck, None, "a probe that does not answer reports nothing");
let started = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&started);
let second = probe_once(&busy, short, move || {
flag.store(true, Ordering::SeqCst);
Some(2)
});
assert_eq!(second, None);
assert!(
!started.load(Ordering::SeqCst),
"no second thread while the first is out"
);
release.send(()).unwrap();
let deadline = Instant::now() + Duration::from_secs(10);
while busy.load(Ordering::Acquire) {
assert!(Instant::now() < deadline, "the first probe never returned");
std::thread::yield_now();
}
assert_eq!(
probe_once(&busy, Duration::from_secs(10), || Some(3)),
Some(3)
);
}
}
+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_core::db::{
use pdfs_store::cache::{Baseline, StagedWrite};
use pdfs_store::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_core::db::Db::effective_node_access
/// [`FAILING_ATTEMPTS`]: pdfs_core::db::FAILING_ATTEMPTS
/// [`Db::effective_node_access`]: pdfs_store::db::Db::effective_node_access
/// [`FAILING_ATTEMPTS`]: pdfs_store::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_core::db::Db::claim_next_due_op
/// [`Db::claim_next_due_op`]: pdfs_store::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_core::db::Db::record_op_failure
/// [`FAILING_ATTEMPTS`]: pdfs_core::db::FAILING_ATTEMPTS
/// [`Db::record_op_failure`]: pdfs_store::db::Db::record_op_failure
/// [`FAILING_ATTEMPTS`]: pdfs_store::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_core::db::Db;
use pdfs_store::db::Db;
use proton_drive_rs::NodeKind;
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
use std::cell::Cell;
+10 -15
View File
@@ -467,21 +467,16 @@ impl Filesystem for ProtonFs {
let handled = {
let mut st = self.core.state();
match st.active_writes.get_mut(&ino.0) {
Some(aw) => {
if size < aw.len {
// Shrink: drop authored ranges past the new end.
aw.written.clip(size);
} else if size > aw.len {
// Grow: the new tail is defined as zeros, so claim
// it as authored rather than base content.
aw.written.add(aw.len, size);
}
let _ = aw.file.set_len(size);
aw.len = size;
aw.dirty = true;
true
}
None => false,
Some(aw) => aw.resize(size).map(|()| true).map_err(Errno::from),
None => Ok(false),
}
};
let handled = match handled {
Ok(handled) => handled,
Err(error) => {
debug!(ino = ino.0, size, ?error, "setattr resize refused");
reply.error(error);
return;
}
};
debug!(ino = ino.0, size, fh = ?fh, handled, "setattr resize");
+1 -1
View File
@@ -15,7 +15,7 @@
use std::process::{Child, Command, Stdio};
use std::time::Duration;
use pdfs_core::db::PendingCounts;
use pdfs_store::db::PendingCounts;
use tracing::{debug, warn};
use super::Core;
+26 -100
View File
@@ -55,21 +55,23 @@ 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};
@@ -87,8 +89,12 @@ 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;
@@ -500,6 +506,8 @@ struct Core {
/// downloads, renames, moves and trashes. The real client in production, an
/// in-memory Drive in the simulation tests. See [`drive`].
drive: Arc<dyn DriveApi>,
/// What [`Core::drive`] has been asked, for the diagnostics report.
drive_calls: Arc<pdfs_drive::counted::CallStats>,
/// The concrete client, for what [`DriveApi`] does not cover: sharing,
/// Photos, devices, invitations and public links.
client: ProtonDriveClient,
@@ -744,6 +752,9 @@ struct Core {
sync_progress: Arc<Mutex<HashMap<i64, SyncProgress>>>,
/// Whether the folder-sync engine is alive, and which pass it is on.
sync_engine: Arc<sync::EngineHealth>,
/// Set while a diagnostics report's database probe is still out, so a
/// database that does not answer costs one stuck thread, not one per report.
pending_probe: Arc<AtomicBool>,
/// Channel to the folder-sync engine: nudges it to
/// reconcile a folder, reconcile everything, or re-scan its watch set.
sync_tx: std::sync::mpsc::Sender<sync::SyncMsg>,
@@ -3347,7 +3358,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_core::db::local_lid(&uid.to_string()).and_then(|lid| self.landed_lid_uid(lid))
pdfs_store::db::local_lid(&uid.to_string()).and_then(|lid| self.landed_lid_uid(lid))
}
fn landed_lid_uid(&self, lid: i64) -> Option<NodeUid> {
@@ -4679,7 +4690,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::cache::Pin> {
fn list_pins(&self) -> Vec<pdfs_core::control::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) {
@@ -6407,7 +6418,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_core::db::local_uid`]
/// its row's local id, as [`pdfs_store::db::local_uid`]
/// has it.
fn local_node_uid(lid: i64) -> NodeUid {
NodeUid::new(VolumeId::from(LOCAL_VOLUME), LinkId::from(lid.to_string()))
@@ -6498,70 +6509,6 @@ 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,
@@ -6603,16 +6550,6 @@ 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())
@@ -7124,17 +7061,6 @@ 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.
@@ -7314,7 +7240,7 @@ fn unix_secs(secs: i64) -> SystemTime {
#[cfg(test)]
mod merge_over_pending_tests {
use super::{PendingRevision, merge_over_pending};
use pdfs_core::cache::{Baseline, StagedWrite};
use pdfs_store::cache::{Baseline, StagedWrite};
use std::io::Write as _;
use std::path::PathBuf;
@@ -7819,13 +7745,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_core::db::local_uid(42));
assert_eq!(uid.to_string(), pdfs_store::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_core::db::local_lid(&uid.to_string()), Some(42));
assert_eq!(pdfs_store::db::local_lid(&uid.to_string()), Some(42));
}
#[test]
@@ -8147,8 +8073,8 @@ mod tests {
}
}
use crate::filesystem::access_allowed;
use pdfs_core::cache::{Baseline, StagedWrite};
use pdfs_core::db::{OP_REVISION, OP_TRASH, PendingOp};
use pdfs_store::cache::{Baseline, StagedWrite};
use pdfs_store::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))
@@ -9961,7 +9887,7 @@ mod tests {
N.fetch_add(1, Ordering::Relaxed)
));
std::fs::create_dir_all(&dir_path).unwrap();
let db = pdfs_core::db::Db::open(&dir_path.join("cache.db")).unwrap();
let db = pdfs_store::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))
+1 -19
View File
@@ -84,25 +84,7 @@ impl Link {
}
}
/// 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,
}
}
pub(crate) use pdfs_drive::is_network_error;
/// The error a call reports when it runs past `after` without an answer.
pub(crate) fn no_answer(after: Duration) -> ProtonError {
+8
View File
@@ -466,6 +466,12 @@ pub(crate) fn mount_with(
// Start the uptime clock here rather than at the first `pdfs diagnostics`,
// so the age it reports is the daemon's own.
super::diagnostics::start_clock();
// Count every call to Drive from the first, the root lookup included.
let drive_calls = Arc::new(pdfs_drive::counted::CallStats::default());
let drive: Arc<dyn DriveApi> = Arc::new(pdfs_drive::counted::Counted::new(
drive,
drive_calls.clone(),
));
check_mountpoint(mountpoint)?;
let (root, start) = fetch_or_recall_root(drive.as_ref(), &rt, &db)?;
let online = start == Start::Online;
@@ -487,6 +493,7 @@ pub(crate) fn mount_with(
gallery_session.map(|session| Arc::new(super::gallery::Gallery::new(gallery_dir, session)));
let core = Core {
drive,
drive_calls,
client,
gallery,
rt: rt.clone(),
@@ -554,6 +561,7 @@ pub(crate) fn mount_with(
indexing: Arc::new(AtomicBool::new(false)),
sync_progress: Arc::new(Mutex::new(HashMap::new())),
sync_engine: Arc::default(),
pending_probe: Arc::default(),
sync_tx,
mounts: Arc::new(Mutex::new(SecondaryMountRegistry::default())),
sync_locks: Arc::new(Mutex::new(HashMap::new())),
+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_core::db`] so the gallery opens instantly and refreshes behind the
//! by [`pdfs_store::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_core::db::StoredSyncFolder>) -> Vec<ProfileFolder> {
fn profile_folders(folders: Vec<pdfs_store::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_core::db::Db::open(&dir.join("cache.db")).unwrap();
let db = pdfs_store::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_core::db::{FAILING_ATTEMPTS, PARK_UNTIL};
use pdfs_store::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};
+30 -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_core::db::Db;
use pdfs_store::cache::ContentCache;
use pdfs_store::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};
@@ -369,6 +369,34 @@ 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 diagnostics_count_the_calls_made_to_drive() {
let drive = FakeDrive::new();
let daemon =
Daemon::start(&scratch("drive-calls"), drive.client(1, Faults::lan())).unwrap();
std::fs::write(daemon.mountpoint.join("a.txt"), b"a").unwrap();
assert!(wait_until(Duration::from_secs(30), || drive
.tree()
.contains_key("a.txt")));
let Ok(Response::Diagnostics { diagnostics }) = daemon.request(&Request::Diagnostics)
else {
panic!("no diagnostics");
};
let calls: BTreeMap<_, _> = diagnostics
.drive_calls
.iter()
.map(|stat| (stat.call.as_str(), stat))
.collect();
assert!(calls.contains_key("get_my_files_folder"), "{calls:?}");
let uploads = calls
.get("upload_file_from")
.or_else(|| calls.get("upload_file_replacing_draft_from"))
.unwrap_or_else(|| panic!("no upload counted: {calls:?}"));
assert!(uploads.count >= 1);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_daemon_on_the_fake_drive_syncs_both_ways() {
+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) mod fake_drive;
pub(crate) use pdfs_drive::sim::fake_drive;
pub(crate) mod model;
pub(crate) mod rng;
pub(crate) use pdfs_drive::sim::rng;
pub(crate) mod run;
pub(crate) mod watchdog;
+45 -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;
@@ -167,6 +167,27 @@ impl WriteHandle {
self.base_revision_id = crate::node_revision_id(node);
}
/// Resize the file to `size`, as `setattr` does through an open handle.
///
/// The scratch file goes first: a resize it refuses (a full disk on a
/// grow) fails with nothing recorded. Otherwise the length and the
/// authored ranges would describe bytes the scratch file does not hold,
/// and the call would have succeeded.
pub(crate) fn resize(&mut self, size: u64) -> std::io::Result<()> {
self.file.set_len(size)?;
if size < self.len {
// Shrink: drop authored ranges past the new end.
self.written.clip(size);
} else if size > self.len {
// Grow: the new tail is defined as zeros, so claim it as authored
// rather than base content.
self.written.add(self.len, size);
}
self.len = size;
self.dirty = true;
Ok(())
}
/// Account for `[offset, end)` having been written through this handle.
///
/// A write past the end leaves a hole that reads as zeros, exactly like a
@@ -1749,9 +1770,9 @@ mod tests {
node("shared-child", "shared", "pending.txt", false),
);
st.flushed_db()
.enqueue_op(&pdfs_core::db::PendingOp {
.enqueue_op(&pdfs_store::db::PendingOp {
id: 0,
kind: pdfs_core::db::OP_RENAME.to_string(),
kind: pdfs_store::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()),
@@ -2304,6 +2325,26 @@ mod tests {
}
}
#[test]
fn a_resize_the_scratch_file_refuses_changes_nothing() {
let mut h = handle(4, 4);
h.written.add(0, 4);
// A read-only descriptor refuses `ftruncate`, as a full disk does a grow.
let path = std::env::temp_dir().join(format!("pdfs-resize-test-{}", std::process::id()));
std::fs::write(&path, b"kept").unwrap();
h.file = Arc::new(File::open(&path).unwrap());
let _ = std::fs::remove_file(&path);
assert!(h.resize(10).is_err());
assert_eq!((h.len, h.dirty), (4, false));
assert_eq!(h.written.segments(4, 10), vec![(4, 10, false)]);
let mut h = handle(4, 4);
h.resize(10).unwrap();
assert_eq!((h.len, h.dirty), (10, true));
assert_eq!(h.written.segments(4, 10), vec![(4, 10, true)]);
}
/// A file created offline is written while its queued create lands. The
/// placeholder had no revision, so the handle takes the empty file the
/// create made as its base (docs/BUGS.md B113).
+1 -1
View File
@@ -73,7 +73,7 @@ pub(crate) fn run(core: Core, control_socket: PathBuf) {
if last_rss.elapsed() >= RSS_EVERY {
info!(
rss_bytes = report.rss_bytes,
pending_ops = report.pending_ops,
pending_ops = ?report.pending_ops,
meta_queued = report.meta_queued,
transfer_queued = report.transfer_queued,
stalled,
+6 -61
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,14 +42,11 @@ 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)]
@@ -59,7 +56,11 @@ 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;
@@ -77,25 +78,6 @@ 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
@@ -3105,43 +3087,6 @@ 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::*;
+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::cache::Pin], mounted: bool) {
pub(crate) fn repaint_pins(ui: &Rc<Ui>, pins: &[pdfs_core::control::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
@@ -0,0 +1,22 @@
[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
@@ -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`]: crate::config::AppDirs::cache_dir
//! [`AppDirs::cache_dir`]: pdfs_core::config::AppDirs::cache_dir
//! [`Node`]: proton_drive_rs::Node
use std::collections::{BTreeMap, HashMap, HashSet};
@@ -33,7 +33,8 @@ use tracing::debug;
use parking_lot::Mutex;
use crate::db::{CacheEntryInput, Db};
use crate::error::{Error, Result};
pub use pdfs_core::control::Pin;
use pdfs_core::error::{Error, Result};
/// `cache_entries.kind` tag for whole-file content blobs.
const KIND_BLOB: &str = "blob";
@@ -276,34 +277,6 @@ 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)]
@@ -3,8 +3,8 @@
use rusqlite::params;
use super::Db;
use crate::Result;
use crate::control::{ActivityEntry, ActivityKind};
use pdfs_core::Result;
use pdfs_core::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.
@@ -34,7 +34,7 @@ impl Db {
/// run, without keeping a second table in step with the log.
pub fn activity_has(&self, kind: ActivityKind, target: &str) -> Result<bool> {
let kind = serde_json::to_string(&kind)?;
let conn = self.read();
let conn = self.read()?;
let mut stmt =
conn.prepare("SELECT 1 FROM activity WHERE kind = ?1 AND target = ?2 LIMIT 1")?;
Ok(stmt.exists(params![kind, target])?)
@@ -44,7 +44,7 @@ impl Db {
/// whose stored `kind` no longer parses (written by an older build) are
/// skipped rather than failing the whole read.
pub fn activity_list(&self, limit: usize) -> Result<Vec<ActivityEntry>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT time, kind, target, detail, ok FROM activity
ORDER BY id DESC LIMIT ?1",
@@ -12,7 +12,7 @@ use rusqlite::params;
use std::collections::HashMap;
use super::{Db, StoredPhoto, THUMB_UNKNOWN};
use crate::Result;
use pdfs_core::Result;
/// One album of the persisted listing, ordered newest-activity-first in `seq`.
#[derive(Clone, Debug, PartialEq)]
@@ -105,7 +105,7 @@ impl Db {
/// The persisted album listing, in stored order.
pub fn albums_list(&self) -> Result<Vec<StoredAlbum>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT uid, name, photo_count, cover_uid, last_activity, shared
FROM albums ORDER BY seq",
@@ -127,7 +127,7 @@ impl Db {
/// Number of albums in the persisted listing.
pub fn albums_count(&self) -> Result<usize> {
let conn = self.read();
let conn = self.read()?;
let n: i64 = conn.query_row("SELECT COUNT(*) FROM albums", [], |r| r.get(0))?;
Ok(n.max(0) as usize)
}
@@ -199,7 +199,7 @@ impl Db {
let name = name.clone().or(learned_name);
let media_type = media_type.clone().or(learned_media);
let kind =
crate::control::PhotoKind::classify(name.as_deref(), media_type.as_deref());
pdfs_core::control::PhotoKind::classify(name.as_deref(), media_type.as_deref());
stmt.execute(params![
album_uid,
uid,
@@ -226,7 +226,7 @@ impl Db {
&self,
album: &str,
) -> Result<HashMap<String, (String, Option<String>)>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT uid,name,media_type FROM album_photos
WHERE album_uid=?1 AND resolved=1 AND name IS NOT NULL
@@ -255,7 +255,7 @@ impl Db {
limit: usize,
excluded: &str,
) -> Result<Vec<StoredPhoto>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT uid, capture_time, name, ratio, thumb_state, kind FROM album_photos
WHERE album_uid = ?1 AND uid NOT IN (SELECT value FROM json_each(?4))
@@ -271,7 +271,7 @@ impl Db {
name: r.get(2)?,
ratio: r.get(3)?,
thumb_state: r.get(4)?,
kind: crate::control::PhotoKind::from_i64(r.get(5)?),
kind: pdfs_core::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.
@@ -293,7 +293,7 @@ impl Db {
/// which has to put the re-uploaded copy back into the albums the original
/// was in.
pub fn albums_of_photo(&self, uid: &str) -> Result<Vec<String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt =
conn.prepare("SELECT DISTINCT album_uid FROM album_photos WHERE uid = ?1")?;
let rows = stmt
@@ -304,7 +304,7 @@ impl Db {
/// How many photos of `album_uid` are persisted.
pub fn album_photos_count(&self, album_uid: &str) -> Result<usize> {
let conn = self.read();
let conn = self.read()?;
let n: i64 = conn.query_row(
"SELECT COUNT(*) FROM album_photos WHERE album_uid = ?1",
[album_uid],
@@ -321,7 +321,7 @@ impl Db {
if uids.is_empty() {
return Ok(Vec::new());
}
let conn = self.read();
let conn = self.read()?;
let placeholders = vec!["?"; uids.len()].join(",");
let mut stmt = conn.prepare(&format!(
"SELECT uid, capture_time, name, ratio, thumb_state, kind FROM album_photos
@@ -335,7 +335,7 @@ impl Db {
name: r.get(2)?,
ratio: r.get(3)?,
thumb_state: r.get(4)?,
kind: crate::control::PhotoKind::from_i64(r.get(5)?),
kind: pdfs_core::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 crate::Result;
use pdfs_core::Result;
pub struct CacheEntryInput<'a> {
/// On-disk filename of the blob or block.
@@ -99,7 +99,7 @@ impl Db {
/// because `enforce_block_budget` runs on every cached block — once per
/// 4 MiB of every cold read — while holding the shared connection.
pub fn cache_total_bytes(&self, kind: &str) -> Result<u64> {
let conn = self.read();
let conn = self.read()?;
let total: i64 = conn.query_row(
"SELECT COALESCE(SUM(size_bytes), 0) FROM cache_entries WHERE kind = ?1",
params![kind],
@@ -121,7 +121,7 @@ impl Db {
limit: usize,
offset: usize,
) -> Result<Vec<(String, u64)>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare_cached(
"SELECT cache_key, size_bytes FROM cache_entries
WHERE kind = ?1 ORDER BY last_accessed ASC LIMIT ?2 OFFSET ?3",
@@ -141,7 +141,7 @@ impl Db {
/// (`clear_unpinned`); incremental eviction wants
/// [`cache_eviction_candidates`](Self::cache_eviction_candidates).
pub fn cache_entries_by_kind(&self, kind: &str) -> Result<Vec<(String, u64)>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT cache_key, size_bytes FROM cache_entries
WHERE kind = ?1 ORDER BY last_accessed ASC",
@@ -3,7 +3,7 @@
use rusqlite::{OptionalExtension, params};
use super::Db;
use crate::Result;
use pdfs_core::Result;
pub struct StoredDevice {
pub uid: String,
@@ -15,7 +15,7 @@ pub struct StoredDevice {
impl Db {
pub fn device_get(&self) -> Result<Option<StoredDevice>> {
let conn = self.read();
let conn = self.read()?;
conn.query_row(
"SELECT uid, share_id, root_uid, name, created FROM device LIMIT 1",
[],
@@ -4,8 +4,8 @@
use rusqlite::{OptionalExtension, params};
use super::Db;
use crate::Result;
use crate::localindex::LocalEntry;
use pdfs_core::Result;
use pdfs_core::localindex::LocalEntry;
use super::nodes::candidate_trigrams;
use super::utils::{TRIGRAM_MIN, like_escape};
@@ -152,7 +152,7 @@ impl Db {
pub fn compact_search_indexes_if_due(&self, now: i64) -> Result<()> {
const EVERY_SECS: i64 = 24 * 60 * 60;
let last: i64 = self
.read()
.read()?
.query_row(
"SELECT value FROM sync_state WHERE key = 'fts_compacted_at'",
[],
@@ -189,7 +189,7 @@ impl Db {
/// has never been built. The daemon uses this to decide whether a fresh mount
/// needs an immediate rescan or can serve the existing index.
pub fn local_indexed_at(&self) -> Result<Option<i64>> {
let conn = self.read();
let conn = self.read()?;
Ok(conn
.query_row(
"SELECT value FROM sync_state WHERE key = 'local_indexed_at'",
@@ -209,7 +209,7 @@ impl Db {
if query.is_empty() {
return Ok(Vec::new());
}
let conn = self.read();
let conn = self.read()?;
let mut stmt;
let rows = if query.chars().count() < TRIGRAM_MIN {
let pat = format!("%{}%", like_escape(query));
@@ -248,7 +248,7 @@ impl Db {
if query.is_empty() || limit == 0 {
return Ok(Vec::new());
}
let conn = self.read();
let conn = self.read()?;
let terms = candidate_trigrams(query);
let lane_limit = limit.div_ceil(2);
let mut rows: Vec<LocalFileHit> = if terms.is_empty() {
@@ -10,7 +10,7 @@
use rusqlite::OptionalExtension;
use super::Db;
use crate::Result;
use pdfs_core::Result;
/// A point-in-time picture of the database's size and contents.
///
@@ -97,7 +97,7 @@ impl Db {
/// waited that long behind it (`docs/BUGS.md` B218). WAL lets it read a
/// consistent snapshot while the writer goes on.
pub fn integrity_check(&self) -> Result<Vec<String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare("PRAGMA integrity_check")?;
let rows = stmt.query_map([], |r| r.get::<_, String>(0))?;
let mut problems = Vec::new();
@@ -116,7 +116,7 @@ impl Db {
/// connection, for the reason [`integrity_check`](Self::integrity_check)
/// gives: counting the rows of every table reads most of the file.
pub fn stats(&self) -> Result<DbStats> {
let conn = self.read();
let conn = self.read()?;
let page_count: i64 = conn.query_row("PRAGMA page_count", [], |r| r.get(0))?;
let free_pages: i64 = conn.query_row("PRAGMA freelist_count", [], |r| r.get(0))?;
let page_size: i64 = conn.query_row("PRAGMA page_size", [], |r| r.get(0))?;
@@ -8,7 +8,7 @@
use rusqlite::OptionalExtension;
use super::Db;
use crate::Result;
use pdfs_core::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(crate::Error::Other(format!(
return Err(pdfs_core::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 [`crate::control::PhotoKind`]) defaults to `0` (still photo), the
/// `kind` (see [`pdfs_core::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 `crate::places`), so the Places view is a plain `GROUP BY`.
/// town (see `pdfs_core::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
/// `crate::similar`): resized and re-encoded copies of one picture land a few
/// `pdfs_core::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 crate::{Error, Result};
use pdfs_core::{Error, Result};
use std::fs::File;
use std::os::fd::AsRawFd;
use std::path::{Path, PathBuf};
@@ -126,19 +126,16 @@ struct ReadPool {
const MAX_IDLE_READERS: usize = 4;
impl ReadPool {
fn take(&self) -> Option<Connection> {
/// An idle connection, or a new one. An error when none can be opened:
/// the caller's read fails rather than queueing behind the writer, which
/// can hold its lock for as long as a large transaction takes.
fn take(&self) -> Result<Connection> {
if let Some(conn) = self.idle.lock().pop() {
return Some(conn);
}
match open_read_only(&self.path) {
Ok(conn) => Some(conn),
Err(error) => {
// Falling back to the write connection is correct, just slower,
// so this is a warning and not a failed read.
tracing::warn!(%error, "could not open a read-only connection");
None
}
return Ok(conn);
}
open_read_only(&self.path).inspect_err(|error| {
tracing::warn!(%error, "could not open a read-only connection");
})
}
fn put(&self, conn: Connection) {
@@ -150,10 +147,10 @@ impl ReadPool {
}
/// A connection to read through: one borrowed from [`ReadPool`], or the write
/// connection when there is no pool (in-memory) or opening one failed.
/// connection for an in-memory database, which has no pool.
///
/// Derefs to `Connection`, so a method converts by swapping `self.conn.lock()`
/// for `self.read()` and nothing else.
/// for `self.read()?` and nothing else.
pub(super) struct Reader<'a> {
pooled: Option<Connection>,
writer: Option<parking_lot::MutexGuard<'a, Connection>>,
@@ -320,21 +317,19 @@ impl Db {
/// Reads see the last committed state, which is the same thing they saw
/// through the write connection: every method here commits before it
/// returns, and nothing holds a transaction open across calls.
pub(super) fn read(&self) -> Reader<'_> {
if let Some(pool) = &self.readers
&& let Some(conn) = pool.take()
{
return Reader {
pooled: Some(conn),
writer: None,
pool: Some(pool),
};
}
Reader {
pooled: None,
writer: Some(self.conn.lock()),
pool: None,
}
pub(super) fn read(&self) -> Result<Reader<'_>> {
let Some(pool) = &self.readers else {
return Ok(Reader {
pooled: None,
writer: Some(self.conn.lock()),
pool: None,
});
};
Ok(Reader {
pooled: Some(pool.take()?),
writer: None,
pool: Some(pool),
})
}
/// Open the file, apply every PRAGMA, and migrate. Split out of
@@ -7,8 +7,8 @@
use rusqlite::params;
use super::Db;
use crate::mounts::{MountAccess, MountKind, MountMode, MountSpec};
use crate::{Error, Result};
use pdfs_core::mounts::{MountAccess, MountKind, MountMode, MountSpec};
use pdfs_core::{Error, Result};
impl Db {
/// Project the configured primary mount into the presentation table.
@@ -74,7 +74,7 @@ impl Db {
/// Every local location, with synced-folder fields joined from `sync_folder`.
pub fn mount_list(&self) -> Result<Vec<MountSpec>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT
m.id,
@@ -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 crate::{Access, Result};
use pdfs_core::{Access, Result};
use proton_drive_rs::proton_sdk::ids::{LinkId, NodeUid, VolumeId};
use proton_drive_rs::{Node, NodeKind};
@@ -65,7 +65,7 @@ impl Db {
/// flag. Synthetic shared listings use this to serve the last completed
/// snapshot while offline, including after a live event expired its TTL.
pub fn visible_children(&self, parent: &NodeUid) -> Result<Vec<Node>> {
let conn = self.read();
let conn = self.read()?;
let (key, parent) = parent_key(&conn, &parent.to_string())?;
let mut stmt = conn.prepare(&format!(
"SELECT {NODE_NOW} FROM nodes n LEFT JOIN nodes p ON p.lid = n.parent_lid
@@ -309,7 +309,7 @@ impl Db {
/// Check if a folder node has any non-trashed children in the database.
pub fn has_children(&self, parent_uid: &NodeUid) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
let (key, parent) = parent_key(&conn, &parent_uid.to_string())?;
let count: i64 = conn.query_row(
&format!(
@@ -329,7 +329,7 @@ impl Db {
/// mountpoint — resolve the roots once through this and do the rest as
/// string arithmetic, instead of a `path_relative_to` walk per pair.
pub fn node_path(&self, uid: &str) -> Result<Option<String>> {
let conn = self.read();
let conn = self.read()?;
let exists: Option<i64> = conn
.query_row(
"SELECT 1 FROM nodes WHERE uid = ?1 AND node_json IS NOT NULL",
@@ -351,7 +351,7 @@ impl Db {
/// chain keeps callers from accidentally joining a Drive-wide path onto the
/// wrong mountpoint. The ancestor itself resolves to the empty path.
pub fn path_relative_to(&self, ancestor_uid: &str, uid: &str) -> Result<Option<String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"WITH RECURSIVE anc(uid, parent_lid, name, depth) AS (
SELECT uid, parent_lid, name, 0 FROM nodes WHERE uid = ?1
@@ -403,7 +403,7 @@ impl Db {
if query.is_empty() {
return Ok(Vec::new());
}
let conn = self.read();
let conn = self.read()?;
let rows: Vec<HitRow> = if query.chars().count() < TRIGRAM_MIN {
let pat = format!("%{}%", like_escape(query));
let mut stmt = conn.prepare(&format!(
@@ -461,7 +461,7 @@ impl Db {
if query.is_empty() || limit == 0 {
return Ok(Vec::new());
}
let conn = self.read();
let conn = self.read()?;
let terms = candidate_trigrams(query);
let lane_limit = limit.div_ceil(2);
let mut rows: Vec<HitRow> = if terms.is_empty() {
@@ -547,7 +547,7 @@ impl Db {
/// local id: a folder that landed has its new uid there, while the node
/// stored below it may still hold the placeholder.
pub fn load_all(&self) -> Result<Vec<StoredNode>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(&format!(
"SELECT {NODE_NOW}, n.listed, n.lid
FROM nodes n LEFT JOIN nodes p ON p.lid = n.parent_lid
@@ -570,7 +570,7 @@ impl Db {
/// Load one persisted node back by uid. Used to recover the My Files root
/// when the API is unreachable, so the mount can still serve the cached tree.
pub fn node_by_uid(&self, uid: &str) -> Result<Option<Node>> {
let conn = self.read();
let conn = self.read()?;
let json: Option<String> = conn
.query_row(
&format!(
@@ -590,7 +590,7 @@ impl Db {
/// The uid of the node with local id `lid`: `None` when it has no row, or
/// is not on Drive yet.
pub fn uid_of_lid(&self, lid: i64) -> Result<Option<String>> {
let conn = self.read();
let conn = self.read()?;
Ok(conn
.query_row("SELECT uid FROM nodes WHERE lid = ?1", params![lid], |r| {
r.get(0)
@@ -604,7 +604,7 @@ impl Db {
/// create lands and the row takes the uid Drive gave it: a node made on
/// this machine is found by its stand-in ([`local_uid`]) before and after.
pub fn lid_of(&self, uid: &str) -> Result<Option<i64>> {
node_lid(&self.read(), uid)
node_lid(&*self.read()?, uid)
}
/// The local id of each node, in order, giving a row to each that has none.
@@ -693,7 +693,7 @@ impl Db {
/// The daemon resumes from this on restart instead of reseeding to the
/// server head, so changes made while unmounted are still applied (P2).
pub fn children_if_listed(&self, parent: &NodeUid) -> Result<Option<Vec<Node>>> {
let conn = self.read();
let conn = self.read()?;
let (key, folder) = row_key(&parent.to_string());
let listed: Option<i64> = conn
.query_row(
@@ -713,7 +713,7 @@ impl Db {
/// listing is still marked complete. Only for when nothing better can be
/// had: a listing dropped as stale may miss or keep a child.
pub fn known_children(&self, parent: &NodeUid) -> Result<Vec<Node>> {
let conn = self.read();
let conn = self.read()?;
let (key, parent) = parent_key(&conn, &parent.to_string())?;
let mut stmt = conn.prepare(&format!(
"SELECT {NODE_NOW} FROM nodes n LEFT JOIN nodes p ON p.lid = n.parent_lid
@@ -736,7 +736,7 @@ impl Db {
/// while a create in it is queued, after a restart say, loses the file
/// until the create lands (`docs/BUGS.md` B132).
pub fn queued_children(&self, parent: &NodeUid) -> Result<(Vec<Node>, HashSet<String>)> {
let conn = self.read();
let conn = self.read()?;
let (key, parent) = parent_key(&conn, &parent.to_string())?;
let mut stmt = conn.prepare(&format!(
"SELECT {NODE_NOW} FROM nodes n LEFT JOIN nodes p ON p.lid = n.parent_lid
@@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize};
use super::Db;
use super::nodes::{adopt_placeholder_row_tx, node_lid};
use crate::Result;
use pdfs_core::Result;
/// The `kind` of a [`PendingOp`] that uploads a staged file as a new revision.
pub const OP_REVISION: &str = "revision";
@@ -503,7 +503,7 @@ impl Db {
/// A folder can look empty locally while Drive still holds the queued
/// moves' source files. A trash has to go through the drain in that case.
pub fn has_pending_moves_out_of(&self, uid: &str) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
Ok(conn
.prepare_cached(&format!(
"SELECT EXISTS (SELECT 1 FROM (SELECT ?1 AS uid) AS source
@@ -520,7 +520,7 @@ impl Db {
/// wait for the trash rather than land under a conflict name. Older rows
/// whose node and parent are unknown are matched by name alone.
pub fn has_pending_trash_named(&self, name: &str, parent_uid: Option<&str>) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
conn.query_row(
"SELECT EXISTS(
SELECT 1 FROM pending_op AS p
@@ -546,7 +546,7 @@ impl Db {
/// and name, so a create of that name there waits for the trash: sent
/// first, it made a node the trash took for the withdrawn one.
pub fn has_withdrawn_create(&self, parent_uid: &str, name: &str) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
conn.query_row(
&format!(
"SELECT EXISTS(
@@ -567,7 +567,7 @@ impl Db {
/// once it lands, so an op that wants the name can wait for it. A create
/// renamed while it was on the wire queues one (`Db::finish_create`).
pub fn has_pending_move_from(&self, name: &str) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
conn.query_row(
&format!("SELECT EXISTS(SELECT 1 FROM pending_op WHERE {MOVES_FROM})"),
params![OP_RENAME, name],
@@ -589,7 +589,7 @@ impl Db {
/// Whether a specific desired-state operation is still queued for a node.
pub fn has_pending_op(&self, uid: &str, kind: &str) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
let lid = node_lid(&conn, uid)?;
conn.query_row(
&format!(
@@ -604,7 +604,7 @@ impl Db {
/// Read an existing operation's metadata before a superseding enqueue.
pub fn pending_op_meta(&self, uid: &str, kind: &str) -> Result<Option<String>> {
let conn = self.read();
let conn = self.read()?;
let lid = node_lid(&conn, uid)?;
conn.query_row(
&format!(
@@ -1099,7 +1099,7 @@ impl Db {
/// Check if a queued create or mkdir op exists for `uid`.
pub fn has_create_op(&self, uid: &str) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
let lid = node_lid(&conn, uid)?;
let count: i64 = conn.query_row(
&format!(
@@ -1119,7 +1119,7 @@ impl Db {
/// bytes are still owed an upload, and dropping it would discard the staged
/// blob that holds them (`docs/BUGS.md` B71).
pub fn has_any_op(&self, uid: &str) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
let lid = node_lid(&conn, uid)?;
let count: i64 = conn.query_row(
&format!("SELECT COUNT(*) FROM pending_op WHERE {}", on_node(2)),
@@ -1227,7 +1227,7 @@ impl Db {
/// sort, and no separate index to maintain. The common case (something is
/// due) exits on the first row.
pub fn next_due_op(&self, now: i64) -> Result<Option<PendingOp>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare_cached(&format!(
"SELECT id, kind, {UID_NOW}, {PARENT_NOW}, name, blob_path, meta_json, created_at,
attempts, last_error, next_attempt_at
@@ -1368,7 +1368,7 @@ impl Db {
/// is not work this worker is waiting for, and counting it would have an
/// idle worker spin on a row it cannot have.
pub fn earliest_due_at(&self) -> Result<Option<i64>> {
let conn = self.read();
let conn = self.read()?;
let ts: Option<i64> = conn
.query_row(
&format!(
@@ -1386,7 +1386,7 @@ impl Db {
/// Every queued op, oldest first. For status read-outs and the CLI — the
/// drain wants [`next_due_op`](Self::next_due_op) instead.
pub fn pending_ops(&self) -> Result<Vec<PendingOp>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(&format!(
"SELECT id, kind, {UID_NOW}, {PARENT_NOW}, name, blob_path, meta_json, created_at,
attempts, last_error, next_attempt_at
@@ -1418,7 +1418,7 @@ impl Db {
/// construction, so nothing else in the drain ever looks at them. This is
/// the one query that does.
pub fn parked_create_ops(&self) -> Result<Vec<PendingOp>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(&format!(
"SELECT id, kind, {UID_NOW}, {PARENT_NOW}, name, blob_path, meta_json, created_at,
attempts, last_error, next_attempt_at
@@ -1453,7 +1453,7 @@ impl Db {
/// mount owes the server, but it carries no bytes and reporting it as an
/// upload is simply untrue.
pub fn pending_op_counts(&self) -> Result<PendingCounts> {
let conn = self.read();
let conn = self.read()?;
let uploads = conn.query_row(
"SELECT COUNT(*) FROM pending_op WHERE kind IN (?1, ?2)",
params![OP_REVISION, OP_CREATE],
@@ -1501,7 +1501,7 @@ impl Db {
/// it gone: the node was deleted, or a newer write superseded it, while the
/// worker was talking to the server.
pub fn op_exists(&self, id: i64) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
let count: i64 = conn.query_row(
"SELECT COUNT(*) FROM pending_op WHERE id = ?1",
params![id],
@@ -1617,7 +1617,7 @@ impl Db {
/// The issue of every op Drive refused, by op id.
pub fn op_issues(&self) -> Result<HashMap<i64, String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare("SELECT id, issue FROM pending_op WHERE issue IS NOT NULL")?;
let rows = stmt
.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?
@@ -1628,7 +1628,7 @@ impl Db {
/// The issue each node with a refused change has, by local id: what the
/// file browser shows on the node itself.
pub fn node_issues(&self) -> Result<HashMap<i64, String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT COALESCE(o.lid, n.lid), o.issue FROM pending_op o
LEFT JOIN nodes n ON o.lid IS NULL AND n.uid = o.uid
@@ -1753,7 +1753,7 @@ impl Db {
/// `staging/`: the difference is bytes the kernel was told were written and
/// that nothing is going to upload.
pub fn op_blob_paths(&self) -> Result<std::collections::HashSet<String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt =
conn.prepare("SELECT blob_path FROM pending_op WHERE blob_path IS NOT NULL")?;
let rows = stmt.query_map([], |r| r.get::<_, String>(0))?;
@@ -1794,7 +1794,7 @@ impl Db {
/// supersedes rather than forking a `(sync-conflict)` copy (docs/BUGS.md
/// B70 layer B).
pub fn own_sealed_rev(&self, uid: &str, now_ms: i64) -> Result<Option<String>> {
let conn = self.read();
let conn = self.read()?;
Ok(conn
.query_row(
"SELECT revision_id FROM own_sealed_rev
@@ -8,7 +8,7 @@ use std::collections::{HashMap, HashSet};
use proton_gallery_rs::grouping::{Grouped, group_photos, name_stem};
use super::Db;
use crate::Result;
use pdfs_core::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: crate::control::PhotoKind,
pub kind: pdfs_core::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 [`crate::places`]), how
/// A town photos were taken in: its GeoNames id (see [`pdfs_core::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 [`crate::similar`]).
/// What its thumbnail looks like (see [`pdfs_core::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: crate::control::PhotoKind::from_i64(r.get(5)?),
kind: pdfs_core::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,
@@ -209,7 +209,7 @@ fn photos_delete_tx(tx: &Transaction<'_>, uids: &[String]) -> Result<usize> {
impl Db {
pub fn photo_projection_generation(&self) -> Result<i64> {
Ok(photos_generation(&self.read())?)
Ok(photos_generation(&*self.read()?)?)
}
/// One transaction records the deletion, stale metadata, listing work and feed position.
@@ -265,7 +265,7 @@ impl Db {
}
pub fn photos_need_work(&self) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
Ok(conn.query_row(
"SELECT NOT EXISTS(SELECT 1 FROM sync_state WHERE key=?1)
OR EXISTS(SELECT 1 FROM photos WHERE resolved_at IS NULL)",
@@ -275,7 +275,7 @@ impl Db {
}
pub fn photos_pending(&self) -> Result<Vec<String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt =
conn.prepare("SELECT uid FROM photos WHERE resolved_at IS NULL ORDER BY seq")?;
Ok(stmt
@@ -284,7 +284,7 @@ impl Db {
}
pub fn photo_removed(&self, uid: &str) -> Result<bool> {
Ok(self.read().query_row(
Ok(self.read()?.query_row(
"SELECT EXISTS(SELECT 1 FROM photo_tombstones WHERE uid=?1)",
[uid],
|r| r.get(0),
@@ -292,7 +292,7 @@ impl Db {
}
pub fn photos_contains(&self, uid: &str, album: Option<&str>) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
Ok(match album {
Some(album) => conn.query_row(
"SELECT EXISTS(SELECT 1 FROM album_photos WHERE album_uid=?1 AND uid=?2)",
@@ -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 = crate::control::PhotoKind::classify(
let kind = pdfs_core::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)| crate::places::nearest(lat, lon))
.and_then(|(lat, lon)| pdfs_core::places::nearest(lat, lon))
.map(|city| city.id),
row.resolved_at
])?;
@@ -356,8 +356,8 @@ impl Db {
Ok((
Grouped {
uid: r.get(0)?,
raw: crate::control::PhotoKind::from_i64(r.get(1)?)
== crate::control::PhotoKind::Raw,
raw: pdfs_core::control::PhotoKind::from_i64(r.get(1)?)
== pdfs_core::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, crate::control::PhotoKind)> = items
let resolved: Vec<(&TimelineRow, Learned, pdfs_core::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 = crate::control::PhotoKind::classify(
let kind = pdfs_core::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 == crate::control::PhotoKind::Raw,
raw: *kind == pdfs_core::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)| crate::places::nearest(lat, lon))
.and_then(|(lat, lon)| pdfs_core::places::nearest(lat, lon))
.map(|city| city.id),
carried.similar_hash,
])?;
@@ -572,7 +572,7 @@ impl Db {
/// one a remote event marked stale — is resolved. That is what keeps a
/// 12k-photo library off 63 round-trips of `enumerate_nodes` every refresh.
pub fn photos_resolved(&self) -> Result<Vec<String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare("SELECT uid FROM photos WHERE resolved_at IS NOT NULL")?;
let rows = stmt.query_map([], |r| r.get::<_, String>(0))?;
let mut uids = Vec::new();
@@ -652,7 +652,7 @@ impl Db {
&self,
offset: usize,
limit: usize,
kind: Option<crate::control::PhotoKind>,
kind: Option<pdfs_core::control::PhotoKind>,
range: Option<(i64, i64)>,
favorites: bool,
not_in_album: bool,
@@ -665,13 +665,13 @@ impl Db {
&self,
offset: usize,
limit: usize,
kind: Option<crate::control::PhotoKind>,
kind: Option<pdfs_core::control::PhotoKind>,
range: Option<(i64, i64)>,
favorites: bool,
not_in_album: bool,
excluded: &str,
) -> Result<Vec<StoredPhoto>> {
let conn = self.read();
let conn = self.read()?;
// Built up so any combination of the optional filters is one indexed
// query rather than a statement per case.
let mut sql = String::from(PHOTO_SELECT);
@@ -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(crate::control::PhotoKind::Raw) {
if kind != Some(pdfs_core::control::PhotoKind::Raw) {
conds.push("p.uid = COALESCE(p.group_key, p.uid)".to_string());
}
if let Some(k) = kind {
@@ -729,7 +729,7 @@ impl Db {
/// of a shot, or just the photo itself when it stands alone. The lightbox
/// switches between these, and deleting a tile trashes all of them.
pub fn photos_group(&self, uid: &str) -> Result<Vec<StoredPhoto>> {
let conn = self.read();
let conn = self.read()?;
let sql = format!(
"{PHOTO_SELECT} WHERE COALESCE(p.group_key, p.uid) = \
(SELECT COALESCE(group_key, uid) FROM photos WHERE uid = ?1) ORDER BY p.seq"
@@ -748,7 +748,7 @@ impl Db {
return Ok(HashSet::new());
}
let ids = serde_json::to_string(uids).expect("file identifiers serialize");
let conn = self.read();
let conn = self.read()?;
let mut query = conn.prepare(
"SELECT uid FROM photos WHERE COALESCE(group_key, uid) IN (
SELECT COALESCE(group_key, uid) FROM photos
@@ -764,7 +764,7 @@ impl Db {
/// per group. Only for whole-library passes (the photo re-date); the gallery
/// pages with [`Db::photos_page`].
pub fn photos_all(&self) -> Result<Vec<StoredPhoto>> {
let conn = self.read();
let conn = self.read()?;
let sql = format!("{PHOTO_SELECT} ORDER BY p.seq");
let mut stmt = conn.prepare(&sql)?;
let rows = stmt
@@ -780,21 +780,21 @@ impl Db {
/// scopes the counts to one tab when set.
pub fn photos_months(
&self,
kind: Option<crate::control::PhotoKind>,
kind: Option<pdfs_core::control::PhotoKind>,
) -> Result<Vec<(i32, i32, usize)>> {
self.photos_months_visible(kind, "[]")
}
pub fn photos_months_visible(
&self,
kind: Option<crate::control::PhotoKind>,
kind: Option<pdfs_core::control::PhotoKind>,
excluded: &str,
) -> Result<Vec<(i32, i32, usize)>> {
let conn = self.read();
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(crate::control::PhotoKind::Raw) => "kind = ?2",
Some(pdfs_core::control::PhotoKind::Raw) => "kind = ?2",
Some(_) => "uid = COALESCE(group_key, uid) AND kind = ?2",
None => "uid = COALESCE(group_key, uid) AND ?2 IS NULL",
};
@@ -837,7 +837,7 @@ impl Db {
limit: usize,
excluded: &str,
) -> Result<Vec<StoredPhoto>> {
let conn = self.read();
let conn = self.read()?;
let sql = format!(
"{PHOTO_SELECT} WHERE p.uid = COALESCE(p.group_key, p.uid) \
AND strftime('%m-%d', p.capture_time, 'unixepoch', 'localtime') \
@@ -863,7 +863,7 @@ impl Db {
pub fn photo_places_visible(&self, excluded: &str) -> Result<Vec<StoredPlace>> {
let rows: Vec<(u32, usize, String)> = {
let conn = self.read();
let conn = self.read()?;
// SQLite fills the bare `uid` from the row `MIN(seq)` picked, which
// is the newest photo of the place.
let mut stmt = conn.prepare(
@@ -912,7 +912,7 @@ impl Db {
limit: usize,
excluded: &str,
) -> Result<Vec<StoredPhoto>> {
let conn = self.read();
let conn = self.read()?;
let sql = format!(
"{PHOTO_SELECT} WHERE p.uid = COALESCE(p.group_key, p.uid) AND p.place_id = ?1
AND p.uid NOT IN (SELECT value FROM json_each(?4))
@@ -934,7 +934,7 @@ impl Db {
pub fn photo_locations_at_place(&self, id: u32) -> Result<Vec<(StoredPhoto, (f64, f64))>> {
let photos = self.photos_at_place(id, 0, usize::MAX >> 1)?;
let located: HashMap<String, (f64, f64)> = {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT uid, latitude, longitude FROM photos \
WHERE place_id = ?1 AND latitude IS NOT NULL AND longitude IS NOT NULL",
@@ -961,7 +961,7 @@ impl Db {
/// set left with one member is no set.
pub fn photo_duplicates(&self) -> Result<Vec<Vec<StoredPhoto>>> {
let rows: Vec<(String, String, String)> = {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT p.uid, p.content_hash, COALESCE(p.group_key, p.uid) AS k FROM photos p \
WHERE p.content_hash IN (SELECT content_hash FROM photos \
@@ -1008,7 +1008,7 @@ impl Db {
/// any of its files is, since they all show one picture.
pub fn photos_unhashed(&self, limit: usize) -> Result<Vec<StoredPhoto>> {
let uids: Vec<String> = {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT COALESCE(group_key, uid) AS k FROM photos \
GROUP BY k \
@@ -1018,7 +1018,7 @@ impl Db {
)?;
stmt.query_map(
params![
crate::control::PhotoKind::Video.as_i64(),
pdfs_core::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
/// [`crate::similar::NO_HASH`] when its thumbnail gave none.
/// [`pdfs_core::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(
@@ -1042,38 +1042,38 @@ impl Db {
/// How many shots have been hashed, out of how many could be.
pub fn similar_progress(&self) -> Result<(usize, usize)> {
let conn = self.read();
let conn = self.read()?;
let (hashed, total): (i64, i64) = conn.query_row(
"SELECT COUNT(*) FILTER (WHERE hashed), COUNT(*) FROM \
(SELECT MAX(similar_hash) IS NOT NULL AS hashed FROM photos \
GROUP BY COALESCE(group_key, uid) \
HAVING MAX(similar_hash) IS NOT NULL \
OR MAX(kind != ?1 AND thumb_state != ?2))",
params![crate::control::PhotoKind::Video.as_i64(), THUMB_NONE],
params![pdfs_core::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 [`crate::similar`]), one photo per
/// Sets of shots that look alike (see [`pdfs_core::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>>> {
let rows: Vec<(String, u64, Option<String>)> = {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT COALESCE(group_key, uid) AS k, MAX(similar_hash), \
MAX(content_hash) FILTER (WHERE uid = COALESCE(group_key, uid)) \
FROM photos GROUP BY k \
HAVING MAX(similar_hash) IS NOT NULL AND MAX(similar_hash) != ?1",
)?;
stmt.query_map(params![crate::similar::NO_HASH as i64], |r| {
stmt.query_map(params![pdfs_core::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>> = crate::similar::sets(&hashes)
let found: Vec<Vec<usize>> = pdfs_core::similar::sets(&hashes)
.into_iter()
.filter(|set| {
let first = &rows[set[0]].2;
@@ -1108,8 +1108,8 @@ impl Db {
}
pub fn photos_counts_visible(&self, excluded: &str) -> Result<(usize, usize, usize)> {
use crate::control::PhotoKind;
let conn = self.read();
use pdfs_core::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
// them individually.
@@ -1140,7 +1140,7 @@ impl Db {
if uids.is_empty() {
return Ok(Vec::new());
}
let conn = self.read();
let conn = self.read()?;
let placeholders = vec!["?"; uids.len()].join(",");
let sql = format!("{PHOTO_SELECT} WHERE p.uid IN ({placeholders})");
let mut stmt = conn.prepare(&sql)?;
@@ -1178,7 +1178,7 @@ impl Db {
/// Number of photos in the persisted timeline.
pub fn photos_count(&self) -> Result<usize> {
let conn = self.read();
let conn = self.read()?;
let n: i64 = conn.query_row("SELECT COUNT(*) FROM photos", [], |r| r.get(0))?;
Ok(n.max(0) as usize)
}
@@ -5,7 +5,7 @@ use rusqlite::{OptionalExtension, params};
use super::Db;
use super::utils::MAX_PATH_DEPTH;
use crate::Result;
use pdfs_core::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
@@ -40,7 +40,7 @@ impl Db {
/// Every directly-pinned entry, ordered by uid.
pub fn pin_list(&self) -> Result<Vec<PinRow>> {
let conn = self.read();
let conn = self.read()?;
// `recursive` is pin policy; the node's kind comes from `nodes`, and is
// NULL for a pin whose node was never cached.
let mut stmt = conn.prepare(
@@ -73,7 +73,7 @@ impl Db {
/// terminates — while holding the daemon's only SQLite connection, on a path
/// that runs per cached read.
pub fn is_pinned(&self, uid: &str) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
let direct: Option<i64> = conn
.query_row("SELECT 1 FROM pins WHERE uid = ?1", params![uid], |r| {
r.get(0)
@@ -107,7 +107,7 @@ impl Db {
/// every descendant of a recursively-pinned folder. Used to build the
/// eviction-exempt set (the budget enforcer hashes these into cache keys).
pub fn pinned_uids(&self) -> Result<Vec<String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"WITH RECURSIVE sub(uid, lid) AS (
SELECT p.uid, n.lid FROM pins p LEFT JOIN nodes n ON n.uid = p.uid
@@ -130,7 +130,7 @@ impl Db {
/// Every descendant uid of `folder` (all depths), via a `parent_lid` CTE.
/// Used to evict a recursively-pinned subtree's cached blobs on unpin.
pub fn descendants(&self, folder: &str) -> Result<Vec<String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"WITH RECURSIVE sub(uid, lid) AS (
SELECT c.uid, c.lid FROM nodes c JOIN nodes f ON c.parent_lid = f.lid
@@ -6,7 +6,7 @@ use proton_drive_rs::proton_sdk::ids::{LinkId, NodeUid, VolumeId};
use rusqlite::{OptionalExtension, params};
use super::Db;
use crate::{Access, Error, Result};
use pdfs_core::{Access, Error, Result};
impl Db {
/// Load the complete, deliberately small shared-root authority map.
@@ -16,7 +16,7 @@ impl Db {
/// remains the restart/offline authority and every explicit role change is
/// written through before this cache is updated.
pub fn all_share_access(&self) -> Result<HashMap<NodeUid, Access>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare("SELECT root_uid, access FROM share_access")?;
let rows = stmt.query_map([], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
@@ -42,7 +42,7 @@ impl Db {
/// Read the effective access recorded for a shared-tree root.
pub fn share_access(&self, uid: &NodeUid) -> Result<Option<Access>> {
let conn = self.read();
let conn = self.read()?;
let value = conn
.query_row(
"SELECT access FROM share_access WHERE root_uid = ?1",
@@ -101,7 +101,7 @@ impl Db {
/// Drive gave it. The tree learns that uid a moment later, and a rename in
/// between was refused (`docs/BUGS.md` B174).
pub fn effective_node_access(&self, uid: &NodeUid) -> Result<Option<Access>> {
let conn = self.read();
let conn = self.read()?;
let key = uid.to_string();
let key = match super::local_lid(&key) {
Some(lid) => conn
@@ -4,11 +4,11 @@
use rusqlite::{OptionalExtension, params};
use super::Db;
use crate::Result;
use pdfs_core::Result;
impl Db {
pub fn get_event_cursor(&self) -> Result<Option<String>> {
let conn = self.read();
let conn = self.read()?;
let v = conn
.query_row(
"SELECT value FROM sync_state WHERE key = 'event_cursor'",
@@ -32,7 +32,7 @@ impl Db {
/// Read a `sync_state` value as a string.
pub fn state_str(&self, key: &str) -> Result<Option<String>> {
let conn = self.read();
let conn = self.read()?;
let v = conn
.query_row(
"SELECT value FROM sync_state WHERE key = ?1",
@@ -66,7 +66,7 @@ impl Db {
/// dropping it would leave a file that exists nowhere but this machine with
/// nothing left to create it. (Writes to a node that is itself still queued
pub fn state_i64(&self, key: &str) -> Result<Option<i64>> {
let conn = self.read();
let conn = self.read()?;
let v: Option<String> = conn
.query_row(
"SELECT value FROM sync_state WHERE key = ?1",
@@ -4,7 +4,7 @@
use rusqlite::{OptionalExtension, params};
use super::Db;
use crate::Result;
use pdfs_core::Result;
use std::collections::HashMap;
/// What a mirror pass has walked of Drive, saved so a pass cut short
@@ -141,7 +141,7 @@ impl Db {
/// Every synced folder, oldest first.
pub fn sync_folder_list(&self) -> Result<Vec<StoredSyncFolder>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT id, local_path, remote_uid, remote_share_id, mode, pending_mode, state, last_sync, kind
FROM sync_folder ORDER BY id",
@@ -168,7 +168,7 @@ impl Db {
/// Look up one synced folder by id.
pub fn sync_folder_get(&self, id: i64) -> Result<Option<StoredSyncFolder>> {
let conn = self.read();
let conn = self.read()?;
conn.query_row(
"SELECT id, local_path, remote_uid, remote_share_id, mode, pending_mode, state, last_sync, kind
FROM sync_folder WHERE id = ?1",
@@ -263,7 +263,7 @@ impl Db {
/// The whole per-file sync baseline for a folder, keyed by relative path.
pub fn sync_entries(&self, folder_id: i64) -> Result<HashMap<String, StoredSyncEntry>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT rel_path, remote_uid, local_mtime, local_size, remote_rev, remote_hash,
local_mtime_ns, remote_revision_id
@@ -296,7 +296,7 @@ impl Db {
/// `sync_folder` and descendants come from the last successful
/// `sync_entry` baseline.
pub fn mirror_contains_uid(&self, uid: &str) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
conn.query_row(
"SELECT EXISTS(
SELECT 1
@@ -345,7 +345,7 @@ impl Db {
/// How many baseline rows each synced folder has, by folder id. A folder
/// with none is absent.
pub fn sync_entry_counts(&self) -> Result<HashMap<i64, usize>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt =
conn.prepare("SELECT folder_id, COUNT(*) FROM sync_entry GROUP BY folder_id")?;
let rows = stmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)))?;
@@ -564,7 +564,7 @@ impl Db {
/// device or by a pass. [`Db::sync_remote_changed`] and the baseline's
/// triggers mark them.
pub fn sync_remote_dirty(&self, folder_id: i64) -> Result<Vec<(i64, String)>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt =
conn.prepare("SELECT seq, dir FROM sync_remote_dirty WHERE folder_id = ?1")?;
let rows = stmt
@@ -612,7 +612,7 @@ impl Db {
// Looked up on a reader: most events are about nodes no walk holds,
// and those must not queue behind the writer.
let marked: Vec<(i64, String)> = {
let conn = self.read();
let conn = self.read()?;
let mut marked: Vec<(i64, String)> = conn
.prepare_cached(
"SELECT folder_id, rtrim(rtrim(rel_path, replace(rel_path, '/', '')), '/')
@@ -1,8 +1,8 @@
use super::activity::ACTIVITY_KEEP;
use super::migrations::SCHEMA_VERSION;
use super::*;
use crate::control::{ActivityEntry, ActivityKind};
use crate::localindex::LocalEntry;
use pdfs_core::control::{ActivityEntry, ActivityKind};
use pdfs_core::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, crate::control::PhotoKind::Video);
assert_eq!(page[1].kind, pdfs_core::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(crate::control::PhotoKind::Video),
Some(pdfs_core::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(crate::control::PhotoKind::Video),
Some(pdfs_core::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 = crate::places::city(place.id).expect("a known town");
let city = pdfs_core::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", crate::similar::NO_HASH)
db.photo_set_similar_hash("flat", pdfs_core::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, crate::Access::Editor)
db.set_share_access(&shared.uid, pdfs_core::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(crate::Access::Viewer)
Some(pdfs_core::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: crate::Access::Viewer,
access: pdfs_core::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(crate::Access::Viewer),
Some(pdfs_core::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, crate::Access::Viewer)
db.set_share_access(&shared.uid, pdfs_core::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: crate::Access::Editor,
access: pdfs_core::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(crate::Access::Viewer)
Some(pdfs_core::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, crate::Access::Editor)
db.set_share_access(&shared.uid, pdfs_core::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(crate::Access::Viewer),
Some(pdfs_core::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, crate::Access::Editor)
db.set_share_access(&deleted.uid, pdfs_core::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(crate::Access::Viewer)
Some(pdfs_core::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 [
crate::Access::Owner,
crate::Access::Editor,
crate::Access::Viewer,
crate::Access::Unknown,
pdfs_core::Access::Owner,
pdfs_core::Access::Editor,
pdfs_core::Access::Viewer,
pdfs_core::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"), crate::Access::Viewer)
db.set_share_access(&uid("shared"), pdfs_core::Access::Viewer)
.unwrap();
assert_eq!(
db.effective_node_access(&uid("child")).unwrap(),
Some(crate::Access::Viewer)
Some(pdfs_core::Access::Viewer)
);
assert_eq!(
db.effective_node_access(&uid("root")).unwrap(),
Some(crate::Access::Owner)
Some(pdfs_core::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"), crate::Access::Editor)
db.set_share_access(&uid("outer"), pdfs_core::Access::Editor)
.unwrap();
db.set_share_access(&uid("inner"), crate::Access::Viewer)
db.set_share_access(&uid("inner"), pdfs_core::Access::Viewer)
.unwrap();
assert_eq!(
db.effective_node_access(&uid("child")).unwrap(),
Some(crate::Access::Viewer)
Some(pdfs_core::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"), crate::Access::Viewer)
db.set_share_access(&uid("shared"), pdfs_core::Access::Viewer)
.unwrap();
db.delete_node(&uid("shared")).unwrap();
assert_eq!(
db.effective_node_access(&uid("child")).unwrap(),
Some(crate::Access::Viewer)
Some(pdfs_core::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"), crate::Access::Editor)
db.set_share_access(&uid("shared"), pdfs_core::Access::Editor)
.unwrap();
assert_eq!(db.downgrade_all_share_access().unwrap(), 1);
assert_eq!(
db.effective_node_access(&uid("shared")).unwrap(),
Some(crate::Access::Viewer)
Some(pdfs_core::Access::Viewer)
);
assert_eq!(
db.effective_node_access(&uid("root")).unwrap(),
Some(crate::Access::Owner)
Some(pdfs_core::Access::Owner)
);
}
@@ -2168,8 +2168,12 @@ fn migration_v17_adds_share_access_to_a_v16_fixture() {
Some("survives")
);
let root = uid("offline-share");
db.set_share_access(&root, crate::Access::Viewer).unwrap();
assert_eq!(db.share_access(&root).unwrap(), Some(crate::Access::Viewer));
db.set_share_access(&root, pdfs_core::Access::Viewer)
.unwrap();
assert_eq!(
db.share_access(&root).unwrap(),
Some(pdfs_core::Access::Viewer)
);
// Migrating an old fixture always lands on head, whatever head is today.
assert_eq!(
db.state_str("schema_version").unwrap().as_deref(),
@@ -2251,12 +2255,12 @@ fn migration_v18_projects_v17_sync_folders_and_cascades_deletes() {
let projected = &locations[0];
assert!(matches!(
projected.kind,
crate::mounts::MountKind::Device {
pdfs_core::mounts::MountKind::Device {
sync_folder_id
} if sync_folder_id == existing
));
assert_eq!(projected.local_path, "/home/me/Existing");
assert_eq!(projected.mode, crate::mounts::MountMode::OnDemand);
assert_eq!(projected.mode, pdfs_core::mounts::MountMode::OnDemand);
assert_eq!(projected.state, "syncing");
assert_eq!(projected.last_sync, 123);
assert_eq!(
@@ -2303,7 +2307,7 @@ fn my_files_projection_retains_share_id_only_for_the_same_root() {
assert_eq!(locations.len(), 1);
assert!(matches!(
locations[0].kind,
crate::mounts::MountKind::MyFiles
pdfs_core::mounts::MountKind::MyFiles
));
assert_eq!(locations[0].local_path, "/mnt/proton");
assert_eq!(locations[0].root_uid, "vol~root-new");
@@ -3700,7 +3704,7 @@ fn a_stand_in_keeps_its_access_once_its_create_has_landed() {
.unwrap();
assert_eq!(
db.effective_node_access(&stand_in).unwrap(),
Some(crate::Access::Owner)
Some(pdfs_core::Access::Owner)
);
db.claim_next_due_op(1).unwrap().unwrap();
db.finish_create(
@@ -3714,11 +3718,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(crate::Access::Owner)
Some(pdfs_core::Access::Owner)
);
assert_eq!(
db.effective_node_access(&uid("real")).unwrap(),
Some(crate::Access::Owner)
Some(pdfs_core::Access::Owner)
);
}
@@ -3908,7 +3912,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(crate::Access::Owner),
Some(pdfs_core::Access::Owner),
"the child's authority resolves without a network re-read"
);
let names: Vec<_> = db
@@ -4510,7 +4514,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"), crate::Access::Owner)
db.set_share_access(&uid("root"), pdfs_core::Access::Owner)
.unwrap();
let stub = file("stub", "root", "stub.txt", 1);
let [lid] = db.lids_for(&[&stub]).unwrap()[..] else {
@@ -6417,7 +6421,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, crate::control::PhotoKind::Video);
assert_eq!(page[1].kind, pdfs_core::control::PhotoKind::Video);
assert_eq!(page[0].thumb_state, THUMB_UNKNOWN);
// Paging is relative to the album, and the shared flag round-trips.
@@ -7197,7 +7201,7 @@ fn a_raw_and_its_jpeg_are_one_entry_in_the_grid() {
.photos_page(
0,
10,
Some(crate::control::PhotoKind::Raw),
Some(pdfs_core::control::PhotoKind::Raw),
None,
false,
false,
@@ -7857,7 +7861,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 crate::mounts::MountKind;
use pdfs_core::mounts::MountKind;
let db = Db::open_in_memory().unwrap();
let id = db
.sync_folder_attach("/work", "vol~work", "myfiles-share")
@@ -8349,3 +8353,31 @@ fn a_change_on_drive_marks_the_folders_it_touches() {
db.sync_walks_clear_all().unwrap();
assert!(db.sync_walk_load(id).unwrap().is_none());
}
/// A read that cannot get a read-only connection fails. It does not wait on
/// the write connection, which a long transaction can hold for seconds and a
/// wedged one forever (`docs/BUGS.md` B296).
#[test]
fn a_read_without_a_reader_connection_fails_instead_of_waiting_on_the_writer() {
let dir = std::env::temp_dir().join(format!("pdfs-db-noreader-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("cache.db");
let db = std::sync::Arc::new(Db::open(&path).unwrap());
// The writer keeps its open file; a new read-only connection finds nothing.
std::fs::remove_dir_all(&dir).unwrap();
let writer = db.conn.lock();
let (tx, rx) = std::sync::mpsc::channel();
let reader = std::sync::Arc::clone(&db);
std::thread::spawn(move || {
let _ = tx.send(reader.pending_op_counts().is_err());
});
let failed = rx.recv_timeout(std::time::Duration::from_secs(10));
drop(writer);
assert_eq!(
failed,
Ok(true),
"the read must fail, not queue behind the writer"
);
}
@@ -5,7 +5,7 @@ use std::collections::{HashMap, HashSet};
use rusqlite::params;
use super::Db;
use crate::Result;
use pdfs_core::Result;
pub struct StoredTrash {
pub uid: String,
@@ -105,7 +105,7 @@ impl Db {
/// The persisted trash listing, folders first then by name — the order the
/// Trash page shows it in.
pub fn trash_list(&self) -> Result<Vec<StoredTrash>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT uid, name, is_dir, size, mtime, parent_uid, trashed_at FROM trash
ORDER BY is_dir DESC, name COLLATE NOCASE",
@@ -132,7 +132,7 @@ impl Db {
/// restore's tree walk. Kept separate from [`Db::trash_list`] because the
/// restore wants only the links, not the names, sizes or ordering.
pub fn trash_parents(&self) -> Result<Vec<(String, Option<String>)>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare("SELECT uid, parent_uid FROM trash")?;
let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
let mut pairs = Vec::new();
@@ -145,7 +145,7 @@ impl Db {
/// When each node now in the trash was first seen there, keyed by uid, so
/// a refresh can carry the times over into the listing it writes.
pub fn trash_seen(&self) -> Result<HashMap<String, Option<i64>>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare("SELECT uid, trashed_at FROM trash")?;
let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
let mut seen = HashMap::new();
@@ -2,7 +2,7 @@
use rusqlite::{Connection, OptionalExtension, params};
use crate::Result;
use pdfs_core::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`.
+9
View File
@@ -0,0 +1,9 @@
//! 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
@@ -0,0 +1,17 @@
[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
@@ -0,0 +1,24 @@
//! 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;
@@ -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_core::db::StoredSyncEntry).
/// [`StoredSyncEntry::local_mtime_ns`](pdfs_store::db::StoredSyncEntry).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct LocalSig {
pub(super) mtime: i64,
pub(super) mtime_ns: Option<i64>,
pub(super) size: i64,
pub struct LocalSig {
pub mtime: i64,
pub mtime_ns: Option<i64>,
pub 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(super) fn same_content(&self, other: &Self) -> bool {
pub fn same_content(&self, other: &Self) -> bool {
if self.size != other.size {
return false;
}
@@ -63,52 +63,52 @@ impl From<&StoredSyncEntry> for LocalSig {
}
}
pub(super) struct LocalItem {
pub(super) is_dir: bool,
pub(super) mtime: i64,
pub struct LocalItem {
pub is_dir: bool,
pub mtime: i64,
/// [`LocalItem::mtime`] to nanosecond precision, when the filesystem
/// reports one.
pub(super) mtime_ns: Option<i64>,
pub(super) size: i64,
pub mtime_ns: Option<i64>,
pub 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(super) open_for_write: bool,
pub open_for_write: bool,
}
/// One item found while walking a remote tree.
pub(super) struct RemoteItem {
pub(super) uid: NodeUid,
pub(super) is_dir: bool,
pub(super) mtime: i64,
pub(super) size: i64,
pub struct RemoteItem {
pub uid: NodeUid,
pub is_dir: bool,
pub mtime: i64,
pub 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(super) revision: Option<String>,
pub 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(super) sha1: Option<String>,
pub 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(super) struct RemoteSeen {
pub(super) mtime: i64,
pub(super) size: i64,
pub(super) revision: Option<String>,
pub struct RemoteSeen {
pub mtime: i64,
pub size: i64,
pub 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(super) fn still_current(&self, node: &Node) -> bool {
match (&self.revision, crate::node_revision_id(node)) {
pub fn still_current(&self, node: &Node) -> bool {
match (&self.revision, pdfs_drive::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(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,
pub struct Outcome {
pub uploaded: usize,
pub downloaded: usize,
pub created: usize,
pub deleted: usize,
pub conflicts: usize,
pub errors: usize,
/// Files skipped because another process held them open for writing.
pub(super) deferred: usize,
pub 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(super) unscanned: Vec<String>,
pub 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(super) first_error: Option<String>,
pub first_error: Option<String>,
}
impl Outcome {
/// Count one failed step, keeping the first one's message.
pub(super) fn failed(&mut self, error: &str) {
pub 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(super) fn record(&mut self, applied: &Applied) {
pub 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(super) fn is_empty(&self) -> bool {
pub 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(super) fn summary(&self) -> String {
pub 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(super) enum Pending {
pub 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(super) enum Pending {
impl Pending {
/// The path this op acts on, relative to the folder root.
pub(super) fn rel(&self) -> &str {
pub 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(super) fn call(&self) -> Call {
pub 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(super) fn kind(&self) -> ActivityKind {
pub 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(super) fn detail(&self) -> &'static str {
pub 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(super) enum PassAbort {
pub 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,3 +329,60 @@ 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())
}
+78
View File
@@ -0,0 +1,78 @@
//! 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())
}
@@ -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(super) fn classification_order<L, R, B>(
pub 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(super) trait HasKind {
pub 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(super) fn filter_baseline<'a, B>(
pub fn filter_baseline<'a, B>(
baseline: &'a HashMap<String, B>,
rules: &IgnoreRules,
) -> HashMap<String, &'a B> {
@@ -101,7 +101,7 @@ pub(super) 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(super) struct Unscanned {
pub 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(super) struct Unscanned {
impl Unscanned {
/// Leave out `rel`, which vanished while the scan looked at it.
pub(super) fn vanished(&mut self, rel: String) {
pub fn vanished(&mut self, rel: String) {
self.covered.insert(rel);
}
/// Leave out `rel`, which cannot be read for `reason`.
pub(super) fn unreadable(&mut self, rel: String, reason: &str) {
pub 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(super) fn covers(&self, rel: &str) -> bool {
pub 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(super) fn report(&self) -> Vec<String> {
pub 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(super) fn tracked_baseline<'a, B>(
pub fn tracked_baseline<'a, B>(
baseline: &'a HashMap<String, B>,
rules: &IgnoreRules,
unscanned: &Unscanned,
@@ -167,7 +167,7 @@ pub(super) 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(super) fn local_deletions<B, L>(
pub 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(super) fn guard_local_wipe<B, L>(
pub fn guard_local_wipe<B, L>(
baseline: &HashMap<String, B>,
local: &HashMap<String, L>,
) -> Result<(), String> {
@@ -231,7 +231,7 @@ pub(super) 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(super) fn guard_remote_wipe<B, R>(
pub fn guard_remote_wipe<B, R>(
baseline: &HashMap<String, B>,
remote: &HashMap<String, R>,
) -> Result<(), String> {
@@ -259,7 +259,7 @@ pub(super) 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(super) struct RemoteGaps {
pub 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(super) struct RemoteGaps {
impl RemoteGaps {
/// The listing of `folder` named nodes that did not come back.
pub(super) fn short_listing(&mut self, folder: &str) {
pub 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(super) fn unread(&mut self, rel: String) {
pub fn unread(&mut self, rel: String) {
self.unread.insert(rel);
}
/// The listing of `folder` failed, so nothing under it was walked.
pub(super) fn unlisted(&mut self, folder: &str) {
pub 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(super) fn forget(&mut self, rel: &str) {
pub fn forget(&mut self, rel: &str) {
self.short.remove(rel);
self.unread.remove(rel);
self.unlisted.remove(rel);
}
pub(super) fn is_empty(&self) -> bool {
pub 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(super) fn hides<R>(
pub 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(super) fn report(&self) -> Vec<String> {
pub 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(super) fn remote_subtree_changed(
pub fn remote_subtree_changed(
rel: &str,
remote: &HashMap<String, RemoteItem>,
baseline: &HashMap<String, StoredSyncEntry>,
@@ -389,7 +389,7 @@ pub(super) 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(super) fn unchanged_remote_size(
pub fn unchanged_remote_size(
baseline: &HashMap<String, StoredSyncEntry>,
rel: &str,
mtime: i64,
@@ -410,12 +410,12 @@ pub(super) 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(super) fn revision_confirms_baseline(base: &StoredSyncEntry, mtime: i64, size: i64) -> bool {
pub 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(super) fn join_rel(prefix: &str, name: &str) -> String {
pub fn join_rel(prefix: &str, name: &str) -> String {
if prefix.is_empty() {
name.to_string()
} else {
@@ -427,7 +427,7 @@ pub(super) 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(super) fn revision_moved(base: Option<&StoredSyncEntry>, now: Option<&str>) -> bool {
pub 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(super) fn revision_moved(base: Option<&StoredSyncEntry>, now: Option<&str>)
}
/// The stored remote signature of a baseline row, if it has one.
pub(super) fn remote_sig(e: &StoredSyncEntry) -> Option<(i64, i64)> {
pub 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(super) fn remote_sig(e: &StoredSyncEntry) -> Option<(i64, i64)> {
}
/// The parent of a `/`-joined relative path (`""` for a top-level entry).
pub(super) fn parent_rel(rel: &str) -> &str {
pub fn parent_rel(rel: &str) -> &str {
match rel.rfind('/') {
Some(i) => &rel[..i],
None => "",
@@ -451,7 +451,7 @@ pub(super) fn parent_rel(rel: &str) -> &str {
}
/// The final component of a `/`-joined relative path.
pub(crate) fn base_name(rel: &str) -> &str {
pub fn base_name(rel: &str) -> &str {
match rel.rfind('/') {
Some(i) => &rel[i + 1..],
None => rel,
@@ -460,28 +460,27 @@ pub(crate) 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(super) fn rel_to_path(rel: &str) -> PathBuf {
pub 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`.
#[cfg(test)]
pub(super) fn conflict_path(path: &Path, stamp: i64) -> PathBuf {
pub 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(super) fn conflict_path_with_suffix(path: &Path, stamp: i64, suffix: u32) -> PathBuf {
conflict_path_as(path, crate::conflict_label(), stamp, suffix)
pub fn conflict_path_with_suffix(path: &Path, stamp: i64, suffix: u32) -> PathBuf {
conflict_path_as(path, crate::naming::conflict_label(), stamp, suffix)
}
/// [`conflict_path_with_suffix`] with the machine's label given.
pub(super) fn conflict_path_as(path: &Path, label: &str, stamp: i64, suffix: u32) -> PathBuf {
pub 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::conflict_tag(label, stamp, suffix);
let tag = crate::naming::conflict_tag(label, stamp, suffix);
let name = match ext {
Some(ext) => format!("{stem} (sync-conflict {tag}).{ext}"),
None => format!("{stem} (sync-conflict {tag})"),
@@ -495,7 +494,7 @@ pub(super) fn conflict_path_as(path: &Path, label: &str, stamp: i64, suffix: u32
/// 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(super) enum FilePlan {
pub enum FilePlan {
Unchanged,
Deferred,
UploadNew,
@@ -516,7 +515,7 @@ pub(super) enum FilePlan {
AdoptBaseline,
}
pub(super) fn plan_file(
pub 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(crate) enum Phase {
pub 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(crate) enum Call {
pub 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(crate) enum Count {
pub 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(crate) struct PassTrace {
pub 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(crate) struct PassTrace {
}
impl PassTrace {
pub(crate) fn new(folder_id: i64) -> Self {
pub fn new(folder_id: i64) -> Self {
Self {
folder_id,
started: Instant::now(),
@@ -208,28 +208,28 @@ impl PassTrace {
}
}
pub(crate) fn folder_id(&self) -> i64 {
pub fn folder_id(&self) -> i64 {
self.folder_id
}
pub(crate) fn is_ended(&self) -> bool {
pub fn is_ended(&self) -> bool {
self.ended.is_some()
}
pub(crate) fn phase(&mut self, phase: Phase, took: Duration) {
pub fn phase(&mut self, phase: Phase, took: Duration) {
self.phases[phase as usize].add(took);
}
pub(crate) fn call(&mut self, call: Call, took: Duration) {
pub fn call(&mut self, call: Call, took: Duration) {
self.calls[call as usize].add(took);
}
pub(crate) fn count(&mut self, count: Count, n: usize) {
pub 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(crate) fn listing(&mut self, rel: &str, took: Duration) {
pub fn listing(&mut self, rel: &str, took: Duration) {
if self
.slowest_listing
.as_ref()
@@ -239,7 +239,7 @@ impl PassTrace {
}
}
pub(crate) fn end(&mut self, how: &'static str) {
pub 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(crate) fn summary(&self) -> SyncPassTrace {
pub fn summary(&self) -> SyncPassTrace {
SyncPassTrace {
folder_id: self.folder_id,
ended: self
+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-core/src/db/photos.rs`, `pdfs-gui/src/app/pages/photos.rs`.
`pdfs-fuse/src/photos.rs`, `pdfs-store/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
+57
View File
@@ -108,6 +108,7 @@ a live account since.
| Entry | Title |
|---|---|
| [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) |
| [B291](#b291--on-fedora-45s-oo7-every-saved-sign-in-is-lost-at-the-next-reboot) | On Fedora 45's oo7, every saved sign-in is lost at the next reboot |
@@ -397,6 +398,62 @@ a live account since.
Newest first.
### B296 — A busy database stalls reads, and piles up diagnostics threads
**Status:** Fixed (unverified)
**Found:** 2026-11-25, while hunting a hang in the remote-dirty simulation (B294). The stuck
process held one `pdfs-diagnostics` thread per supervisor tick, every one of them waiting on the
database.
**Where:** `crates/pdfs-core/src/db/mod.rs` `Db::read`; `crates/pdfs-fuse/src/diagnostics.rs`
`Core::pending_ops_quickly`
**Repro:** Hold the write connection, for example with a long transaction, and make opening a
read-only connection fail (too many open files, or the file gone). Every `SELECT`-only method
waits for the writer. Ask for diagnostics while the database does not answer: each report
starts a new thread, and none of them ends.
**Cause:** `Db::read` used the write connection whenever it could not open a read-only one, so
a read waited behind whatever transaction the writer was in. The diagnostics report counted the
queued operations on a new thread each time and stopped waiting after half a second, but left
the thread behind. The supervisor asks for a report every tick, so a database that never
answered gained a thread per tick. The report also showed `0` queued operations when the count
did not come back, which reads as "nothing to upload".
**Fix:** `Db::read` returns an error when it cannot open a read-only connection. Only an
in-memory database, which has no read-only connections, still reads through the writer. The
diagnostics report starts a probe only when the previous one has returned, and reports the count
as unknown (`null` in JSON, `unknown (database busy)` in `pdfs diagnostics`) when it has none.
**Verified:** `a_read_without_a_reader_connection_fails_instead_of_waiting_on_the_writer` and
`a_stuck_probe_is_not_started_again`.
---
### B295 — A resize the scratch file refused still succeeded
**Status:** Fixed
**Found:** 2026-11-25, in a review of the mount's write path.
**Where:** `crates/pdfs-fuse/src/filesystem.rs` `setattr`; `crates/pdfs-fuse/src/state.rs`
`WriteHandle::resize`
**Repro:** Open a file for writing in the mount, then `ftruncate` it larger while the disk that
holds the cache is full.
**Cause:** A resize through an open handle recorded the new length and claimed the grown tail as
written, then called `set_len` on the scratch file and ignored the result. When the scratch file
refused, the call still succeeded. The handle's length and written ranges then described bytes the
scratch file did not hold, and the version sent to Drive was built from that.
**Fix:** `WriteHandle::resize` resizes the scratch file first and records the new length and
ranges only when that succeeds. `setattr` answers the scratch file's error.
**Verified:** `state::tests::a_resize_the_scratch_file_refuses_changes_nothing`, which resizes a
handle whose scratch file refuses `ftruncate`, 2026-11-25.
### B294 — A mirror folder too large to finish in one run never syncs, and holds back the others
**Status:** Fixed (unverified)
+11 -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-core/src/db/migrations.rs`) a
`Schema:` lines record the SQLite `SCHEMA_VERSION` (`pdfs-store/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).
@@ -15,6 +15,9 @@ Schema: **49**. New tables save a mirror folder's walk of Proton Drive (48). A f
kept, with a list of the folders that changed on Proton Drive since (49).
### Added
- **`pdfs diagnostics` counts every call the daemon makes to Proton Drive.** Per kind of call it
shows how many were made since start, how many failed, and their total and longest time. The
JSON report has them as `drive_calls`.
- **`pdfs diagnostics` and the journal say where a sync pass spends its time.** Each pass over a
synced folder records how long it took to walk this computer's copy, list Proton Drive, plan
and apply. It also records how many calls to Proton Drive it made of each kind, how long they
@@ -47,6 +50,10 @@ kept, with a list of the folders that changed on Proton Drive since (49).
first pass, and whenever the change feed lost track (#53).
### Fixed
- **A busy database no longer stalls reads or piles up threads.** A read that cannot get its own
connection fails instead of waiting behind a long write. `pdfs diagnostics` reports the
number of queued operations as unknown when the database does not answer in time, and no
longer starts a new thread for every report while it waits (B296).
- Files dragged in from a file manager on Wayland upload. The compositor offers
such a drag as a move at first, and My files, answering only to a copy, refused
it without a word. It now asks for a copy, which the compositor then picks.
@@ -116,6 +123,9 @@ dropped once so they are read again with real deletion times.
### Fixed
- A resize of an open file in the mount that the disk refused, for example a grow on a full disk,
failed with nothing changed. It used to succeed, and the file then had a length and content the
disk never held (B295).
- A large trash listed only its first items and never refreshed, and Empty Trash
never emptied it (B293). Empty Trash no longer reports the server's "Accepted"
answer as an error. Needs proton-sdk and proton-drive-rs 0.12.6.
+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-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.
`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.
**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 (`sync/trace.rs`) is how we measure this design against the current one. Get
The pass trace (`crates/pdfs-sync/src/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-core/src/db/tests.rs`; a schema change adds one that migrates from the previous
`crates/pdfs-store/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-core a_copy_of_a_real_database -- --ignored
cargo test -p pdfs-store a_copy_of_a_real_database -- --ignored
```
## Simulation runs