Compare commits

..
Author SHA1 Message Date
nvrl 1f4b1ce4b9 Merge pull request #164 from narrrl/refactor/single-owners
refactor(fuse): make sharing a service, split the control socket by area, give the pause an owner
2026-11-26 21:10:47 +01:00
23 changed files with 574 additions and 724 deletions

No files matched your search

@@ -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
//! ([`super`]): a listing already on disk is served immediately and
//! ([`crate::photos`]): 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,16 +23,15 @@ use proton_drive_rs::NodeKind;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use tracing::warn;
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,
use super::{
ALBUM_SYNCED_PREFIX, ALBUMS_SYNCED_MS, Core, PHOTOS_AVAILABLE, TIMELINE_ENRICH_CHUNK,
TIMELINE_TTL, link, now_ms, parse_uid,
};
impl Photos {
impl Core {
/// The album listing, served from disk and refreshed behind the caller when
/// stale. `None` means the account has no photos volume — the same signal
/// [`Photos::photos_timeline`] gives.
/// [`Core::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
@@ -45,13 +44,13 @@ impl Photos {
// 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 && !listing_stale(&self.db, ALBUMS_SYNCED_MS, TIMELINE_TTL) {
if known_empty && !self.listing_stale(ALBUMS_SYNCED_MS, TIMELINE_TTL) {
return Ok(None);
}
if !self.rt.block_on(self.refresh_albums())? {
return Ok(None);
}
} else if listing_stale(&self.db, ALBUMS_SYNCED_MS, TIMELINE_TTL) {
} else if self.listing_stale(ALBUMS_SYNCED_MS, TIMELINE_TTL) {
self.spawn_albums_refresh();
}
@@ -67,7 +66,7 @@ impl Photos {
.db
.photo_projection_generation()
.map_err(CoreError::from)?;
let photos = self.photos_api();
let photos = self.photos();
if link::bounded(photos.get_photos_root())
.await
.map_err(|e| CoreError::from_api(&e, "photos root"))?
@@ -133,16 +132,22 @@ impl Photos {
/// Refresh the album listing off the request path. At most one runs at a time.
pub(crate) fn spawn_albums_refresh(&self) {
if self.jobs.albums_refreshing.swap(true, Ordering::SeqCst) {
if self
.photo_jobs
.albums_refreshing
.swap(true, Ordering::SeqCst)
{
return;
}
let this = self.clone();
let core = self.clone();
self.services
.spawn_task_job(&self.rt, "pdfs-albums-refresh", async move {
let refreshed = this.refresh_albums().await;
this.jobs.albums_refreshing.store(false, Ordering::SeqCst);
let refreshed = core.refresh_albums().await;
core.photo_jobs
.albums_refreshing
.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => this.events.publish(&[Topic::Photos]),
Ok(_) => core.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background album refresh failed"),
}
});
@@ -172,12 +177,12 @@ impl Photos {
.is_none()
{
self.rt.block_on(self.refresh_album(album))?;
} else if listing_stale(&self.db, &stamp, TIMELINE_TTL) {
let this = self.clone();
} else if self.listing_stale(&stamp, TIMELINE_TTL) {
let core = self.clone();
let album = album.clone();
self.services
.spawn_task_job(&self.rt, "pdfs-album-refresh", async move {
if let Err(e) = this.refresh_album(&album).await {
if let Err(e) = core.refresh_album(&album).await {
warn!(%album, error = %e, "background album refresh failed");
}
});
@@ -230,7 +235,7 @@ impl Photos {
.db
.photo_projection_generation()
.map_err(CoreError::from)?;
let photos = self.photos_api();
let photos = self.photos();
let items = link::bounded(photos.enumerate_album(album))
.await
.map_err(|e| CoreError::from_api(&e, "album"))?;
@@ -280,11 +285,11 @@ impl Photos {
}
/// Create an album and return its uid. The listing is refreshed before
/// answering, so the next [`Photos::albums`] already shows it.
/// answering, so the next [`Core::albums`] already shows it.
pub(crate) fn create_album(&self, name: &str) -> CoreResult<String> {
let uid = self
.rt
.block_on(self.photos_api().create_album(name))
.block_on(self.photos().create_album(name))
.map_err(|e| CoreError::from_api(&e, "create album"))?;
self.after_album_change(None);
Ok(uid.to_string())
@@ -292,7 +297,7 @@ impl Photos {
pub(crate) fn rename_album(&self, album: &NodeUid, name: &str) -> CoreResult<()> {
self.rt
.block_on(self.photos_api().rename_album(album, name))
.block_on(self.photos().rename_album(album, name))
.map_err(|e| CoreError::from_api(&e, "rename album"))?;
self.after_album_change(None);
Ok(())
@@ -302,7 +307,7 @@ impl Photos {
/// 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_api().delete_album(album, delete_photos))
.block_on(self.photos().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]) {
@@ -320,7 +325,7 @@ impl Photos {
) -> CoreResult<AlbumOutcome> {
let outcomes = self
.rt
.block_on(self.photos_api().add_photos_to_album(album, photos))
.block_on(self.photos().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))
@@ -335,7 +340,7 @@ impl Photos {
) -> CoreResult<AlbumOutcome> {
let outcomes = self
.rt
.block_on(self.photos_api().remove_photos_from_album(album, photos))
.block_on(self.photos().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))
@@ -358,7 +363,7 @@ impl Photos {
}
/// Drop the album listing's and every album's freshness stamp, so the next
/// request re-enumerates. Paired with [`Core::invalidate_photos`](crate::Core::invalidate_photos) — a change
/// request re-enumerates. Paired with [`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);
+2 -2
View File
@@ -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_api();
let photos = core.photos();
// 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.photos().spawn_timeline_refresh();
core.spawn_timeline_refresh();
}
core.next_poll(POLL_INTERVAL).await;
}
+5 -7
View File
@@ -68,7 +68,7 @@ fn clamp_limit(limit: usize) -> usize {
fn album_change(
uid: &str,
photos: &[String],
change: impl FnOnce(&NodeUid, &[NodeUid]) -> CoreResult<super::photos::AlbumOutcome>,
change: impl FnOnce(&NodeUid, &[NodeUid]) -> CoreResult<super::albums::AlbumOutcome>,
) -> CtlResponse {
let Some(album) = parse_uid(uid) else {
return CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}")));
@@ -689,9 +689,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
core.invalidate_trash();
Ok(())
}
RefreshScope::Photos { full }
if !full && core.photos().timeline_refreshing() =>
{
RefreshScope::Photos { full } if !full && core.timeline_refreshing() => {
// A refresh is already running and will publish exactly the
// timeline this request asks for. Doing the work again
// cannot make it newer, and the invalidation plus the
@@ -711,7 +709,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
}
// Whatever changed the timeline can just as easily have
// changed an album; one scope covers the whole photos view.
core.photos().invalidate_albums();
core.invalidate_albums();
// The refresh is started here, not awaited. A library of
// twelve thousand photos is re-read in chunks of
// `TIMELINE_ENRICH_CHUNK` nodes, which takes minutes —
@@ -719,7 +717,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
// returned `Resource temporarily unavailable` to a caller
// whose refresh was in fact running fine (B92). The front
// end follows it with `PhotosRefreshStatus`.
core.photos().spawn_timeline_refresh();
core.spawn_timeline_refresh();
Ok(())
}
};
@@ -1135,7 +1133,7 @@ fn start_takeout_import(core: &Core, paths: Vec<PathBuf>, dry_run: bool) -> CtlR
)));
}
let count = paths.len();
match core.photos().spawn_takeout_import(paths, dry_run) {
match core.spawn_takeout_import(paths, dry_run) {
Ok(()) => CtlResponse::Ok {
message: format!(
"{} {count} archive(s)",
+38 -49
View File
@@ -69,7 +69,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
range,
favorites,
not_in_album,
} => match core.photos().photos_timeline(
} => match core.photos_timeline(
offset,
clamp_limit(limit),
kind,
@@ -90,11 +90,11 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::PhotoDuplicates => match core.photos().photo_duplicates() {
CtlRequest::PhotoDuplicates => match core.photo_duplicates() {
Ok(sets) => CtlResponse::PhotoDuplicates { sets },
Err(e) => CtlResponse::error(e),
},
CtlRequest::PhotoSimilar => match core.photos().photo_similar() {
CtlRequest::PhotoSimilar => match core.photo_similar() {
Ok((sets, hashing, uncompared)) => CtlResponse::PhotoSimilar {
sets,
hashing,
@@ -102,18 +102,15 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::PhotoPlaces => match core.photos().photo_places(excluded) {
CtlRequest::PhotoPlaces => match core.photo_places(excluded) {
Ok(items) => CtlResponse::Places {
items,
mapping: core.photos().timeline_progress(),
mapping: core.timeline_progress(),
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::PlacePhotos { id, offset, limit } => {
match core
.photos()
.place_photos(id, offset, clamp_limit(limit), excluded)
{
match core.place_photos(id, offset, clamp_limit(limit), excluded) {
Ok(items) => CtlResponse::Photos {
available: true,
items,
@@ -122,15 +119,12 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::PlaceLocations { id } => match core.photos().place_locations(id) {
CtlRequest::PlaceLocations { id } => match core.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)
{
match core.photos_on_this_day(clamp_limit(limit), excluded) {
Ok(items) => CtlResponse::Photos {
available: true,
items,
@@ -139,7 +133,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::PhotoGroup { uid } => match core.photos().photo_group(&uid) {
CtlRequest::PhotoGroup { uid } => match core.photo_group(&uid) {
Ok(items) => CtlResponse::Photos {
available: true,
items,
@@ -148,7 +142,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
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) {
Some(node_uid) => match core.set_photo_favorite(&node_uid, favorite) {
Ok(()) => CtlResponse::Ok {
message: if favorite {
"added to favorites".to_string()
@@ -160,7 +154,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
},
None => CtlResponse::error(CoreError::invalid(format!("invalid uid: {uid}"))),
},
CtlRequest::PhotoAlbums => match core.photos().albums() {
CtlRequest::PhotoAlbums => match core.albums() {
Ok(Some(items)) => CtlResponse::Albums {
available: true,
items,
@@ -175,10 +169,10 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
// 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)
}) {
Some(album) => match visibility
.permits(&uid)
.and_then(|()| core.album_photos(&album, offset, clamp_limit(limit), excluded))
{
Ok(items) => CtlResponse::Photos {
available: true,
items,
@@ -188,12 +182,12 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
},
None => CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}"))),
},
CtlRequest::CreateAlbum { name } => match core.photos().create_album(&name) {
CtlRequest::CreateAlbum { name } => match core.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) {
Some(album) => match core.rename_album(&album, &name) {
Ok(()) => CtlResponse::Ok {
message: format!("renamed album to {name}"),
},
@@ -202,7 +196,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
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) {
Some(album) => match core.delete_album(&album, delete_photos) {
Ok(()) => CtlResponse::Ok {
message: "album deleted".to_string(),
},
@@ -211,11 +205,11 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
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)
core.add_to_album(album, photos)
}),
CtlRequest::RemoveFromAlbum { uid, photos } => {
album_change(&uid, &photos, |album, photos| {
core.photos().remove_from_album(album, photos)
core.remove_from_album(album, photos)
})
}
CtlRequest::PhotoPresence { uid, album } => match core.cached_gallery_visibility() {
@@ -241,45 +235,42 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
.filter_map(|u| parse_uid(u))
.collect();
CtlResponse::Thumbs {
items: core.photos().photo_thumbs(&parsed),
items: core.photo_thumbs(&parsed),
}
}
CtlRequest::FileThumbs { items, generation } => {
match core.photos().file_thumbs(&items, generation) {
match core.file_thumbs(&items, generation) {
Some(items) => CtlResponse::Thumbs { items },
None => CtlResponse::FileThumbsStale,
}
}
CtlRequest::ReserveFileThumbGeneration => CtlResponse::FileThumbGeneration {
generation: core.photos().reserve_file_thumb_generation(),
generation: core.reserve_file_thumb_generation(),
},
CtlRequest::CancelFileThumbs { generation } => {
core.photos().cancel_file_thumbs(generation);
core.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(rel) => match core.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(),
status: core.cancel_thumbnail_build(),
},
CtlRequest::ThumbnailBuildStatus => CtlResponse::ThumbnailBuild {
status: core.photos().thumbnail_build_status(),
status: core.thumbnail_build_status(),
},
CtlRequest::PhotosRefreshStatus => CtlResponse::PhotosRefresh {
running: core.photos().timeline_refreshing(),
running: core.timeline_refreshing(),
},
CtlRequest::OpenPhoto { uid } => match parse_uid(&uid) {
Some(u) => match visibility
.permits(&uid)
.and_then(|()| core.photos().open_photo(&u))
{
Some(u) => match visibility.permits(&uid).and_then(|()| core.open_photo(&u)) {
Ok(p) => CtlResponse::FilePath {
path: p.display().to_string(),
},
@@ -328,7 +319,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
}
}
CtlRequest::ImportStatus => {
let report = crate::photos::takeout::import_status();
let report = crate::takeout::import_status();
CtlResponse::ImportStatus {
running: report.running,
summary: report.summary,
@@ -336,12 +327,12 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
resumable: report.resumable,
}
}
CtlRequest::ResumeImport => match crate::photos::takeout::resumable_archives() {
CtlRequest::ResumeImport => match crate::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() {
if crate::takeout::cancel_import() {
CtlResponse::Ok {
message: "stopping the import".to_string(),
}
@@ -353,7 +344,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
dry_run,
limit,
range,
} => match core.photos().spawn_redate(dry_run, limit, range) {
} => match core.spawn_redate(dry_run, limit, range) {
Ok(()) => CtlResponse::Ok {
message: if dry_run {
"checking photo dates".to_string()
@@ -364,11 +355,11 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
Err(e) => CtlResponse::error(e),
},
CtlRequest::RedateStatus => {
let (running, summary) = crate::photos::redate::redate_status();
let (running, summary) = crate::redate::redate_status();
CtlResponse::RedateStatus { running, summary }
}
CtlRequest::CancelRedate => {
if crate::photos::redate::cancel_redate() {
if crate::redate::cancel_redate() {
CtlResponse::Ok {
message: "stopping the re-date".to_string(),
}
@@ -392,7 +383,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
"cannot read {source_path}: {e}"
))),
Ok((file, len)) => {
let photos = core.photos_api();
let photos = core.photos();
// 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(|| {
@@ -410,9 +401,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
.and_then(pdfs_core::timestamp::modification_time),
..Default::default()
};
let thumbnails = core
.photos()
.upload_thumbnails(Path::new(&source_path), &name);
let thumbnails = core.upload_thumbnails(Path::new(&source_path), &name);
let guard =
core.transfers
.begin(name.clone(), "", TransferDirection::Upload, len);
@@ -432,7 +421,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
// 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() {
if let Err(e) = core.refresh_timeline_joined() {
warn!(error = %e, "timeline refresh after upload failed");
}
CtlResponse::Ok {
+55 -76
View File
@@ -19,104 +19,83 @@ macro_rules! request {
}
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)),
CtlRequest::ListRevisions { path } => match rel_to_mount(mountpoint, &path) {
Ok(rel) => match core.list_revisions(&rel) {
Ok(items) => CtlResponse::Revisions { items },
Err(e) => CtlResponse::error(e),
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::ListRevisionsByUid { uid } => match core.list_revisions_by_uid(&uid) {
Ok(items) => CtlResponse::Revisions { items },
Err(e) => CtlResponse::error(e),
},
CtlRequest::RestoreRevision { path, revision_id } => {
match rel_to_mount(mountpoint, &path) {
Ok(rel) => match core.restore_revision(&rel, &revision_id) {
Ok(()) => CtlResponse::Ok {
message: format!("restoring version {revision_id} of {path}"),
},
Err(e) => CtlResponse::error(e),
},
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::ListRevisionsByUid { uid } => match Target::uid(core, &uid) {
Ok(file) => listed(revisions.list(&file.uid)),
CtlRequest::RestoreRevisionByUid { uid, revision_id } => {
match core.restore_revision_by_uid(&uid, &revision_id) {
Ok(()) => CtlResponse::Ok {
message: format!("restoring version {revision_id}"),
},
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::DeleteRevision { path, revision_id } => match rel_to_mount(mountpoint, &path) {
Ok(rel) => match core.delete_revision(&rel, &revision_id) {
Ok(()) => CtlResponse::Ok {
message: format!("deleted version {revision_id} of {path}"),
},
Err(e) => CtlResponse::error(e),
},
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}"))
}))
match core.delete_revision_by_uid(&uid, &revision_id) {
Ok(()) => CtlResponse::Ok {
message: format!("deleted version {revision_id}"),
},
Err(e) => CtlResponse::error(e),
}
}
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)))
})),
} => match rel_to_mount(mountpoint, &path) {
Ok(rel) => match core.save_revision_as(&rel, &revision_id, Path::new(&dest)) {
Ok(written) => CtlResponse::Ok {
message: format!("wrote {} to {dest}", human_bytes(written)),
},
Err(e) => CtlResponse::error(e),
},
Err(e) => CtlResponse::error(e),
},
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)))
})),
} => match core.save_revision_as_by_uid(&uid, &revision_id, Path::new(&dest)) {
Ok(written) => CtlResponse::Ok {
message: format!("wrote {} to {dest}", human_bytes(written)),
},
Err(e) => CtlResponse::error(e),
},
// `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),
}
}
+5 -5
View File
@@ -24,15 +24,15 @@ pub(super) use request;
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
let Ask { core, .. } = *ask;
match request {
CtlRequest::ListTrash => match core.trash().list_trash() {
CtlRequest::ListTrash => match core.list_trash() {
Ok(entries) => CtlResponse::Entries { entries },
Err(e) => CtlResponse::error(e),
},
CtlRequest::ListTrashedFolder { uid } => match core.trash().list_trashed_folder(&uid) {
CtlRequest::ListTrashedFolder { uid } => match core.list_trashed_folder(&uid) {
Ok(entries) => CtlResponse::Entries { entries },
Err(e) => CtlResponse::error(e),
},
CtlRequest::Restore { uids } => match core.trash().restore(&uids) {
CtlRequest::Restore { uids } => match core.restore(&uids) {
Ok(n) => {
core.log_activity(ActivityKind::Restore, format!("{n} item(s)"), "", true);
CtlResponse::Ok {
@@ -41,7 +41,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
}
Err(e) => CtlResponse::error(e),
},
CtlRequest::DeleteForever { uids } => match core.trash().delete_forever(&uids) {
CtlRequest::DeleteForever { uids } => match core.delete_forever(&uids) {
Ok(n) => {
core.log_activity(
ActivityKind::DeleteForever,
@@ -55,7 +55,7 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
}
Err(e) => CtlResponse::error(e),
},
CtlRequest::EmptyTrash => match core.trash().empty_trash() {
CtlRequest::EmptyTrash => match core.empty_trash() {
Ok(n) => {
let items = if n == 1 {
"1 item".to_string()
+1 -1
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,
+1 -1
View File
@@ -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.photos().upload_thumbnails(Path::new(blob), name);
let thumbnails = self.upload_thumbnails(Path::new(blob), name);
let guard = self
.transfers
.begin(name, op.uid.clone(), TransferDirection::Upload, meta.len);
+2 -2
View File
@@ -232,7 +232,7 @@ impl Core {
}
let alt = conflict_name(&name, now_secs());
let thumbnails = self.photos().upload_thumbnails(blob, &alt);
let thumbnails = self.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.photos().upload_thumbnails(&blob, &name);
let thumbnails = self.upload_thumbnails(&blob, &name);
let guard =
self.transfers
.begin(&name, meta.uid.clone(), TransferDirection::Upload, meta.len);
+25 -2
View File
@@ -82,6 +82,7 @@ use proton_drive_rs::{
};
mod activity;
mod albums;
mod attach;
mod background;
mod conflicts;
@@ -120,6 +121,7 @@ mod queue;
mod quota;
mod reads;
mod recovery;
mod redate;
mod relocate;
mod remote;
mod requests;
@@ -138,6 +140,7 @@ mod supervisor;
mod sweep;
mod sync;
mod systemd;
mod takeout;
use pdfs_core::transfers;
mod upload;
mod r#virtual;
@@ -584,7 +587,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_jobs: trash::TrashState,
trash: trash::TrashState,
/// What the conflict sweep may do, and the copies it already checked this
/// run.
sweep: sweep::SweepState,
@@ -1394,6 +1397,26 @@ impl Core {
Ok(out.into_inner())
}
/// Like [`download_file_tracked_to`] for a photo, streaming through the
/// photos client's [`download_photo_to`].
///
/// [`download_file_tracked_to`]: 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())
}
/// 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.
@@ -1453,7 +1476,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_api(&self) -> ProtonPhotosClient {
fn photos(&self) -> ProtonPhotosClient {
ProtonPhotosClient::from_drive_client(self.client.clone())
}
+5 -11
View File
@@ -434,17 +434,11 @@ 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 [`Photos::photo_thumbs`](crate::photos::Photos::photo_thumbs).
/// thumbnails it actually paints via [`Core::photo_thumbs`].
pub(super) fn listing_stale(&self, key: &str, ttl: Duration) -> bool {
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,
match self.db.state_i64(key).ok().flatten() {
Some(ms) => now_ms().saturating_sub(ms) >= ttl.as_millis() as i64,
None => true,
}
}
}
+1 -1
View File
@@ -542,7 +542,7 @@ pub(crate) fn mount_with(
drain: super::drain::DrainState::new(),
pin_work: Arc::new(Mutex::new(Default::default())),
sizes: super::sizes::SizeState::new(),
trash_jobs: super::trash::TrashState::new(),
trash: super::trash::TrashState::new(),
shared: super::shared::SharedState::new(),
quota: super::quota::QuotaCache::new(),
sharing,
+2 -110
View File
@@ -31,20 +31,11 @@ use proton_drive_rs::proton_sdk::ids::NodeUid;
use proton_drive_rs::{NodeKind, PhotoTag, PhotoTagsUpdate, Thumbnail, ThumbnailType};
use tracing::{debug, info, warn};
use super::ContentCache;
use super::drive::{DriveApi, RevisionRead};
use super::events::EventHub;
use super::shutdown::Shutdown;
use super::transfers::{CountingWriter, TransferRegistry};
use super::drive::RevisionRead;
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
@@ -138,107 +129,8 @@ 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
@@ -257,7 +149,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
/// [`Photos::photo_similar`]), so asking again doesn't start a second one.
/// [`Core::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
+95 -76
View File
@@ -4,14 +4,14 @@
use super::*;
impl Photos {
impl Core {
/// [`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())
}
/// [`Photos::upload_thumbnails`] on the blocking pool, for async callers.
/// [`Core::upload_thumbnails`] on the blocking pool, for async callers.
pub(crate) async fn upload_thumbnails_async(
&self,
path: PathBuf,
@@ -26,7 +26,7 @@ impl Photos {
/// 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
/// [`Photos::generate_thumbs`]). Requested on demand as tiles scroll into view,
/// [`Core::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 Photos {
self.photo_thumbs_with(requested, true)
}
/// [`Photos::photo_thumbs`], with local generation only when `generate` is
/// [`Core::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 Photos {
if !want.is_empty() {
let mut missing = want.clone();
match self.rt.block_on(
self.photos_api()
self.photos()
.enumerate_thumbnails(&want, ThumbnailType::Thumbnail),
) {
Ok(thumbs) => {
@@ -154,7 +154,7 @@ impl Photos {
}
}
let pending = self.jobs.thumb_gen.lock();
let pending = self.photo_jobs.thumb_gen.lock();
requested
.iter()
.zip(uids)
@@ -197,7 +197,7 @@ impl Photos {
}
/// Thumbnails for image files shown by the regular file browser, Shared and
/// Trash pages. Unlike [`Photos::photo_thumbs`], these nodes need not be in the
/// Trash pages. Unlike [`Core::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 Photos {
items: &[FileThumbRequest],
generation: u64,
) -> Option<Vec<PhotoThumb>> {
let current =
generation != 0 && self.jobs.file_thumb_generation.load(Ordering::SeqCst) == generation;
let current = generation != 0
&& self.photo_jobs.file_thumb_generation.load(Ordering::SeqCst) == generation;
if !current {
return None;
}
@@ -238,7 +238,7 @@ impl Photos {
.cached_thumbnail_path(uid, ttype, *modified)
.is_some()
|| self
.jobs
.photo_jobs
.thumbnail_misses
.lock()
.local_contains(&(uid.clone(), ttype), *modified)
@@ -253,7 +253,7 @@ impl Photos {
self.spawn_generate_thumbs(wanted, &tags, &names, ThumbJob::Files(generation));
}
let pending = self.jobs.thumb_gen.lock();
let pending = self.photo_jobs.thumb_gen.lock();
Some(
items
.iter()
@@ -279,14 +279,14 @@ impl Photos {
pub(crate) fn reserve_file_thumb_generation(&self) -> u64 {
let next = |current| if current == u64::MAX { 1 } else { current + 1 };
let previous = self
.jobs
.photo_jobs
.file_thumb_generation
.try_update(Ordering::SeqCst, Ordering::SeqCst, |current| {
Some(next(current))
})
.expect("generation update always succeeds");
let generation = next(previous);
self.jobs.file_thumb_cancel.notify_waiters();
self.photo_jobs.file_thumb_cancel.notify_waiters();
generation
}
@@ -295,11 +295,11 @@ impl Photos {
/// recursive builds do not use this generation and continue normally.
pub(crate) fn cancel_file_thumbs(&self, generation: u64) {
let previous = self
.jobs
.photo_jobs
.file_thumb_generation
.fetch_max(generation, Ordering::SeqCst);
if generation > previous {
self.jobs.file_thumb_cancel.notify_waiters();
self.photo_jobs.file_thumb_cancel.notify_waiters();
}
}
@@ -314,7 +314,7 @@ impl Photos {
job: ThumbJob,
) {
let fresh: Vec<NodeUid> = {
let mut inflight = self.jobs.thumb_gen.lock();
let mut inflight = self.photo_jobs.thumb_gen.lock();
uids.into_iter()
.filter(|uid| inflight.insert(uid.clone()))
.collect()
@@ -323,16 +323,16 @@ impl Photos {
return;
}
let this = self.clone();
let core = 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(|| {
this.generate_thumbs(&fresh, &tags, &names, job)
core.generate_thumbs(&fresh, &tags, &names, job)
}));
let mut inflight = this.jobs.thumb_gen.lock();
let mut inflight = core.photo_jobs.thumb_gen.lock();
for uid in &fresh {
inflight.remove(uid);
}
@@ -354,10 +354,13 @@ impl Photos {
pub(super) fn thumb_job_current(&self, job: ThumbJob) -> bool {
match job {
ThumbJob::Files(generation) => {
self.jobs.file_thumb_generation.load(Ordering::SeqCst) == generation
self.photo_jobs.file_thumb_generation.load(Ordering::SeqCst) == generation
}
ThumbJob::Photos => true,
ThumbJob::Build => !self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst),
ThumbJob::Build => !self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst),
}
}
@@ -374,12 +377,12 @@ impl Photos {
for chunk in uids.chunks(THUMB_GEN_CONCURRENCY) {
let mut set = tokio::task::JoinSet::new();
for uid in chunk {
let this = self.clone();
let core = 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 !this.thumb_job_current(job) {
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
let video = is_video_name(&name);
@@ -394,19 +397,19 @@ impl Photos {
// 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 = this.jobs.thumb_gen_budget.clone().acquire_owned();
let acquire = core.photo_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(),
_ = this.jobs.file_thumb_cancel.notified() => {
if !this.thumb_job_current(job) {
_ = core.photo_jobs.file_thumb_cancel.notified() => {
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !this.thumb_job_current(job) {
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
@@ -415,13 +418,13 @@ impl Photos {
ThumbJob::Build => loop {
tokio::select! {
permit = &mut acquire => break permit.ok(),
_ = this.jobs.thumbnail_build_cancel.notified() => {
if !this.thumb_job_current(job) {
_ = core.photo_jobs.thumbnail_build_cancel.notified() => {
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !this.thumb_job_current(job) {
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
@@ -432,12 +435,12 @@ impl Photos {
let Some(_permit) = _permit else {
return (uid, ThumbAttempt::Unavailable);
};
if !this.thumb_job_current(job) {
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
let download_uid = uid.clone();
let drive = this.drive.clone();
let drive = core.drive.clone();
let audio_name = name.clone();
let download = async move {
// Photos asked the server in one batch already. A
@@ -475,13 +478,13 @@ impl Photos {
ThumbJob::Files(_) => loop {
tokio::select! {
result = &mut download => break Some(result),
_ = this.jobs.file_thumb_cancel.notified() => {
if !this.thumb_job_current(job) {
_ = core.photo_jobs.file_thumb_cancel.notified() => {
if !core.thumb_job_current(job) {
break None;
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !this.thumb_job_current(job) {
if !core.thumb_job_current(job) {
break None;
}
}
@@ -490,13 +493,13 @@ impl Photos {
ThumbJob::Build => loop {
tokio::select! {
result = &mut download => break Some(result),
_ = this.jobs.thumbnail_build_cancel.notified() => {
if !this.thumb_job_current(job) {
_ = core.photo_jobs.thumbnail_build_cancel.notified() => {
if !core.thumb_job_current(job) {
break None;
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !this.thumb_job_current(job) {
if !core.thumb_job_current(job) {
break None;
}
}
@@ -514,12 +517,12 @@ impl Photos {
return (uid, ThumbAttempt::Unavailable);
}
};
if !this.thumb_job_current(job) {
if !core.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 = this.cache.raw_thumbnail_staging_dir().to_path_buf();
let staging_dir = core.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) => {
@@ -544,12 +547,12 @@ impl Photos {
// A song without a picture of its own shows its
// folder's cover.
let made = match made {
ScaleAttempt::Undecodable if audio && this.thumb_job_current(job) => {
this.folder_cover_thumbnail(&uid, staging).await
ScaleAttempt::Undecodable if audio && core.thumb_job_current(job) => {
core.folder_cover_thumbnail(&uid, staging).await
}
made => made,
};
if !this.thumb_job_current(job) {
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
match made {
@@ -580,7 +583,7 @@ impl Photos {
match self.cache.store_thumbnail(&uid, ttype, tag, &thumb.bytes) {
Ok(()) => {
summary.made += 1;
self.jobs
self.photo_jobs
.thumbnail_misses
.lock()
.forget_local(&(uid.clone(), ttype));
@@ -597,7 +600,7 @@ impl Photos {
ThumbAttempt::Undecodable => {
summary.undecodable += 1;
if let Some(&tag) = tags.get(&uid.to_string()) {
self.jobs
self.photo_jobs
.thumbnail_misses
.lock()
.remember_local((uid.clone(), ttype), tag);
@@ -695,7 +698,7 @@ impl Photos {
}
pub(crate) fn thumbnail_build_status(&self) -> ThumbnailBuildStatus {
self.jobs.thumbnail_build.lock().clone()
self.photo_jobs.thumbnail_build.lock().clone()
}
/// Start one recursive local-thumbnail build. A request for the same root
@@ -704,11 +707,11 @@ impl Photos {
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.jobs.thumbnail_build.lock();
let mut status = self.photo_jobs.thumbnail_build.lock();
if !thumbnail_build_may_start(&status, &path)? {
return Ok(status.clone());
}
self.jobs
self.photo_jobs
.thumbnail_build_cancelled
.store(false, Ordering::SeqCst);
*status = ThumbnailBuildStatus {
@@ -724,18 +727,18 @@ impl Photos {
status.clone()
};
let this = self.clone();
let core = self.clone();
self.rt.spawn_blocking(move || {
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
this.run_thumbnail_build(root)
core.run_thumbnail_build(root)
}))
.is_err()
{
let mut status = this.jobs.thumbnail_build.lock();
let mut status = core.photo_jobs.thumbnail_build.lock();
status.running = false;
status.scanning = false;
status.message = Some("Thumbnail generation stopped unexpectedly".to_string());
this.jobs
core.photo_jobs
.thumbnail_build_cancelled
.store(false, Ordering::SeqCst);
warn!(path = %status.path, "recursive thumbnail build panicked");
@@ -746,25 +749,25 @@ impl Photos {
pub(crate) fn cancel_thumbnail_build(&self) -> ThumbnailBuildStatus {
let (status, cancelled) = {
let status = self.jobs.thumbnail_build.lock();
let status = self.photo_jobs.thumbnail_build.lock();
let cancelled = status.running;
if cancelled {
self.jobs
self.photo_jobs
.thumbnail_build_cancelled
.store(true, Ordering::SeqCst);
}
(status.clone(), cancelled)
};
if cancelled {
self.jobs.thumbnail_build_cancel.notify_waiters();
self.photo_jobs.thumbnail_build_cancel.notify_waiters();
}
status
}
pub(crate) fn finish_thumbnail_build(&self) {
let mut status = self.jobs.thumbnail_build.lock();
let mut status = self.photo_jobs.thumbnail_build.lock();
let cancelled = self
.jobs
.photo_jobs
.thumbnail_build_cancelled
.swap(false, Ordering::SeqCst);
status.running = false;
@@ -788,19 +791,23 @@ impl Photos {
let mut seen_images = HashSet::new();
while let Some(folder) = folders.pop() {
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
self.finish_thumbnail_build();
return;
}
let listing = self.host.list_dir(&folder);
let listing = self.list_dir(&folder);
{
let mut status = self.jobs.thumbnail_build.lock();
let mut status = self.photo_jobs.thumbnail_build.lock();
status.folders_scanned += 1;
}
let entries = match listing {
Ok(entries) => entries,
Err(error) => {
let mut status = self.jobs.thumbnail_build.lock();
let mut status = self.photo_jobs.thumbnail_build.lock();
if status.message.is_none() {
status.message = Some(format!(
"Some folders could not be read ({}: {error})",
@@ -832,14 +839,18 @@ impl Photos {
}
}
}
let mut status = self.jobs.thumbnail_build.lock();
let mut status = self.photo_jobs.thumbnail_build.lock();
status.images_found += found_here;
status.completed += invalid_here;
status.failed += invalid_here;
}
self.jobs.thumbnail_build.lock().scanning = false;
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
self.photo_jobs.thumbnail_build.lock().scanning = false;
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
self.finish_thumbnail_build();
return;
}
@@ -851,14 +862,14 @@ impl Photos {
.cached_thumbnail_path(&uid, ttype, modified)
.is_some()
{
self.jobs.thumbnail_build.lock().completed += 1;
self.photo_jobs.thumbnail_build.lock().completed += 1;
} else if self
.jobs
.photo_jobs
.thumbnail_misses
.lock()
.local_contains(&(uid.clone(), ttype), modified)
{
let mut status = self.jobs.thumbnail_build.lock();
let mut status = self.photo_jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
} else {
@@ -867,7 +878,11 @@ impl Photos {
}
for chunk in todo.chunks(THUMB_BUILD_CHUNK) {
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
self.finish_thumbnail_build();
return;
}
@@ -880,7 +895,11 @@ impl Photos {
// than downloading the full image twice.
let waiting_since = Instant::now();
loop {
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
self.finish_thumbnail_build();
return;
}
@@ -889,28 +908,28 @@ impl Photos {
.cached_thumbnail_path(uid, ttype, *modified)
.is_some()
{
self.jobs.thumbnail_build.lock().completed += 1;
self.photo_jobs.thumbnail_build.lock().completed += 1;
break;
}
if self
.jobs
.photo_jobs
.thumbnail_misses
.lock()
.local_contains(&(uid.clone(), ttype), *modified)
{
let mut status = self.jobs.thumbnail_build.lock();
let mut status = self.photo_jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
break;
}
if self.jobs.thumb_gen.lock().insert(uid.clone()) {
if self.photo_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.jobs.thumbnail_build.lock();
let mut status = self.photo_jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
if status.message.is_none() {
@@ -931,12 +950,12 @@ impl Photos {
self.generate_thumbs(&claimed, &tags, &names, ThumbJob::Build)
}));
{
let mut inflight = self.jobs.thumb_gen.lock();
let mut inflight = self.photo_jobs.thumb_gen.lock();
for uid in &claimed {
inflight.remove(uid);
}
}
let mut status = self.jobs.thumbnail_build.lock();
let mut status = self.photo_jobs.thumbnail_build.lock();
match result {
Ok(summary) => {
status.completed += summary.processed();
+136 -23
View File
@@ -3,7 +3,7 @@
use super::*;
impl Photos {
impl Core {
#[allow(clippy::too_many_arguments)]
pub(crate) fn photos_timeline(
&self,
@@ -90,7 +90,7 @@ impl Photos {
/// 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_api();
let photos = self.photos();
let update = PhotoTagsUpdate {
node_uid: uid.clone(),
tags_to_add: if favorite {
@@ -114,7 +114,7 @@ impl Photos {
// `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.host.note_self_change(uid);
self.note_self_change(uid);
self.db
.photos_set_favorite(&uid.to_string(), favorite)
.map_err(CoreError::from)?;
@@ -142,7 +142,7 @@ impl Photos {
let sets = self.db.photo_similar().map_err(CoreError::from)?;
let (done, total) = self.db.similar_progress().map_err(CoreError::from)?;
let hashing = self
.jobs
.photo_jobs
.similar_hashing
.load(Ordering::SeqCst)
.then_some(MappingProgress { done, total });
@@ -155,19 +155,23 @@ impl Photos {
}
pub(crate) fn spawn_similar_hashing(&self) {
if self.jobs.similar_hashing.swap(true, Ordering::SeqCst) {
if self.photo_jobs.similar_hashing.swap(true, Ordering::SeqCst) {
return;
}
let this = self.clone();
let core = self.clone();
let spawned = self.services.spawn_job("pdfs-similar", move || {
if let Err(e) = this.hash_similar() {
if let Err(e) = core.hash_similar() {
warn!(error = %e, "similar-photo hashing failed");
}
this.jobs.similar_hashing.store(false, Ordering::SeqCst);
core.photo_jobs
.similar_hashing
.store(false, Ordering::SeqCst);
});
if let Err(e) = spawned {
warn!(error = %e, "could not start similar-photo hashing");
self.jobs.similar_hashing.store(false, Ordering::SeqCst);
self.photo_jobs
.similar_hashing
.store(false, Ordering::SeqCst);
}
}
@@ -316,6 +320,100 @@ impl Photos {
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> {
@@ -324,7 +422,7 @@ impl Photos {
.db
.photo_projection_generation()
.map_err(CoreError::from)?;
let photos = self.photos_api();
let photos = self.photos();
if self
.db
.state_i64(PHOTOS_SYNCED_MS)
@@ -370,7 +468,7 @@ impl Photos {
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.jobs.timeline_progress);
let progress = ProgressGuard(&self.photo_jobs.timeline_progress);
for (index, chunk) in pending.chunks(TIMELINE_ENRICH_CHUNK).enumerate() {
if self.shutdown.is_stopping() {
break;
@@ -439,8 +537,12 @@ impl Photos {
/// 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.jobs.timeline_refreshing.swap(true, Ordering::SeqCst) {
while self.jobs.timeline_refreshing.load(Ordering::SeqCst)
if self
.photo_jobs
.timeline_refreshing
.swap(true, Ordering::SeqCst)
{
while self.photo_jobs.timeline_refreshing.load(Ordering::SeqCst)
&& !self.shutdown.is_stopping()
{
std::thread::sleep(std::time::Duration::from_millis(200));
@@ -453,13 +555,18 @@ impl Photos {
.state_i64(PHOTOS_SYNCED_MS)
.map_err(CoreError::from)?
.is_some()
|| self.jobs.timeline_refreshing.swap(true, Ordering::SeqCst)
|| self
.photo_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.jobs.timeline_refreshing.store(false, Ordering::SeqCst);
self.photo_jobs
.timeline_refreshing
.store(false, Ordering::SeqCst);
if refreshed.is_ok() {
self.events.publish(&[Topic::Photos]);
}
@@ -467,18 +574,24 @@ impl Photos {
}
pub(crate) fn spawn_timeline_refresh(&self) {
if self.jobs.timeline_refreshing.swap(true, Ordering::SeqCst) {
if self
.photo_jobs
.timeline_refreshing
.swap(true, Ordering::SeqCst)
{
return;
}
let this = self.clone();
let core = self.clone();
self.services
.spawn_task_job(&self.rt, "pdfs-timeline-refresh", async move {
let refreshed = this.refresh_timeline().await;
this.jobs.timeline_refreshing.store(false, Ordering::SeqCst);
let refreshed = core.refresh_timeline().await;
core.photo_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(_) => this.events.publish(&[Topic::Photos]),
Ok(_) => core.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background timeline refresh failed"),
}
});
@@ -487,7 +600,7 @@ impl Photos {
/// 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.jobs
self.photo_jobs
.timeline_progress
.lock()
.map(|(done, total)| MappingProgress { done, total })
@@ -496,13 +609,13 @@ impl Photos {
/// 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.jobs.timeline_refreshing.load(Ordering::SeqCst)
self.photo_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_api();
let photos = self.photos();
let node = self
.rt
.block_on(photos.get_node(uid))
-101
View File
@@ -1,101 +0,0 @@
//! 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))
}
}
@@ -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::Photos;
use super::Core;
use crate::parse_uid as parse_node_uid;
use crate::transfers::CountingReader;
@@ -84,7 +84,7 @@ struct Candidate {
albums: Vec<String>,
}
impl Photos {
impl Core {
/// 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 Photos {
/// 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_api();
let photos = self.photos();
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 Photos {
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.host.note_self_change(&new_uid),
Ok(_) => self.note_self_change(&new_uid),
Err(e) => {
warn!(name = candidate.name, error = %e, "cannot re-favorite re-dated photo")
}
@@ -287,9 +287,9 @@ impl Photos {
state.last = None;
}
let this = self.clone();
let core = self.clone();
if let Err(error) = self.services.spawn_job("pdfs-redate", move || {
let outcome = this.redate_photos(dry_run, limit, range, cancel);
let outcome = core.redate_photos(dry_run, limit, range, cancel);
let mut state = REDATE.lock();
state.running = false;
state.cancel = None;
+113 -86
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. [`Revisions::delete`] refuses locally
//! is what enforces that. [`Core::delete_revision_for_uid`] refuses locally
//! too, so the user gets a sentence instead of an API code.
use std::path::Path;
@@ -27,12 +27,7 @@ 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 {
@@ -50,65 +45,20 @@ fn revision_info(revision: Revision) -> RevisionInfo {
}
}
/// 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>,
}
/// 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);
}
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, 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
// again when the event of the swap arrives (`docs/BUGS.md` B282).
if self.cache.is_pinned(uid) {
self.recheck_pinned(uid);
}
}
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()),
}
/// 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)
}
}
impl Revisions {
pub(crate) fn list(&self, uid: &NodeUid) -> CoreResult<Vec<RevisionInfo>> {
/// [`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)
}
fn list_revisions_for_uid(&self, uid: &NodeUid) -> CoreResult<Vec<RevisionInfo>> {
let revisions = self
.rt
.block_on(self.client.enumerate_revisions(uid))
@@ -116,30 +66,59 @@ impl Revisions {
Ok(revisions.into_iter().map(revision_info).collect())
}
pub(crate) fn restore(&self, uid: &NodeUid, revision_id: &str, name: &str) -> CoreResult<()> {
/// 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.
self.host.require_writable(uid, "restore revision")?;
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.host.log_activity(
ActivityKind::Restore,
name.to_string(),
error.to_string(),
false,
);
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.
self.host.content_replaced(uid);
self.host.log_activity(
self.cache.evict(uid);
self.evict_reader(uid);
// A file kept offline gets the restored content back on disk, and
// again when the event of the swap arrives (`docs/BUGS.md` B282).
if self.cache.is_pinned(uid) {
self.recheck_pinned(uid);
}
self.log_activity(
ActivityKind::Restore,
name.to_string(),
name,
format!("restored version {revision_id}"),
true,
);
@@ -147,8 +126,32 @@ impl Revisions {
Ok(())
}
pub(crate) fn delete(&self, uid: &NodeUid, revision_id: &str, name: &str) -> CoreResult<()> {
self.host.require_writable(uid, "delete revision")?;
/// 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"))?;
// 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.
@@ -168,9 +171,9 @@ impl Revisions {
self.rt
.block_on(self.client.delete_revision(uid, revision_id))
.map_err(|e| CoreError::from_api(&e, "delete revision"))?;
self.host.log_activity(
self.log_activity(
ActivityKind::DeleteForever,
name.to_string(),
name,
format!("deleted version {revision_id}"),
true,
);
@@ -178,7 +181,36 @@ impl Revisions {
Ok(())
}
pub(crate) fn save_as(
/// 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(
&self,
uid: &NodeUid,
revision_id: &str,
@@ -221,18 +253,13 @@ impl Revisions {
// A half-written file looks like a successful export to every
// tool that opens it afterwards.
let _ = std::fs::remove_file(dest);
self.host.log_activity(
ActivityKind::Download,
name.to_string(),
error.to_string(),
false,
);
self.log_activity(ActivityKind::Download, name, &error, false);
return Err(error);
}
};
self.host.log_activity(
self.log_activity(
ActivityKind::Download,
name.to_string(),
name,
format!("saved version {revision_id} to {}", dest.display()),
true,
);
+1 -1
View File
@@ -38,7 +38,7 @@ impl SyncHost for Core {
}
fn upload_thumbnails(&self, path: &Path, name: &str) -> Vec<Thumbnail> {
self.photos().upload_thumbnails(path, name)
Core::upload_thumbnails(self, path, name)
}
}
@@ -47,7 +47,7 @@ use tracing::{info, warn};
pub(crate) use pdfs_drive::digest::sha1_of;
use super::Photos;
use super::Core;
use crate::photos::can_make_thumbnail;
use crate::transfers::CountingReader;
@@ -468,7 +468,7 @@ fn read_entry<R>(
Ok(sink(&mut file))
}
impl Photos {
impl Core {
/// 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 Photos {
));
}
let photos = self.photos_api();
let photos = self.photos();
if self
.rt
.block_on(photos.get_photos_root())
@@ -668,7 +668,7 @@ impl Photos {
report: &Reporter,
) -> CoreResult<()> {
report.phase(ImportPhase::Checking, 0);
let photos = self.photos_api();
let photos = self.photos();
let names: Vec<String> = planned.iter().map(|p| p.photo.name.clone()).collect();
let collisions = self
.rt
@@ -919,7 +919,7 @@ impl Photos {
report.step();
match done.result {
Ok(uid) => {
self.host.note_self_change(&uid);
self.note_self_change(&uid);
summary.uploaded += 1;
summary.bytes += done.photo.size;
if done.live {
@@ -954,7 +954,7 @@ impl Photos {
tags: Vec<PhotoTag>,
main_uid: Option<NodeUid>,
) -> CoreResult<NodeUid> {
let photos = self.photos_api();
let photos = self.photos();
let guard = self.transfers.begin(
photo.name.clone(),
"",
@@ -1035,7 +1035,7 @@ impl Photos {
tags_to_remove: Vec::new(),
})
.collect();
if let Err(e) = self.rt.block_on(self.photos_api().update_photos(&updates)) {
if let Err(e) = self.rt.block_on(self.photos().update_photos(&updates)) {
warn!(error = %e, "marking imported favorites failed");
}
}
@@ -1049,7 +1049,7 @@ impl Photos {
summary: &mut ImportSummary,
report: &Reporter,
) -> CoreResult<()> {
let photos = self.photos_api();
let photos = self.photos();
// 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 Photos {
state.save();
}
let this = self.clone();
let core = 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 = this.transfers.begin_job("Importing Google Photos");
let job = core.transfers.begin_job("Importing Google Photos");
let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
this.import_takeout(&archives, dry_run, &cancel, &job)
core.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 Photos {
}
drop(job);
if !dry_run {
this.host.log_activity(
core.log_activity(
ActivityKind::Upload,
"Google Photos import".to_string(),
"Google Photos import",
activity_line(&summary),
summary.complete(),
);
+37 -106
View File
@@ -2,7 +2,6 @@
//! 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.
@@ -14,7 +13,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
/// [`Trash::await_trash_refresh`].
/// [`Core::await_trash_refresh`].
pub(crate) trash_progress: Arc<tokio::sync::Notify>,
}
@@ -27,75 +26,7 @@ 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
@@ -105,7 +36,7 @@ impl Trash {
/// 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
/// [`Trash::invalidate_trash`]), so the TTL only covers changes made elsewhere.
/// [`Core::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
@@ -113,9 +44,9 @@ impl Trash {
/// 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(crate) fn list_trash(&self) -> CoreResult<Vec<DirEntry>> {
pub(super) fn list_trash(&self) -> CoreResult<Vec<DirEntry>> {
let never_fetched = self.db.state_i64(TRASH_SYNCED_MS).ok().flatten().is_none();
if never_fetched || listing_stale(&self.db, TRASH_SYNCED_MS, TRASH_TTL) {
if never_fetched || self.listing_stale(TRASH_SYNCED_MS, TRASH_TTL) {
self.spawn_trash_refresh();
}
if never_fetched {
@@ -168,7 +99,7 @@ impl Trash {
/// What a trashed folder holds: its children on the server, and the
/// stored trash entries trashed inside it before it went.
pub(crate) fn list_trashed_folder(&self, uid: &str) -> CoreResult<Vec<DirEntry>> {
pub(super) 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
@@ -246,7 +177,7 @@ impl Trash {
/// [`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(crate) async fn refresh_trash(&self) -> CoreResult<()> {
pub(super) async fn refresh_trash(&self) -> CoreResult<()> {
let started = Instant::now();
let uids = within_trash_call("enumerate trash", self.drive.enumerate_trash_node_uids())
.await?
@@ -269,7 +200,7 @@ impl Trash {
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.jobs.trash_progress.notify_waiters();
self.trash.trash_progress.notify_waiters();
}
let missing: Vec<NodeUid> = uids
.into_iter()
@@ -304,7 +235,7 @@ impl Trash {
.collect();
materialized += items.len();
self.db.trash_upsert(&items).map_err(CoreError::from)?;
self.jobs.trash_progress.notify_waiters();
self.trash.trash_progress.notify_waiters();
self.events.publish(&[Topic::Trash]);
debug!(
materialized,
@@ -327,44 +258,44 @@ impl Trash {
}
/// Refresh the trash off the request path. At most one refresh at a time —
/// including the one a first-ever [`Trash::list_trash`] waits on, so a burst
/// including the one a first-ever [`Core::list_trash`] waits on, so a burst
/// of requests against an unfetched trash joins one refresh instead of
/// starting one apiece.
pub(crate) fn spawn_trash_refresh(&self) {
if self.jobs.trash_refreshing.swap(true, Ordering::SeqCst) {
pub(super) fn spawn_trash_refresh(&self) {
if self.trash.trash_refreshing.swap(true, Ordering::SeqCst) {
return;
}
let this = self.clone();
let core = self.clone();
self.services
.spawn_task_job(&self.rt, "pdfs-trash-refresh", async move {
let refreshed = this.refresh_trash().await;
this.jobs.trash_refreshing.store(false, Ordering::SeqCst);
let refreshed = core.refresh_trash().await;
core.trash.trash_refreshing.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => this.events.publish(&[Topic::Trash]),
Ok(_) => core.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.
this.jobs.trash_progress.notify_waiters();
core.trash.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(crate) fn await_trash_refresh(&self, budget: Duration) {
pub(super) fn await_trash_refresh(&self, budget: Duration) {
let deadline = Instant::now() + budget;
self.rt.block_on(async {
while self.jobs.trash_refreshing.load(Ordering::SeqCst) {
while self.trash.trash_refreshing.load(Ordering::SeqCst) {
let Some(left) = deadline.checked_duration_since(Instant::now()) else {
break;
};
let notified = self.jobs.trash_progress.notified();
let notified = self.trash.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.jobs.trash_refreshing.load(Ordering::SeqCst) {
if !self.trash.trash_refreshing.load(Ordering::SeqCst) {
break;
}
if tokio::time::timeout(left, notified).await.is_err() {
@@ -382,8 +313,8 @@ impl Trash {
/// 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(crate) fn invalidate_trash(&self) {
invalidate_trash(&self.db);
pub(super) fn invalidate_trash(&self) {
let _ = self.db.clear_state(TRASH_SYNCED_MS);
}
/// Restore trashed nodes to the folders they were trashed from, together
@@ -404,8 +335,8 @@ impl Trash {
/// 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(crate) fn restore(&self, uids: &[String]) -> CoreResult<usize> {
let requested = Core::parse_uids(uids)?;
pub(super) fn restore(&self, uids: &[String]) -> CoreResult<usize> {
let requested = Self::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();
@@ -468,7 +399,13 @@ impl Trash {
}
// 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.host.invalidate_listings_of(&parents);
self.for_each_state(|st| {
for parent in &parents {
if let Some(&ino) = st.by_uid.get(parent) {
st.invalidate_listing(ino);
}
}
});
let back: Vec<String> = restored.iter().map(ToString::to_string).collect();
let _ = self.db.trash_remove(&back);
self.invalidate_trash();
@@ -477,8 +414,8 @@ impl Trash {
/// Permanently delete trashed nodes. Irreversible on the server; locally it
/// drops any metadata and cached content the node still owns.
pub(crate) fn delete_forever(&self, uids: &[String]) -> CoreResult<usize> {
let parsed = Core::parse_uids(uids)?;
pub(super) fn delete_forever(&self, uids: &[String]) -> CoreResult<usize> {
let parsed = Self::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
@@ -493,7 +430,7 @@ impl Trash {
let (uid, outcome) = item?;
match outcome {
Ok(()) => {
self.host.drop_local(std::slice::from_ref(&uid));
self.drop_local(std::slice::from_ref(&uid));
gone.push(uid.to_string());
deleted += 1;
}
@@ -524,7 +461,7 @@ impl Trash {
/// 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(crate) fn empty_trash(&self) -> CoreResult<usize> {
pub(super) fn empty_trash(&self) -> CoreResult<usize> {
let uids: Vec<String> = self
.db
.trash_seen()
@@ -535,7 +472,7 @@ impl Trash {
.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.host.drop_local(&parsed);
self.drop_local(&parsed);
let _ = self.db.trash_replace(&[]);
let _ = self.db.set_state_i64(TRASH_SYNCED_MS, now_ms());
self.events.publish(&[Topic::Trash]);
@@ -543,7 +480,7 @@ impl Trash {
}
}
/// An entry inside a trashed folder, for [`Trash::list_trashed_folder`].
/// An entry inside a trashed folder, for [`Core::list_trashed_folder`].
pub(super) fn trashed_entry(
uid: String,
name: String,
@@ -682,9 +619,3 @@ 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,7 +70,6 @@ async fn run_uploads(
));
}
let thumbnails = core
.photos()
.upload_thumbnails_async(t.path.clone(), t.name.clone())
.await;
match core
-18
View File
@@ -772,24 +772,6 @@ only the handles it calls (the client, Drive, the content cache, the transfer li
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