Compare commits

...
Author SHA1 Message Date
nvrl 69d7441d89 Merge pull request #165 from narrrl/refactor/photos-service
refactor(fuse): make Photos, the trash and revisions services with host ports
2026-11-26 21:31:00 +01:00
nvrl 45e0b60994 refactor(fuse): make revisions a service that takes resolved nodes
Each revision operation was a method on `Core` in three copies: by path, by
uid, and the one that did the work. `revisions::Revisions` keeps only the
last, and takes the node's uid and the name the activity feed shows.
`control/revisions.rs` resolves the path or the uid once and, for a restore
by path, re-enumerates the parent folder afterwards, as before.

The service reaches the filesystem through `RevisionsHost`: check that the
node may be written, drop what describes the old content and fetch it again
if it is kept offline, and add an activity entry. Error messages and
activity entries are unchanged.
2026-11-26 20:49:41 +01:00
nvrl 96248e41e2 refactor(fuse): make the trash a service with a two-method host port
Listing, refreshing, restoring and deleting from the Drive trash move from
`Core` onto `trash::Trash`. It holds Drive, the runtime, the database, the
event hub, the service board, the write state (to unhide a restored node)
and its own refresh state. It reaches the mounts through `TrashHost`, which
re-enumerates the folders a restored node comes back into and forgets nodes
the server no longer has, in every mount. `Core::trash` builds it on demand.

`Core`'s field for the refresh state is renamed `trash_jobs` so the accessor
can be called `trash`. Marking the stored listing stale only clears a
database row, so `Core::invalidate_trash` stays and calls the same free
function as the service instead of building it.
2026-11-26 20:46:26 +01:00
nvrl ee2f28c5cd refactor(fuse): move the Google Photos import and the redate job into Photos
Both jobs only touched the Photos API, the runtime, the cache, the transfer
list and the shutdown signal, so they become methods on `photos::Photos` and
their modules move under `photos/`. The import's activity entry goes through
a third `PhotosHost` method, `log_activity`.
2026-11-26 20:40:16 +01:00
nvrl acc251c3d3 refactor(fuse): make Photos a service with a two-method host port
The timeline, albums and thumbnails were methods on `Core`. They are now
methods on `photos::Photos`, which holds only the handles it calls: the
client, Drive, the runtime, the content cache, the database, shutdown, the
service board, the event hub, the transfer list and the `PhotoJobs` state.
It reaches the filesystem through `PhotosHost`, which lists a folder for the
recursive thumbnail build and notes a change made here so its echo is not
taken for a remote edit. `Core::photos` builds one on demand with the daemon
as host, the same way `Core::syncer` builds the sync engine.

Albums move under `photos/`. Downloading a photo with a progress entry moves
from `Core` into the service. `listing_stale` becomes a free function over
the database so the service can use it. The Photos API handle is now named
`photos_api` on both `Core` and the service, which frees `photos` for the
service.

Trashing photos stays on `Core` in `photos/trash.rs`, because it checks
write authority against the tree, drops open readers and clears the trash
listing.
2026-11-26 20:35:59 +01:00
nvrl e855498edf docs(architecture): describe the Sharing service and the control modules 2026-11-26 20:20:24 +01:00
nvrl 54bb2fd10d refactor(fuse): answer control requests in one module per area
The control socket answered every request in one match inside
handle_control_conn, over 1,500 lines long. The requests about Photos,
synced folders and devices, revisions, and the trash and cache now each
have a module under control/, next to the sharing one.

Each module exports a pattern macro naming its requests. The main match
hands those over in one arm, so the compiler still checks that every
request has an answer, and a request added to a module's pattern but
not to its match fails loudly rather than falling through. What an
answer may need besides the request (the Core, the mountpoint, the
connection and the hidden gallery's filter) travels in an Ask value.

The answers themselves are unchanged.
2026-11-26 20:20:08 +01:00
nvrl c6806362ae refactor(fuse): give the sync pause an owner type
The global pause was an AtomicI64 on Core that pause.rs and mount.rs
read and wrote directly, with the database row kept in step by hand at
each site. SyncPause now owns both: it loads the persisted value,
stores a new one only once it is saved, and ends a timed pause only if
it is still the one in force. Core keeps what a pause does to the rest
of the daemon: waking the drain and the reconcile, and the timer.
2026-11-26 20:16:00 +01:00
nvrl 7462edc07c refactor(fuse): make sharing a service and answer its requests in one place
Sharing was a set of methods on Core in three copies each: one taking a
path, one taking a wire-format uid, and the one that did the work. It
now is a Sharing struct that holds only the handles it calls (the
client, Drive, the content cache, the transfer list and a read of the
tree) and whose methods all take a resolved node.

The control socket resolves the path or uid once, in control/share.rs,
and logs the activity entry there. The main request match hands the
sharing requests over through a pattern macro, so the compiler still
checks that every request is covered.

The account quota, which is not about sharing, moves to quota.rs.
2026-11-26 20:11:16 +01:00
nvrl b9571ad045 docs(bugs): record a new sighting of B139 in the trash-restore sim
A first write logged "access changed before the write could be queued" once in a full sim run; five reruns passed on the branch and on main.
2026-11-26 19:56:44 +01:00
nvrl b210485430 refactor(fuse): group a mount's session cells and fold the online flag into Link
`primary`, `root`, `notifier` and `session_live` belong to one mount's FUSE
session, not to the daemon. They move into `session::SessionCells`, and an
on-demand fork takes fresh cells from `SessionCells::fork` instead of
resetting four fields by hand.

The `online` flag joins `link::Link`, next to when the link went down and
the condvar for its coming back. Code that read the atomic directly asks
`Core::is_online` instead.

ARCHITECTURE.md describes the three interfaces and what is left in `Core`.
2026-11-26 19:38:03 +01:00
nvrl 24f1f51c2c refactor(fuse): put the write-back's state behind WriteState
`pending`, `hidden` and `self_changes` move off `Core` into
`writes::WriteState`. The read path, listings, the pin keeper and the event
feed now ask it through methods (`queued`, `is_queued`, `queued_len`,
`queued_sizes`, `hidden`, `hide`, `unhide`, `note_echo`, `take_echo`)
instead of taking its locks. `hidden` and `self_changes` are private to the
module. `pending` stays visible to the queue, the drain and recovery, which
update it together with the database under one lock.
2026-11-26 19:29:21 +01:00
nvrl bbaa24e6ce Merge pull request #162 from narrrl/refactor/services
feat(core,fuse): stop the event-stream loops with the mount's other services
2026-11-26 19:18:41 +01:00
47 changed files with 2597 additions and 2087 deletions

No files matched your search

+1 -1
View File
@@ -57,7 +57,7 @@ impl Core {
mountpoint: &Path,
) -> CoreResult<StoredSyncFolder> {
let _registration = super::devices::SYNC_ROOT_REGISTRATION.lock();
if !self.primary {
if !self.session.primary {
return Err(CoreError::invalid("attach must use My files"));
}
if remote.is_absolute()
+3 -3
View File
@@ -176,7 +176,7 @@ fn apply_event(core: &Core, event: &DriveEvent, dirty: &mut DirtyParents) -> pdf
// even for a trash, so an echo we no longer care about does not
// linger to suppress a later foreign change.
let echo = core.take_self_change(node_uid);
let ours = !*is_trashed && (echo || core.pending.lock().contains_key(node_uid));
let ours = !*is_trashed && (echo || core.writes.is_queued(node_uid));
if ours {
debug!(uid = %node_uid, "ignoring remote event for a node with a queued write");
}
@@ -568,7 +568,7 @@ pub(super) async fn run_event_sync(
/// Follow the Photos volume and commit changes with its durable event cursor.
pub(super) async fn run_photos_event_sync(core: Core) {
let photos = core.photos();
let photos = core.photos_api();
// The photos volume only exists once the user has used Photos at all, and
// the daemon may well start before the network does.
let scope = loop {
@@ -635,7 +635,7 @@ pub(super) async fn run_photos_event_sync(core: Core) {
}
}
if core.db.photos_need_work().unwrap_or(true) {
core.spawn_timeline_refresh();
core.photos().spawn_timeline_refresh();
}
core.next_poll(POLL_INTERVAL).await;
}
File diff suppressed because it is too large. Load diff
+455
View File
@@ -0,0 +1,455 @@
//! The control requests about Photos: the timeline, albums, thumbnails, the gallery, and Takeout imports and redating.
use super::*;
/// The requests [`answer`] serves, as a pattern, so the control socket's match
/// hands exactly these over and the compiler still checks that it covers every
/// request.
macro_rules! request {
() => {
::pdfs_core::control::Request::PhotosTimeline { .. }
| ::pdfs_core::control::Request::PhotoDuplicates
| ::pdfs_core::control::Request::PhotoSimilar
| ::pdfs_core::control::Request::PhotoPlaces
| ::pdfs_core::control::Request::PlacePhotos { .. }
| ::pdfs_core::control::Request::PlaceLocations { .. }
| ::pdfs_core::control::Request::PhotosOnThisDay { .. }
| ::pdfs_core::control::Request::PhotoGroup { .. }
| ::pdfs_core::control::Request::SetPhotoFavorite { .. }
| ::pdfs_core::control::Request::PhotoAlbums
| ::pdfs_core::control::Request::AlbumPhotos { .. }
| ::pdfs_core::control::Request::CreateAlbum { .. }
| ::pdfs_core::control::Request::RenameAlbum { .. }
| ::pdfs_core::control::Request::DeleteAlbum { .. }
| ::pdfs_core::control::Request::AddToAlbum { .. }
| ::pdfs_core::control::Request::RemoveFromAlbum { .. }
| ::pdfs_core::control::Request::PhotoPresence { .. }
| ::pdfs_core::control::Request::PhotoMonths { .. }
| ::pdfs_core::control::Request::PhotoThumbs { .. }
| ::pdfs_core::control::Request::FileThumbs { .. }
| ::pdfs_core::control::Request::ReserveFileThumbGeneration
| ::pdfs_core::control::Request::CancelFileThumbs { .. }
| ::pdfs_core::control::Request::StartThumbnailBuild { .. }
| ::pdfs_core::control::Request::CancelThumbnailBuild
| ::pdfs_core::control::Request::ThumbnailBuildStatus
| ::pdfs_core::control::Request::PhotosRefreshStatus
| ::pdfs_core::control::Request::OpenPhoto { .. }
| ::pdfs_core::control::Request::DriveGallery { .. }
| ::pdfs_core::control::Request::OpenGalleryVideo { .. }
| ::pdfs_core::control::Request::OpenGalleryImage { .. }
| ::pdfs_core::control::Request::CloseGalleryVideo { .. }
| ::pdfs_core::control::Request::GalleryThumbnail { .. }
| ::pdfs_core::control::Request::ImportTakeout { .. }
| ::pdfs_core::control::Request::ImportStatus
| ::pdfs_core::control::Request::ResumeImport
| ::pdfs_core::control::Request::CancelImport
| ::pdfs_core::control::Request::RedatePhotos { .. }
| ::pdfs_core::control::Request::RedateStatus
| ::pdfs_core::control::Request::CancelRedate
| ::pdfs_core::control::Request::UploadPhoto { .. }
};
}
pub(super) use request;
/// Answer a request that [`request!`] matches.
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
let Ask {
core,
mountpoint,
stream,
visibility,
excluded,
..
} = *ask;
match request {
CtlRequest::PhotosTimeline {
offset,
limit,
kind,
range,
favorites,
not_in_album,
} => match core.photos().photos_timeline(
offset,
clamp_limit(limit),
kind,
range,
favorites,
not_in_album,
excluded,
) {
Ok(Some(items)) => CtlResponse::Photos {
available: true,
items,
counts: core.db.photos_counts_visible(excluded).ok(),
},
Ok(None) => CtlResponse::Photos {
available: false,
items: Vec::new(),
counts: None,
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::PhotoDuplicates => match core.photos().photo_duplicates() {
Ok(sets) => CtlResponse::PhotoDuplicates { sets },
Err(e) => CtlResponse::error(e),
},
CtlRequest::PhotoSimilar => match core.photos().photo_similar() {
Ok((sets, hashing, uncompared)) => CtlResponse::PhotoSimilar {
sets,
hashing,
uncompared,
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::PhotoPlaces => match core.photos().photo_places(excluded) {
Ok(items) => CtlResponse::Places {
items,
mapping: core.photos().timeline_progress(),
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::PlacePhotos { id, offset, limit } => {
match core
.photos()
.place_photos(id, offset, clamp_limit(limit), excluded)
{
Ok(items) => CtlResponse::Photos {
available: true,
items,
counts: None,
},
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::PlaceLocations { id } => match core.photos().place_locations(id) {
Ok(items) => CtlResponse::PhotoLocations { items },
Err(e) => CtlResponse::error(e),
},
CtlRequest::PhotosOnThisDay { limit } => {
match core
.photos()
.photos_on_this_day(clamp_limit(limit), excluded)
{
Ok(items) => CtlResponse::Photos {
available: true,
items,
counts: None,
},
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::PhotoGroup { uid } => match core.photos().photo_group(&uid) {
Ok(items) => CtlResponse::Photos {
available: true,
items,
counts: None,
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::SetPhotoFavorite { uid, favorite } => match parse_uid(&uid) {
Some(node_uid) => match core.photos().set_photo_favorite(&node_uid, favorite) {
Ok(()) => CtlResponse::Ok {
message: if favorite {
"added to favorites".to_string()
} else {
"removed from favorites".to_string()
},
},
Err(e) => CtlResponse::error(e),
},
None => CtlResponse::error(CoreError::invalid(format!("invalid uid: {uid}"))),
},
CtlRequest::PhotoAlbums => match core.photos().albums() {
Ok(Some(items)) => CtlResponse::Albums {
available: true,
items,
},
Ok(None) => CtlResponse::Albums {
available: false,
items: Vec::new(),
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::AlbumPhotos { uid, offset, limit } => match parse_uid(&uid) {
// An album page is a timeline page as far as the front-end is
// concerned, so it comes back in the same reply — with `counts`
// unset, which describe the whole timeline rather than this album.
Some(album) => match visibility.permits(&uid).and_then(|()| {
core.photos()
.album_photos(&album, offset, clamp_limit(limit), excluded)
}) {
Ok(items) => CtlResponse::Photos {
available: true,
items,
counts: None,
},
Err(e) => CtlResponse::error(e),
},
None => CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}"))),
},
CtlRequest::CreateAlbum { name } => match core.photos().create_album(&name) {
Ok(uid) => CtlResponse::AlbumCreated { uid },
Err(e) => CtlResponse::error(e),
},
CtlRequest::RenameAlbum { uid, name } => match parse_uid(&uid) {
Some(album) => match core.photos().rename_album(&album, &name) {
Ok(()) => CtlResponse::Ok {
message: format!("renamed album to {name}"),
},
Err(e) => CtlResponse::error(e),
},
None => CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}"))),
},
CtlRequest::DeleteAlbum { uid, delete_photos } => match parse_uid(&uid) {
Some(album) => match core.photos().delete_album(&album, delete_photos) {
Ok(()) => CtlResponse::Ok {
message: "album deleted".to_string(),
},
Err(e) => CtlResponse::error(e),
},
None => CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}"))),
},
CtlRequest::AddToAlbum { uid, photos } => album_change(&uid, &photos, |album, photos| {
core.photos().add_to_album(album, photos)
}),
CtlRequest::RemoveFromAlbum { uid, photos } => {
album_change(&uid, &photos, |album, photos| {
core.photos().remove_from_album(album, photos)
})
}
CtlRequest::PhotoPresence { uid, album } => match core.cached_gallery_visibility() {
Ok(visibility)
if visibility.media.contains(&uid)
|| album
.as_ref()
.is_some_and(|uid| visibility.albums.contains(uid)) =>
{
CtlResponse::PhotoPresence { present: false }
}
Ok(_) => match core.db.photos_contains(&uid, album.as_deref()) {
Ok(present) => CtlResponse::PhotoPresence { present },
Err(error) => CtlResponse::error(error.into()),
},
Err(error) => CtlResponse::error(error),
},
CtlRequest::PhotoMonths { .. } => unreachable!("handled before visibility requests"),
CtlRequest::PhotoThumbs { uids } => {
let parsed: Vec<NodeUid> = uids
.iter()
.filter(|uid| !visibility.media.contains(*uid))
.filter_map(|u| parse_uid(u))
.collect();
CtlResponse::Thumbs {
items: core.photos().photo_thumbs(&parsed),
}
}
CtlRequest::FileThumbs { items, generation } => {
match core.photos().file_thumbs(&items, generation) {
Some(items) => CtlResponse::Thumbs { items },
None => CtlResponse::FileThumbsStale,
}
}
CtlRequest::ReserveFileThumbGeneration => CtlResponse::FileThumbGeneration {
generation: core.photos().reserve_file_thumb_generation(),
},
CtlRequest::CancelFileThumbs { generation } => {
core.photos().cancel_file_thumbs(generation);
CtlResponse::Ok {
message: "thumbnail requests cancelled".to_string(),
}
}
CtlRequest::StartThumbnailBuild { path } => match rel_to_mount(mountpoint, &path) {
Ok(rel) => match core.photos().start_thumbnail_build(rel) {
Ok(status) => CtlResponse::ThumbnailBuild { status },
Err(error) => CtlResponse::error(error),
},
Err(error) => CtlResponse::error(error),
},
CtlRequest::CancelThumbnailBuild => CtlResponse::ThumbnailBuild {
status: core.photos().cancel_thumbnail_build(),
},
CtlRequest::ThumbnailBuildStatus => CtlResponse::ThumbnailBuild {
status: core.photos().thumbnail_build_status(),
},
CtlRequest::PhotosRefreshStatus => CtlResponse::PhotosRefresh {
running: core.photos().timeline_refreshing(),
},
CtlRequest::OpenPhoto { uid } => match parse_uid(&uid) {
Some(u) => match visibility
.permits(&uid)
.and_then(|()| core.photos().open_photo(&u))
{
Ok(p) => CtlResponse::FilePath {
path: p.display().to_string(),
},
Err(e) => CtlResponse::error(e),
},
None => CtlResponse::error(CoreError::invalid(format!("bad uid: {uid}"))),
},
CtlRequest::DriveGallery {
action: pdfs_core::control::GalleryAction::AuthenticateHidden,
} => core
.authenticate_hidden_gallery(stream)
.unwrap_or_else(CtlResponse::error),
CtlRequest::DriveGallery { action } => core
.drive_gallery(action)
.unwrap_or_else(CtlResponse::error),
CtlRequest::OpenGalleryVideo { uid, private } => core
.open_gallery_video(&uid, private)
.unwrap_or_else(CtlResponse::error),
CtlRequest::OpenGalleryImage { uid, private: true } => {
core.gallery_image(&uid).unwrap_or_else(CtlResponse::error)
}
CtlRequest::OpenGalleryImage {
uid,
private: false,
} => match visibility
.permits(&uid)
.and_then(|()| core.sharing.open_shared_file(&uid))
{
Ok(path) => CtlResponse::FilePath {
path: path.display().to_string(),
},
Err(error) => CtlResponse::error(error),
},
CtlRequest::CloseGalleryVideo { token } => core
.close_gallery_video(&token)
.unwrap_or_else(CtlResponse::error),
CtlRequest::GalleryThumbnail { uid, private } => core
.gallery_thumbnail(&uid, private)
.unwrap_or_else(CtlResponse::error),
CtlRequest::ImportTakeout { archives, dry_run } => {
if archives.is_empty() {
CtlResponse::error(CoreError::invalid("no Takeout archives given"))
} else {
let paths = archives.into_iter().map(PathBuf::from).collect();
start_takeout_import(core, paths, dry_run)
}
}
CtlRequest::ImportStatus => {
let report = crate::photos::takeout::import_status();
CtlResponse::ImportStatus {
running: report.running,
summary: report.summary,
progress: report.progress,
resumable: report.resumable,
}
}
CtlRequest::ResumeImport => match crate::photos::takeout::resumable_archives() {
None => CtlResponse::error(CoreError::not_found("there is no import to resume")),
Some(paths) => start_takeout_import(core, paths, false),
},
CtlRequest::CancelImport => {
if crate::photos::takeout::cancel_import() {
CtlResponse::Ok {
message: "stopping the import".to_string(),
}
} else {
CtlResponse::error(CoreError::invalid("no import is running"))
}
}
CtlRequest::RedatePhotos {
dry_run,
limit,
range,
} => match core.photos().spawn_redate(dry_run, limit, range) {
Ok(()) => CtlResponse::Ok {
message: if dry_run {
"checking photo dates".to_string()
} else {
"fixing photo dates".to_string()
},
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::RedateStatus => {
let (running, summary) = crate::photos::redate::redate_status();
CtlResponse::RedateStatus { running, summary }
}
CtlRequest::CancelRedate => {
if crate::photos::redate::cancel_redate() {
CtlResponse::Ok {
message: "stopping the re-date".to_string(),
}
} else {
CtlResponse::error(CoreError::invalid("no photo re-date is running"))
}
}
CtlRequest::UploadPhoto {
name,
media_type,
source_path,
capture_time,
} => {
// Streamed off disk rather than carried over the socket: see the note
// on `Request::UploadPhoto`. The length comes from the same handle the
// bytes do, so a file changing size under us cannot make the two
// disagree.
match std::fs::File::open(&source_path).and_then(|f| f.metadata().map(|m| (f, m.len())))
{
Err(e) => CtlResponse::error(CoreError::invalid(format!(
"cannot read {source_path}: {e}"
))),
Ok((file, len)) => {
let photos = core.photos_api();
// Unless the caller knows better: the photo's own EXIF,
// then the file's modification time, which a copy resets.
let capture_time = capture_time.or_else(|| {
let path = Path::new(&source_path);
pdfs_core::exiftime::capture_time_of(path).or_else(|| {
let modified =
std::fs::metadata(path).and_then(|m| m.modified()).ok()?;
let since = modified.duration_since(std::time::UNIX_EPOCH).ok()?;
Some(since.as_secs() as i64)
})
});
let metadata = proton_drive_rs::PhotoUploadMetadata {
capture_time,
last_modification_time: capture_time
.and_then(pdfs_core::timestamp::modification_time),
..Default::default()
};
let thumbnails = core
.photos()
.upload_thumbnails(Path::new(&source_path), &name);
let guard =
core.transfers
.begin(name.clone(), "", TransferDirection::Upload, len);
let reader = CountingReader::new(std::io::BufReader::new(file), &guard);
match core.rt.block_on(photos.upload_photo_from(
&name,
&media_type,
reader,
len as i64,
thumbnails,
metadata,
false,
)) {
Ok(uid) => {
// The photo we just uploaded belongs at the head of the
// timeline, and the GUI reloads the gallery the moment this
// reply lands — so refresh now rather than leaving it to a
// background pass that would land just after that reload.
core.invalidate_photos();
if let Err(e) = core.photos().refresh_timeline_joined() {
warn!(error = %e, "timeline refresh after upload failed");
}
CtlResponse::Ok {
message: format!("uploaded photo with uid {uid}"),
}
}
Err(e) => {
// The reply goes to the app's toast only; without
// this the journal shows a failure and no reason.
warn!(error = %e, "photo upload failed");
CtlResponse::error(CoreError::from_api(&e, "upload photo failed"))
}
}
}
}
}
// `control` only hands over what `request!` matches.
_ => CtlResponse::error(CoreError::internal("not a photos request".to_string())),
}
}
+122
View File
@@ -0,0 +1,122 @@
//! The control requests about a file's earlier revisions: listing, restoring, deleting and saving one as a new file, by path or by uid.
use super::*;
/// The requests [`answer`] serves, as a pattern, so the control socket's match
/// hands exactly these over and the compiler still checks that it covers every
/// request.
macro_rules! request {
() => {
::pdfs_core::control::Request::ListRevisions { .. }
| ::pdfs_core::control::Request::ListRevisionsByUid { .. }
| ::pdfs_core::control::Request::RestoreRevision { .. }
| ::pdfs_core::control::Request::RestoreRevisionByUid { .. }
| ::pdfs_core::control::Request::DeleteRevision { .. }
| ::pdfs_core::control::Request::DeleteRevisionByUid { .. }
| ::pdfs_core::control::Request::SaveRevisionAs { .. }
| ::pdfs_core::control::Request::SaveRevisionAsByUid { .. }
};
}
pub(super) use request;
/// The file a request is about, and how the activity feed names it: the file
/// name under the mount, or the uid.
struct Target {
uid: NodeUid,
name: String,
}
impl Target {
fn path(core: &Core, rel: &Path) -> CoreResult<Self> {
let (_ino, uid) = core.resolve(rel)?;
let name = rel
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| uid.to_string());
Ok(Self { uid, name })
}
fn uid(core: &Core, uid: &str) -> CoreResult<Self> {
let uid = core.resolve_anywhere(uid)?;
let name = uid.to_string();
Ok(Self { uid, name })
}
}
/// Answer a request that [`request!`] matches.
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
let Ask {
core, mountpoint, ..
} = *ask;
let revisions = core.revisions();
let at = |path: &str| rel_to_mount(mountpoint, path);
let reply = |result: CoreResult<String>| match result {
Ok(message) => CtlResponse::Ok { message },
Err(e) => CtlResponse::error(e),
};
match request {
CtlRequest::ListRevisions { path } => {
match at(&path).and_then(|rel| Target::path(core, &rel)) {
Ok(file) => listed(revisions.list(&file.uid)),
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::ListRevisionsByUid { uid } => match Target::uid(core, &uid) {
Ok(file) => listed(revisions.list(&file.uid)),
Err(e) => CtlResponse::error(e),
},
CtlRequest::RestoreRevision { path, revision_id } => reply(at(&path).and_then(|rel| {
let file = Target::path(core, &rel)?;
revisions.restore(&file.uid, &revision_id, &file.name)?;
// The size and mtime a listing shows describe the revision that
// was active a moment ago.
core.invalidate_parent_listing(&rel);
Ok(format!("restoring version {revision_id} of {path}"))
})),
CtlRequest::RestoreRevisionByUid { uid, revision_id } => {
reply(Target::uid(core, &uid).and_then(|file| {
revisions.restore(&file.uid, &revision_id, &file.name)?;
Ok(format!("restoring version {revision_id}"))
}))
}
CtlRequest::DeleteRevision { path, revision_id } => reply(at(&path).and_then(|rel| {
let file = Target::path(core, &rel)?;
revisions.delete(&file.uid, &revision_id, &file.name)?;
Ok(format!("deleted version {revision_id} of {path}"))
})),
CtlRequest::DeleteRevisionByUid { uid, revision_id } => {
reply(Target::uid(core, &uid).and_then(|file| {
revisions.delete(&file.uid, &revision_id, &file.name)?;
Ok(format!("deleted version {revision_id}"))
}))
}
CtlRequest::SaveRevisionAs {
path,
revision_id,
dest,
} => reply(at(&path).and_then(|rel| {
let file = Target::path(core, &rel)?;
let written =
revisions.save_as(&file.uid, &revision_id, &file.name, Path::new(&dest))?;
Ok(format!("wrote {} to {dest}", human_bytes(written)))
})),
CtlRequest::SaveRevisionAsByUid {
uid,
revision_id,
dest,
} => reply(Target::uid(core, &uid).and_then(|file| {
let written =
revisions.save_as(&file.uid, &revision_id, &file.name, Path::new(&dest))?;
Ok(format!("wrote {} to {dest}", human_bytes(written)))
})),
// `control` only hands over what `request!` matches.
_ => CtlResponse::error(CoreError::internal("not a revisions request".to_string())),
}
}
fn listed(result: CoreResult<Vec<pdfs_core::control::RevisionInfo>>) -> CtlResponse {
match result {
Ok(items) => CtlResponse::Revisions { items },
Err(e) => CtlResponse::error(e),
}
}
+371
View File
@@ -0,0 +1,371 @@
//! The control requests about sharing: who a node is shared with, its public
//! link, what others share with this account, invitations and saved links.
//!
//! Most of them come in two forms, one naming the node by its path under the
//! mount and one by its uid. Both are resolved to a uid here, once, and the
//! [`Sharing`](crate::sharing::Sharing) service is only ever asked about a
//! resolved node.
use std::path::Path;
use pdfs_core::CoreResult;
use pdfs_core::control::{ActivityKind, Request as CtlRequest, Response as CtlResponse};
use proton_drive_rs::proton_sdk::ids::NodeUid;
use super::rel_to_mount;
use crate::Core;
use crate::sharing::StopSharingOutcome;
/// The requests [`answer`] serves, as a pattern, so the control socket's
/// match hands exactly these over and the compiler still checks that it covers
/// every request.
macro_rules! request {
() => {
::pdfs_core::control::Request::ShareNode { .. }
| ::pdfs_core::control::Request::ShareNodeByUid { .. }
| ::pdfs_core::control::Request::ListShare { .. }
| ::pdfs_core::control::Request::ListShareByUid { .. }
| ::pdfs_core::control::Request::UpdateShareRole { .. }
| ::pdfs_core::control::Request::UpdateShareRoleByUid { .. }
| ::pdfs_core::control::Request::RemoveShareEntry { .. }
| ::pdfs_core::control::Request::RemoveShareEntryByUid { .. }
| ::pdfs_core::control::Request::CreatePublicLink { .. }
| ::pdfs_core::control::Request::CreatePublicLinkByUid { .. }
| ::pdfs_core::control::Request::UpdatePublicLink { .. }
| ::pdfs_core::control::Request::UpdatePublicLinkByUid { .. }
| ::pdfs_core::control::Request::RemovePublicLink { .. }
| ::pdfs_core::control::Request::RemovePublicLinkByUid { .. }
| ::pdfs_core::control::Request::StopSharing { .. }
| ::pdfs_core::control::Request::StopSharingByUid { .. }
| ::pdfs_core::control::Request::ListSharedWithMe
| ::pdfs_core::control::Request::ListSharedFolder { .. }
| ::pdfs_core::control::Request::OpenSharedFile { .. }
| ::pdfs_core::control::Request::LeaveShared { .. }
| ::pdfs_core::control::Request::ListInvitations
| ::pdfs_core::control::Request::AcceptInvitation { .. }
| ::pdfs_core::control::Request::RejectInvitation { .. }
| ::pdfs_core::control::Request::ListBookmarks
| ::pdfs_core::control::Request::CreateBookmark { .. }
| ::pdfs_core::control::Request::DeleteBookmark { .. }
| ::pdfs_core::control::Request::ListSharedByMe
};
}
pub(super) use request;
/// The node a request is about, and how the activity feed names it: the path
/// the user gave, or the uid.
struct Target {
label: String,
/// The node, or why it could not be resolved. A failure is reported
/// through the request's own reply, so a share that fails here is logged
/// as a failed share, as it was before the split.
node: CoreResult<NodeUid>,
}
impl Target {
/// A node named by its path. A path outside the mount fails the request
/// before it starts, without an activity entry.
fn path(core: &Core, mountpoint: &Path, path: String) -> CoreResult<Self> {
let rel = rel_to_mount(mountpoint, &path)?;
Ok(Self {
node: core.resolve(&rel).map(|(_ino, uid)| uid),
label: path,
})
}
/// A node named by its uid, which one of this daemon's locations, or the
/// Photos timeline, must show to be this account's.
fn uid(core: &Core, uid: String) -> Self {
Self {
node: core.resolve_shareable(&uid),
label: uid,
}
}
}
/// Answer a request that [`request!`] matches.
pub(super) fn answer(ask: &super::Ask<'_>, request: CtlRequest) -> CtlResponse {
let (core, mountpoint) = (ask.core, ask.mountpoint);
match answer_or_refuse(core, mountpoint, request) {
Ok(response) => response,
Err(e) => CtlResponse::error(e),
}
}
fn answer_or_refuse(
core: &Core,
mountpoint: &Path,
request: CtlRequest,
) -> CoreResult<CtlResponse> {
let sharing = &core.sharing;
Ok(match request {
CtlRequest::ShareNode {
path,
emails,
role,
message,
} => share_node(
core,
Target::path(core, mountpoint, path)?,
&emails,
&role,
message,
),
CtlRequest::ShareNodeByUid {
uid,
emails,
role,
message,
} => share_node(core, Target::uid(core, uid), &emails, &role, message),
CtlRequest::ListShare { path } => list_share(core, Target::path(core, mountpoint, path)?),
CtlRequest::ListShareByUid { uid } => list_share(core, Target::uid(core, uid)),
CtlRequest::UpdateShareRole {
path,
id,
kind,
role,
} => {
let target = Target::path(core, mountpoint, path)?;
target
.node
.and_then(|uid| sharing.update_share_role(&uid, &id, kind, &role))?;
role_updated(&role)
}
CtlRequest::UpdateShareRoleByUid {
uid,
id,
kind,
role,
} => {
let target = Target::uid(core, uid);
target
.node
.and_then(|uid| sharing.update_share_role(&uid, &id, kind, &role))?;
role_updated(&role)
}
CtlRequest::RemoveShareEntry { path, id, kind } => {
let target = Target::path(core, mountpoint, path)?;
remove_share_entry(core, target, &id, kind)?
}
CtlRequest::RemoveShareEntryByUid { uid, id, kind } => {
remove_share_entry(core, Target::uid(core, uid), &id, kind)?
}
CtlRequest::CreatePublicLink {
path,
role,
password,
expires,
} => {
let target = Target::path(core, mountpoint, path)?;
create_public_link(core, target, &role, password.as_deref(), expires)
}
CtlRequest::CreatePublicLinkByUid {
uid,
role,
password,
expires,
} => create_public_link(
core,
Target::uid(core, uid),
&role,
password.as_deref(),
expires,
),
CtlRequest::UpdatePublicLink {
path,
id,
role,
password,
expires,
} => {
let uid = Target::path(core, mountpoint, path)?.node?;
let link = sharing.update_public_link(&uid, &id, role.as_deref(), password, expires)?;
CtlResponse::PublicLink { link }
}
CtlRequest::UpdatePublicLinkByUid {
uid,
id,
role,
password,
expires,
} => {
let uid = Target::uid(core, uid).node?;
let link = sharing.update_public_link(&uid, &id, role.as_deref(), password, expires)?;
CtlResponse::PublicLink { link }
}
CtlRequest::RemovePublicLink { path, id } => {
remove_public_link(core, Target::path(core, mountpoint, path)?, &id)?
}
CtlRequest::RemovePublicLinkByUid { uid, id } => {
remove_public_link(core, Target::uid(core, uid), &id)?
}
CtlRequest::StopSharing { path } => {
stop_sharing(core, Target::path(core, mountpoint, path)?)
}
CtlRequest::StopSharingByUid { uid } => stop_sharing(core, Target::uid(core, uid)),
CtlRequest::ListSharedWithMe => CtlResponse::Entries {
entries: sharing.list_shared_with_me()?,
},
CtlRequest::ListSharedFolder { uid } => CtlResponse::Entries {
entries: sharing.list_shared_folder(&uid)?,
},
CtlRequest::OpenSharedFile { uid } => CtlResponse::FilePath {
path: sharing.open_shared_file(&uid)?.display().to_string(),
},
CtlRequest::LeaveShared { uid } => {
sharing.leave_shared(&uid)?;
core.log_activity(ActivityKind::Unshare, "shared item", "left", true);
ok("left shared item")
}
CtlRequest::ListInvitations => CtlResponse::Invitations {
items: sharing.list_invitations()?,
},
CtlRequest::AcceptInvitation { id } => {
sharing.accept_invitation(&id)?;
ok("invitation accepted")
}
CtlRequest::RejectInvitation { id } => {
sharing.reject_invitation(&id)?;
ok("invitation rejected")
}
CtlRequest::ListBookmarks => CtlResponse::Bookmarks {
items: sharing.list_bookmarks()?,
},
CtlRequest::CreateBookmark { url, password } => {
sharing.create_bookmark(&url, password.as_deref())?;
ok("bookmark saved")
}
CtlRequest::DeleteBookmark { token } => {
sharing.delete_bookmark(&token)?;
ok("bookmark removed")
}
CtlRequest::ListSharedByMe => CtlResponse::SharedByMe {
items: sharing.list_shared_by_me()?,
},
// `control` only hands over what `request!` matches.
_ => CtlResponse::error(pdfs_core::CoreError::internal(
"not a sharing request".to_string(),
)),
})
}
fn ok(message: &str) -> CtlResponse {
CtlResponse::Ok {
message: message.to_string(),
}
}
fn role_updated(role: &str) -> CtlResponse {
CtlResponse::Ok {
message: format!("role updated to {role}"),
}
}
fn share_node(
core: &Core,
target: Target,
emails: &[String],
role: &str,
message: Option<String>,
) -> CtlResponse {
let shared = target.node.and_then(|uid| {
core.sharing
.share_node(&uid, emails, role, message.as_deref())
});
match shared {
Ok((proton, external)) => {
core.log_activity(
ActivityKind::Share,
&target.label,
format!("{} recipient(s) as {role}", proton + external),
true,
);
ok(&format!(
"invited {proton} Proton and {external} external user(s)"
))
}
Err(e) => {
core.log_activity(ActivityKind::Share, &target.label, &e, false);
CtlResponse::error(e)
}
}
}
fn list_share(core: &Core, target: Target) -> CtlResponse {
match target.node.and_then(|uid| core.sharing.list_share(&uid)) {
Ok((entries, link)) => CtlResponse::Share { entries, link },
Err(e) => CtlResponse::error(e),
}
}
fn remove_share_entry(
core: &Core,
target: Target,
id: &str,
kind: pdfs_core::control::ShareEntryKind,
) -> CoreResult<CtlResponse> {
target
.node
.and_then(|uid| core.sharing.remove_share_entry(&uid, id, kind))?;
core.log_activity(ActivityKind::Unshare, &target.label, "access removed", true);
Ok(ok("removed"))
}
fn create_public_link(
core: &Core,
target: Target,
role: &str,
password: Option<&str>,
expires: Option<i64>,
) -> CtlResponse {
let created = target.node.and_then(|uid| {
core.sharing
.create_public_link(&uid, role, password, expires)
});
match created {
Ok(link) => {
core.log_activity(
ActivityKind::PublicLink,
&target.label,
"link created",
true,
);
CtlResponse::PublicLink { link }
}
Err(e) => {
core.log_activity(ActivityKind::PublicLink, &target.label, &e, false);
CtlResponse::error(e)
}
}
}
fn remove_public_link(core: &Core, target: Target, id: &str) -> CoreResult<CtlResponse> {
target
.node
.and_then(|uid| core.sharing.remove_public_link(&uid, id))?;
core.log_activity(ActivityKind::Unshare, &target.label, "link removed", true);
Ok(ok("public link removed"))
}
/// Log a stop-sharing request, and turn a partial removal into an error that
/// names what is still shared.
fn stop_sharing(core: &Core, target: Target) -> CtlResponse {
let result: CoreResult<StopSharingOutcome> =
target.node.and_then(|uid| core.sharing.stop_sharing(&uid));
match result.map(|outcome| outcome.into_result()) {
Ok(Ok(message)) => {
core.log_activity(
ActivityKind::Unshare,
&target.label,
"stopped sharing",
true,
);
CtlResponse::Ok { message }
}
Ok(Err(left)) => {
core.log_activity(ActivityKind::Unshare, &target.label, &left, false);
CtlResponse::error(pdfs_core::CoreError::remote(left))
}
Err(e) => CtlResponse::error(e),
}
}
+286
View File
@@ -0,0 +1,286 @@
//! The control requests about synced folders and devices: adding, attaching, switching and removing folders, pausing, conflicts, the pending-change queue, and restoring a device's folders.
use super::*;
/// The requests [`answer`] serves, as a pattern, so the control socket's match
/// hands exactly these over and the compiler still checks that it covers every
/// request.
macro_rules! request {
() => {
::pdfs_core::control::Request::ListDevices
| ::pdfs_core::control::Request::ListLocations
| ::pdfs_core::control::Request::RenameDevice { .. }
| ::pdfs_core::control::Request::DeleteDevice { .. }
| ::pdfs_core::control::Request::AdoptDevice { .. }
| ::pdfs_core::control::Request::MigrateDevice { .. }
| ::pdfs_core::control::Request::AddSyncFolder { .. }
| ::pdfs_core::control::Request::AttachSyncFolder { .. }
| ::pdfs_core::control::Request::ListSyncFolders
| ::pdfs_core::control::Request::RemoveSyncFolder { .. }
| ::pdfs_core::control::Request::SetSyncFolderMode { .. }
| ::pdfs_core::control::Request::SetSyncFolderPaused { .. }
| ::pdfs_core::control::Request::ResetSyncFolder { .. }
| ::pdfs_core::control::Request::SyncNow { .. }
| ::pdfs_core::control::Request::SetSyncPaused { .. }
| ::pdfs_core::control::Request::ListConflicts
| ::pdfs_core::control::Request::ResolveConflict { .. }
| ::pdfs_core::control::Request::ListPendingOps
| ::pdfs_core::control::Request::ExportPendingOp { .. }
| ::pdfs_core::control::Request::DiscardPendingOp { .. }
| ::pdfs_core::control::Request::RetryPendingOp { .. }
| ::pdfs_core::control::Request::ListRestorableFolders
| ::pdfs_core::control::Request::ListDeviceRestorableFolders { .. }
| ::pdfs_core::control::Request::RestoreSyncFolders { .. }
| ::pdfs_core::control::Request::RestoreDeviceFolders { .. }
};
}
pub(super) use request;
/// Answer a request that [`request!`] matches.
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
let Ask {
core, mountpoint, ..
} = *ask;
match request {
CtlRequest::ListDevices => match core.list_devices() {
Ok(items) => CtlResponse::Devices { items },
Err(e) => CtlResponse::error(e),
},
CtlRequest::ListLocations => match core.list_locations() {
Ok(items) => CtlResponse::Locations { items },
Err(e) => CtlResponse::error(e),
},
CtlRequest::RenameDevice { uid, name } => match core.rename_device(&uid, &name) {
Ok(()) => CtlResponse::Ok {
message: format!("renamed device to {name}"),
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::DeleteDevice { uid } => match core.delete_device(&uid) {
Ok(()) => CtlResponse::Ok {
message: "device deleted".to_string(),
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::AdoptDevice { uid } => match core.adopt_device(uid.as_deref()) {
Ok(message) => CtlResponse::Ok { message },
Err(e) => CtlResponse::error(e),
},
CtlRequest::MigrateDevice { uid } => match core.migrate_device(&uid) {
Ok(message) => CtlResponse::Ok { message },
Err(e) => CtlResponse::error(e),
},
CtlRequest::AddSyncFolder { local_path } => {
// Registering the device and uploading a folder tree far outlasts the
// socket read timeout, so ack immediately and work on a background
// thread. The folder appears in ListSyncFolders once the row lands;
// completion (and any failures) go to the activity log.
let core = core.clone();
let path = PathBuf::from(&local_path);
if let Err(error) = core
.services
.clone()
.spawn_job("pdfs-add-sync-folder", move || {
let started = Instant::now();
match core.add_sync_folder(&path) {
Ok(folder) => {
core.touch_profile();
let name = Path::new(&folder.local_path)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or(&folder.local_path)
.to_string();
core.log_activity(
ActivityKind::Upload,
format!("synced {name}"),
human_duration(started.elapsed()),
folder.state != "error",
);
}
Err(e) => {
warn!(error = %e, "add sync folder failed");
core.log_activity(ActivityKind::Upload, "add sync folder", &e, false);
}
}
})
{
tracing::warn!(%error, "could not start pdfs-add-sync-folder");
}
CtlResponse::Ok {
message: format!("adding {local_path}"),
}
}
CtlRequest::AttachSyncFolder {
local_path,
remote_path,
} => {
let result = rel_to_mount(mountpoint, &remote_path).and_then(|remote| {
core.attach_sync_folder(Path::new(&local_path), &remote, mountpoint)
});
match result {
Ok(folder) => CtlResponse::Ok {
message: format!("sync folder {} attached: {}", folder.id, folder.local_path),
},
Err(error) => CtlResponse::error(error),
}
}
CtlRequest::ListSyncFolders => match core.list_sync_folders() {
Ok(items) => CtlResponse::SyncFolders { items },
Err(e) => CtlResponse::error(e),
},
CtlRequest::RemoveSyncFolder { id, delete_remote } => {
match core.remove_sync_folder(id, delete_remote) {
Ok(()) => {
core.touch_profile();
CtlResponse::Ok {
message: "removed synced folder".to_string(),
}
}
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::SetSyncFolderMode { id, mode } => {
match core.request_sync_folder_mode(id, &mode) {
Ok(message) => {
core.touch_profile();
core.log_activity(ActivityKind::Upload, &message, "", true);
CtlResponse::Ok { message }
}
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::SetSyncFolderPaused { id, paused } => {
match core.set_sync_folder_paused(id, paused) {
Ok(()) => CtlResponse::Ok {
message: match paused {
true => format!("folder {id} paused"),
false => format!("folder {id} resumed"),
},
},
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::ResetSyncFolder { id } => match core.reset_sync_folder(id) {
Ok(message) => {
core.log_activity(ActivityKind::Sync, &message, "", true);
CtlResponse::Ok { message }
}
Err(e) => CtlResponse::error(e),
},
CtlRequest::SyncNow { id } => {
core.sync_now(id);
CtlResponse::Ok {
message: match id {
Some(id) => format!("reconciling folder {id}"),
None => "reconciling all folders".to_string(),
},
}
}
CtlRequest::SetSyncPaused { paused, until } => match core.set_sync_paused(paused, until) {
Ok(()) => CtlResponse::Ok {
message: match (paused, until) {
(false, _) => "sync resumed".to_string(),
(true, None) => "sync paused until resumed".to_string(),
(true, Some(_)) => "sync paused".to_string(),
},
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::ListConflicts => match core.list_conflicts() {
Ok(items) => CtlResponse::Conflicts { items },
Err(e) => CtlResponse::error(e),
},
CtlRequest::ResolveConflict { path, keep } => match route_change(core, mountpoint, &path) {
Ok((core, rel)) => match core.resolve_conflict(&rel, &keep) {
Ok(message) => CtlResponse::Ok { message },
Err(e) => CtlResponse::error(e),
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::ListPendingOps => match core.pending_op_infos() {
Ok(items) => CtlResponse::PendingOps { items },
Err(e) => CtlResponse::error(e),
},
CtlRequest::ExportPendingOp { id, dest } => {
match core.export_pending_op(id, Path::new(&dest)) {
Ok(written) => CtlResponse::Ok {
message: format!("wrote {} to {dest}", human_bytes(written)),
},
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::DiscardPendingOp { id } => match core.discard_pending_op(id) {
Ok(path) => CtlResponse::Ok {
message: format!("discarded the queued change to {path}"),
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::RetryPendingOp { id } => match core.retry_pending_ops(id) {
Ok(0) if id.is_some() => CtlResponse::Ok {
message: "nothing to retry: the operation is already due or waiting for a rename"
.to_string(),
},
Ok(moved) => CtlResponse::Ok {
message: format!("retrying {moved} queued operation(s) now"),
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::ListRestorableFolders => match core.list_restorable_folders(None) {
Ok(items) => CtlResponse::RestorableFolders { items },
Err(e) => CtlResponse::error(e),
},
CtlRequest::ListDeviceRestorableFolders { device } => {
match core.list_restorable_folders(Some(&device)) {
Ok(items) => CtlResponse::RestorableFolders { items },
Err(e) => CtlResponse::error(e),
}
}
request @ (CtlRequest::RestoreSyncFolders { .. }
| CtlRequest::RestoreDeviceFolders { .. }) => {
let (device, items) = match request {
CtlRequest::RestoreDeviceFolders { device, items } => (Some(device), items),
CtlRequest::RestoreSyncFolders { items } => (None, items),
_ => unreachable!("matched above"),
};
// Like AddSyncFolder: each restored folder downloads a whole tree,
// which outlasts the socket timeout. Ack, then work.
let core = core.clone();
if let Err(error) =
core.services
.clone()
.spawn_job("pdfs-restore-sync-folders", move || {
match core.restore_sync_folders(&items, device.as_deref()) {
Ok(outcome) => {
core.touch_profile();
if !outcome.complete() {
warn!(skipped = ?outcome.skipped, "restore skipped folders");
}
core.log_activity(
ActivityKind::Download,
outcome.summary(),
outcome.skipped.join("; "),
outcome.complete(),
);
}
Err(e) => {
warn!(error = %e, "restore failed");
core.log_activity(
ActivityKind::Download,
"restore folders",
&e,
false,
);
}
}
})
{
tracing::warn!(%error, "could not start pdfs-restore-sync-folders");
}
CtlResponse::Ok {
message: "restoring folders".to_string(),
}
}
// `control` only hands over what `request!` matches.
_ => CtlResponse::error(CoreError::internal("not a sync request".to_string())),
}
}
+139
View File
@@ -0,0 +1,139 @@
//! The control requests about Drive's trash and the local content cache.
use super::*;
/// The requests [`answer`] serves, as a pattern, so the control socket's match
/// hands exactly these over and the compiler still checks that it covers every
/// request.
macro_rules! request {
() => {
::pdfs_core::control::Request::ListTrash
| ::pdfs_core::control::Request::ListTrashedFolder { .. }
| ::pdfs_core::control::Request::Restore { .. }
| ::pdfs_core::control::Request::DeleteForever { .. }
| ::pdfs_core::control::Request::EmptyTrash
| ::pdfs_core::control::Request::PurgeCache
| ::pdfs_core::control::Request::CacheInspect { .. }
| ::pdfs_core::control::Request::CacheVacuum
| ::pdfs_core::control::Request::SetCacheBudget { .. }
};
}
pub(super) use request;
/// Answer a request that [`request!`] matches.
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
let Ask { core, .. } = *ask;
match request {
CtlRequest::ListTrash => match core.trash().list_trash() {
Ok(entries) => CtlResponse::Entries { entries },
Err(e) => CtlResponse::error(e),
},
CtlRequest::ListTrashedFolder { uid } => match core.trash().list_trashed_folder(&uid) {
Ok(entries) => CtlResponse::Entries { entries },
Err(e) => CtlResponse::error(e),
},
CtlRequest::Restore { uids } => match core.trash().restore(&uids) {
Ok(n) => {
core.log_activity(ActivityKind::Restore, format!("{n} item(s)"), "", true);
CtlResponse::Ok {
message: format!("restored {n} item(s)"),
}
}
Err(e) => CtlResponse::error(e),
},
CtlRequest::DeleteForever { uids } => match core.trash().delete_forever(&uids) {
Ok(n) => {
core.log_activity(
ActivityKind::DeleteForever,
format!("{n} item(s)"),
"",
true,
);
CtlResponse::Ok {
message: format!("permanently deleted {n} item(s)"),
}
}
Err(e) => CtlResponse::error(e),
},
CtlRequest::EmptyTrash => match core.trash().empty_trash() {
Ok(n) => {
let items = if n == 1 {
"1 item".to_string()
} else {
format!("{n} items")
};
core.log_activity(ActivityKind::EmptyTrash, items.clone(), "", true);
CtlResponse::Ok {
message: format!("emptied trash ({items})"),
}
}
Err(e) => CtlResponse::error(e),
},
CtlRequest::PurgeCache => {
let freed = core.cache.clear_unpinned();
CtlResponse::Ok {
message: format!(
"purged {:.1} MiB of unpinned cache",
freed as f64 / 1_048_576.0
),
}
}
CtlRequest::CacheInspect { deep } => match core.db.stats() {
Ok(stats) => {
// The deep check reads every page — tens of seconds on a real
// database, all of it holding the connection every FUSE handler
// needs — so it runs on a thread and this request returns
// whatever the last completed check found. `integrity_checked`
// tells the caller which answer it is holding, since "no
// problems found" and "never looked" are both an empty list;
// `integrity_running` says a fresh answer is on its way.
let (integrity_problems, integrity_checked, integrity_running) = if deep {
core.start_or_read_integrity_check()
} else {
(Vec::new(), false, false)
};
CtlResponse::CacheReport {
integrity_running,
schema_version: stats.schema_version,
db_bytes: stats.total_bytes(),
db_reclaimable_bytes: stats.reclaimable_bytes(),
tables: stats.tables,
cache_used: core.cache.usage(),
cache_budget: core.cache.budget(),
integrity_problems,
integrity_checked,
}
}
Err(e) => CtlResponse::error(CoreError::internal(format!("read db stats: {e:?}"))),
},
CtlRequest::CacheVacuum => match core.start_vacuum() {
Ok(()) => CtlResponse::Ok {
message: "compacting the cache database in the background".into(),
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::SetCacheBudget { bytes } => {
core.cache.set_budget(bytes);
// Persist so the next mount keeps the new cap. Best-effort: a config
// write failure is reported but the live cap is already applied.
match AppDirs::new()
.map(|dirs| dirs.update_config(|cfg| cfg.cache_budget = Some(bytes)))
{
Ok(Ok(())) => {
core.touch_profile();
CtlResponse::Ok {
message: format!("cache budget set to {bytes} bytes"),
}
}
Ok(Err(e)) => CtlResponse::error(CoreError::internal(format!(
"budget applied but config write failed: {e}"
))),
Err(e) => CtlResponse::error(CoreError::internal(format!(
"budget applied but config unavailable: {e}"
))),
}
}
// `control` only hands over what `request!` matches.
_ => CtlResponse::error(CoreError::internal("not a trash request".to_string())),
}
}
+2 -7
View File
@@ -9,7 +9,6 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use parking_lot::Mutex;
use pdfs_core::batch;
@@ -23,7 +22,6 @@ 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;
use tracing::{info, warn};
use super::sync::{self, base_name};
@@ -782,10 +780,7 @@ impl Core {
/// kernel channel, both filled in when the session is built.
pub(crate) fn fork_state(&self) -> Core {
let mut fork = self.clone();
fork.primary = false;
fork.root = Arc::new(OnceLock::new());
fork.notifier = Arc::new(OnceLock::new());
fork.session_live = Arc::new(std::sync::atomic::AtomicBool::new(false));
fork.session = self.session.fork();
fork
}
@@ -1173,7 +1168,7 @@ impl Core {
root: Node,
) -> CoreResult<SecondaryMount> {
let core = self.fork_state();
let session_live = core.session_live.clone();
let session_live = core.session.session_live.clone();
// The fork owns this state/path registration. `spawn_session` only
// marks it live after FUSE has spawned successfully.
core.register_state(local);
+3 -3
View File
@@ -41,8 +41,8 @@ use proton_drive_rs::{Node, NodeKind};
use tracing::{debug, error, info, warn};
use super::link::{self, is_network_error};
use super::photos::sha1_of;
use super::state::{Intervals, PendingRevision};
use super::takeout::sha1_of;
use super::transfers::CountingReader;
use super::{
Core, DRAIN_BACKOFF_MAX, DRAIN_BACKOFF_MIN, DRAIN_IDLE_POLL, DRAIN_REVISION_DEBOUNCE,
@@ -394,7 +394,7 @@ impl Core {
// the wire, so trashing its folder kept it as a trash; claimed
// only to be handed back, it was kept although nothing had sent
// it (`docs/BUGS.md` B178).
let online = self.online.load(Ordering::Relaxed);
let online = self.is_online();
let paused = self.sync_paused();
// One row, chosen and *claimed* by the database. Reading the whole
// queue to pick one op made a long queue quadratic to drain, and
@@ -773,7 +773,7 @@ impl Core {
/// is disarmed, letting a gap-fill read from a revision that no longer
/// describes the file.
pub(crate) fn release_pending(&self, uid: &NodeUid, blob: &Path) {
let mut pending = self.pending.lock();
let mut pending = self.writes.pending.lock();
if let Some(current) = pending.get(uid)
&& current.path == blob
{
+4 -4
View File
@@ -233,7 +233,7 @@ impl Core {
.insert(real.clone(), local.clone());
}
// The feed will report this create back to us; the tree already has it
// under its real uid, so that event is ours to ignore (`Core::self_changes`).
// under its real uid, so that event is ours to ignore (`WriteState::note_echo`).
self.note_self_change(&real);
// The uploaded blob is done with either way: a write that replaced it
// while it was on the wire already discarded it when it attached.
@@ -358,7 +358,7 @@ impl Core {
// while its trash is on the wire or a listing still shows it. Taking a
// folder removed and made again put the new one's contents into the
// old one, and its trash took them along (docs/BUGS.md B162).
let hidden = self.hidden.lock().clone();
let hidden = self.writes.hidden();
let Some(twin) = children
.into_iter()
.find(|node| node.name == name && !node.trashed && !hidden.contains(&node.uid))
@@ -475,7 +475,7 @@ impl Core {
// a newer blob by the time it is retried (`Core::adoptable_twin`).
let sha = staged_sha1(Path::new(blob))?;
self.db.note_create_sent(op.id, &sha)?;
let thumbnails = self.upload_thumbnails(Path::new(blob), name);
let thumbnails = self.photos().upload_thumbnails(Path::new(blob), name);
let guard = self
.transfers
.begin(name, op.uid.clone(), TransferDirection::Upload, meta.len);
@@ -514,7 +514,7 @@ impl Core {
real: &NodeUid,
) -> Result<CreateRetired, Box<dyn std::error::Error>> {
let retired = {
let mut pending = self.pending.lock();
let mut pending = self.writes.pending.lock();
let retired = self.db.finish_create(op.id, uploaded, landing, |json| {
let mut meta: StagedWrite = serde_json::from_str(json).ok()?;
meta.uid = landing.real.to_string();
+4 -4
View File
@@ -232,7 +232,7 @@ impl Core {
}
let alt = conflict_name(&name, now_secs());
let thumbnails = self.upload_thumbnails(blob, &alt);
let thumbnails = self.photos().upload_thumbnails(blob, &alt);
let guard =
self.transfers
.begin(&alt, meta.uid.clone(), TransferDirection::Upload, meta.len);
@@ -377,7 +377,7 @@ impl Core {
}
let name = self.node_name(&uid);
let thumbnails = self.upload_thumbnails(&blob, &name);
let thumbnails = self.photos().upload_thumbnails(&blob, &name);
let guard =
self.transfers
.begin(&name, meta.uid.clone(), TransferDirection::Upload, meta.len);
@@ -552,7 +552,7 @@ impl Core {
// This function's whole job is to bring the tree level with the revision
// we just sealed, so the feed's report of that revision has nothing left
// to tell us. Claimed here rather than at the upload call so it is only
// recorded when the node was actually re-read (`Core::self_changes`).
// recorded when the node was actually re-read (`WriteState::note_echo`).
self.note_self_change(uid);
// Rebase any *open* write handles targeting this node. A handle opened
// before this upload carries a stale base — its `base_mtime`/`base_size`
@@ -680,7 +680,7 @@ impl Core {
hash: None,
revision_id: node_revision_id(sealed),
};
let mut pending = self.pending.lock();
let mut pending = self.writes.pending.lock();
let Some(p) = pending.get_mut(uid) else {
return false;
};
+3 -3
View File
@@ -19,7 +19,7 @@ impl Core {
if is_local_uid_str(&op.uid) {
match self.withdrawn_twin(op)? {
Some(twin) => {
self.hidden.lock().insert(twin.clone());
self.writes.hide(&twin);
match self
.block_on_bounded(self.drive.trash_nodes(std::slice::from_ref(&twin)))
.and_then(batch::into_unit)
@@ -131,7 +131,7 @@ impl Core {
// mount trashed is not one, and a node in the tree was answered for.
// A file of the user's renamed to the name the create was sent under
// was taken for it, and trashed (`docs/BUGS.md` B193).
let hidden = self.hidden.lock().clone();
let hidden = self.writes.hidden();
let Some(twin) = children
.into_iter()
.find(|node| node.name == name && !node.trashed && !hidden.contains(&node.uid))
@@ -191,7 +191,7 @@ impl Core {
real: &NodeUid,
name: &str,
) -> Result<(), Box<dyn std::error::Error>> {
self.hidden.lock().insert(real.clone());
self.writes.hide(real);
self.note_self_change(real);
let trash = PendingOp {
id: trash,
+4 -4
View File
@@ -7,22 +7,22 @@ impl Core {
/// Record that this daemon just changed `uid` on the remote, so the event
/// feed's echo of that change is recognised instead of re-applied. Called
/// from the drain once the remote has actually accepted the change and the
/// tree has been brought level with it. See [`Core::self_changes`].
/// tree has been brought level with it. See [`writes::WriteState`].
pub(crate) fn note_self_change(&self, uid: &NodeUid) {
note_self_change(&mut self.self_changes.lock(), uid, now_millis());
self.writes.note_echo(uid, now_millis());
}
/// Claim one outstanding echo for `uid`, reporting whether this event is one
/// this daemon caused. Consuming rather than merely testing is what bounds
/// the suppression: the next event for the node applies normally.
pub(super) fn take_self_change(&self, uid: &NodeUid) -> bool {
take_self_change(&mut self.self_changes.lock(), uid, now_millis())
self.writes.take_echo(uid, now_millis())
}
}
/// How long a change this daemon made stays recognisable as its own. Generous
/// against a feed that can lag, but finite: past it, an event for the node is
/// applied like any other. See [`Core::self_changes`].
/// applied like any other. See [`writes::WriteState`].
pub(super) const SELF_CHANGE_TTL_MS: i64 = 120_000;
/// A remote change this daemon made, awaiting its echo from the event feed.
+10 -9
View File
@@ -204,7 +204,7 @@ impl Core {
if is_local_uid(uid) {
return None;
}
match self.pending.lock().get(uid) {
match self.writes.pending.lock().get(uid) {
Some(p) => p.meta.based_on.clone(),
None => Some(Baseline {
mtime: base_mtime,
@@ -247,7 +247,7 @@ impl Core {
// of exactly the ranges this write did not touch, and what neither wrote
// is still the remote content that the earlier write was based on, which
// is why the baseline is inherited along with them.
let previous = self.pending.lock().get(uid).cloned();
let previous = self.writes.queued(uid);
if !meta.complete
&& let Some(previous) = previous
&& let Err(error) = merge_over_pending(&mut meta, src, &previous)
@@ -302,7 +302,7 @@ impl Core {
// carries it over, or has already finished and this write
// queues against the real uid below (`Core::retire_create`).
let meta_json = serde_json::to_string(&meta).unwrap_or_default();
let mut pending = self.pending.lock();
let mut pending = self.writes.pending.lock();
let attached = self
.db
.attach_blob_to_create(&uid.to_string(), &path.to_string_lossy(), &meta_json)
@@ -325,7 +325,7 @@ impl Core {
debug!(local = %uid, %real, "create landed under an open write; queueing a revision");
uid = real;
meta.uid = uid.to_string();
let previous = self.pending.lock().get(&uid).cloned();
let previous = self.writes.queued(&uid);
meta.based_on = previous.as_ref().and_then(|p| p.meta.based_on.clone());
if !meta.complete
&& let Some(previous) = previous
@@ -353,7 +353,8 @@ impl Core {
error!(%uid, error = %e, "queueing upload failed");
Errno::EIO
})?;
self.pending
self.writes
.pending
.lock()
.insert(uid.clone(), PendingRevision { path, meta });
superseded
@@ -436,7 +437,7 @@ impl Core {
// case the remote is *not* our base: the complete staged revision is.
// Compose from those local bytes so the truncate can supersede the
// queued upload without fetching stale remote content or returning EIO.
let pending_base = self.pending.lock().get(&uid).cloned();
let pending_base = self.writes.queued(&uid);
if pending_base
.as_ref()
.is_some_and(|pending| !pending.meta.complete)
@@ -726,7 +727,7 @@ impl Core {
} else {
self.release_dropped_ops(uid, blobs);
}
self.hidden.lock().insert(uid.clone());
self.writes.hide(uid);
// Withdrawn from the tree, which every mount serves from, so no other
// mount goes on serving a file the user just trashed (`docs/BUGS.md`
// B74).
@@ -786,7 +787,7 @@ impl Core {
/// (`docs/BUGS.md` B102), so the entries to forget are found by blob, not
/// only by `uid`.
pub(super) fn release_dropped_ops(&self, uid: &NodeUid, blobs: Vec<String>) {
self.pending.lock().remove(uid);
self.writes.pending.lock().remove(uid);
self.release_dropped_below(blobs);
}
@@ -794,7 +795,7 @@ impl Core {
/// entry.
pub(super) fn release_dropped_below(&self, blobs: Vec<String>) {
let below: Vec<NodeUid> = {
let mut pending = self.pending.lock();
let mut pending = self.writes.pending.lock();
let below: Vec<NodeUid> = pending
.iter()
.filter(|(_, p)| blobs.iter().any(|b| p.path == Path::new(b)))
+5 -5
View File
@@ -325,7 +325,7 @@ impl Filesystem for ProtonFs {
};
let is_video =
PhotoKind::classify(Some(&e.node.name), media_type) == PhotoKind::Video;
let queued = self.core.pending.lock().get(&e.uid).map(|p| p.meta.len);
let queued = self.core.writes.queued_len(&e.uid);
// Still the cheap enumeration's ciphertext size (B12).
let provisional = queued.is_none()
&& matches!(
@@ -1160,7 +1160,7 @@ impl ProtonFs {
/// the folder an on-demand location shows).
pub(super) fn new(core: Core, root: Node) -> Self {
let root = core.state().install_root(root);
let _ = core.root.set(root);
let _ = core.session.root.set(root);
// SAFETY: geteuid/getegid are infallible and have no preconditions.
let (uid, gid) = unsafe { (libc::geteuid(), libc::getegid()) };
Self {
@@ -1413,7 +1413,7 @@ impl ProtonFs {
}
}
}
let pending_base = self.core.pending.lock().get(&uid).cloned();
let pending_base = self.core.writes.queued(&uid);
let (file, path) = match self.core.cache.create_scratch() {
Ok(x) => x,
Err(e) => {
@@ -2234,7 +2234,7 @@ impl ProtonFs {
// before it lets those updates overwrite our invalidation
// and retain an empty destination readdir page.
reply.ok();
if let Some(notifier) = self.core.notifier.get() {
if let Some(notifier) = self.core.session.notifier.get() {
let _ = notifier.inval_entry(parent, OsStr::new(&name));
let _ = notifier.inval_entry(newparent, OsStr::new(&newname));
let _ = notifier.inval_inode(parent);
@@ -2402,7 +2402,7 @@ impl ProtonFs {
}
// Only remove the namespace entry after Drive accepted the mutation.
// Otherwise an EIO response still made the path disappear locally.
self.core.hidden.lock().insert(uid.clone());
self.core.writes.hide(&uid);
self.core.state().forget_or_unlink(&uid);
if open_now {
// The open handle keeps the staged bytes; the drain must not send
+1 -1
View File
@@ -231,7 +231,7 @@ impl Core {
claimed_size.is_none(),
)
};
if is_local_uid(&uid) || self.pending.lock().contains_key(&uid) {
if is_local_uid(&uid) || self.writes.is_queued(&uid) {
return None;
}
let size = match provisional {
+46 -122
View File
@@ -82,7 +82,6 @@ use proton_drive_rs::{
};
mod activity;
mod albums;
mod attach;
mod background;
mod conflicts;
@@ -108,6 +107,8 @@ mod inhibit;
mod keeper;
mod link;
mod listing;
mod session;
mod writes;
pub use filesystem::ProtonFs;
mod maintenance;
mod mount;
@@ -116,9 +117,9 @@ mod photos;
mod pins;
mod profile;
mod queue;
mod quota;
mod reads;
mod recovery;
mod redate;
mod relocate;
mod remote;
mod requests;
@@ -137,7 +138,6 @@ mod supervisor;
mod sweep;
mod sync;
mod systemd;
mod takeout;
use pdfs_core::transfers;
mod upload;
mod r#virtual;
@@ -533,14 +533,15 @@ struct Core {
/// The daemon's My Files root. Forked on-demand sessions retain this value
/// so ownership checks never mistake their own mount root for account scope.
primary_root_uid: NodeUid,
/// False only for a forked on-demand device mount. The synthetic shared
/// directory belongs exclusively to the primary My Files mount.
primary: bool,
/// What belongs to one mount's FUSE session rather than to the daemon: whether
/// it is the primary My Files mount, the tree inode it is rooted at, its
/// kernel channel and whether the session is up.
///
/// Every other part of `Core` is shared between the primary mount and its
/// on-demand forks. A fork gets fresh cells from [`SessionCells::fork`].
session: session::SessionCells,
/// The one tree every mount of the daemon serves from.
state: Arc<Ranked<State>>,
/// The tree inode this mount's session is rooted at, set when the session
/// is built ([`ProtonFs::new`]). Each fork has its own cell.
root: Arc<OnceLock<u64>>,
cache: Arc<ContentCache>,
/// What the read path keeps between reads: open revision readers, decrypted
/// blocks, fetches in flight and prefetch. See [`reads::ReadState`].
@@ -556,29 +557,20 @@ struct Core {
/// Publication of the shared listing, and what invalidates a listing on the
/// wire or suppresses its next refresh.
shared: shared::SharedState,
/// False while the API is unreachable and we are serving the cached tree.
/// Set by the probe thread; read by front-ends through
/// `Response::Status` so the UI can say so rather than leaving the user to
/// infer it from a wall of EIO.
online: Arc<AtomicBool>,
/// When the link went down and a condvar for its coming back; the other
/// half of `online` (see [`link`]).
/// Whether Drive answers, when the link went down and a condvar for its
/// coming back (see [`link`]).
link: Arc<link::Link>,
/// When the user paused syncing, the Unix second it resumes by itself;
/// [`pause::PAUSED_INDEFINITELY`] for "until resumed", `0` when not paused.
/// Persisted, so a pause survives a restart (see [`Core::sync_paused`]).
sync_paused_until: Arc<AtomicI64>,
/// Writes accepted from the kernel but not yet uploaded, keyed by node.
/// The in-memory face of the `pending_op` table, from
/// which it is rebuilt on mount.
/// Whether the user paused syncing, and until when. Persisted, so a pause
/// survives a restart. See [`pause::SyncPause`].
pause: pause::SyncPause,
/// The write-back's state: writes accepted from the kernel and not yet sent,
/// nodes removed here that a stale listing may still return, and the changes
/// this daemon made that Drive's event feed will echo back.
///
/// Two things read it: [`Core::read_range`], because until the op drains the
/// staged blob *is* the file's content and the remote still holds the old
/// revision; and the drain worker, which performs the uploads.
pending: Arc<Mutex<HashMap<NodeUid, PendingRevision>>>,
/// Nodes removed through this daemon which a briefly stale remote listing
/// may still return. Uids are not reused; an explicit restore clears one.
hidden: Arc<Mutex<HashSet<NodeUid>>>,
/// The drain, the queue and recovery own it. Everything else, the read path,
/// listings, the pin keeper and the event feed, asks through the methods
/// below instead of taking its locks.
writes: writes::WriteState,
/// The drain's own bookkeeping: its wake-up, the creates and uploads on
/// the wire, and what they left behind. See [`drain::DrainState`].
drain: drain::DrainState,
@@ -592,7 +584,7 @@ struct Core {
services: pdfs_core::lifecycle::ServiceBoard,
/// Whether a trash refresh is running, and the wake-up for requests waiting
/// on its progress.
trash: trash::TrashState,
trash_jobs: trash::TrashState,
/// What the conflict sweep may do, and the copies it already checked this
/// run.
sweep: sweep::SweepState,
@@ -605,7 +597,10 @@ struct Core {
photo_jobs: photos::PhotoJobs,
/// The last account quota answer, for `statfs(2)`, and whether a refresh
/// of it is running.
quota_cache: sharing::QuotaCache,
quota: quota::QuotaCache,
/// Sharing, public links, invitations and bookmarks. See
/// [`sharing::Sharing`].
sharing: sharing::Sharing,
/// Database maintenance that has been moved off the request thread.
///
/// `VACUUM` and a deep `integrity_check` both hold the single connection for
@@ -617,19 +612,6 @@ struct Core {
/// The size upgrades running now, and the replies parked on them. Shared
/// by every mount: the bound that matters is per daemon.
sizes: sizes::SizeState,
/// This mount's kernel notification channel, for telling the kernel to drop
/// metadata it has cached. Set once the session exists — which is *after*
/// the `Core` it is built from, hence the cell.
///
/// Per mount, not per daemon: each session calls its own root inode 1.
/// [`Core::fork_state`] gives each fork an empty cell of its own. Work that
/// changes the tree for every mount tells every session
/// ([`Core::for_each_mount`]).
notifier: Arc<OnceLock<KernelChannel>>,
/// True only after this mount's FUSE session spawned successfully.
/// Registration happens earlier for the primary drain, so registration
/// alone cannot answer whether the location is mounted.
session_live: Arc<AtomicBool>,
/// In-flight upload/download progress, served to `GetQueueStatus`. Shared
/// across the FUSE session and the control-socket task.
transfers: Arc<TransferRegistry>,
@@ -653,26 +635,6 @@ struct Core {
/// FUSE connection id and the fork's exact liveness flag so teardown first
/// makes that mount unroutable.
mounts: Arc<Mutex<mount::SecondaryMountRegistry<SecondaryMount>>>,
/// Nodes this daemon changed on the remote itself, and how many echoes of
/// those changes the event feed still owes us.
///
/// The feed replays our own writes back at us seconds later, and a
/// `NodeUpdated` carries no revision id — nothing in it distinguishes "another
/// device changed this file" from "you changed this file". Treating the echo
/// as foreign is not free: it evicts the content blob we just uploaded, so the
/// next read re-downloads a revision the API may not be serving yet. That is
/// how a SQLite database written on the mount came back `malformed`, and how a
/// mount doing bulk uploads spent its time re-fetching its own bytes.
///
/// So the first event for a node we changed ourselves, within
/// [`SELF_CHANGE_TTL_MS`], is consumed rather than applied: the tree already
/// holds what that event describes, because [`Core::refresh_after_upload`] put
/// it there. Anything beyond that applies normally, which bounds the staleness
/// a genuine remote change can suffer to one event.
///
/// Shared across forks like `pending`: the drain that records the change and
/// the event task that consumes the echo are both per-daemon.
self_changes: Arc<Mutex<HashMap<NodeUid, echoes::SelfChange>>>,
/// Every live mount: the primary and one per on-demand fork
/// ([`Core::fork_state`]), with its mountpoint, root and kernel channel.
/// Shared by every fork.
@@ -820,16 +782,16 @@ impl Core {
fn register_state(&self, mountpoint: &Path) {
self.states.register(
mountpoint,
&self.notifier,
self.session_live.clone(),
self.root.clone(),
&self.session.notifier,
self.session.session_live.clone(),
self.session.root.clone(),
);
}
/// The tree inode this mount is rooted at. [`ROOT_INO`] until the session
/// is built, which is where a test that builds a bare tree puts its root.
pub(crate) fn root_ino(&self) -> u64 {
self.root.get().copied().unwrap_or(ROOT_INO)
self.session.root.get().copied().unwrap_or(ROOT_INO)
}
/// Whether `uid` names an owned node reachable from the root of a mounted
@@ -857,14 +819,16 @@ impl Core {
let mount = self.states.covering(abs)?;
let rel = abs.strip_prefix(&mount.mountpoint).ok()?.to_path_buf();
let mut core = self.clone();
if !Arc::ptr_eq(&mount.notifier, &self.notifier) {
if !Arc::ptr_eq(&mount.notifier, &self.session.notifier) {
// Another mount, so adopt its per-mount half wholesale. `primary`
// is a property of the mount, and the only mount this `Core` can
// be the primary of is the one it was built for.
core.primary = false;
core.notifier = mount.notifier;
core.session_live = mount.session_live;
core.root = mount.root;
core.session = session::SessionCells {
primary: false,
notifier: mount.notifier,
session_live: mount.session_live,
root: mount.root,
};
}
Some((core, rel))
}
@@ -1398,7 +1362,7 @@ impl Core {
/// swaps the map entry to point at it, so an unchanged path means the base a
/// caller sampled earlier is still the base now (`docs/BUGS.md` B32).
fn pending_blob(&self, uid: &NodeUid) -> Option<PathBuf> {
self.pending.lock().get(uid).map(|p| p.path.clone())
self.writes.queued(uid).map(|queued| queued.path)
}
/// Nudge the drain worker to re-examine the queue now.
@@ -1408,32 +1372,12 @@ impl Core {
cv.notify_all();
}
/// Download a whole file's plaintext, registering the transfer so
/// Download a whole file into `out`, registering the transfer so
/// `GetQueueStatus` can report its progress. `total` is the expected size
/// (`0` if unknown). Streams through [`download_file_to`] so each block ticks
/// the progress counter.
/// the progress counter, and nothing is held in memory.
///
/// [`download_file_to`]: ProtonDriveClient::download_file_to
fn download_file_tracked(
&self,
uid: &NodeUid,
name: &str,
total: u64,
) -> std::result::Result<Vec<u8>, ProtonError> {
let guard = self
.transfers
.begin(name, uid.to_string(), TransferDirection::Download, total);
let mut out = CountingWriter::new(Vec::with_capacity(total as usize), &guard);
self.rt
.block_on(self.drive.download_file_to(uid, &mut out))?;
Ok(out.into_inner())
}
/// Download a whole file directly into `out`, without retaining its
/// plaintext in memory. This is the disk-backed twin of
/// [`Core::download_file_tracked`], and preserves the same transfer
/// accounting while allowing callers that only need an on-disk file to
/// keep memory use independent of file size.
fn download_file_tracked_to<W: Write + Send>(
&self,
uid: &NodeUid,
@@ -1450,26 +1394,6 @@ impl Core {
Ok(out.into_inner())
}
/// Like [`download_file_tracked`] for a photo, streaming through the photos
/// client's [`download_photo_to`].
///
/// [`download_file_tracked`]: Core::download_file_tracked
/// [`download_photo_to`]: ProtonPhotosClient::download_photo_to
fn download_photo_tracked(
&self,
photos: &ProtonPhotosClient,
uid: &NodeUid,
name: &str,
total: u64,
) -> std::result::Result<Vec<u8>, ProtonError> {
let guard = self
.transfers
.begin(name, uid.to_string(), TransferDirection::Download, total);
let mut out = CountingWriter::new(Vec::with_capacity(total as usize), &guard);
self.rt.block_on(photos.download_photo_to(uid, &mut out))?;
Ok(out.into_inner())
}
/// Fetch a thumbnail of `ttype` for the file at `ino`, served from the cache
/// when fresh and otherwise downloaded from the remote and cached. Returns
/// `Ok(None)` when the node is not a file or has no thumbnail of that type.
@@ -1529,7 +1453,7 @@ impl Core {
/// reuses the daemon's single authenticated session rather than logging in
/// again (Proton refresh tokens are single-use). Cheap — the Drive client
/// is `Clone` over `Arc`-backed state.
fn photos(&self) -> ProtonPhotosClient {
fn photos_api(&self) -> ProtonPhotosClient {
ProtonPhotosClient::from_drive_client(self.client.clone())
}
@@ -3924,7 +3848,7 @@ mod tests {
assert_before(revision, "preserve_on_access_denied", "fill_gaps");
let staged = function_source(source, "fn enqueue_staged_write(");
assert_before(staged, "preserve_on_access_denied", "self.pending.lock()");
assert_before(staged, "preserve_on_access_denied", "self.writes.queued(");
assert_before(
staged,
"preserve_on_access_denied",
@@ -3932,7 +3856,7 @@ mod tests {
);
let truncate = function_source(source, "fn queue_truncate(");
assert_before(truncate, "require_uid_writable", "self.pending.lock()");
assert_before(truncate, "require_uid_writable", "self.writes.queued(");
assert_before(truncate, "require_uid_writable", "create_scratch");
for (signature, first_side_effect) in [
@@ -4081,7 +4005,7 @@ mod tests {
assert_before(
restore,
"self.drive.restore_nodes(",
"self.hidden.lock().remove(uid)",
"self.writes.unhide(uid)",
);
assert!(restore.contains("st.invalidate_listing(ino)"));
assert!(restore.contains("notify.inval_entry(ino, name.to_string())"));
@@ -4328,7 +4252,7 @@ mod tests {
// once; the bytes the handle reads go with the last close.
let withdraw = function_source(CORE_SOURCE, "fn withdraw_queued_ops(");
assert_before(withdraw, "self.pending_blob(uid)", "release_dropped_below");
assert!(!withdraw.contains("self.pending.lock().remove(uid)"));
assert!(!withdraw.contains("self.writes.pending.lock().remove(uid)"));
let filesystem = include_str!("filesystem.rs");
let trash = function_source(filesystem, "fn trash_child(");
+12 -6
View File
@@ -58,6 +58,11 @@ const IDLE_CHECK: Duration = Duration::from_secs(1);
/// that fires on every change so waiters need not poll.
#[derive(Default)]
pub(crate) struct Link {
/// False while the API is unreachable and we are serving the cached tree.
/// Set by the probe thread; read by front-ends through
/// `Response::Status` so the UI can say so rather than leaving the user to
/// infer it from a wall of EIO.
online: AtomicBool,
lost_at: Mutex<Option<Instant>>,
changed: Condvar,
/// Folders listed from the DB alone while offline, to relist once back.
@@ -74,10 +79,11 @@ pub(crate) struct Link {
}
impl Link {
/// The link of a mount that comes up with Proton refusing its session, or
/// not.
pub(crate) fn starting(session_expired: bool) -> Self {
/// The link of a mount that comes up online or from the cache, with
/// Proton refusing its session or not.
pub(crate) fn starting(online: bool, session_expired: bool) -> Self {
Self {
online: AtomicBool::new(online),
session_expired: AtomicBool::new(session_expired),
..Default::default()
}
@@ -154,7 +160,7 @@ fn next_probe_delay(delay: Duration, outage: Duration) -> Duration {
impl Core {
/// Whether the mount currently believes Proton is reachable.
pub(crate) fn is_online(&self) -> bool {
self.online.load(Ordering::Relaxed)
self.link.online.load(Ordering::Relaxed)
}
/// Whether a namespace change through the mount goes to Drive inside the
@@ -237,7 +243,7 @@ impl Core {
/// outage logs it; the rest are the same outage.
pub(crate) fn mark_offline(&self, what: &str, error: &dyn std::fmt::Display) {
let mut lost_at = self.link.lost_at.lock();
if self.online.swap(false, Ordering::Relaxed) {
if self.link.online.swap(false, Ordering::Relaxed) {
*lost_at = Some(Instant::now());
warn!(during = what, %error,
"lost the connection to Proton; queueing changes until it returns");
@@ -250,7 +256,7 @@ impl Core {
fn mark_online(&self) {
{
let mut lost_at = self.link.lost_at.lock();
self.online.store(true, Ordering::Relaxed);
self.link.online.store(true, Ordering::Relaxed);
match lost_at.take() {
Some(since) => {
info!(
+20 -26
View File
@@ -32,10 +32,7 @@ impl Core {
None
};
freshness.is_none_or(|key| {
!listing_needs_refresh(
self.online.load(Ordering::Relaxed),
self.shared_listing_stale(&key),
)
!listing_needs_refresh(self.is_online(), self.shared_listing_stale(&key))
})
}
@@ -58,16 +55,10 @@ impl Core {
/// lock: no site in the daemon holds `pending` and `state` at once, and this
/// is not the place to become the first.
pub(super) fn stamp_pending_sizes(&self, nodes: &mut [Node]) {
let sizes: HashMap<NodeUid, u64> = {
let pending = self.pending.lock();
if pending.is_empty() {
return;
}
pending
.iter()
.map(|(uid, pr)| (uid.clone(), pr.meta.len))
.collect()
};
let sizes = self.writes.queued_sizes();
if sizes.is_empty() {
return;
}
apply_pending_sizes(nodes, &sizes);
}
@@ -167,7 +158,7 @@ impl Core {
// Before the lock: a DB row carries the size the server last
// sealed, which a queued write is ahead of (B11).
self.stamp_pending_sizes(&mut nodes);
let hidden = self.hidden.lock().clone();
let hidden = self.writes.hidden();
let mut st = self.state();
if st.children.contains_key(&ino) {
return Ok(());
@@ -235,14 +226,11 @@ impl Core {
}
let primary_root =
is_primary_root_listing(self.primary, &folder_uid, &self.primary_root_uid);
is_primary_root_listing(self.session.primary, &folder_uid, &self.primary_root_uid);
let foreign = !self.is_own_or_virtual(&folder_uid) && !is_local_uid(&folder_uid);
let foreign_key = foreign.then(|| Self::shared_folder_freshness_key(&folder_uid));
let refresh_foreign = foreign_key.as_deref().is_some_and(|key| {
listing_needs_refresh(
self.online.load(Ordering::Relaxed),
self.shared_listing_stale(key),
)
listing_needs_refresh(self.is_online(), self.shared_listing_stale(key))
});
if cached && !refresh_foreign {
if primary_root {
@@ -334,7 +322,7 @@ impl Core {
// Same as the DB path above: the remote's size for a file with a write
// still queued is the pre-write one (B11).
self.stamp_pending_sizes(&mut nodes);
let hidden = self.hidden.lock().clone();
let hidden = self.writes.hidden();
let mut filtered_nodes: Vec<Node> = nodes
.into_iter()
.filter(|node| node_visible(node, &folder_uid, &hidden))
@@ -446,11 +434,17 @@ impl Core {
///
/// Metadata only: a thumbnail path is attached for photos whose thumbnail is
/// already cached, and nothing is downloaded here — the front-end pulls the
/// thumbnails it actually paints via [`Core::photo_thumbs`].
/// thumbnails it actually paints via [`Photos::photo_thumbs`](crate::photos::Photos::photo_thumbs).
pub(super) fn listing_stale(&self, key: &str, ttl: Duration) -> bool {
match self.db.state_i64(key).ok().flatten() {
Some(ms) => now_ms().saturating_sub(ms) >= ttl.as_millis() as i64,
None => true,
}
listing_stale(&self.db, key, ttl)
}
}
/// Whether the listing stamped under `key` is older than `ttl`, or was never
/// stamped.
pub(crate) fn listing_stale(db: &Db, key: &str, ttl: Duration) -> bool {
match db.state_i64(key).ok().flatten() {
Some(ms) => now_ms().saturating_sub(ms) >= ttl.as_millis() as i64,
None => true,
}
}
+31 -26
View File
@@ -351,16 +351,17 @@ pub(super) fn spawn_session(
clear_stale_mount(mountpoint);
info!(mountpoint = %mountpoint.display(), "mounting Proton Drive location");
let fs = ProtonFs::new(core.clone(), root);
if core.primary {
if core.session.primary {
// Only My Files rehydrates the daemon-wide node cache, once. A
// secondary mount shares the tree it fills.
core.hydrate();
}
let session = Session::new(fs, mountpoint, &config)?.spawn()?;
let _ = core
.session
.notifier
.set(KernelChannel::new(session.notifier(), core.root_ino()));
core.session_live.store(true, Ordering::Release);
core.session.session_live.store(true, Ordering::Release);
Ok(session)
}
@@ -488,7 +489,7 @@ pub(crate) fn mount_with(
// handlers can trigger reconciles.
let (sync_tx, sync_rx) = std::sync::mpsc::channel::<sync::SyncMsg>();
let paused_until = pause::load_paused_until(&db);
let pause = pause::SyncPause::load(db.clone());
let gallery_dir = control_socket.with_file_name("gallery-catalog");
let gallery =
gallery_session.map(|session| Arc::new(super::gallery::Gallery::new(gallery_dir, session)));
@@ -511,6 +512,18 @@ pub(crate) fn mount_with(
abandon: Arc::default(),
events_read_at: Arc::new(AtomicI64::new(0)),
};
let state = Arc::new(Ranked::new(
Rank::State,
State::new(db.clone(), share_access),
));
let sharing = super::sharing::Sharing::new(
client.clone(),
drive.clone(),
rt.clone(),
cache.clone(),
transfers.clone(),
state.clone(),
);
let core = Core {
drive,
drive_calls,
@@ -519,35 +532,27 @@ pub(crate) fn mount_with(
rt: rt.clone(),
maintenance: Arc::new(Mutex::new(Default::default())),
primary_root_uid: root.uid.clone(),
primary: true,
state: Arc::new(Ranked::new(
Rank::State,
State::new(db.clone(), share_access),
)),
root: Arc::new(OnceLock::new()),
state: state.clone(),
cache,
reads: super::reads::ReadState::new(),
workers: Arc::new(Workers::new(FUSE_WORKERS)?),
db,
online: Arc::new(AtomicBool::new(online)),
link: Arc::new(link::Link::starting(start == Start::SessionExpired)),
sync_paused_until: Arc::new(AtomicI64::new(paused_until)),
pending: Arc::new(Mutex::new(HashMap::new())),
hidden: Arc::new(Mutex::new(HashSet::new())),
link: Arc::new(link::Link::starting(online, start == Start::SessionExpired)),
pause,
drain: super::drain::DrainState::new(),
pin_work: Arc::new(Mutex::new(Default::default())),
sizes: super::sizes::SizeState::new(),
trash: super::trash::TrashState::new(),
trash_jobs: super::trash::TrashState::new(),
shared: super::shared::SharedState::new(),
quota_cache: super::sharing::QuotaCache::new(),
quota: super::quota::QuotaCache::new(),
sharing,
sweep: super::sweep::SweepState::new(sweep_mode),
writes: super::writes::WriteState::new(),
session: super::session::SessionCells::new(),
shutdown,
services: ServiceBoard::default(),
photo_jobs: super::photos::PhotoJobs::new(),
local_first,
self_changes: Arc::new(Mutex::new(HashMap::new())),
notifier: Arc::new(OnceLock::new()),
session_live: Arc::new(AtomicBool::new(false)),
transfers,
sync,
events: Arc::new(Default::default()),
@@ -612,8 +617,8 @@ pub(crate) fn mount_with(
}
}
// A timed pause persisted by an earlier run still has to end on time.
if pause::paused_at(paused_until, now_secs()) && paused_until != pause::PAUSED_INDEFINITELY {
core.arm_pause_timer(paused_until);
if let Some(until) = core.pause.deadline() {
core.arm_pause_timer(until);
}
// Reconcile leftover `(sync-conflict …)` copies: drop the ones that turned
@@ -736,7 +741,7 @@ pub(crate) fn mount_with(
warn!(id, error = %unmount_error, "secondary teardown after control startup failure failed");
}
}
if let Err(unmount_error) = teardown_session(&core.session_live, || {
if let Err(unmount_error) = teardown_session(&core.session.session_live, || {
umount_session_unblocked(bg, main_conn)
}) {
warn!(error = %unmount_error, "unmount after control startup failure failed");
@@ -853,7 +858,7 @@ pub(crate) fn mount_with(
Ok(()) => {
info!("stop requested; unmounting");
core.mounts.lock().close();
if let Err(e) = teardown_session(&core.session_live, || {
if let Err(e) = teardown_session(&core.session.session_live, || {
umount_session_unblocked(bg, main_conn)
}) {
warn!(error = %e, "umount_and_join failed");
@@ -865,7 +870,7 @@ pub(crate) fn mount_with(
{
info!("unmounting to resume the stored session");
core.mounts.lock().close();
if let Err(e) = teardown_session(&core.session_live, || {
if let Err(e) = teardown_session(&core.session.session_live, || {
umount_session_unblocked(bg, main_conn)
}) {
warn!(error = %e, "umount_and_join failed");
@@ -876,7 +881,7 @@ pub(crate) fn mount_with(
if bg.guard.is_finished() {
info!("mount ended externally");
core.mounts.lock().close();
if let Err(e) = teardown_session(&core.session_live, || bg.join()) {
if let Err(e) = teardown_session(&core.session.session_live, || bg.join()) {
warn!(error = %e, "session join failed");
}
break MountOutcome::Unmounted;
@@ -885,7 +890,7 @@ pub(crate) fn mount_with(
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
// Signal task gone (failed to install); fall back to join.
core.mounts.lock().close();
let _ = teardown_session(&core.session_live, || bg.join());
let _ = teardown_session(&core.session.session_live, || bg.join());
break MountOutcome::Unmounted;
}
}
+84 -35
View File
@@ -51,41 +51,106 @@ fn store_folder_paused(db: &Db, id: i64, paused: bool) -> pdfs_core::Result<()>
/// A pause with no end time: it lasts until the user resumes.
pub(crate) const PAUSED_INDEFINITELY: i64 = i64::MAX;
/// The persisted pause, or `0` when there is none (or it cannot be read — a
/// broken state row must not keep sync paused forever).
pub(crate) fn load_paused_until(db: &Db) -> i64 {
match db.state_i64(PAUSED_UNTIL_KEY) {
Ok(Some(until)) => until,
Ok(None) => 0,
Err(error) => {
warn!(%error, "reading the sync pause failed; treating sync as running");
0
/// The global pause: when it ends, in memory and in the database.
///
/// The value is the Unix second the pause ends, [`PAUSED_INDEFINITELY`] for
/// "until resumed", or `0` when sync runs. Only this type reads or writes it;
/// the rest of the daemon asks [`Core::sync_paused`].
#[derive(Clone)]
pub(crate) struct SyncPause {
until: Arc<AtomicI64>,
db: Arc<Db>,
}
impl SyncPause {
/// The persisted pause, or none when there is no row or it cannot be read:
/// a broken state row must not keep sync paused forever.
pub(crate) fn load(db: Arc<Db>) -> Self {
let until = match db.state_i64(PAUSED_UNTIL_KEY) {
Ok(Some(until)) => until,
Ok(None) => 0,
Err(error) => {
warn!(%error, "reading the sync pause failed; treating sync as running");
0
}
};
Self {
until: Arc::new(AtomicI64::new(until)),
db,
}
}
fn is_paused(&self) -> bool {
paused_at(self.until.load(Ordering::Relaxed), now_secs())
}
/// `None` when not paused, `Some(None)` when paused until resumed,
/// `Some(Some(t))` when it ends at Unix second `t`.
fn status(&self) -> Option<Option<i64>> {
let until = self.until.load(Ordering::Relaxed);
match paused_at(until, now_secs()) {
false => None,
true if until == PAUSED_INDEFINITELY => Some(None),
true => Some(Some(until)),
}
}
/// The end of a timed pause still in force, which needs a timer.
pub(crate) fn deadline(&self) -> Option<i64> {
self.status().flatten()
}
/// Persist `value`, then take it. A pause that cannot be saved is not
/// taken, so what the user sees never outlives a restart by surprise.
fn store(&self, value: i64) -> Result<(), CoreError> {
let persisted = match value {
0 => self.db.clear_state(PAUSED_UNTIL_KEY),
value => self.db.set_state_i64(PAUSED_UNTIL_KEY, value),
};
if let Err(error) = persisted {
return Err(CoreError::internal(format!(
"saving the sync pause: {error}"
)));
}
self.until.store(value, Ordering::Relaxed);
Ok(())
}
/// End the pause that lasts until `until`, if it is still the one in
/// force. Returns whether it was: a later pause or resume replaced it
/// otherwise, and the timer that asks has nothing to do.
fn expire(&self, until: i64) -> bool {
if self
.until
.compare_exchange(until, 0, Ordering::Relaxed, Ordering::Relaxed)
.is_err()
{
return false;
}
if let Err(error) = self.db.clear_state(PAUSED_UNTIL_KEY) {
warn!(%error, "clearing an expired sync pause failed");
}
true
}
}
/// Whether a pause lasting until `until` is still in force at `now` (both Unix
/// seconds). `0` is "not paused".
pub(crate) fn paused_at(until: i64, now: i64) -> bool {
fn paused_at(until: i64, now: i64) -> bool {
until != 0 && now < until
}
impl Core {
/// True while the user has sync paused.
pub(crate) fn sync_paused(&self) -> bool {
paused_at(self.sync_paused_until.load(Ordering::Relaxed), now_secs())
self.pause.is_paused()
}
/// The pause's end, for status reporting: `None` when not paused,
/// `Some(None)` when paused until resumed, `Some(Some(t))` when it ends at
/// Unix second `t`.
pub(crate) fn sync_pause(&self) -> Option<Option<i64>> {
let until = self.sync_paused_until.load(Ordering::Relaxed);
match paused_at(until, now_secs()) {
false => None,
true if until == PAUSED_INDEFINITELY => Some(None),
true => Some(Some(until)),
}
self.pause.status()
}
/// Pause sync until Unix second `until` (`None`: until resumed), or resume
@@ -103,16 +168,7 @@ impl Core {
}
(true, Some(until)) => until,
};
let persisted = match value {
0 => self.db.clear_state(PAUSED_UNTIL_KEY),
value => self.db.set_state_i64(PAUSED_UNTIL_KEY, value),
};
if let Err(error) = persisted {
return Err(CoreError::internal(format!(
"saving the sync pause: {error}"
)));
}
self.sync_paused_until.store(value, Ordering::Relaxed);
self.pause.store(value)?;
match value {
0 => {
info!("sync resumed");
@@ -186,14 +242,7 @@ impl Core {
if !core.shutdown.sleep(wait) {
return;
}
if core
.sync_paused_until
.compare_exchange(until, 0, Ordering::Relaxed, Ordering::Relaxed)
.is_ok()
{
if let Err(error) = core.db.clear_state(PAUSED_UNTIL_KEY) {
warn!(%error, "clearing an expired sync pause failed");
}
if core.pause.expire(until) {
info!("sync pause ended");
core.resume_sync_work();
}
+110 -2
View File
@@ -31,11 +31,20 @@ use proton_drive_rs::proton_sdk::ids::NodeUid;
use proton_drive_rs::{NodeKind, PhotoTag, PhotoTagsUpdate, Thumbnail, ThumbnailType};
use tracing::{debug, info, warn};
use super::drive::RevisionRead;
use super::ContentCache;
use super::drive::{DriveApi, RevisionRead};
use super::events::EventHub;
use super::shutdown::Shutdown;
use super::transfers::{CountingWriter, TransferRegistry};
use super::{
Core, PHOTOS_AVAILABLE, PHOTOS_SYNCED_MS, TIMELINE_ENRICH_CHUNK, ThumbnailMissCaches,
WriteAuthority, link, node_size, now_ms, parse_uid,
};
use pdfs_core::control::TransferDirection;
use pdfs_core::control::{ActivityKind, DirEntry};
use pdfs_core::lifecycle::ServiceBoard;
use proton_drive_rs::proton_sdk::error::ProtonError;
use proton_drive_rs::{ProtonDriveClient, ProtonPhotosClient};
/// Longest edge, in px, of a thumbnail generated locally for a photo the server
/// has none for. Matches the server's own thumbnail scale closely enough that a
@@ -129,8 +138,107 @@ const DECODE_BUDGET_BYTES: u64 = 512 * 1024 * 1024;
/// The process-wide [`DecodeBudget`] every thumbnail decode draws from.
static DECODE_BUDGET: DecodeBudget = DecodeBudget::new(DECODE_BUDGET_BYTES);
mod albums;
pub(crate) mod redate;
pub(crate) mod takeout;
pub(crate) use albums::AlbumOutcome;
pub(crate) use takeout::sha1_of;
mod thumbs;
mod timeline;
mod trash;
/// The Photos service: the timeline, albums and thumbnails.
///
/// It holds only the handles it calls, and reaches the filesystem through
/// [`PhotosHost`], so it does not depend on [`Core`]. [`Core::photos`] builds
/// one on demand, the same way [`Core::syncer`] builds the sync engine. A clone
/// shares everything, which is how a refresh or a thumbnail job moves onto a
/// background task.
#[derive(Clone)]
pub(crate) struct Photos {
client: ProtonDriveClient,
drive: Arc<dyn DriveApi>,
rt: tokio::runtime::Handle,
cache: Arc<ContentCache>,
db: Arc<pdfs_store::db::Db>,
shutdown: Arc<Shutdown>,
services: ServiceBoard,
events: Arc<EventHub>,
transfers: Arc<TransferRegistry>,
jobs: PhotoJobs,
host: Arc<dyn PhotosHost>,
}
/// What the Photos service needs from the filesystem.
pub(crate) trait PhotosHost: Send + Sync {
/// List a folder of the mount, for the recursive thumbnail build.
fn list_dir(&self, rel: &Path) -> CoreResult<Vec<DirEntry>>;
/// Record a change this daemon made, so its echo in the event feed is not
/// taken for a remote edit.
fn note_self_change(&self, uid: &NodeUid);
/// Add an entry to the activity log.
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool);
}
impl PhotosHost for Core {
fn list_dir(&self, rel: &Path) -> CoreResult<Vec<DirEntry>> {
Core::list_dir(self, rel)
}
fn note_self_change(&self, uid: &NodeUid) {
Core::note_self_change(self, uid)
}
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool) {
Core::log_activity(self, kind, target, detail, ok);
}
}
impl Core {
/// The Photos service, with this daemon as its host.
pub(crate) fn photos(&self) -> Photos {
Photos {
client: self.client.clone(),
drive: self.drive.clone(),
rt: self.rt.clone(),
cache: self.cache.clone(),
db: self.db.clone(),
shutdown: self.shutdown.clone(),
services: self.services.clone(),
events: self.events.clone(),
transfers: self.transfers.clone(),
jobs: self.photo_jobs.clone(),
host: Arc::new(self.clone()),
}
}
}
impl Photos {
/// The Photos API over the daemon's single authenticated session.
fn photos_api(&self) -> ProtonPhotosClient {
ProtonPhotosClient::from_drive_client(self.client.clone())
}
/// Like [`download_file_tracked_to`] for a photo, streaming through the
/// photos client's [`download_photo_to`].
///
/// [`download_file_tracked_to`]: crate::Core::download_file_tracked_to
/// [`download_photo_to`]: ProtonPhotosClient::download_photo_to
fn download_photo_tracked(
&self,
photos: &ProtonPhotosClient,
uid: &NodeUid,
name: &str,
total: u64,
) -> std::result::Result<Vec<u8>, ProtonError> {
let guard = self
.transfers
.begin(name, uid.to_string(), TransferDirection::Download, total);
let mut out = CountingWriter::new(Vec::with_capacity(total as usize), &guard);
self.rt.block_on(photos.download_photo_to(uid, &mut out))?;
Ok(out.into_inner())
}
}
/// What the Photos and thumbnail jobs are doing right now: which refreshes
/// and builds are running, how far they got, and which thumbnails are known
@@ -149,7 +257,7 @@ pub(crate) struct PhotoJobs {
/// The same, for the album listing.
pub(crate) albums_refreshing: Arc<AtomicBool>,
/// True while the similar-photo pass hashes thumbnails (see
/// [`Core::photo_similar`]), so asking again doesn't start a second one.
/// [`Photos::photo_similar`]), so asking again doesn't start a second one.
pub(crate) similar_hashing: Arc<AtomicBool>,
/// Photos whose missing thumbnail is being generated right now. A tile that is
/// still on screen asks for its thumbnail again every few seconds, and each of
@@ -2,7 +2,7 @@
//!
//! Both are persisted projections of what the photos volume reports, refreshed
//! on the same stale-while-serving rule as the timeline
//! ([`crate::photos`]): a listing already on disk is served immediately and
//! ([`super`]): a listing already on disk is served immediately and
//! refreshed behind the caller, and only an empty one waits on the network.
//!
//! An album is a folder node carrying album properties, so it has a name like
@@ -23,15 +23,16 @@ use proton_drive_rs::NodeKind;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use tracing::warn;
use super::{
ALBUM_SYNCED_PREFIX, ALBUMS_SYNCED_MS, Core, PHOTOS_AVAILABLE, TIMELINE_ENRICH_CHUNK,
TIMELINE_TTL, link, now_ms, parse_uid,
use super::Photos;
use crate::{
ALBUM_SYNCED_PREFIX, ALBUMS_SYNCED_MS, PHOTOS_AVAILABLE, TIMELINE_ENRICH_CHUNK, TIMELINE_TTL,
link, listing::listing_stale, now_ms, parse_uid,
};
impl Core {
impl Photos {
/// The album listing, served from disk and refreshed behind the caller when
/// stale. `None` means the account has no photos volume — the same signal
/// [`Core::photos_timeline`] gives.
/// [`Photos::photos_timeline`] gives.
pub(crate) fn albums(&self) -> CoreResult<Option<Vec<AlbumInfo>>> {
let count = self.db.albums_count().map_err(CoreError::from)?;
if count == 0
@@ -44,13 +45,13 @@ impl Core {
// Nothing on disk, so this one request waits for the fetch — unless
// the account is already known to have no photos volume.
let known_empty = self.db.state_i64(PHOTOS_AVAILABLE).ok().flatten() == Some(0);
if known_empty && !self.listing_stale(ALBUMS_SYNCED_MS, TIMELINE_TTL) {
if known_empty && !listing_stale(&self.db, ALBUMS_SYNCED_MS, TIMELINE_TTL) {
return Ok(None);
}
if !self.rt.block_on(self.refresh_albums())? {
return Ok(None);
}
} else if self.listing_stale(ALBUMS_SYNCED_MS, TIMELINE_TTL) {
} else if listing_stale(&self.db, ALBUMS_SYNCED_MS, TIMELINE_TTL) {
self.spawn_albums_refresh();
}
@@ -66,7 +67,7 @@ impl Core {
.db
.photo_projection_generation()
.map_err(CoreError::from)?;
let photos = self.photos();
let photos = self.photos_api();
if link::bounded(photos.get_photos_root())
.await
.map_err(|e| CoreError::from_api(&e, "photos root"))?
@@ -132,22 +133,16 @@ impl Core {
/// Refresh the album listing off the request path. At most one runs at a time.
pub(crate) fn spawn_albums_refresh(&self) {
if self
.photo_jobs
.albums_refreshing
.swap(true, Ordering::SeqCst)
{
if self.jobs.albums_refreshing.swap(true, Ordering::SeqCst) {
return;
}
let core = self.clone();
let this = self.clone();
self.services
.spawn_task_job(&self.rt, "pdfs-albums-refresh", async move {
let refreshed = core.refresh_albums().await;
core.photo_jobs
.albums_refreshing
.store(false, Ordering::SeqCst);
let refreshed = this.refresh_albums().await;
this.jobs.albums_refreshing.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => core.events.publish(&[Topic::Photos]),
Ok(_) => this.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background album refresh failed"),
}
});
@@ -177,12 +172,12 @@ impl Core {
.is_none()
{
self.rt.block_on(self.refresh_album(album))?;
} else if self.listing_stale(&stamp, TIMELINE_TTL) {
let core = self.clone();
} else if listing_stale(&self.db, &stamp, TIMELINE_TTL) {
let this = self.clone();
let album = album.clone();
self.services
.spawn_task_job(&self.rt, "pdfs-album-refresh", async move {
if let Err(e) = core.refresh_album(&album).await {
if let Err(e) = this.refresh_album(&album).await {
warn!(%album, error = %e, "background album refresh failed");
}
});
@@ -235,7 +230,7 @@ impl Core {
.db
.photo_projection_generation()
.map_err(CoreError::from)?;
let photos = self.photos();
let photos = self.photos_api();
let items = link::bounded(photos.enumerate_album(album))
.await
.map_err(|e| CoreError::from_api(&e, "album"))?;
@@ -285,11 +280,11 @@ impl Core {
}
/// Create an album and return its uid. The listing is refreshed before
/// answering, so the next [`Core::albums`] already shows it.
/// answering, so the next [`Photos::albums`] already shows it.
pub(crate) fn create_album(&self, name: &str) -> CoreResult<String> {
let uid = self
.rt
.block_on(self.photos().create_album(name))
.block_on(self.photos_api().create_album(name))
.map_err(|e| CoreError::from_api(&e, "create album"))?;
self.after_album_change(None);
Ok(uid.to_string())
@@ -297,7 +292,7 @@ impl Core {
pub(crate) fn rename_album(&self, album: &NodeUid, name: &str) -> CoreResult<()> {
self.rt
.block_on(self.photos().rename_album(album, name))
.block_on(self.photos_api().rename_album(album, name))
.map_err(|e| CoreError::from_api(&e, "rename album"))?;
self.after_album_change(None);
Ok(())
@@ -307,7 +302,7 @@ impl Core {
/// which only matters for photos that exist in the album alone.
pub(crate) fn delete_album(&self, album: &NodeUid, delete_photos: bool) -> CoreResult<()> {
self.rt
.block_on(self.photos().delete_album(album, delete_photos))
.block_on(self.photos_api().delete_album(album, delete_photos))
.map_err(|e| CoreError::from_api(&e, "delete album"))?;
let key = album.to_string();
if let Err(error) = self.db.photos_delete(&[key]) {
@@ -325,7 +320,7 @@ impl Core {
) -> CoreResult<AlbumOutcome> {
let outcomes = self
.rt
.block_on(self.photos().add_photos_to_album(album, photos))
.block_on(self.photos_api().add_photos_to_album(album, photos))
.map_err(|e| CoreError::from_api(&e, "add to album"))?;
self.after_album_change(Some(album));
Ok(album_outcome(outcomes))
@@ -340,7 +335,7 @@ impl Core {
) -> CoreResult<AlbumOutcome> {
let outcomes = self
.rt
.block_on(self.photos().remove_photos_from_album(album, photos))
.block_on(self.photos_api().remove_photos_from_album(album, photos))
.map_err(|e| CoreError::from_api(&e, "remove from album"))?;
self.after_album_change(Some(album));
Ok(album_outcome(outcomes))
@@ -363,7 +358,7 @@ impl Core {
}
/// Drop the album listing's and every album's freshness stamp, so the next
/// request re-enumerates. Paired with [`Core::invalidate_photos`] — a change
/// request re-enumerates. Paired with [`Core::invalidate_photos`](crate::Core::invalidate_photos) — a change
/// to the timeline can just as easily be a change to an album.
pub(crate) fn invalidate_albums(&self) {
let _ = self.db.clear_state(ALBUMS_SYNCED_MS);
@@ -27,7 +27,7 @@ use proton_drive_rs::proton_sdk::ids::NodeUid;
use proton_drive_rs::{PhotoTag, PhotoTagsUpdate, PhotoUploadMetadata};
use tracing::{info, warn};
use super::Core;
use super::Photos;
use crate::parse_uid as parse_node_uid;
use crate::transfers::CountingReader;
@@ -84,7 +84,7 @@ struct Candidate {
albums: Vec<String>,
}
impl Core {
impl Photos {
/// Re-date mis-dated photos. Blocking; run on its own thread.
///
/// `cancel` stops the run at the next photo boundary. A photo is only ever
@@ -184,7 +184,7 @@ impl Core {
/// trash the original. Every earlier step failing leaves the account exactly
/// as it was.
fn redate_one(&self, candidate: &Candidate, summary: &mut RedateSummary) -> CoreResult<()> {
let photos = self.photos();
let photos = self.photos_api();
let path = self.open_photo(&candidate.uid)?;
let size = std::fs::metadata(&path)
.map_err(|e| CoreError::internal(format!("stat {}: {e}", path.display())))?
@@ -227,7 +227,7 @@ impl Core {
match self.rt.block_on(photos.update_photos(&[update])) {
// As in `set_photo_favorite`: claim our own echo, so the tag we
// just set does not come back as a remote change.
Ok(_) => self.note_self_change(&new_uid),
Ok(_) => self.host.note_self_change(&new_uid),
Err(e) => {
warn!(name = candidate.name, error = %e, "cannot re-favorite re-dated photo")
}
@@ -287,9 +287,9 @@ impl Core {
state.last = None;
}
let core = self.clone();
let this = self.clone();
if let Err(error) = self.services.spawn_job("pdfs-redate", move || {
let outcome = core.redate_photos(dry_run, limit, range, cancel);
let outcome = this.redate_photos(dry_run, limit, range, cancel);
let mut state = REDATE.lock();
state.running = false;
state.cancel = None;
@@ -47,7 +47,7 @@ use tracing::{info, warn};
pub(crate) use pdfs_drive::digest::sha1_of;
use super::Core;
use super::Photos;
use crate::photos::can_make_thumbnail;
use crate::transfers::CountingReader;
@@ -468,7 +468,7 @@ fn read_entry<R>(
Ok(sink(&mut file))
}
impl Core {
impl Photos {
/// Copy archive entry `entry` into the thumbnail staging folder and return
/// its path. The caller removes it.
fn stage_takeout_entry(
@@ -611,7 +611,7 @@ impl Core {
));
}
let photos = self.photos();
let photos = self.photos_api();
if self
.rt
.block_on(photos.get_photos_root())
@@ -668,7 +668,7 @@ impl Core {
report: &Reporter,
) -> CoreResult<()> {
report.phase(ImportPhase::Checking, 0);
let photos = self.photos();
let photos = self.photos_api();
let names: Vec<String> = planned.iter().map(|p| p.photo.name.clone()).collect();
let collisions = self
.rt
@@ -919,7 +919,7 @@ impl Core {
report.step();
match done.result {
Ok(uid) => {
self.note_self_change(&uid);
self.host.note_self_change(&uid);
summary.uploaded += 1;
summary.bytes += done.photo.size;
if done.live {
@@ -954,7 +954,7 @@ impl Core {
tags: Vec<PhotoTag>,
main_uid: Option<NodeUid>,
) -> CoreResult<NodeUid> {
let photos = self.photos();
let photos = self.photos_api();
let guard = self.transfers.begin(
photo.name.clone(),
"",
@@ -1035,7 +1035,7 @@ impl Core {
tags_to_remove: Vec::new(),
})
.collect();
if let Err(e) = self.rt.block_on(self.photos().update_photos(&updates)) {
if let Err(e) = self.rt.block_on(self.photos_api().update_photos(&updates)) {
warn!(error = %e, "marking imported favorites failed");
}
}
@@ -1049,7 +1049,7 @@ impl Core {
summary: &mut ImportSummary,
report: &Reporter,
) -> CoreResult<()> {
let photos = self.photos();
let photos = self.photos_api();
// Existing albums by decrypted name, so a second import of the same
// export adds to the album it made the first time instead of a twin.
@@ -1152,14 +1152,14 @@ impl Core {
state.save();
}
let core = self.clone();
let this = self.clone();
if let Err(error) = self.services.spawn_job("pdfs-import", move || {
// The job is dropped only after the final state is stored: the
// job leaving the transfer snapshot is the front-ends' cue to ask
// for the result, which must then be there.
let job = core.transfers.begin_job("Importing Google Photos");
let job = this.transfers.begin_job("Importing Google Photos");
let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
core.import_takeout(&archives, dry_run, &cancel, &job)
this.import_takeout(&archives, dry_run, &cancel, &job)
}));
// A panic must not leave the import marked as running for the
// life of the daemon, refusing every later one.
@@ -1179,9 +1179,9 @@ impl Core {
}
drop(job);
if !dry_run {
core.log_activity(
this.host.log_activity(
ActivityKind::Upload,
"Google Photos import",
"Google Photos import".to_string(),
activity_line(&summary),
summary.complete(),
);
+76 -95
View File
@@ -4,14 +4,14 @@
use super::*;
impl Core {
impl Photos {
/// [`upload_thumbnails`] for a file about to upload, staging any RAW copy
/// under this cache. Blocking.
pub(crate) fn upload_thumbnails(&self, path: &Path, name: &str) -> Vec<Thumbnail> {
upload_thumbnails(path, name, self.cache.raw_thumbnail_staging_dir())
}
/// [`Core::upload_thumbnails`] on the blocking pool, for async callers.
/// [`Photos::upload_thumbnails`] on the blocking pool, for async callers.
pub(crate) async fn upload_thumbnails_async(
&self,
path: PathBuf,
@@ -26,7 +26,7 @@ impl Core {
/// Thumbnails for `uids`, served from the cache, fetched from the server for
/// whatever is missing, and — for the photos the server has no thumbnail for
/// at all — *generated locally* from the full file (see
/// [`Core::generate_thumbs`]). Requested on demand as tiles scroll into view,
/// [`Photos::generate_thumbs`]). Requested on demand as tiles scroll into view,
/// so a cold timeline paints immediately and only the photos actually on
/// screen cost a round-trip.
///
@@ -41,7 +41,7 @@ impl Core {
self.photo_thumbs_with(requested, true)
}
/// [`Core::photo_thumbs`], with local generation only when `generate` is
/// [`Photos::photo_thumbs`], with local generation only when `generate` is
/// set. Without it, a photo the server has no thumbnail for is left
/// without one rather than downloaded whole.
pub(crate) fn photo_thumbs_with(
@@ -117,7 +117,7 @@ impl Core {
if !want.is_empty() {
let mut missing = want.clone();
match self.rt.block_on(
self.photos()
self.photos_api()
.enumerate_thumbnails(&want, ThumbnailType::Thumbnail),
) {
Ok(thumbs) => {
@@ -154,7 +154,7 @@ impl Core {
}
}
let pending = self.photo_jobs.thumb_gen.lock();
let pending = self.jobs.thumb_gen.lock();
requested
.iter()
.zip(uids)
@@ -197,7 +197,7 @@ impl Core {
}
/// Thumbnails for image files shown by the regular file browser, Shared and
/// Trash pages. Unlike [`Core::photo_thumbs`], these nodes need not be in the
/// Trash pages. Unlike [`Photos::photo_thumbs`], these nodes need not be in the
/// Photos timeline: the request supplies each file's modification time as
/// the cache validity tag.
pub(crate) fn file_thumbs(
@@ -205,8 +205,8 @@ impl Core {
items: &[FileThumbRequest],
generation: u64,
) -> Option<Vec<PhotoThumb>> {
let current = generation != 0
&& self.photo_jobs.file_thumb_generation.load(Ordering::SeqCst) == generation;
let current =
generation != 0 && self.jobs.file_thumb_generation.load(Ordering::SeqCst) == generation;
if !current {
return None;
}
@@ -238,7 +238,7 @@ impl Core {
.cached_thumbnail_path(uid, ttype, *modified)
.is_some()
|| self
.photo_jobs
.jobs
.thumbnail_misses
.lock()
.local_contains(&(uid.clone(), ttype), *modified)
@@ -253,7 +253,7 @@ impl Core {
self.spawn_generate_thumbs(wanted, &tags, &names, ThumbJob::Files(generation));
}
let pending = self.photo_jobs.thumb_gen.lock();
let pending = self.jobs.thumb_gen.lock();
Some(
items
.iter()
@@ -279,14 +279,14 @@ impl Core {
pub(crate) fn reserve_file_thumb_generation(&self) -> u64 {
let next = |current| if current == u64::MAX { 1 } else { current + 1 };
let previous = self
.photo_jobs
.jobs
.file_thumb_generation
.try_update(Ordering::SeqCst, Ordering::SeqCst, |current| {
Some(next(current))
})
.expect("generation update always succeeds");
let generation = next(previous);
self.photo_jobs.file_thumb_cancel.notify_waiters();
self.jobs.file_thumb_cancel.notify_waiters();
generation
}
@@ -295,11 +295,11 @@ impl Core {
/// recursive builds do not use this generation and continue normally.
pub(crate) fn cancel_file_thumbs(&self, generation: u64) {
let previous = self
.photo_jobs
.jobs
.file_thumb_generation
.fetch_max(generation, Ordering::SeqCst);
if generation > previous {
self.photo_jobs.file_thumb_cancel.notify_waiters();
self.jobs.file_thumb_cancel.notify_waiters();
}
}
@@ -314,7 +314,7 @@ impl Core {
job: ThumbJob,
) {
let fresh: Vec<NodeUid> = {
let mut inflight = self.photo_jobs.thumb_gen.lock();
let mut inflight = self.jobs.thumb_gen.lock();
uids.into_iter()
.filter(|uid| inflight.insert(uid.clone()))
.collect()
@@ -323,16 +323,16 @@ impl Core {
return;
}
let core = self.clone();
let this = self.clone();
let tags = tags.clone();
let names = names.clone();
// `generate_thumbs` blocks on the runtime itself, so it belongs on the
// blocking pool rather than on an async worker.
self.rt.spawn_blocking(move || {
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
core.generate_thumbs(&fresh, &tags, &names, job)
this.generate_thumbs(&fresh, &tags, &names, job)
}));
let mut inflight = core.photo_jobs.thumb_gen.lock();
let mut inflight = this.jobs.thumb_gen.lock();
for uid in &fresh {
inflight.remove(uid);
}
@@ -354,13 +354,10 @@ impl Core {
pub(super) fn thumb_job_current(&self, job: ThumbJob) -> bool {
match job {
ThumbJob::Files(generation) => {
self.photo_jobs.file_thumb_generation.load(Ordering::SeqCst) == generation
self.jobs.file_thumb_generation.load(Ordering::SeqCst) == generation
}
ThumbJob::Photos => true,
ThumbJob::Build => !self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst),
ThumbJob::Build => !self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst),
}
}
@@ -377,12 +374,12 @@ impl Core {
for chunk in uids.chunks(THUMB_GEN_CONCURRENCY) {
let mut set = tokio::task::JoinSet::new();
for uid in chunk {
let core = self.clone();
let this = self.clone();
let client = self.client.clone();
let uid = uid.clone();
let name = names.get(&uid.to_string()).cloned().unwrap_or_default();
set.spawn(async move {
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
let video = is_video_name(&name);
@@ -397,19 +394,19 @@ impl Core {
// One shared permit pool bounds all thumbnail batches,
// rather than multiplying the limit by every control
// request the GUI happens to have in flight.
let acquire = core.photo_jobs.thumb_gen_budget.clone().acquire_owned();
let acquire = this.jobs.thumb_gen_budget.clone().acquire_owned();
tokio::pin!(acquire);
let _permit = match job {
ThumbJob::Files(_) => loop {
tokio::select! {
permit = &mut acquire => break permit.ok(),
_ = core.photo_jobs.file_thumb_cancel.notified() => {
if !core.thumb_job_current(job) {
_ = this.jobs.file_thumb_cancel.notified() => {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
@@ -418,13 +415,13 @@ impl Core {
ThumbJob::Build => loop {
tokio::select! {
permit = &mut acquire => break permit.ok(),
_ = core.photo_jobs.thumbnail_build_cancel.notified() => {
if !core.thumb_job_current(job) {
_ = this.jobs.thumbnail_build_cancel.notified() => {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
@@ -435,12 +432,12 @@ impl Core {
let Some(_permit) = _permit else {
return (uid, ThumbAttempt::Unavailable);
};
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
let download_uid = uid.clone();
let drive = core.drive.clone();
let drive = this.drive.clone();
let audio_name = name.clone();
let download = async move {
// Photos asked the server in one batch already. A
@@ -478,13 +475,13 @@ impl Core {
ThumbJob::Files(_) => loop {
tokio::select! {
result = &mut download => break Some(result),
_ = core.photo_jobs.file_thumb_cancel.notified() => {
if !core.thumb_job_current(job) {
_ = this.jobs.file_thumb_cancel.notified() => {
if !this.thumb_job_current(job) {
break None;
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
break None;
}
}
@@ -493,13 +490,13 @@ impl Core {
ThumbJob::Build => loop {
tokio::select! {
result = &mut download => break Some(result),
_ = core.photo_jobs.thumbnail_build_cancel.notified() => {
if !core.thumb_job_current(job) {
_ = this.jobs.thumbnail_build_cancel.notified() => {
if !this.thumb_job_current(job) {
break None;
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
break None;
}
}
@@ -517,12 +514,12 @@ impl Core {
return (uid, ThumbAttempt::Unavailable);
}
};
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
// Decoding + scaling a 20 MP JPEG is CPU-bound and would
// stall the runtime's worker; hand it to the blocking pool.
let staging_dir = core.cache.raw_thumbnail_staging_dir().to_path_buf();
let staging_dir = this.cache.raw_thumbnail_staging_dir().to_path_buf();
let staging = staging_dir.clone();
let made = tokio::task::spawn_blocking(move || match fetched {
Fetched::Audio(sample) => {
@@ -547,12 +544,12 @@ impl Core {
// A song without a picture of its own shows its
// folder's cover.
let made = match made {
ScaleAttempt::Undecodable if audio && core.thumb_job_current(job) => {
core.folder_cover_thumbnail(&uid, staging).await
ScaleAttempt::Undecodable if audio && this.thumb_job_current(job) => {
this.folder_cover_thumbnail(&uid, staging).await
}
made => made,
};
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
match made {
@@ -583,7 +580,7 @@ impl Core {
match self.cache.store_thumbnail(&uid, ttype, tag, &thumb.bytes) {
Ok(()) => {
summary.made += 1;
self.photo_jobs
self.jobs
.thumbnail_misses
.lock()
.forget_local(&(uid.clone(), ttype));
@@ -600,7 +597,7 @@ impl Core {
ThumbAttempt::Undecodable => {
summary.undecodable += 1;
if let Some(&tag) = tags.get(&uid.to_string()) {
self.photo_jobs
self.jobs
.thumbnail_misses
.lock()
.remember_local((uid.clone(), ttype), tag);
@@ -698,7 +695,7 @@ impl Core {
}
pub(crate) fn thumbnail_build_status(&self) -> ThumbnailBuildStatus {
self.photo_jobs.thumbnail_build.lock().clone()
self.jobs.thumbnail_build.lock().clone()
}
/// Start one recursive local-thumbnail build. A request for the same root
@@ -707,11 +704,11 @@ impl Core {
pub(crate) fn start_thumbnail_build(&self, root: PathBuf) -> CoreResult<ThumbnailBuildStatus> {
let path = root.to_string_lossy().into_owned();
let status = {
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
if !thumbnail_build_may_start(&status, &path)? {
return Ok(status.clone());
}
self.photo_jobs
self.jobs
.thumbnail_build_cancelled
.store(false, Ordering::SeqCst);
*status = ThumbnailBuildStatus {
@@ -727,18 +724,18 @@ impl Core {
status.clone()
};
let core = self.clone();
let this = self.clone();
self.rt.spawn_blocking(move || {
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
core.run_thumbnail_build(root)
this.run_thumbnail_build(root)
}))
.is_err()
{
let mut status = core.photo_jobs.thumbnail_build.lock();
let mut status = this.jobs.thumbnail_build.lock();
status.running = false;
status.scanning = false;
status.message = Some("Thumbnail generation stopped unexpectedly".to_string());
core.photo_jobs
this.jobs
.thumbnail_build_cancelled
.store(false, Ordering::SeqCst);
warn!(path = %status.path, "recursive thumbnail build panicked");
@@ -749,25 +746,25 @@ impl Core {
pub(crate) fn cancel_thumbnail_build(&self) -> ThumbnailBuildStatus {
let (status, cancelled) = {
let status = self.photo_jobs.thumbnail_build.lock();
let status = self.jobs.thumbnail_build.lock();
let cancelled = status.running;
if cancelled {
self.photo_jobs
self.jobs
.thumbnail_build_cancelled
.store(true, Ordering::SeqCst);
}
(status.clone(), cancelled)
};
if cancelled {
self.photo_jobs.thumbnail_build_cancel.notify_waiters();
self.jobs.thumbnail_build_cancel.notify_waiters();
}
status
}
pub(crate) fn finish_thumbnail_build(&self) {
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
let cancelled = self
.photo_jobs
.jobs
.thumbnail_build_cancelled
.swap(false, Ordering::SeqCst);
status.running = false;
@@ -791,23 +788,19 @@ impl Core {
let mut seen_images = HashSet::new();
while let Some(folder) = folders.pop() {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
self.finish_thumbnail_build();
return;
}
let listing = self.list_dir(&folder);
let listing = self.host.list_dir(&folder);
{
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
status.folders_scanned += 1;
}
let entries = match listing {
Ok(entries) => entries,
Err(error) => {
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
if status.message.is_none() {
status.message = Some(format!(
"Some folders could not be read ({}: {error})",
@@ -839,18 +832,14 @@ impl Core {
}
}
}
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
status.images_found += found_here;
status.completed += invalid_here;
status.failed += invalid_here;
}
self.photo_jobs.thumbnail_build.lock().scanning = false;
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
self.jobs.thumbnail_build.lock().scanning = false;
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
self.finish_thumbnail_build();
return;
}
@@ -862,14 +851,14 @@ impl Core {
.cached_thumbnail_path(&uid, ttype, modified)
.is_some()
{
self.photo_jobs.thumbnail_build.lock().completed += 1;
self.jobs.thumbnail_build.lock().completed += 1;
} else if self
.photo_jobs
.jobs
.thumbnail_misses
.lock()
.local_contains(&(uid.clone(), ttype), modified)
{
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
} else {
@@ -878,11 +867,7 @@ impl Core {
}
for chunk in todo.chunks(THUMB_BUILD_CHUNK) {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
self.finish_thumbnail_build();
return;
}
@@ -895,11 +880,7 @@ impl Core {
// than downloading the full image twice.
let waiting_since = Instant::now();
loop {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
self.finish_thumbnail_build();
return;
}
@@ -908,28 +889,28 @@ impl Core {
.cached_thumbnail_path(uid, ttype, *modified)
.is_some()
{
self.photo_jobs.thumbnail_build.lock().completed += 1;
self.jobs.thumbnail_build.lock().completed += 1;
break;
}
if self
.photo_jobs
.jobs
.thumbnail_misses
.lock()
.local_contains(&(uid.clone(), ttype), *modified)
{
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
break;
}
if self.photo_jobs.thumb_gen.lock().insert(uid.clone()) {
if self.jobs.thumb_gen.lock().insert(uid.clone()) {
tags.insert(uid.to_string(), *modified);
names.insert(uid.to_string(), name.clone());
claimed.push(uid.clone());
break;
}
if waiting_since.elapsed() >= THUMB_BUILD_CLAIM_TIMEOUT {
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
if status.message.is_none() {
@@ -950,12 +931,12 @@ impl Core {
self.generate_thumbs(&claimed, &tags, &names, ThumbJob::Build)
}));
{
let mut inflight = self.photo_jobs.thumb_gen.lock();
let mut inflight = self.jobs.thumb_gen.lock();
for uid in &claimed {
inflight.remove(uid);
}
}
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
match result {
Ok(summary) => {
status.completed += summary.processed();
+23 -136
View File
@@ -3,7 +3,7 @@
use super::*;
impl Core {
impl Photos {
#[allow(clippy::too_many_arguments)]
pub(crate) fn photos_timeline(
&self,
@@ -90,7 +90,7 @@ impl Core {
/// The SDK reports one outcome per photo rather than failing the call, so the
/// single outcome is unwrapped back into this request's result.
pub(crate) fn set_photo_favorite(&self, uid: &NodeUid, favorite: bool) -> CoreResult<()> {
let photos = self.photos();
let photos = self.photos_api();
let update = PhotoTagsUpdate {
node_uid: uid.clone(),
tags_to_add: if favorite {
@@ -114,7 +114,7 @@ impl Core {
// `NodeUpdated`, which is indistinguishable from the same photo being
// favorited on a phone. Claim the echo, or the gallery pays for a
// resolve of a node whose one changed field is already stored below.
self.note_self_change(uid);
self.host.note_self_change(uid);
self.db
.photos_set_favorite(&uid.to_string(), favorite)
.map_err(CoreError::from)?;
@@ -142,7 +142,7 @@ impl Core {
let sets = self.db.photo_similar().map_err(CoreError::from)?;
let (done, total) = self.db.similar_progress().map_err(CoreError::from)?;
let hashing = self
.photo_jobs
.jobs
.similar_hashing
.load(Ordering::SeqCst)
.then_some(MappingProgress { done, total });
@@ -155,23 +155,19 @@ impl Core {
}
pub(crate) fn spawn_similar_hashing(&self) {
if self.photo_jobs.similar_hashing.swap(true, Ordering::SeqCst) {
if self.jobs.similar_hashing.swap(true, Ordering::SeqCst) {
return;
}
let core = self.clone();
let this = self.clone();
let spawned = self.services.spawn_job("pdfs-similar", move || {
if let Err(e) = core.hash_similar() {
if let Err(e) = this.hash_similar() {
warn!(error = %e, "similar-photo hashing failed");
}
core.photo_jobs
.similar_hashing
.store(false, Ordering::SeqCst);
this.jobs.similar_hashing.store(false, Ordering::SeqCst);
});
if let Err(e) = spawned {
warn!(error = %e, "could not start similar-photo hashing");
self.photo_jobs
.similar_hashing
.store(false, Ordering::SeqCst);
self.jobs.similar_hashing.store(false, Ordering::SeqCst);
}
}
@@ -320,100 +316,6 @@ impl Core {
out
}
/// Mutation admission for a photo, which [`Core::require_uid_writable`]
/// cannot answer on its own.
///
/// Photos live on the photo volume, and that volume is not part of the FUSE
/// tree: a photo has no `nodes` row, so every authority comes back
/// [`WriteAuthority::Unknown`] and the plain check refuses the whole
/// library. Membership of our own timeline is the authority that does exist
/// here — the timeline is enumerated from our photo share, so a uid in it is
/// ours to trash. Anything else (an album photo on someone else's volume)
/// still fails closed.
pub(crate) fn require_photo_writable(&self, uid: &NodeUid) -> Result<(), fuser::Errno> {
match self.uid_write_authority(uid) {
WriteAuthority::Writable => Ok(()),
WriteAuthority::Denied => Err(fuser::Errno::EACCES),
WriteAuthority::Unknown => {
let key = uid.to_string();
let known = self
.db
.photos_by_uid(std::slice::from_ref(&key))
.map(|rows| !rows.is_empty())
.unwrap_or(false);
if known {
Ok(())
} else {
Err(fuser::Errno::EACCES)
}
}
}
}
/// Trash photos by uid, and forget them locally.
///
/// The gallery is not part of the FUSE mount, so this is the photos-side
/// counterpart of [`Core::delete`]: same destination (Proton trash, so the
/// Trash page can restore them), addressed by uid because that is all a tile
/// has.
///
/// The server answers per node, and so does this: a batch where one photo
/// fails still removes the ones that went, and the caller is told which is
/// which. Only what actually left the server is forgotten locally.
///
/// A photo that is one file of a group takes its whole group with it. The
/// gallery shows a RAW+JPEG shot as one tile, so deleting that tile has to
/// delete the shot — leaving the RAW behind would put the photo back on the
/// Raw tab and nowhere else. `files_only` turns that off, for removing
/// one copy of a shot that is stored twice.
pub(crate) fn trash_photos(
&self,
uids: &[NodeUid],
files_only: bool,
) -> CoreResult<TrashOutcome> {
if uids.is_empty() {
return Ok((Vec::new(), Vec::new()));
}
let expanded;
let uids = if files_only {
uids
} else {
expanded = self.expand_photo_groups(uids);
&expanded
};
for uid in uids {
self.require_photo_writable(uid)
.map_err(|errno| self.errno_error(errno, "trash access"))?;
}
let outcomes = self
.rt
.block_on(self.drive.trash_nodes(uids))
.map_err(|e| CoreError::from_api(&e, "trash"))?;
let (trashed, failed) = pdfs_core::batch::split(outcomes);
let trashed: Vec<String> = trashed.iter().map(|uid| uid.to_string()).collect();
for uid in &trashed {
if let Some(parsed) = parse_uid(uid) {
self.cache.evict(&parsed);
self.evict_reader(&parsed);
}
}
// The timeline is served from the database, so removing the rows is what
// makes the photos disappear now rather than at the next refresh.
if let Err(error) = self.db.photos_delete(&trashed) {
warn!(%error, "trashed photos could not be removed from the timeline");
}
self.invalidate_photos();
self.invalidate_albums();
self.invalidate_trash();
let failed = failed
.into_iter()
.map(|(uid, error)| (uid.to_string(), error.to_string()))
.collect();
Ok((trashed, failed))
}
/// Commit the lightweight listing before resolving pending nodes. The
/// feed generation fences both commits against events received in flight.
pub(crate) async fn refresh_timeline(&self) -> CoreResult<bool> {
@@ -422,7 +324,7 @@ impl Core {
.db
.photo_projection_generation()
.map_err(CoreError::from)?;
let photos = self.photos();
let photos = self.photos_api();
if self
.db
.state_i64(PHOTOS_SYNCED_MS)
@@ -468,7 +370,7 @@ impl Core {
let total = self.db.photos_count().map_err(CoreError::from)?;
let skipped = total.saturating_sub(pending.len());
let mut resolved = 0;
let progress = ProgressGuard(&self.photo_jobs.timeline_progress);
let progress = ProgressGuard(&self.jobs.timeline_progress);
for (index, chunk) in pending.chunks(TIMELINE_ENRICH_CHUNK).enumerate() {
if self.shutdown.is_stopping() {
break;
@@ -537,12 +439,8 @@ impl Core {
/// whole library at once, sharing the session's rate limit and taking
/// minutes. Returns whether the account has a photos library.
pub(crate) fn refresh_timeline_joined(&self) -> CoreResult<bool> {
if self
.photo_jobs
.timeline_refreshing
.swap(true, Ordering::SeqCst)
{
while self.photo_jobs.timeline_refreshing.load(Ordering::SeqCst)
if self.jobs.timeline_refreshing.swap(true, Ordering::SeqCst) {
while self.jobs.timeline_refreshing.load(Ordering::SeqCst)
&& !self.shutdown.is_stopping()
{
std::thread::sleep(std::time::Duration::from_millis(200));
@@ -555,18 +453,13 @@ impl Core {
.state_i64(PHOTOS_SYNCED_MS)
.map_err(CoreError::from)?
.is_some()
|| self
.photo_jobs
.timeline_refreshing
.swap(true, Ordering::SeqCst)
|| self.jobs.timeline_refreshing.swap(true, Ordering::SeqCst)
{
return Ok(self.db.state_i64(PHOTOS_AVAILABLE).ok().flatten() != Some(0));
}
}
let refreshed = self.rt.block_on(self.refresh_timeline());
self.photo_jobs
.timeline_refreshing
.store(false, Ordering::SeqCst);
self.jobs.timeline_refreshing.store(false, Ordering::SeqCst);
if refreshed.is_ok() {
self.events.publish(&[Topic::Photos]);
}
@@ -574,24 +467,18 @@ impl Core {
}
pub(crate) fn spawn_timeline_refresh(&self) {
if self
.photo_jobs
.timeline_refreshing
.swap(true, Ordering::SeqCst)
{
if self.jobs.timeline_refreshing.swap(true, Ordering::SeqCst) {
return;
}
let core = self.clone();
let this = self.clone();
self.services
.spawn_task_job(&self.rt, "pdfs-timeline-refresh", async move {
let refreshed = core.refresh_timeline().await;
core.photo_jobs
.timeline_refreshing
.store(false, Ordering::SeqCst);
let refreshed = this.refresh_timeline().await;
this.jobs.timeline_refreshing.store(false, Ordering::SeqCst);
// Only a refresh that landed: a front-end re-reading after a failed
// one would find the timeline still stale and start another.
match refreshed {
Ok(_) => core.events.publish(&[Topic::Photos]),
Ok(_) => this.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background timeline refresh failed"),
}
});
@@ -600,7 +487,7 @@ impl Core {
/// How far the running timeline refresh has got reading photo metadata, or
/// `None` when no refresh is reading any.
pub(crate) fn timeline_progress(&self) -> Option<MappingProgress> {
self.photo_jobs
self.jobs
.timeline_progress
.lock()
.map(|(done, total)| MappingProgress { done, total })
@@ -609,13 +496,13 @@ impl Core {
/// Whether a timeline refresh is running. A front-end that asked for one
/// watches this to know when the new timeline is worth re-reading.
pub(crate) fn timeline_refreshing(&self) -> bool {
self.photo_jobs.timeline_refreshing.load(Ordering::SeqCst)
self.jobs.timeline_refreshing.load(Ordering::SeqCst)
}
/// Download a photo's full content into the content cache, returning its
/// on-disk path (served from cache when a fresh blob already exists).
pub(crate) fn open_photo(&self, uid: &NodeUid) -> CoreResult<PathBuf> {
let photos = self.photos();
let photos = self.photos_api();
let node = self
.rt
.block_on(photos.get_node(uid))
+101
View File
@@ -0,0 +1,101 @@
//! Trashing photos by uid. This stays on [`Core`] rather than [`Photos`]: it
//! checks write authority against the tree, drops open readers and clears the
//! trash listing, all of which belong to the filesystem side.
use super::*;
impl Core {
/// Mutation admission for a photo, which [`Core::require_uid_writable`]
/// cannot answer on its own.
///
/// Photos live on the photo volume, and that volume is not part of the FUSE
/// tree: a photo has no `nodes` row, so every authority comes back
/// [`WriteAuthority::Unknown`] and the plain check refuses the whole
/// library. Membership of our own timeline is the authority that does exist
/// here — the timeline is enumerated from our photo share, so a uid in it is
/// ours to trash. Anything else (an album photo on someone else's volume)
/// still fails closed.
pub(crate) fn require_photo_writable(&self, uid: &NodeUid) -> Result<(), fuser::Errno> {
match self.uid_write_authority(uid) {
WriteAuthority::Writable => Ok(()),
WriteAuthority::Denied => Err(fuser::Errno::EACCES),
WriteAuthority::Unknown => {
let key = uid.to_string();
let known = self
.db
.photos_by_uid(std::slice::from_ref(&key))
.map(|rows| !rows.is_empty())
.unwrap_or(false);
if known {
Ok(())
} else {
Err(fuser::Errno::EACCES)
}
}
}
}
/// Trash photos by uid, and forget them locally.
///
/// The gallery is not part of the FUSE mount, so this is the photos-side
/// counterpart of [`Core::delete`]: same destination (Proton trash, so the
/// Trash page can restore them), addressed by uid because that is all a tile
/// has.
///
/// The server answers per node, and so does this: a batch where one photo
/// fails still removes the ones that went, and the caller is told which is
/// which. Only what actually left the server is forgotten locally.
///
/// A photo that is one file of a group takes its whole group with it. The
/// gallery shows a RAW+JPEG shot as one tile, so deleting that tile has to
/// delete the shot — leaving the RAW behind would put the photo back on the
/// Raw tab and nowhere else. `files_only` turns that off, for removing
/// one copy of a shot that is stored twice.
pub(crate) fn trash_photos(
&self,
uids: &[NodeUid],
files_only: bool,
) -> CoreResult<TrashOutcome> {
if uids.is_empty() {
return Ok((Vec::new(), Vec::new()));
}
let expanded;
let uids = if files_only {
uids
} else {
expanded = self.photos().expand_photo_groups(uids);
&expanded
};
for uid in uids {
self.require_photo_writable(uid)
.map_err(|errno| self.errno_error(errno, "trash access"))?;
}
let outcomes = self
.rt
.block_on(self.drive.trash_nodes(uids))
.map_err(|e| CoreError::from_api(&e, "trash"))?;
let (trashed, failed) = pdfs_core::batch::split(outcomes);
let trashed: Vec<String> = trashed.iter().map(|uid| uid.to_string()).collect();
for uid in &trashed {
if let Some(parsed) = parse_uid(uid) {
self.cache.evict(&parsed);
self.evict_reader(&parsed);
}
}
// The timeline is served from the database, so removing the rows is what
// makes the photos disappear now rather than at the next refresh.
if let Err(error) = self.db.photos_delete(&trashed) {
warn!(%error, "trashed photos could not be removed from the timeline");
}
self.invalidate_photos();
self.photos().invalidate_albums();
self.invalidate_trash();
let failed = failed
.into_iter()
.map(|(uid, error)| (uid.to_string(), error.to_string()))
.collect();
Ok((trashed, failed))
}
}
+1 -1
View File
@@ -172,7 +172,7 @@ impl Core {
CoreError::conflict(format!("{path} is being sent right now; try again"))
})?;
self.release_dropped_ops(uid, blobs);
self.hidden.lock().remove(uid);
self.writes.unhide(uid);
match node {
Some(node) => self.for_each_mount(|st, notify| {
put_back(st, notify, node);
+87
View File
@@ -0,0 +1,87 @@
//! The account's storage quota, as `statfs(2)` and the control socket ask
//! for it.
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use parking_lot::Mutex;
use pdfs_core::{CoreError, CoreResult};
use tracing::debug;
use super::{Core, QUOTA_TTL};
/// The last account quota answer, for `statfs(2)`, and whether a refresh
/// of it is running.
#[derive(Clone)]
pub(crate) struct QuotaCache {
/// Last account quota answer and when it was learned, for `statfs(2)`.
///
/// `df` and the free-space preflight of every file manager and installer ask
/// for this, and the answer costs a round trip — so it is served from here
/// for [`QUOTA_TTL`] and refreshed on a worker afterwards. Total account
/// storage moves slowly enough that a minute-old number is a better answer
/// than either a stall or the zeroes the default implementation returns.
last: Arc<Mutex<Option<(std::time::Instant, i64, i64)>>>,
/// Set while a `statfs` is refreshing [`QuotaCache::last`], so the others serve
/// the last figures instead of each holding a worker on the same request.
refreshing: Arc<AtomicBool>,
}
impl QuotaCache {
pub(crate) fn new() -> Self {
Self {
last: Arc::new(Mutex::new(None)),
refreshing: Arc::new(AtomicBool::new(false)),
}
}
}
impl Core {
/// Total account storage usage `(max_space, used_space)` in bytes, across all
/// Proton products (not Drive-only). A remote round-trip; nothing here is
/// cached.
pub(crate) fn account_quota(&self) -> CoreResult<(i64, i64)> {
let q = self.block_on_bounded(self.drive.quota()).map_err(|e| {
self.lost_link(&e, "account quota");
CoreError::from_api(&e, "account quota")
})?;
*self.quota.last.lock() = Some((std::time::Instant::now(), q.max_space, q.used_space));
Ok((q.max_space, q.used_space))
}
/// The account quota as `statfs(2)` needs it: cached for [`QUOTA_TTL`],
/// refetched after that, and `None` when there is no usable answer at all —
/// offline with nothing cached.
///
/// Never blocks on the network for a *fresh* value when a recent one exists,
/// because the callers are `df` and every "is there room?" preflight, and a
/// stale byte count is worth more to them than a stalled syscall. Offline,
/// the last known figures keep being served rather than degrading to zero.
pub(crate) fn account_quota_cached(&self) -> Option<(i64, i64)> {
if let Some((at, max_space, used_space)) = *self.quota.last.lock()
&& at.elapsed() < QUOTA_TTL
{
return Some((max_space, used_space));
}
let last = || self.quota.last.lock().map(|(_, max, used)| (max, used));
if !self.is_online()
|| self
.quota
.refreshing
.swap(true, std::sync::atomic::Ordering::AcqRel)
{
return last();
}
let refreshed = self.account_quota();
self.quota
.refreshing
.store(false, std::sync::atomic::Ordering::Release);
match refreshed {
Ok(q) => Some(q),
Err(error) => {
debug!(%error, "account quota refresh failed; serving the last known figures");
last()
}
}
}
}
+2 -2
View File
@@ -507,7 +507,7 @@ impl Core {
// A queued write has not reached the remote yet, so the remote's current
// revision is stale and the staged blob is the truth. Serve from it until
// the drain worker lands the upload.
if let Some(pending) = self.pending.lock().get(uid).cloned() {
if let Some(pending) = self.writes.queued(uid) {
return self.read_pending(&pending, offset, len);
}
// A node created offline and never written has no blob and no remote: it
@@ -1132,7 +1132,7 @@ impl Core {
true => self.landed_stand_in_uid(&uid).unwrap_or(uid),
false => uid,
};
if let Some(pending) = self.pending.lock().get(&uid).cloned() {
if let Some(pending) = self.writes.queued(&uid) {
let m = &pending.meta;
let file = File::open(&pending.path).map_err(|e| {
error!(%uid, path = %pending.path.display(), error = %e, "open staged blob failed");
+7 -13
View File
@@ -28,17 +28,11 @@ impl Core {
// lying about the size reads as data loss. `hydrate_pending` ran before
// us, so the pending map is populated; snapshot it here rather than hold
// both locks at once.
let pending_sizes: HashMap<NodeUid, u64> = {
let pending = self.pending.lock();
pending
.iter()
.map(|(uid, pr)| (uid.clone(), pr.meta.len))
.collect()
};
let pending_sizes = self.writes.queued_sizes();
// `hydrate_pending` runs first and restores queued-trash tombstones.
// Their node rows remain persisted as drain-time access authority, but
// must not reappear in the mounted namespace after a restart.
let hidden = self.hidden.lock().clone();
let hidden = self.writes.hidden();
let mut st = self.state();
// Pass 1: give every uid its inode from its local id (the root is
@@ -123,7 +117,7 @@ impl Core {
return;
}
};
let mut map = self.pending.lock();
let mut map = self.writes.pending.lock();
let mut restored = 0usize;
for op in ops {
let Some(uid) = parse_node_uid(&op.uid) else {
@@ -132,7 +126,7 @@ impl Core {
continue;
};
if op.kind == OP_TRASH {
self.hidden.lock().insert(uid.clone());
self.writes.hide(&uid);
}
restored += 1;
// Only a revision must have a blob. A create carries none until
@@ -225,7 +219,7 @@ impl Core {
example.get_or_insert_with(|| blob.clone());
continue;
};
if self.pending.lock().contains_key(&uid) {
if self.writes.is_queued(&uid) {
// A newer write for the same node is queued and carries its own
// blob. These bytes are older; keeping them is right, uploading
// them over the newer ones is not.
@@ -266,7 +260,7 @@ impl Core {
if let Some(old) = superseded {
self.cache.discard_staged(Path::new(&old));
}
self.pending.lock().insert(
self.writes.pending.lock().insert(
uid.clone(),
PendingRevision {
path: blob.clone(),
@@ -336,7 +330,7 @@ impl Core {
// now would use the wrong remote base. enqueue_staged_write would abandon it
// to staging; keep it in recovery instead so the drain loop can queue it
// once the queue clears.
if !meta.complete && self.pending.lock().contains_key(&uid) {
if !meta.complete && self.writes.is_queued(&uid) {
continue;
}
+1 -1
View File
@@ -172,7 +172,7 @@ impl Core {
rel: dest_rel,
},
) = (&source, &dest)
&& Arc::ptr_eq(&core.root, &dest_core.root)
&& Arc::ptr_eq(&core.session.root, &dest_core.session.root)
{
return core.move_to(rel, dest_rel);
}
+2 -2
View File
@@ -693,7 +693,7 @@ impl Core {
self.for_each_state(|st| {
st.forget_or_unlink(uid);
});
self.hidden.lock().insert(uid.clone());
self.writes.hide(uid);
if open_now {
if let Err(error) = self.withdraw_queued_ops(uid) {
error!(%uid, "remote replacement landed but queued-op cleanup failed");
@@ -763,7 +763,7 @@ impl Core {
.and_then(batch::into_unit)
{
Ok(()) => {
self.hidden.lock().remove(uid);
self.writes.unhide(uid);
self.for_each_mount(|st, notify| {
if let Some(&ino) = st.by_uid.get(parent) {
st.invalidate_listing(ino);
+1 -1
View File
@@ -133,7 +133,7 @@ impl Core {
// These paths walk the tree lazily, so a cold node needs the API.
// Offline that surfaces as EIO, which on its own would read to the
// user as a broken file rather than a missing network.
libc::EIO if !self.online.load(Ordering::Relaxed) => CoreError::offline(),
libc::EIO if !self.is_online() => CoreError::offline(),
libc::EINVAL => CoreError::invalid(format!("{what}: not a usable path")),
libc::ENOSPC => CoreError::new(ErrorKind::Quota, format!("{what}: out of space")),
libc::EEXIST => CoreError::conflict(format!("{what}: already exists")),
+98 -125
View File
@@ -16,7 +16,7 @@
//! file rather than trying to describe the new one. The next read repopulates
//! from whatever is live by then.
//! - **The active revision cannot be deleted**, and the server — not this code —
//! is what enforces that. [`Core::delete_revision_for_uid`] refuses locally
//! is what enforces that. [`Revisions::delete`] refuses locally
//! too, so the user gets a sentence instead of an API code.
use std::path::Path;
@@ -27,7 +27,12 @@ use proton_drive_rs::Revision;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use tracing::info;
use std::sync::Arc;
use proton_drive_rs::ProtonDriveClient;
use super::Core;
use crate::drive::DriveApi;
/// A [`Revision`] as the control protocol reports it.
fn revision_info(revision: Revision) -> RevisionInfo {
@@ -45,70 +50,37 @@ fn revision_info(revision: Revision) -> RevisionInfo {
}
}
impl Core {
/// The version history of the file at mountpoint-relative `rel`.
pub(crate) fn list_revisions(&self, rel: &Path) -> CoreResult<Vec<RevisionInfo>> {
let (_ino, uid) = self.resolve(rel)?;
self.list_revisions_for_uid(&uid)
}
/// A file's revisions on Drive. Every method takes a node already resolved to
/// its uid, and the name the activity feed shows for it.
///
/// It reaches the filesystem through [`RevisionsHost`]. [`Core::revisions`]
/// builds one on demand with the daemon as its host.
pub(crate) struct Revisions {
client: ProtonDriveClient,
drive: Arc<dyn DriveApi>,
rt: tokio::runtime::Handle,
host: Arc<dyn RevisionsHost>,
}
/// [`Core::list_revisions`] for a node addressed through any daemon location.
pub(crate) fn list_revisions_by_uid(&self, uid: &str) -> CoreResult<Vec<RevisionInfo>> {
let uid = self.resolve_anywhere(uid)?;
self.list_revisions_for_uid(&uid)
}
/// What [`Revisions`] needs from the filesystem.
pub(crate) trait RevisionsHost: Send + Sync {
/// Refuse unless this daemon may change the node's content. `what` names
/// the operation in the error.
fn require_writable(&self, uid: &NodeUid, what: &str) -> CoreResult<()>;
/// The node's active revision changed on the server: forget its cached
/// content and open readers, and fetch it again if it is kept offline.
fn content_replaced(&self, uid: &NodeUid);
/// Add an entry to the activity log.
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool);
}
fn list_revisions_for_uid(&self, uid: &NodeUid) -> CoreResult<Vec<RevisionInfo>> {
let revisions = self
.rt
.block_on(self.client.enumerate_revisions(uid))
.map_err(|e| CoreError::from_api(&e, "list revisions"))?;
Ok(revisions.into_iter().map(revision_info).collect())
}
/// Make `revision_id` the current content of the file at `rel`.
pub(crate) fn restore_revision(&self, rel: &Path, revision_id: &str) -> CoreResult<()> {
let (_ino, uid) = self.resolve(rel)?;
let name = rel
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| uid.to_string());
self.restore_revision_for_uid(&uid, revision_id, &name)?;
// The size and mtime a listing shows describe the revision that was
// active a moment ago.
self.invalidate_parent_listing(rel);
Ok(())
}
/// [`Core::restore_revision`] for a node addressed through any daemon
/// location.
pub(crate) fn restore_revision_by_uid(&self, uid: &str, revision_id: &str) -> CoreResult<()> {
let uid = self.resolve_anywhere(uid)?;
let name = uid.to_string();
self.restore_revision_for_uid(&uid, revision_id, &name)
}
fn restore_revision_for_uid(
&self,
uid: &NodeUid,
revision_id: &str,
name: &str,
) -> CoreResult<()> {
// Restoring rewrites the file's content: the same authority a write
// needs, not the one a read needs.
impl RevisionsHost for Core {
fn require_writable(&self, uid: &NodeUid, what: &str) -> CoreResult<()> {
self.require_uid_writable(uid)
.map_err(|error| self.errno_error(error, "restore revision"))?;
if let Err(e) = self
.rt
.block_on(self.client.restore_revision(uid, revision_id))
{
let error = CoreError::from_api(&e, "restore revision");
self.log_activity(ActivityKind::Restore, name, &error, false);
return Err(error);
}
// The active revision is changing behind our back — anything describing
// the old one (cached blocks, an open reader, the size in a listing) is
// stale from here on, and the server may not have applied the swap yet.
.map_err(|error| self.errno_error(error, what))
}
fn content_replaced(&self, uid: &NodeUid) {
self.cache.evict(uid);
self.evict_reader(uid);
// A file kept offline gets the restored content back on disk, and
@@ -116,9 +88,58 @@ impl Core {
if self.cache.is_pinned(uid) {
self.recheck_pinned(uid);
}
self.log_activity(
}
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool) {
Core::log_activity(self, kind, target, detail, ok);
}
}
impl Core {
/// The revisions service, with this daemon as its host.
pub(crate) fn revisions(&self) -> Revisions {
Revisions {
client: self.client.clone(),
drive: self.drive.clone(),
rt: self.rt.clone(),
host: Arc::new(self.clone()),
}
}
}
impl Revisions {
pub(crate) fn list(&self, uid: &NodeUid) -> CoreResult<Vec<RevisionInfo>> {
let revisions = self
.rt
.block_on(self.client.enumerate_revisions(uid))
.map_err(|e| CoreError::from_api(&e, "list revisions"))?;
Ok(revisions.into_iter().map(revision_info).collect())
}
pub(crate) fn restore(&self, uid: &NodeUid, revision_id: &str, name: &str) -> CoreResult<()> {
// Restoring rewrites the file's content: the same authority a write
// needs, not the one a read needs.
self.host.require_writable(uid, "restore revision")?;
if let Err(e) = self
.rt
.block_on(self.client.restore_revision(uid, revision_id))
{
let error = CoreError::from_api(&e, "restore revision");
self.host.log_activity(
ActivityKind::Restore,
name.to_string(),
error.to_string(),
false,
);
return Err(error);
}
// The active revision is changing behind our back — anything describing
// the old one (cached blocks, an open reader, the size in a listing) is
// stale from here on, and the server may not have applied the swap yet.
self.host.content_replaced(uid);
self.host.log_activity(
ActivityKind::Restore,
name,
name.to_string(),
format!("restored version {revision_id}"),
true,
);
@@ -126,32 +147,8 @@ impl Core {
Ok(())
}
/// Permanently delete `revision_id` from the history of the file at `rel`.
pub(crate) fn delete_revision(&self, rel: &Path, revision_id: &str) -> CoreResult<()> {
let (_ino, uid) = self.resolve(rel)?;
let name = rel
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| uid.to_string());
self.delete_revision_for_uid(&uid, revision_id, &name)
}
/// [`Core::delete_revision`] for a node addressed through any daemon
/// location.
pub(crate) fn delete_revision_by_uid(&self, uid: &str, revision_id: &str) -> CoreResult<()> {
let uid = self.resolve_anywhere(uid)?;
let name = uid.to_string();
self.delete_revision_for_uid(&uid, revision_id, &name)
}
fn delete_revision_for_uid(
&self,
uid: &NodeUid,
revision_id: &str,
name: &str,
) -> CoreResult<()> {
self.require_uid_writable(uid)
.map_err(|error| self.errno_error(error, "delete revision"))?;
pub(crate) fn delete(&self, uid: &NodeUid, revision_id: &str, name: &str) -> CoreResult<()> {
self.host.require_writable(uid, "delete revision")?;
// The server rejects deleting the active revision; saying so here is a
// sentence the user can act on instead of an API code, and it costs one
// listing the front-end already made to show the version list.
@@ -171,9 +168,9 @@ impl Core {
self.rt
.block_on(self.client.delete_revision(uid, revision_id))
.map_err(|e| CoreError::from_api(&e, "delete revision"))?;
self.log_activity(
self.host.log_activity(
ActivityKind::DeleteForever,
name,
name.to_string(),
format!("deleted version {revision_id}"),
true,
);
@@ -181,36 +178,7 @@ impl Core {
Ok(())
}
/// Write `revision_id` of the file at `rel` to the absolute local path
/// `dest`, leaving the file itself untouched.
pub(crate) fn save_revision_as(
&self,
rel: &Path,
revision_id: &str,
dest: &Path,
) -> CoreResult<u64> {
let (_ino, uid) = self.resolve(rel)?;
let name = rel
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| uid.to_string());
self.save_revision_for_uid(&uid, revision_id, &name, dest)
}
/// [`Core::save_revision_as`] for a node addressed through any daemon
/// location.
pub(crate) fn save_revision_as_by_uid(
&self,
uid: &str,
revision_id: &str,
dest: &Path,
) -> CoreResult<u64> {
let uid = self.resolve_anywhere(uid)?;
let name = uid.to_string();
self.save_revision_for_uid(&uid, revision_id, &name, dest)
}
fn save_revision_for_uid(
pub(crate) fn save_as(
&self,
uid: &NodeUid,
revision_id: &str,
@@ -253,13 +221,18 @@ impl Core {
// A half-written file looks like a successful export to every
// tool that opens it afterwards.
let _ = std::fs::remove_file(dest);
self.log_activity(ActivityKind::Download, name, &error, false);
self.host.log_activity(
ActivityKind::Download,
name.to_string(),
error.to_string(),
false,
);
return Err(error);
}
};
self.log_activity(
self.host.log_activity(
ActivityKind::Download,
name,
name.to_string(),
format!("saved version {revision_id} to {}", dest.display()),
true,
);
+52
View File
@@ -0,0 +1,52 @@
//! The cells that belong to one mount's FUSE session (`SessionCells`).
use super::*;
/// What belongs to one mount's FUSE session rather than to the daemon: whether
/// it is the primary My Files mount, the tree inode it is rooted at, its
/// kernel channel and whether the session is up.
///
/// Every other part of `Core` is shared between the primary mount and its
/// on-demand forks. A fork gets fresh cells from [`SessionCells::fork`].
#[derive(Clone)]
pub(crate) struct SessionCells {
/// False only for a forked on-demand device mount. The synthetic shared
/// directory belongs exclusively to the primary My Files mount.
pub(crate) primary: bool,
/// The tree inode this mount's session is rooted at, set when the session
/// is built ([`ProtonFs::new`]). Each fork has its own cell.
pub(crate) root: Arc<OnceLock<u64>>,
/// This mount's kernel notification channel, for telling the kernel to drop
/// metadata it has cached. Set once the session exists — which is *after*
/// the `Core` it is built from, hence the cell.
///
/// Per mount, not per daemon: each session calls its own root inode 1.
/// [`Core::fork_state`] gives each fork an empty cell of its own. Work that
/// changes the tree for every mount tells every session
/// ([`Core::for_each_mount`]).
pub(crate) notifier: Arc<OnceLock<KernelChannel>>,
/// True only after this mount's FUSE session spawned successfully.
/// Registration happens earlier for the primary drain, so registration
/// alone cannot answer whether the location is mounted.
pub(crate) session_live: Arc<AtomicBool>,
}
impl SessionCells {
pub(crate) fn new() -> Self {
Self {
primary: true,
root: Arc::new(OnceLock::new()),
notifier: Arc::new(OnceLock::new()),
session_live: Arc::new(AtomicBool::new(false)),
}
}
/// Fresh cells for an on-demand fork: not the primary mount, and no root,
/// channel or session until the fork's own session is built.
pub(crate) fn fork(&self) -> Self {
Self {
primary: false,
..Self::new()
}
}
}
+2 -2
View File
@@ -122,7 +122,7 @@ impl Core {
}
pub(super) fn ensure_shared_children(&self, ino: u64) -> Result<(), Errno> {
let online = self.online.load(Ordering::Relaxed);
let online = self.is_online();
let resident = self.state().children.contains_key(&ino);
match shared_listing_plan(
resident,
@@ -235,7 +235,7 @@ impl Core {
drop(st);
self.flush_access_changes();
self.mark_shared_refresh_success(SHARED_WITH_ME_SYNCED_MS);
if let Some(notifier) = self.notifier.get() {
if let Some(notifier) = self.session.notifier.get() {
let _ = notifier.inval_inode(ino);
}
Ok(())
+70 -267
View File
@@ -2,54 +2,62 @@
//! account has received, saved public-link bookmarks, and the reverse view of
//! everything this account shares out.
//!
//! All of it is remote-only state — nothing here touches the inode maps or the
//! content cache, so every method is a round-trip wrapped in the crate error
//! shape the control socket expects.
//! All of it is remote-only state: nothing here changes the tree or the
//! content cache's entries for this account's own files, so every method is a
//! round trip wrapped in the error shape the control socket expects.
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use parking_lot::Mutex;
use pdfs_core::control::{
BookmarkInfo, DirEntry, InvitationInfo, LinkChange, PublicLinkInfo, ShareEntry, ShareEntryKind,
SharedItem,
SharedItem, TransferDirection,
};
use pdfs_core::lockrank::Ranked;
use pdfs_core::{CoreError, CoreResult};
use tracing::debug;
use crate::QUOTA_TTL;
use pdfs_store::cache::ContentCache;
use proton_drive_rs::proton_sdk::crypto::VerificationStatus;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use proton_drive_rs::{MemberRole, NodeKind};
use proton_drive_rs::{MemberRole, Node, NodeKind, ProtonDriveClient};
use tracing::debug;
use proton_drive_rs::Node;
use super::drive::DriveApi;
use super::transfers::{CountingWriter, TransferRegistry};
use super::{State, node_size, parse_uid, public_link_info, role_from_str, role_to_str};
use super::{Core, node_size, parse_uid, public_link_info, role_from_str, role_to_str};
/// The last account quota answer, for `statfs(2)`, and whether a refresh
/// of it is running.
/// Sharing as a service of its own: what this account shares and with whom,
/// its public links, what others share with it, and its saved links.
///
/// Every method takes a node already resolved to its uid. Turning a path or a
/// wire-format uid into one, and the check that the node is this daemon's to
/// share, are the caller's (the control socket's), so this holds only the
/// handles it calls: the client, Drive, the content cache and the transfer
/// list for opening a shared file, and a read of the tree for paths.
#[derive(Clone)]
pub(crate) struct QuotaCache {
/// Last account quota answer and when it was learned, for `statfs(2)`.
///
/// `df` and the free-space preflight of every file manager and installer ask
/// for this, and the answer costs a round trip — so it is served from here
/// for [`QUOTA_TTL`] and refreshed on a worker afterwards. Total account
/// storage moves slowly enough that a minute-old number is a better answer
/// than either a stall or the zeroes the default implementation returns.
pub(crate) quota: Arc<Mutex<Option<(std::time::Instant, i64, i64)>>>,
/// Set while a `statfs` is refreshing [`Core::quota`], so the others serve
/// the last figures instead of each holding a worker on the same request.
pub(crate) quota_refreshing: Arc<AtomicBool>,
pub(crate) struct Sharing {
client: ProtonDriveClient,
drive: Arc<dyn DriveApi>,
rt: tokio::runtime::Handle,
cache: Arc<ContentCache>,
transfers: Arc<TransferRegistry>,
state: Arc<Ranked<State>>,
}
impl QuotaCache {
pub(crate) fn new() -> Self {
impl Sharing {
pub(crate) fn new(
client: ProtonDriveClient,
drive: Arc<dyn DriveApi>,
rt: tokio::runtime::Handle,
cache: Arc<ContentCache>,
transfers: Arc<TransferRegistry>,
state: Arc<Ranked<State>>,
) -> Self {
Self {
quota: Arc::new(Mutex::new(None)),
quota_refreshing: Arc::new(AtomicBool::new(false)),
client,
drive,
rt,
cache,
transfers,
state,
}
}
}
@@ -62,7 +70,7 @@ impl QuotaCache {
/// offer path-keyed actions on it. The local-state flags (`pinned`, `cached`)
/// stay false: they describe content this account owns a local copy policy for,
/// which a share on someone else's volume is not.
fn shared_entry_of(core: &Core, n: Node) -> DirEntry {
fn shared_entry_of(sharing: &Sharing, n: Node) -> DirEntry {
let is_dir = n.is_folder();
let size = match &n.kind {
NodeKind::File {
@@ -99,7 +107,7 @@ fn shared_entry_of(core: &Core, n: Node) -> DirEntry {
pinned: false,
pinned_by_folder: false,
cached: false,
path: core.rel_path_for_uid(&n.uid).unwrap_or_default(),
path: sharing.rel_path_for_uid(&n.uid).unwrap_or_default(),
uid: n.uid.to_string(),
role,
shared_by,
@@ -112,35 +120,12 @@ fn shared_entry_of(core: &Core, n: Node) -> DirEntry {
}
}
impl Core {
impl Sharing {
// ---- sharing a node ---------------------------------------------------
/// Invite Proton and/or external emails to the node at `rel` at `role`.
/// Invite Proton and/or external emails to the node `uid` at `role`.
/// Returns `(proton_invited, external_invited)`.
pub(crate) fn share_node(
&self,
rel: &Path,
emails: &[String],
role: &str,
message: Option<&str>,
) -> CoreResult<(usize, usize)> {
let (_ino, uid) = self.resolve(rel)?;
self.share_node_for_uid(&uid, emails, role, message)
}
/// [`Core::share_node`] for a node addressed through any daemon location.
pub(crate) fn share_node_by_uid(
&self,
uid: &str,
emails: &[String],
role: &str,
message: Option<&str>,
) -> CoreResult<(usize, usize)> {
let uid = self.resolve_shareable(uid)?;
self.share_node_for_uid(&uid, emails, role, message)
}
fn share_node_for_uid(
&self,
uid: &NodeUid,
emails: &[String],
@@ -155,25 +140,8 @@ impl Core {
.map_err(|e| CoreError::from_api(&e, "share"))
}
/// List the members, pending invitations and public link of the node at `rel`.
/// List the members, pending invitations and public link of the node `uid`.
pub(crate) fn list_share(
&self,
rel: &Path,
) -> CoreResult<(Vec<ShareEntry>, Option<PublicLinkInfo>)> {
let (_ino, uid) = self.resolve(rel)?;
self.list_share_for_uid(&uid)
}
/// [`Core::list_share`] for a node addressed through any daemon location.
pub(crate) fn list_share_by_uid(
&self,
uid: &str,
) -> CoreResult<(Vec<ShareEntry>, Option<PublicLinkInfo>)> {
let uid = self.resolve_shareable(uid)?;
self.list_share_for_uid(&uid)
}
fn list_share_for_uid(
&self,
uid: &NodeUid,
) -> CoreResult<(Vec<ShareEntry>, Option<PublicLinkInfo>)> {
@@ -225,32 +193,8 @@ impl Core {
}
/// Change the role of a member or pending Proton invitation on the node at
/// `rel`. External invitations have no role-update endpoint.
/// `uid`. External invitations have no role-update endpoint.
pub(crate) fn update_share_role(
&self,
rel: &Path,
id: &str,
kind: ShareEntryKind,
role: &str,
) -> CoreResult<()> {
let (_ino, uid) = self.resolve(rel)?;
self.update_share_role_for_uid(&uid, id, kind, role)
}
/// [`Core::update_share_role`] for a node addressed through any daemon
/// location.
pub(crate) fn update_share_role_by_uid(
&self,
uid: &str,
id: &str,
kind: ShareEntryKind,
role: &str,
) -> CoreResult<()> {
let uid = self.resolve_shareable(uid)?;
self.update_share_role_for_uid(&uid, id, kind, role)
}
fn update_share_role_for_uid(
&self,
uid: &NodeUid,
id: &str,
@@ -290,30 +234,8 @@ impl Core {
}
/// Remove a member, pending Proton invite, or external invite from the node
/// at `rel`.
/// at `uid`.
pub(crate) fn remove_share_entry(
&self,
rel: &Path,
id: &str,
kind: ShareEntryKind,
) -> CoreResult<()> {
let (_ino, uid) = self.resolve(rel)?;
self.remove_share_entry_for_uid(&uid, id, kind)
}
/// [`Core::remove_share_entry`] for a node addressed through any daemon
/// location.
pub(crate) fn remove_share_entry_by_uid(
&self,
uid: &str,
id: &str,
kind: ShareEntryKind,
) -> CoreResult<()> {
let uid = self.resolve_shareable(uid)?;
self.remove_share_entry_for_uid(&uid, id, kind)
}
fn remove_share_entry_for_uid(
&self,
uid: &NodeUid,
id: &str,
@@ -359,32 +281,8 @@ impl Core {
}
}
/// Create a public link on the node at `rel`, returning its info (with URL).
/// Create a public link on the node `uid`, returning its info (with URL).
pub(crate) fn create_public_link(
&self,
rel: &Path,
role: &str,
password: Option<&str>,
expires: Option<i64>,
) -> CoreResult<PublicLinkInfo> {
let (_ino, uid) = self.resolve(rel)?;
self.create_public_link_for_uid(&uid, role, password, expires)
}
/// [`Core::create_public_link`] for a node addressed through any daemon
/// location.
pub(crate) fn create_public_link_by_uid(
&self,
uid: &str,
role: &str,
password: Option<&str>,
expires: Option<i64>,
) -> CoreResult<PublicLinkInfo> {
let uid = self.resolve_shareable(uid)?;
self.create_public_link_for_uid(&uid, role, password, expires)
}
fn create_public_link_for_uid(
&self,
uid: &NodeUid,
role: &str,
@@ -399,36 +297,11 @@ impl Core {
Ok(public_link_info(link))
}
/// Change the public link `id` on the node at `rel`, keeping its URL.
pub(crate) fn update_public_link(
&self,
rel: &Path,
id: &str,
role: Option<&str>,
password: LinkChange<String>,
expires: LinkChange<i64>,
) -> CoreResult<PublicLinkInfo> {
let (_ino, uid) = self.resolve(rel)?;
self.update_public_link_for_uid(&uid, id, role, password, expires)
}
/// [`Core::update_public_link`] for a node addressed through any daemon
/// location.
pub(crate) fn update_public_link_by_uid(
&self,
uid: &str,
id: &str,
role: Option<&str>,
password: LinkChange<String>,
expires: LinkChange<i64>,
) -> CoreResult<PublicLinkInfo> {
let uid = self.resolve_shareable(uid)?;
self.update_public_link_for_uid(&uid, id, role, password, expires)
}
/// Change the public link `id` on the node `uid`, keeping its URL.
///
/// The SDK sets all three options on every update, so each `Keep` is
/// filled in from the link as it stands.
fn update_public_link_for_uid(
pub(crate) fn update_public_link(
&self,
uid: &NodeUid,
id: &str,
@@ -482,20 +355,8 @@ impl Core {
Ok(public_link_info(link))
}
/// Remove the public link `id` from the node at `rel`.
pub(crate) fn remove_public_link(&self, rel: &Path, id: &str) -> CoreResult<()> {
let (_ino, uid) = self.resolve(rel)?;
self.remove_public_link_for_uid(&uid, id)
}
/// [`Core::remove_public_link`] for a node addressed through any daemon
/// location.
pub(crate) fn remove_public_link_by_uid(&self, uid: &str, id: &str) -> CoreResult<()> {
let uid = self.resolve_shareable(uid)?;
self.remove_public_link_for_uid(&uid, id)
}
fn remove_public_link_for_uid(&self, uid: &NodeUid, id: &str) -> CoreResult<()> {
/// Remove the public link `id` from the node `uid`.
pub(crate) fn remove_public_link(&self, uid: &NodeUid, id: &str) -> CoreResult<()> {
let link = self
.rt
.block_on(self.client.get_public_link(uid))
@@ -507,25 +368,15 @@ impl Core {
.map_err(|e| CoreError::from_api(&e, "remove public link"))
}
/// Stop sharing the node at `rel`: remove its public link, then every
/// Stop sharing the node `uid`: remove its public link, then every
/// external invitation, Proton invitation and member. The SDK has no call
/// that deletes a share outright, so this composes the per-entry ones.
pub(crate) fn stop_sharing(&self, rel: &Path) -> CoreResult<StopSharingOutcome> {
let (_ino, uid) = self.resolve(rel)?;
self.stop_sharing_for_uid(&uid)
}
/// [`Core::stop_sharing`] for a node addressed through any daemon location.
pub(crate) fn stop_sharing_by_uid(&self, uid: &str) -> CoreResult<StopSharingOutcome> {
let uid = self.resolve_shareable(uid)?;
self.stop_sharing_for_uid(&uid)
}
///
/// Each step runs even when an earlier one failed, so a single stuck
/// member does not leave the public link up. The link goes first: it is the
/// widest exposure. Only a failure to list what is there fails the whole
/// request; a failed removal is counted in the outcome.
fn stop_sharing_for_uid(&self, uid: &NodeUid) -> CoreResult<StopSharingOutcome> {
pub(crate) fn stop_sharing(&self, uid: &NodeUid) -> CoreResult<StopSharingOutcome> {
let mut outcome = StopSharingOutcome::default();
let link = self
.rt
@@ -637,9 +488,17 @@ impl Core {
if let Some(p) = self.cache.cached_content_path(&uid, mtime, size) {
return Ok(p);
}
let bytes = self
.download_file_tracked(&uid, &node.name, size)
let guard = self.transfers.begin(
&node.name,
uid.to_string(),
TransferDirection::Download,
size,
);
let mut out = CountingWriter::new(Vec::with_capacity(size as usize), &guard);
self.rt
.block_on(self.drive.download_file_to(&uid, &mut out))
.map_err(|e| CoreError::from_api(&e, "download"))?;
let bytes = out.into_inner();
self.cache
.store(&uid, mtime, size, &bytes)
.map_err(|e| CoreError::internal(format!("cache store: {e}")))?;
@@ -721,62 +580,6 @@ impl Core {
.map_err(|e| CoreError::from_api(&e, "delete bookmark"))
}
// ---- account ----------------------------------------------------------
/// Total account storage usage `(max_space, used_space)` in bytes, across all
/// Proton products (not Drive-only). A remote round-trip; nothing here is
/// cached.
pub(crate) fn account_quota(&self) -> CoreResult<(i64, i64)> {
let q = self.block_on_bounded(self.drive.quota()).map_err(|e| {
self.lost_link(&e, "account quota");
CoreError::from_api(&e, "account quota")
})?;
*self.quota_cache.quota.lock() =
Some((std::time::Instant::now(), q.max_space, q.used_space));
Ok((q.max_space, q.used_space))
}
/// The account quota as `statfs(2)` needs it: cached for [`QUOTA_TTL`],
/// refetched after that, and `None` when there is no usable answer at all —
/// offline with nothing cached.
///
/// Never blocks on the network for a *fresh* value when a recent one exists,
/// because the callers are `df` and every "is there room?" preflight, and a
/// stale byte count is worth more to them than a stalled syscall. Offline,
/// the last known figures keep being served rather than degrading to zero.
pub(crate) fn account_quota_cached(&self) -> Option<(i64, i64)> {
if let Some((at, max_space, used_space)) = *self.quota_cache.quota.lock()
&& at.elapsed() < QUOTA_TTL
{
return Some((max_space, used_space));
}
let last = || {
self.quota_cache
.quota
.lock()
.map(|(_, max, used)| (max, used))
};
if !self.is_online()
|| self
.quota_cache
.quota_refreshing
.swap(true, std::sync::atomic::Ordering::AcqRel)
{
return last();
}
let refreshed = self.account_quota();
self.quota_cache
.quota_refreshing
.store(false, std::sync::atomic::Ordering::Release);
match refreshed {
Ok(q) => Some(q),
Err(error) => {
debug!(%error, "account quota refresh failed; serving the last known figures");
last()
}
}
}
// ---- shared by me -----------------------------------------------------
/// List the nodes I have shared with others, each with a summary of its share
@@ -846,15 +649,15 @@ impl Core {
/// tree, by walking parent inodes to the root. `None` when the node has never
/// been seen through the mount (e.g. shared but not browsed to this session) —
/// the caller then leaves the path empty.
pub(crate) fn rel_path_for_uid(&self, uid: &NodeUid) -> Option<String> {
fn rel_path_for_uid(&self, uid: &NodeUid) -> Option<String> {
// Relative to whichever root the node sits under: a node browsed
// through a sync folder is under that fork's root, not My Files
// (`docs/BUGS.md` B74).
walk_to_root(&self.state(), uid)
walk_to_root(&self.state.lock(), uid)
}
}
/// What [`Core::stop_sharing`] managed to remove.
/// What [`Sharing::stop_sharing`] managed to remove.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct StopSharingOutcome {
/// Entries removed (the link, invitations and members alike).
+1 -1
View File
@@ -154,7 +154,7 @@ impl Core {
}
let roots = self.search_roots();
let online = self.online.load(std::sync::atomic::Ordering::Relaxed);
let online = self.is_online();
for node in &nodes {
if node.trashed || node.is_folder() {
continue;
+1 -1
View File
@@ -38,7 +38,7 @@ impl SyncHost for Core {
}
fn upload_thumbnails(&self, path: &Path, name: &str) -> Vec<Thumbnail> {
Core::upload_thumbnails(self, path, name)
self.photos().upload_thumbnails(path, name)
}
}
+107 -38
View File
@@ -2,6 +2,7 @@
//! listing in the background, restoring from it, deleting from it for good.
use super::*;
use crate::listing::listing_stale;
/// Whether a trash refresh is running, and the wake-up for requests waiting
/// on its progress.
@@ -13,7 +14,7 @@ pub(crate) struct TrashState {
/// Fires whenever a trash refresh persists a batch or finishes, so a
/// `ListTrash` request waiting on a first-ever refresh wakes on progress
/// instead of polling or blocking for the whole run. See
/// [`Core::await_trash_refresh`].
/// [`Trash::await_trash_refresh`].
pub(crate) trash_progress: Arc<tokio::sync::Notify>,
}
@@ -26,7 +27,75 @@ impl TrashState {
}
}
/// The Drive trash as a service: listing it, refreshing that listing, and
/// restoring or deleting from it.
///
/// It holds only the handles it calls, and reaches the mounted trees through
/// [`TrashHost`]. [`Core::trash`] builds one on demand with the daemon as its
/// host. A clone shares everything, which is how a refresh moves onto a
/// background task.
#[derive(Clone)]
pub(crate) struct Trash {
drive: Arc<dyn DriveApi>,
rt: tokio::runtime::Handle,
db: Arc<Db>,
events: Arc<events::EventHub>,
services: pdfs_core::lifecycle::ServiceBoard,
writes: writes::WriteState,
jobs: TrashState,
host: Arc<dyn TrashHost>,
}
/// What the trash needs from the mounted trees.
pub(crate) trait TrashHost: Send + Sync {
/// Re-enumerate these folders on next access, in every mount, because a
/// restored node reappears under one of them.
fn invalidate_listings_of(&self, parents: &[NodeUid]);
/// Forget nodes the server no longer has, in every mount, with any cached
/// content they own.
fn drop_local(&self, uids: &[NodeUid]);
}
impl TrashHost for Core {
fn invalidate_listings_of(&self, parents: &[NodeUid]) {
// Keyed by uid, so it applies to every mount: a restored node reappears
// in whichever mounts show its parent, not only the primary one.
self.for_each_state(|st| {
for parent in parents {
if let Some(&ino) = st.by_uid.get(parent) {
st.invalidate_listing(ino);
}
}
});
}
fn drop_local(&self, uids: &[NodeUid]) {
Core::drop_local(self, uids);
}
}
impl Core {
/// [`Trash::invalidate_trash`], without building the service.
pub(super) fn invalidate_trash(&self) {
invalidate_trash(&self.db);
}
/// The trash service, with this daemon as its host.
pub(crate) fn trash(&self) -> Trash {
Trash {
drive: self.drive.clone(),
rt: self.rt.clone(),
db: self.db.clone(),
events: self.events.clone(),
services: self.services.clone(),
writes: self.writes.clone(),
jobs: self.trash_jobs.clone(),
host: Arc::new(self.clone()),
}
}
}
impl Trash {
/// List the account's trash, from the DB. Trashed nodes are outside the
/// mounted tree — the FUSE side forgot them when they were trashed — so the
/// listing is persisted in its own table rather than derived from `State`, and
@@ -36,7 +105,7 @@ impl Core {
/// Stale-while-revalidate, like the photos timeline: a persisted listing comes
/// back at DB speed and is refreshed in the background past [`TRASH_TTL`].
/// Our own trash mutations invalidate it outright (see
/// [`Core::invalidate_trash`]), so the TTL only covers changes made elsewhere.
/// [`Trash::invalidate_trash`]), so the TTL only covers changes made elsewhere.
///
/// The refresh always runs *off* the request: a never-fetched trash waits for
/// it, but only for [`TRASH_FIRST_WAIT`], and then answers with the batches
@@ -44,9 +113,9 @@ impl Core {
/// made a large trash unlistable — the refresh outran the front-end's read
/// timeout, the user asked again, and each attempt left another full refresh
/// grinding in the daemon (`docs/BUGS.md` B72).
pub(super) fn list_trash(&self) -> CoreResult<Vec<DirEntry>> {
pub(crate) fn list_trash(&self) -> CoreResult<Vec<DirEntry>> {
let never_fetched = self.db.state_i64(TRASH_SYNCED_MS).ok().flatten().is_none();
if never_fetched || self.listing_stale(TRASH_SYNCED_MS, TRASH_TTL) {
if never_fetched || listing_stale(&self.db, TRASH_SYNCED_MS, TRASH_TTL) {
self.spawn_trash_refresh();
}
if never_fetched {
@@ -99,7 +168,7 @@ impl Core {
/// What a trashed folder holds: its children on the server, and the
/// stored trash entries trashed inside it before it went.
pub(super) fn list_trashed_folder(&self, uid: &str) -> CoreResult<Vec<DirEntry>> {
pub(crate) fn list_trashed_folder(&self, uid: &str) -> CoreResult<Vec<DirEntry>> {
let folder =
parse_uid(uid).ok_or_else(|| CoreError::invalid(format!("invalid uid: {uid}")))?;
let children = self
@@ -177,7 +246,7 @@ impl Core {
/// [`TRASH_MATERIALIZE_CHUNK`] is stored as it lands, so a large trash
/// fills the page while it loads. Rows the server no longer lists go once
/// the whole listing is in, never earlier.
pub(super) async fn refresh_trash(&self) -> CoreResult<()> {
pub(crate) async fn refresh_trash(&self) -> CoreResult<()> {
let started = Instant::now();
let uids = within_trash_call("enumerate trash", self.drive.enumerate_trash_node_uids())
.await?
@@ -200,7 +269,7 @@ impl Core {
let listed: HashSet<String> = uids.iter().map(ToString::to_string).collect();
let removed = self.db.trash_retain(&listed).map_err(CoreError::from)?;
if removed > 0 {
self.trash.trash_progress.notify_waiters();
self.jobs.trash_progress.notify_waiters();
}
let missing: Vec<NodeUid> = uids
.into_iter()
@@ -235,7 +304,7 @@ impl Core {
.collect();
materialized += items.len();
self.db.trash_upsert(&items).map_err(CoreError::from)?;
self.trash.trash_progress.notify_waiters();
self.jobs.trash_progress.notify_waiters();
self.events.publish(&[Topic::Trash]);
debug!(
materialized,
@@ -258,44 +327,44 @@ impl Core {
}
/// Refresh the trash off the request path. At most one refresh at a time —
/// including the one a first-ever [`Core::list_trash`] waits on, so a burst
/// including the one a first-ever [`Trash::list_trash`] waits on, so a burst
/// of requests against an unfetched trash joins one refresh instead of
/// starting one apiece.
pub(super) fn spawn_trash_refresh(&self) {
if self.trash.trash_refreshing.swap(true, Ordering::SeqCst) {
pub(crate) fn spawn_trash_refresh(&self) {
if self.jobs.trash_refreshing.swap(true, Ordering::SeqCst) {
return;
}
let core = self.clone();
let this = self.clone();
self.services
.spawn_task_job(&self.rt, "pdfs-trash-refresh", async move {
let refreshed = core.refresh_trash().await;
core.trash.trash_refreshing.store(false, Ordering::SeqCst);
let refreshed = this.refresh_trash().await;
this.jobs.trash_refreshing.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => core.events.publish(&[Topic::Trash]),
Ok(_) => this.events.publish(&[Topic::Trash]),
Err(e) => warn!(error = %e, "background trash refresh failed"),
}
// After the flag, so a waiter that wakes on this sees it cleared.
core.trash.trash_progress.notify_waiters();
this.jobs.trash_progress.notify_waiters();
});
}
/// Wait for the in-flight trash refresh to make progress, for at most
/// `budget`. Returns early when it finishes; never cancels it — the refresh
/// is a detached task, so giving up here costs the work nothing.
pub(super) fn await_trash_refresh(&self, budget: Duration) {
pub(crate) fn await_trash_refresh(&self, budget: Duration) {
let deadline = Instant::now() + budget;
self.rt.block_on(async {
while self.trash.trash_refreshing.load(Ordering::SeqCst) {
while self.jobs.trash_refreshing.load(Ordering::SeqCst) {
let Some(left) = deadline.checked_duration_since(Instant::now()) else {
break;
};
let notified = self.trash.trash_progress.notified();
let notified = self.jobs.trash_progress.notified();
tokio::pin!(notified);
// Register before re-checking the flag: a refresh that finishes
// in between must not leave us waiting for a notify that has
// already fired.
notified.as_mut().enable();
if !self.trash.trash_refreshing.load(Ordering::SeqCst) {
if !self.jobs.trash_refreshing.load(Ordering::SeqCst) {
break;
}
if tokio::time::timeout(left, notified).await.is_err() {
@@ -313,8 +382,8 @@ impl Core {
/// trash ourselves. The next Trash page then *waits* for a fresh listing
/// rather than painting one from before the mutation — the user just made the
/// change and is about to look straight at it.
pub(super) fn invalidate_trash(&self) {
let _ = self.db.clear_state(TRASH_SYNCED_MS);
pub(crate) fn invalidate_trash(&self) {
invalidate_trash(&self.db);
}
/// Restore trashed nodes to the folders they were trashed from, together
@@ -335,8 +404,8 @@ impl Core {
/// The destination parents are read *before* the restore — a restored node
/// reappears in a listing the daemon may already have cached, so each one is
/// invalidated and re-enumerated on next access.
pub(super) fn restore(&self, uids: &[String]) -> CoreResult<usize> {
let requested = Self::parse_uids(uids)?;
pub(crate) fn restore(&self, uids: &[String]) -> CoreResult<usize> {
let requested = Core::parse_uids(uids)?;
// A listing we could not read is not a reason to refuse the restore: it
// only costs the expansion, and the requested nodes still go back.
let relations = self.db.trash_parents().unwrap_or_default();
@@ -379,7 +448,7 @@ impl Core {
let (uid, outcome) = item?;
match outcome {
Ok(()) => {
self.hidden.lock().remove(&uid);
self.writes.unhide(&uid);
restored.push(uid);
}
Err(e) => {
@@ -399,13 +468,7 @@ impl Core {
}
// Keyed by uid, so it applies to every mount: a restored node reappears
// in whichever mounts show its parent, not only the primary one.
self.for_each_state(|st| {
for parent in &parents {
if let Some(&ino) = st.by_uid.get(parent) {
st.invalidate_listing(ino);
}
}
});
self.host.invalidate_listings_of(&parents);
let back: Vec<String> = restored.iter().map(ToString::to_string).collect();
let _ = self.db.trash_remove(&back);
self.invalidate_trash();
@@ -414,8 +477,8 @@ impl Core {
/// Permanently delete trashed nodes. Irreversible on the server; locally it
/// drops any metadata and cached content the node still owns.
pub(super) fn delete_forever(&self, uids: &[String]) -> CoreResult<usize> {
let parsed = Self::parse_uids(uids)?;
pub(crate) fn delete_forever(&self, uids: &[String]) -> CoreResult<usize> {
let parsed = Core::parse_uids(uids)?;
// Streamed, and each node's local state is dropped as its batch lands.
// A permanent delete is irreversible, so the useful property is that a
// daemon interrupted mid-batch has already forgotten exactly the nodes
@@ -430,7 +493,7 @@ impl Core {
let (uid, outcome) = item?;
match outcome {
Ok(()) => {
self.drop_local(std::slice::from_ref(&uid));
self.host.drop_local(std::slice::from_ref(&uid));
gone.push(uid.to_string());
deleted += 1;
}
@@ -461,7 +524,7 @@ impl Core {
/// is what kept the delete from ever being sent (`docs/BUGS.md` B293).
/// The stored listing is cleared at once, and the server is asked again
/// after [`TRASH_TTL`], so anything it still holds then shows up again.
pub(super) fn empty_trash(&self) -> CoreResult<usize> {
pub(crate) fn empty_trash(&self) -> CoreResult<usize> {
let uids: Vec<String> = self
.db
.trash_seen()
@@ -472,7 +535,7 @@ impl Core {
.block_on(within_trash_call("empty trash", self.drive.empty_trash()))?
.map_err(|e| CoreError::from_api(&e, "empty trash"))?;
let parsed: Vec<NodeUid> = uids.iter().filter_map(|uid| parse_uid(uid)).collect();
self.drop_local(&parsed);
self.host.drop_local(&parsed);
let _ = self.db.trash_replace(&[]);
let _ = self.db.set_state_i64(TRASH_SYNCED_MS, now_ms());
self.events.publish(&[Topic::Trash]);
@@ -480,7 +543,7 @@ impl Core {
}
}
/// An entry inside a trashed folder, for [`Core::list_trashed_folder`].
/// An entry inside a trashed folder, for [`Trash::list_trashed_folder`].
pub(super) fn trashed_entry(
uid: String,
name: String,
@@ -619,3 +682,9 @@ pub(super) fn expand_restore(
waves.retain(|wave| !wave.is_empty());
waves
}
/// Mark the stored trash listing stale, so the next listing waits for a
/// fresh one.
fn invalidate_trash(db: &Db) {
let _ = db.clear_state(TRASH_SYNCED_MS);
}
+1
View File
@@ -70,6 +70,7 @@ async fn run_uploads(
));
}
let thumbnails = core
.photos()
.upload_thumbnails_async(t.path.clone(), t.name.clone())
.await;
match core
+110
View File
@@ -0,0 +1,110 @@
//! What the mount accepted and has not yet sent to Drive (`WriteState`).
use super::*;
/// The write-back's state: writes accepted from the kernel and not yet sent,
/// nodes removed here that a stale listing may still return, and the changes
/// this daemon made that Drive's event feed will echo back.
///
/// The drain, the queue and recovery own it. Everything else, the read path,
/// listings, the pin keeper and the event feed, asks through the methods
/// below instead of taking its locks.
#[derive(Clone)]
pub(crate) struct WriteState {
/// Writes accepted from the kernel but not yet uploaded, keyed by node.
/// The in-memory face of the `pending_op` table, from
/// which it is rebuilt on mount.
///
/// Two things read it: [`Core::read_range`], because until the op drains the
/// staged blob *is* the file's content and the remote still holds the old
/// revision; and the drain worker, which performs the uploads.
pub(crate) pending: Arc<Mutex<HashMap<NodeUid, PendingRevision>>>,
/// Nodes removed through this daemon which a briefly stale remote listing
/// may still return. Uids are not reused; an explicit restore clears one.
hidden: Arc<Mutex<HashSet<NodeUid>>>,
/// Nodes this daemon changed on the remote itself, and how many echoes of
/// those changes the event feed still owes us.
///
/// The feed replays our own writes back at us seconds later, and a
/// `NodeUpdated` carries no revision id — nothing in it distinguishes "another
/// device changed this file" from "you changed this file". Treating the echo
/// as foreign is not free: it evicts the content blob we just uploaded, so the
/// next read re-downloads a revision the API may not be serving yet. That is
/// how a SQLite database written on the mount came back `malformed`, and how a
/// mount doing bulk uploads spent its time re-fetching its own bytes.
///
/// So the first event for a node we changed ourselves, within
/// [`SELF_CHANGE_TTL_MS`], is consumed rather than applied: the tree already
/// holds what that event describes, because [`Core::refresh_after_upload`] put
/// it there. Anything beyond that applies normally, which bounds the staleness
/// a genuine remote change can suffer to one event.
///
/// Shared across forks like `pending`: the drain that records the change and
/// the event task that consumes the echo are both per-daemon.
self_changes: Arc<Mutex<HashMap<NodeUid, echoes::SelfChange>>>,
}
impl WriteState {
pub(crate) fn new() -> Self {
Self {
pending: Arc::new(Mutex::new(HashMap::new())),
hidden: Arc::new(Mutex::new(HashSet::new())),
self_changes: Arc::new(Mutex::new(HashMap::new())),
}
}
/// The write queued for `uid`, if any: its staged blob is the file's
/// content until the drain sends it.
pub(crate) fn queued(&self, uid: &NodeUid) -> Option<PendingRevision> {
self.pending.lock().get(uid).cloned()
}
/// Whether a write for `uid` is queued and not yet sent. A remote change
/// to such a node is not applied over it.
pub(crate) fn is_queued(&self, uid: &NodeUid) -> bool {
self.pending.lock().contains_key(uid)
}
/// The size the queued write for `uid` gives the file, if one is queued.
pub(crate) fn queued_len(&self, uid: &NodeUid) -> Option<u64> {
self.pending.lock().get(uid).map(|queued| queued.meta.len)
}
/// The size each queued write gives its file. Empty when nothing is
/// queued.
pub(crate) fn queued_sizes(&self) -> HashMap<NodeUid, u64> {
self.pending
.lock()
.iter()
.map(|(uid, queued)| (uid.clone(), queued.meta.len))
.collect()
}
/// The nodes removed here that a listing must leave out, even if Drive
/// still returns them.
pub(crate) fn hidden(&self) -> HashSet<NodeUid> {
self.hidden.lock().clone()
}
/// Leave `uid` out of listings from now on: it was removed here.
pub(crate) fn hide(&self, uid: &NodeUid) {
self.hidden.lock().insert(uid.clone());
}
/// List `uid` again: it was restored or put back.
pub(crate) fn unhide(&self, uid: &NodeUid) {
self.hidden.lock().remove(uid);
}
/// Record that this daemon just changed `uid` on Drive, so the event
/// feed's echo of the change is recognised (see [`echoes`]).
pub(crate) fn note_echo(&self, uid: &NodeUid, now_ms: i64) {
echoes::note_self_change(&mut self.self_changes.lock(), uid, now_ms);
}
/// Claim one outstanding echo for `uid`: whether the event being applied
/// is one this daemon caused.
pub(crate) fn take_echo(&self, uid: &NodeUid, now_ms: i64) -> bool {
echoes::take_self_change(&mut self.self_changes.lock(), uid, now_ms)
}
}
+47 -4
View File
@@ -750,11 +750,54 @@ Step 3 so far: the daemon's long-lived threads and async loops start and stop th
`Services` set (§9).
`Core`'s fields are grouped by owner, each group a struct in the module that owns it:
`photos::PhotoJobs`, `drain::DrainState`, `reads::ReadState`, `sizes::SizeState`,
`trash::TrashState`, `shared::SharedState`, `sharing::QuotaCache` and `sweep::SweepState`.
`trash::TrashState`, `shared::SharedState`, `quota::QuotaCache`, `pause::SyncPause` and
`sweep::SweepState`.
`Core`'s methods are split by area out of `lib.rs` into their own modules. The daemon's run loop
moved out of `pdfs-cli` into `pdfs-daemon`, which is where the services will be built. What is left in `Core`
is shared by several owners (the tree, the database, the queue's `pending` map) and needs ports
before it can move.
moved out of `pdfs-cli` into `pdfs-daemon`, which is where the services will be built.
State that several owners share sits behind a narrow interface of its own:
- `writes::WriteState` holds the write-back's queued writes, the nodes removed here and the echoes
the event feed owes. The queue, the drain and recovery own it. The read path, listings, the pin
keeper and the event feed ask it whether a node has a queued write, what size it gives the file,
and which nodes to leave out. They do not take its locks.
- `session::SessionCells` holds what belongs to one mount's FUSE session: whether it is the
primary mount, its root inode, its kernel channel and whether it is up. An on-demand fork gets
fresh cells from `SessionCells::fork`, and shares the rest of `Core`.
- `link::Link` holds whether Drive answers, next to when the link went down. Code reads it through
`Core::is_online`.
Some areas are services of their own rather than methods on `Core`. `sharing::Sharing` holds
only the handles it calls (the client, Drive, the content cache, the transfer list and a read of
the tree), and every one of its methods takes a node already resolved to its uid. Like the sync
engine's `Syncer`, it can be built and tested without the rest of the daemon.
`photos::Photos` is the timeline, albums, thumbnails, the Google Photos import and the redate
job. It holds the handles it calls and the `PhotoJobs` state, and reaches the filesystem through a
`PhotosHost` port with three methods: list a folder, for the recursive thumbnail build; note a
change made here, so its echo in the event feed is not taken for a remote edit; and add an entry
to the activity log. `Core::photos` builds one on demand with the daemon as its
host, as `Core::syncer` does for the sync engine. Trashing photos stays on `Core`, because it
checks write authority against the tree and drops open readers.
`trash::Trash` lists the Drive trash, refreshes that listing, and restores or deletes from it. Its
`TrashHost` port has two methods, both of which reach every mount: re-enumerate the folders a
restored node comes back into, and forget nodes the server no longer has. `Core::trash` builds it
on demand.
`revisions::Revisions` lists, restores, deletes and saves a file's earlier revisions. Like
`Sharing`, it only takes a node already resolved to its uid. Its `RevisionsHost` port checks that
the node may be written, drops what describes the old content (cached blocks and open readers)
and fetches it again if it is kept offline, and adds an activity entry.
The control socket answers each area's requests in a module of its own under `control/`:
sharing, Photos, synced folders and devices, revisions, and the trash and cache. Each module
exports a pattern macro naming its requests, and the main match hands them over in one arm, so
the compiler still checks that every request has an answer. A module turns a path or a uid into a
node once, then asks the service.
What is left in `Core` is the tree, the database, the cache and the Drive client, which most
owners use, plus single fields that belong to one module each.
Steps 0 to 3 are 4.0.0. Steps 4 to 6 follow in 4.x, one service at a time. Out of scope for
now: an encrypted local vault (full-disk encryption covers a copied disk today), Windows and
+6
View File
@@ -4801,6 +4801,12 @@ which survives the landing, and queues the write against the real uid when the n
**Test:** the unit tests `a_landed_placeholder_keeps_its_lid` and
`an_inode_gives_back_the_lid_it_was_made_from`. Seed 1 of three-clients passes.
**Seen again:** 2026-11-26, once in a full local sim run, in
`a_move_blocked_by_trash_can_be_retried_after_restore`. Its first write, of a new file in a new
folder, logged "access changed before the write could be queued" for `local~14`, and the file
read back empty. The next five runs of that test passed, and so did five on main. The race left
is somewhere other than the lookup by local id that the fix added.
---
### B138 — A file created where another is leaving lands as a conflict copy