mirror of
https://github.com/narrrl/proton-drive-linux.git
synced 2026-11-26 02:52:14 +01:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6ecf713d3a | ||
|
|
8e3e048005 | ||
|
|
f34ed62f27 | ||
|
|
19cfbf0ae0 | ||
|
|
5e3e242db8 |
No files matched your search
+1
-1
@@ -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
@@ -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
@@ -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"] }
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
@@ -3646,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 {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -2342,6 +2369,22 @@ pub struct Diagnostics {
|
||||
/// 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`].
|
||||
@@ -2479,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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
@@ -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 {
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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"] }
|
||||
@@ -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;
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -18,7 +18,7 @@ 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,6 +164,18 @@ 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(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
+23
-100
@@ -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,
|
||||
@@ -3350,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> {
|
||||
@@ -4682,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) {
|
||||
@@ -6410,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()))
|
||||
@@ -6501,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,
|
||||
@@ -6606,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())
|
||||
@@ -7127,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.
|
||||
@@ -7317,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;
|
||||
|
||||
@@ -7822,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]
|
||||
@@ -8150,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))
|
||||
@@ -9964,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))
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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,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;
|
||||
@@ -7,9 +7,9 @@ use std::fs::File;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use pdfs_core::cache::StagedWrite;
|
||||
use pdfs_core::db::Db;
|
||||
use pdfs_core::{Access, access_for};
|
||||
use pdfs_store::cache::StagedWrite;
|
||||
use pdfs_store::db::Db;
|
||||
#[cfg(test)]
|
||||
use proton_drive_rs::MemberRole;
|
||||
use proton_drive_rs::proton_sdk::ids::NodeUid;
|
||||
@@ -1770,9 +1770,9 @@ mod tests {
|
||||
node("shared-child", "shared", "pending.txt", false),
|
||||
);
|
||||
st.flushed_db()
|
||||
.enqueue_op(&pdfs_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()),
|
||||
|
||||
@@ -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::*;
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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.
|
||||
@@ -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)]
|
||||
@@ -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,
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -3,7 +3,7 @@
|
||||
use rusqlite::{OptionalExtension, params};
|
||||
|
||||
use super::Db;
|
||||
use crate::Result;
|
||||
use pdfs_core::Result;
|
||||
|
||||
pub struct StoredDevice {
|
||||
pub uid: String,
|
||||
File renamed without changes.
@@ -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};
|
||||
@@ -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.
|
||||
///
|
||||
@@ -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};
|
||||
@@ -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.
|
||||
@@ -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};
|
||||
|
||||
@@ -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";
|
||||
@@ -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,
|
||||
@@ -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,
|
||||
])?;
|
||||
@@ -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,7 +665,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,
|
||||
@@ -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 {
|
||||
@@ -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()?;
|
||||
// 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",
|
||||
};
|
||||
@@ -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(
|
||||
@@ -1049,13 +1049,13 @@ impl Db {
|
||||
GROUP BY COALESCE(group_key, uid) \
|
||||
HAVING MAX(similar_hash) IS NOT NULL \
|
||||
OR MAX(kind != ?1 AND thumb_state != ?2))",
|
||||
params![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>>> {
|
||||
@@ -1067,13 +1067,13 @@ impl Db {
|
||||
FROM photos GROUP BY k \
|
||||
HAVING MAX(similar_hash) IS NOT NULL AND MAX(similar_hash) != ?1",
|
||||
)?;
|
||||
stmt.query_map(params![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,7 +1108,7 @@ impl Db {
|
||||
}
|
||||
|
||||
pub fn photos_counts_visible(&self, excluded: &str) -> Result<(usize, usize, usize)> {
|
||||
use crate::control::PhotoKind;
|
||||
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
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -4,7 +4,7 @@
|
||||
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>> {
|
||||
@@ -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
|
||||
@@ -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")
|
||||
@@ -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,
|
||||
@@ -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`.
|
||||
@@ -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;
|
||||
@@ -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
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
+4
-1
@@ -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
|
||||
|
||||
+2
-2
@@ -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
@@ -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
@@ -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
|
||||
|
||||
Reference in new issue
Block a user