Compare commits

...
Author SHA1 Message Date
nvrl 66c67b5a08 refactor(fuse): split photos.rs into the thumbnail and timeline requests
photos.rs keeps the image, RAW and video decoding, the decode budget,
PhotoJobs and the tests. Core's methods move, unchanged, into:

- photos/thumbs.rs: generating and uploading missing thumbnails, file
  thumbnails, folder covers, the recursive build (19 methods)
- photos/timeline.rs: the timeline, favorites, duplicates and similar
  shots, places, on this day, groups, trashing photos (21 methods)

Two doc links in drain/revision.rs point at crate:: instead of super::.
No behaviour changes.
2026-11-26 16:34:34 +01:00
nvrl 27860688ab refactor(fuse): split the drain by op kind into drain/{create,rename,trash,revision}.rs
drain.rs keeps the workers, the claim and dispatch of an op, the access
deferral, the helpers several op kinds share, and the tests. The Core
methods that drain one kind of op move, unchanged, into submodules:

- create.rs: creates and mkdirs, twins left by an unanswered attempt,
  adopting the real uid (16 methods)
- rename.rs: renames and moves (3)
- trash.rs: trashes, and withdrawing a create that never landed (5)
- revision.rs: uploads, the conflict check, placing what landed, the
  revision debounce (13)

The source-order tests read the drain through DRAIN_SOURCE. No behaviour
changes.
2026-11-26 16:29:02 +01:00
nvrl 307bbac96c refactor(cli): split main.rs by command area into seven modules
main.rs keeps the command definitions, main's dispatch and the helpers
every area uses (control_request, ok_or_bail, path_arg, the formatters).
The commands move, unchanged, into:

- account.rs: login, unlock, lock, logout
- files.rs: mount, pins, ls, search, rename, move, copy, du, rm,
  versions, trash, mkdir, upload, refresh
- photos.rs: timeline, favorites, albums, the Google Photos import,
  re-dating
- sharing.rs: share, members, roles, public links, shared items,
  invitations, bookmarks, leave
- status.rs: status, locations, devices, diagnostics, cache
- sync.rs: sync, conflicts, the sync queue, issues, export, restore,
  limits, ignore rules, health
- diagnose.rs: pdfs diagnose and its report, with its tests

main.rs goes from 4,842 lines to 1,620. No behaviour changes.
2026-11-26 16:25:28 +01:00
nvrl 191a9cfe82 feat(daemon): add pdfs-daemon, the daemon's composition root
The daemon's run loop moves out of pdfs-cli into a new crate. run waits
for a stored session, then opens the database and the content cache,
resumes the session on a runtime of its own, and mounts. It remounts
after an external unmount, and retries a failed mount with a backoff,
recording each failure. pdfs daemon and pdfs mount call into it.

Moved unchanged, with their nine tests: login_poll_delay,
wait_for_session, not_empty_cause, mount_retry_schedule,
mount_retry_delay, mount_once and release_runtime. cmd_daemon becomes
pdfs_daemon::run.

The services the mount starts are still built in pdfs-fuse. Moving their
construction here is the next part of step 3.
2026-11-26 16:20:51 +01:00
nvrl 7a3ecf5590 docs: list the new pdfs-fuse modules and where step 3 stands 2026-11-26 16:13:15 +01:00
nvrl 84203c20a8 refactor(fuse): split resolution, remote calls, path requests and the activity log out of lib.rs
- resolve.rs: finding nodes by path or uid, in the tree, the database and
  on Drive (15 methods).
- remote.rs: renames, moves and content changes sent straight to Drive
  (6 methods).
- requests.rs: the control socket's requests by path: list, open,
  rename, move, copy, delete, restore a replaced file (25 methods).
- activity.rs: the activity log (2 methods).

No behaviour changes.
2026-11-26 16:12:51 +01:00
nvrl 5f752616b1 refactor(fuse): split six more areas of Core's methods out of lib.rs
- enqueue.rs: turning what the mount was asked into queued ops, and
  taking them back (17 methods).
- listing.rs: when a folder is listed again and what a listing from
  Drive is merged with (10 methods).
- pins.rs: pin, unpin and the pin listings (8 methods).
- recovery.rs: rebuilding the tree and the queue at startup, and
  recovering fsynced writes (5 methods).
- search.rs: the search requests (4 methods).
- echoes.rs: our own changes echoed back by the event feed, with
  SelfChange and its helpers.

The source-order tests read Core's code through CORE_SOURCE, lib.rs and
the modules its methods were split into. No behaviour changes.
2026-11-26 16:10:25 +01:00
nvrl 3b7e2fffa8 refactor(fuse): move maintenance into its own module; group the quota and sweep state
- maintenance.rs takes the Maintenance struct and the two Core methods
  that start a VACUUM or a deep integrity check.
- The quota answer and its refresh flag become sharing::QuotaCache, held
  as Core::quota_cache, next to the statfs code that uses them.
- The sweep mode and the copies already checked become sweep::SweepState,
  held as Core::sweep.
- Two source-order tests read apply_size_upgrade, run_size_upgrade and
  ensure_shared_children from their new files.

No behaviour changes.
2026-11-26 16:01:05 +01:00
nvrl 8cd30ef0c1 refactor(fuse): move the shared tree's listing into shared.rs
Eight Core methods that build and refresh the mounted shared tree's
listing move out of lib.rs into shared.rs. The three Core fields they use
(the publication lock, the generation and the refresh deadlines) become
shared::SharedState, held as Core::shared. The pure naming rules stay in
virtual.rs. No behaviour changes.
2026-11-26 15:56:03 +01:00
nvrl 4a38b7992c refactor(fuse): move the trash listing, restore and delete into trash.rs
Nine Core methods (list, refresh, restore, delete forever, empty) and
their three helpers move out of lib.rs into trash.rs. The two Core fields
the refresh uses become trash::TrashState, held as Core::trash. No
behaviour changes.
2026-11-26 15:55:22 +01:00
nvrl 200ca1461f refactor(fuse): move the size upgrades into sizes.rs with their state
The size upgrades fill in the file sizes a cheap listing left out. Their
code (nine Core methods, SizeUpgrade, SizeWaitQueue and their tests) moves
out of lib.rs into sizes.rs, and their two Core fields become
sizes::SizeState, held as Core::sizes. No behaviour changes.
2026-11-26 15:54:18 +01:00
nvrl 87dc2b9d6d Merge pull request #156 from narrrl/refactor/read-state
refactor(fuse): keep the read path's state in reads::ReadState
2026-11-26 15:49:00 +01:00
nvrl b1516f1403 refactor(fuse): keep the read path's state in reads::ReadState
Six of Core's fields belong to the read path alone: the open revision
readers, the decrypted block ring, the block fetches in flight, the
whole-file repair locks, and the prefetch detector with its permits.
They move into one ReadState struct in reads.rs, which Core holds as
reads. Every access was already in reads.rs.

The size upgrades stay in Core: they serve getattr, not reads.

The third group of step 3 in docs/ARCHITECTURE.md. No behaviour changes.
2026-11-26 15:18:56 +01:00
nvrl 25b0ea4ce8 Merge pull request #155 from narrrl/refactor/drain-state
refactor(fuse): keep the drain's bookkeeping in drain::DrainState
2026-11-26 15:13:44 +01:00
nvrl c5c376e2b3 refactor(fuse): keep the drain's bookkeeping in drain::DrainState
Eight of Core's fields belong to the write-back drain: its wake-up, the
creates and uploads on the wire (creating, upload_cancel, upload_times,
landing_uploads), and what a landed one leaves behind until the tree
catches up (landed, unadopted, sealed_unread). They move into one
DrainState struct in drain.rs, which Core holds as drain.

pending and hidden stay in Core: the reads and the FUSE handlers use
them as much as the drain does.

The second group of step 3 in docs/ARCHITECTURE.md. No behaviour changes.
2026-11-26 14:55:33 +01:00
nvrl 61994f7754 Merge pull request #154 from narrrl/refactor/photo-jobs
refactor(fuse): keep the Photos and thumbnail jobs' state in photos::PhotoJobs
2026-11-26 14:50:28 +01:00
nvrl c453421a53 refactor(fuse): keep the Photos and thumbnail jobs' state in photos::PhotoJobs
Twelve of Core's fields belong to the Photos and thumbnail jobs alone:
the timeline, album and similar-photo refresh flags, the thumbnail
generation set and its permits, the listing and recursive-build
cancellation, and the negative thumbnail caches. They move into one
PhotoJobs struct in photos.rs, which Core holds as photo_jobs.

The first group of step 3 in docs/ARCHITECTURE.md. No behaviour changes.
2026-11-26 12:50:33 +01:00
nvrl c323def397 Merge pull request #153 from narrrl/refactor/service-lifecycle
feat(core,fuse): start and stop the daemon's threads through one Services set
2026-11-26 12:30:28 +01:00
nvrl 050ac3fe85 feat(core,fuse): start and stop the daemon's threads through one Services set
The mount kept its long-lived threads in a bare list of join handles,
and the calls that wake the ones blocked outside the shutdown signal sat
in halt_workers, far from where each thread was started. Nothing could
say which threads were still alive.

pdfs_core::lifecycle::Services starts each thread with its name and its
wake call. A stop signals, wakes and joins them in reverse start order
under the existing 10-second deadline. ServiceBoard is the live view:
`pdfs diagnostics` lists the services and names any that ended, and the
supervisor warns once about a service that ended while the mount runs.

The shutdown inhibitor is now joined too. The sync engine thread is
started by the mount; pdfs_sync::mirror::spawn becomes run.
2026-11-26 12:07:44 +01:00
nvrl b98364d82a Merge pull request #152 from narrrl/refactor/sync-local-fs
refactor(sync): gather the mirror engine's disk I/O in mirror::local
2026-11-26 11:48:14 +01:00
nvrl 41d7355f9a Merge pull request #151 from narrrl/refactor/sync-store-port
refactor(sync): reach the sync tables through a SyncStore port
2026-11-26 11:18:39 +01:00
nvrl 667c086dd5 refactor(sync): gather the mirror engine's disk I/O in mirror::local
The scan, the hash and open before an upload, the placement of a
download, the removals and the conflict copy move from mirror.rs into
mirror/local.rs unchanged. Placement is split out of download_file as
staging_path and place_download. This is the first step towards the
LocalFs port; no behaviour changes.

Also puts the open_to_upload doc comment back on open_to_upload; it sat
above revisions_to_record.
2026-11-26 11:11:59 +01:00
nvrl e2cbb442f2 refactor(sync): reach the sync tables through a SyncStore port
The mirror engine held the whole database (`Arc<Db>`) but uses only the
18 calls on its own tables: synced folders, baselines, the saved walk of
Drive and its dirty marks. `SyncStore` is exactly those calls, the
database implements it by forwarding, and `SyncParts` now holds an
`Arc<dyn SyncStore>`. No behaviour changes.
2026-11-26 10:59:56 +01:00
nvrl 83391d6d96 Merge pull request #150 from narrrl/feat/pdfs-instance
feat(core,cli): PDFS_INSTANCE runs a second client next to your own
2026-11-26 10:10:51 +01:00
nvrl 67786c9462 Merge pull request #149 from narrrl/refactor/sync-engine-move
refactor(sync,fuse,core): move the mirror engine into pdfs-sync
2026-11-26 10:10:38 +01:00
nvrl 3255bc2f36 Merge pull request #148 from narrrl/refactor/sync-helpers
refactor(drive,core): move the node and digest helpers the sync engine uses
2026-11-26 10:10:24 +01:00
nvrl f6c3e45fd3 Merge pull request #147 from narrrl/refactor/sync-ports
refactor(fuse): give the sync engine its own state and a port to the daemon
2026-11-26 10:10:09 +01:00
nvrl 8dd0c6f424 refactor(sync,fuse,core): move the mirror engine into pdfs-sync
sync.rs and sync/{engine,host,local_scan}.rs become pdfs_sync::mirror.
The engine already ran on a Syncer and reached the daemon only through
SyncHost; the last two links go through it too: upload thumbnails are a
SyncHost call, and the event poll interval is pdfs_sync's constant. The
transfer registry and the shutdown signal, which both sides use, move to
pdfs-core. pdfs-fuse keeps a small sync module: Core's SyncHost impl and
a re-export of the engine.

No behaviour change. pdfs-sync depends on no FUSE or GTK crate.
2026-11-26 09:40:37 +01:00
nvrl 3e0e581bf8 style(fuse): sort the pdfs_drive re-export 2026-11-26 09:40:34 +01:00
nvrl 16970ecf35 refactor(drive,core): move the node and digest helpers the sync engine uses
parse_uid, remote_name_is_safe, node_content_sha1 and media_type_for
move to pdfs-drive next to node_revision_id, the SHA-1 helpers to
pdfs_drive::digest, and now_secs to pdfs_core::timestamp. pdfs-fuse
imports them under their old names. No behaviour change; one step
closer to moving the engine into pdfs-sync.
2026-11-26 09:40:34 +01:00
nvrl d428457514 refactor(fuse): give the sync engine its own state and a port to the daemon
The engine's methods ran on Core, so a pass could reach any lock in the
daemon. Its state (progress, folder locks, engine health, the channel to
the engine, unscanned and abandoned folders, the event-feed clock) now
lives in SyncParts with the handles it borrows, and what it needs from
the rest of the daemon goes through the SyncHost trait: the activity
feed, listing invalidation, the ancestry walk, mode settling and the
pause state. The engine's methods run on a Syncer, the two together.

No behaviour change. First half of moving the engine into pdfs-sync.
2026-11-26 09:33:45 +01:00
nvrl ff37d1b081 Merge pull request #146 from narrrl/fix/attach-past-trashed-root
fix(fuse): a synced folder in the trash no longer blocks every attach (B299)
2026-11-26 09:32:26 +01:00
nvrl 5c1a2c78b6 feat(core,cli): PDFS_INSTANCE runs a second client next to your own
With a name set, the client keeps its own XDG directories, Secret Service
entry, kernel keys and default mountpoint, and leaves the systemd unit
alone. A test account can then sign in without signing the user out.
scripts/live-bench.py uses it to time one edit in a synced folder, from
the write to the new revision on Drive.
2026-11-26 05:22:14 +01:00
nvrl 83938db712 fix(fuse): a synced folder in the trash no longer blocks every attach (B299)
The overlap check walked each existing synced folder's ancestry on Drive
and passed on the walk's failure, so one synced folder whose Drive folder
was in the trash failed every later attach with "remote sync folder is in
the trash". The check now walks through the trash, since a trashed folder
keeps its parent and still overlaps the folders above it, and skips a
folder that no longer exists.
2026-11-26 04:06:44 +01:00
nvrl bfe14b3fc9 Merge pull request #145 from narrrl/fix/conflict-by-hash
fix(sync): hash a both-changed file before keeping a conflict copy (B298)
2026-11-26 02:52:03 +01:00
nvrl bfa58357c9 Merge pull request #142 from narrrl/feat/lock-rank
feat(core,store,fuse): check the lock order in debug builds
2026-11-26 02:51:47 +01:00
nvrl 64906bd786 fix(sync): hash a both-changed file before keeping a conflict copy (B298)
When a mirrored file changed on both sides at the same size and Drive
has a digest, the planner now asks for the hash check it already did on
a first sync. An edit whose upload lost its answer then records a new
baseline instead of a conflict copy of itself. Different bytes take the
conflict path as before.
2026-11-26 02:46:49 +01:00
nvrl 6abb1a6cd9 Merge pull request #144 from narrrl/docs/bugs-sim-flakes
Land #140 on main
2026-11-26 02:45:20 +01:00
nvrl ce97b86638 Merge remote-tracking branch 'origin/main' into docs/bugs-sim-flakes
# Conflicts:
#	crates/pdfs-fuse/src/sim/daemon.rs
2026-11-26 02:42:31 +01:00
nvrl 3879ee7922 Merge pull request #143 from narrrl/refactor/pdfs-sync
Land #137, #138 and #141 on main
2026-11-26 02:37:08 +01:00
nvrl 6ecf713d3a Merge pull request #141 from narrrl/feat/drive-call-stats
feat(drive,fuse,cli): count and time every call to Drive in pdfs diagnostics
2026-11-26 01:58:28 +01:00
nvrl 220d0ed21a feat(core,store,fuse): check the lock order in debug builds
pdfs_core::lockrank::Ranked is a mutex with a rank. In a debug build, a
thread that blocks on a lock while holding one of a higher rank panics,
naming both. The synced-folder locks, shared publication, the inode tree
and the database writer take ranks in the order the code comments
already state: sync folder, publication, state, DB writer. Release builds
check nothing.
2026-11-26 01:44:41 +01:00
nvrl d40c7f7ebb Merge pull request #140 from narrrl/fix/sim-fail-fast
fix(sim): run one simulation's daemons at a time, and abort a mount that will not stop (B297)
2026-11-26 01:38:03 +01:00
nvrl fe9528ce29 Merge branch 'docs/bugs-sim-flakes' into fix/sim-fail-fast 2026-11-26 01:37:51 +01:00
nvrl b6ee07161c Merge pull request #139 from narrrl/docs/architecture-4.0
docs(architecture): the 4.0 target, its rules and its steps
2026-11-26 01:37:21 +01:00
nvrl 8e3e048005 feat(drive,fuse,cli): count and time every call to Drive in pdfs diagnostics
pdfs_drive::counted::Counted wraps any DriveApi and records, per method,
how many calls were made, how many failed, and their total and longest
time. The mount wraps its Drive in it before the first call, so the root
lookup counts too. Diagnostics gains drive_calls (serde default, so an
older CLI or daemon still reads the report), and pdfs diagnostics prints
it. A streaming batch call is counted when it starts, untimed.
2026-11-26 01:37:04 +01:00
nvrl c2f5537bd7 fix(sim): run one simulation's daemons at a time, and abort a mount that will not stop (B297)
Daemon::start takes a turn: a daemon started on one test thread waits
while another test thread still has one, so plain cargo test no longer
runs the simulations side by side. A stop that does not end within 60 s,
or a daemon alive after 20 minutes, aborts the mount's FUSE connection,
which the mounting user may do, so a mount that stops answering fails the
test instead of hanging the run.
2026-11-26 01:29:54 +01:00
nvrl 06d099f0de docs(architecture): the 4.0 target, its rules and its steps
Where 4.0 takes the daemon: services that own their state and threads,
behind ports, with dependencies pointing inward. Six rules to check in
review, and the steps from the current open fixes to pdfs-vfs.
2026-11-26 01:28:27 +01:00
nvrl c171a713cb Merge pull request #136 from narrrl/docs/bugs-sim-flakes
docs(bugs): B297, the simulations fail and hang when run in parallel
2026-11-26 01:10:37 +01:00
nvrl 23a961d020 Merge branch 'main' into docs/bugs-sim-flakes 2026-11-26 01:10:26 +01:00
nvrl d84b35c039 Merge pull request #135 from narrrl/feat/db-read-no-writer-fallback
fix(core,fuse): fail a read rather than wait on the writer, and keep one diagnostics probe
2026-11-26 01:09:55 +01:00
nvrl bf7d26ce23 docs(bugs): list B295 in the index 2026-11-26 01:04:33 +01:00
nvrl f34ed62f27 refactor: move the sync planner, pass model and trace into pdfs-sync
Third crate seam of 4.0. `sync/model.rs`, `sync/planner.rs` and
`sync/trace.rs` decide and record without doing I/O, so they move into a
new `pdfs-sync` crate that depends only on pdfs-core, pdfs-drive,
pdfs-store and the SDK's node types. The naming of conflict copies moves
with them as `pdfs_sync::naming`. `Applied` and the mtime and size
signature helpers move from `sync.rs` into the model, which uses them.
`node_revision_id` moves to pdfs-drive.

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

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

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

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

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

The diagnostics report counted queued operations on a new thread per report
and left it behind after half a second. The supervisor asks every tick, so a
database that did not answer gained a thread per tick. A probe now starts
only when the previous one has returned, and the count is reported as
unknown instead of 0 when it does not come back (B296).
2026-11-26 00:47:49 +01:00
nvrl 62ae18efbf docs(bugs): B297 is the simulations run in parallel
The local runs behind the first version left out --test-threads=1, which
CI and TESTING.md use. Run serially, the same branches pass in CI.
2026-11-26 00:34:34 +01:00
nvrl 7cffeb924d docs(bugs): B297, the simulations fail or hang about one run in two
Twelve local runs of the full suite on three branches based on main:
five passed, six failed and one hung. CI on main fails too. Records
which tests fail, with what, and the hang's stuck FUSE request.
2026-11-26 00:34:34 +01:00
nvrl b85c2bf786 Merge pull request #134 from narrrl/feat/sync-remote-dirty
feat(fuse,core): list only the folders that changed on Drive in a mirror pass (#53)
2026-11-26 00:26:26 +01:00
nvrl 2d9fb03d8b Merge pull request #133 from narrrl/fix/resize-scratch-refused
fix(fuse): fail a resize the scratch file refuses instead of recording it (B295)
2026-11-26 00:25:51 +01:00
nvrl c7c2197457 fix(sim): take the watchdog test's stacks in a process of its own
Taking stacks signals every thread of the process, and the handler
allocates. Run inside the shared test process, the watchdog test caught
other sims' daemon threads inside the allocator or holding the database
writer, and those never came back: the sims beside it hung.
2026-11-25 22:02:56 +01:00
nvrl 4ca085d001 feat(fuse,core): list only the folders that changed on Drive in a mirror pass (#53)
Every pass listed the whole mirror folder on Drive to find a few
changes, so a pass over half a million files took hours even when
nothing had changed.

A complete walk of Drive is now kept as the next pass's picture of
Drive (schema 49: sync_walk.complete, sync_remote_dirty). Folders are
marked dirty in two ways:

- the event stream marks the folder a changed node is in now, and the
  folder the saved walk last saw it in, since a move names only its
  new parent;
- triggers on sync_entry mark the folder of every baseline row a pass
  writes, so a pass never relies on the echo of its own change.

A pass loads the picture, lists the dirty folders again (shallowest
first), lists new folders whole, and drops what a folder no longer
holds with everything under it. It then drops the marks it read and
keeps the ones made meanwhile. A folder whose listing failed or came
back short is marked again. The event loop also starts a pass for each
folder it marked, so a change made elsewhere syncs within ten seconds.

The picture is only used when the folder's root is in the account's
own volume, the event stream was read in the last 30 s (a pass right
after a start waits up to 30 s for it), and the last full walk is less
than a day old. ContinuityLost and a new cursor drop every saved walk.

A folder's baseline row was written again on every pass, unchanged,
which would mark its parent every time; it is now written only when it
changes.

Tests: three DB tests for the marks and the listing replacement, and
the sim a_pass_lists_only_the_folders_changed_on_drive. It covers an
edit, a new folder holding a folder, and a deletion, all of which
arrive, and checks that a folder nothing changed in is never listed.
2026-11-25 22:02:56 +01:00
nvrl 293fda9177 fix(fuse): fail a resize the scratch file refuses instead of recording it (B295)
A resize through an open handle recorded the new length and claimed the
grown tail as written before calling set_len on the scratch file, and
ignored its result. A refused grow (full disk) then succeeded, and the
handle described bytes the scratch file never held.

WriteHandle::resize now resizes the scratch file first and records the
length and ranges only on success; setattr answers its error.
2026-11-25 21:47:09 +01:00
nvrl 0b9e849506 Merge pull request #132 from narrrl/feat/sync-walk-resume
feat(fuse,core): resume a mirror pass's walk of Drive after a restart (B294)
2026-11-25 21:26:08 +01:00
nvrl 180fa3f7d1 Merge remote-tracking branch 'origin/main' into feat/sync-walk-resume
# Conflicts:
#	docs/CHANGELOG.md
2026-11-25 20:29:11 +01:00
nvrl 163ff5c529 docs: publish SYNC_ENGINE.md in the wiki's Contributing section 2026-11-25 20:16:21 +01:00
nvrl 8a25eefa84 Merge pull request #130 from narrrl/fix/sync-starvation
fix(fuse,core): keep a mirror folder too large for one run from starving the rest (B294)
2026-11-25 20:11:29 +01:00
nvrl 82fc6fc06a Merge pull request #126 from RyanBeckett/feat/gui-file-manager-dnd
feat(gui): drag files to and from file managers, show uploads in place
2026-11-25 20:11:15 +01:00
nvrl f9b9320487 feat(fuse,core): resume a mirror pass's walk of Drive after a restart (B294)
The walk of Drive is the slow half of a pass over a large mirror folder.
It used to start over after every stop, so a folder too large to walk
between two restarts never synced.

The walk is now a queue of folders. Each listing is saved, together
with the subfolders it found, in one transaction (schema 48: sync_walk,
sync_walk_dir, sync_walk_item). A pass resumes a saved walk over the
same root that is less than 24 h old, and lists only the folders that
are left. A failed listing is not saved, so the next walk asks for it
again. Planning and the wipe guards still see the whole tree.

A saved listing is never used against a newer baseline. SQLite triggers
drop a folder's saved walk on any change to its baseline other than a
filled-in revision id, and on a change to the folder's path, root or
mode. The pass drops the walk once it is complete, before applying
anything, and fails if that does not work. The push pass drops it as
well. Otherwise a move to another synced folder would leave a listing
that reads the moved file as deleted on Drive.

docs/SYNC_ENGINE.md has the design of the coming state machine and
records why planning and applying are not yet split by subtree.
2026-11-25 19:53:30 +01:00
nvrl 2d5ec1bd08 feat(fuse,core,cli): trace where each sync pass spends its time
Each pass over a mirror folder now records how long its stages take
(lock wait, baseline, local walk, remote walk, plan, apply, cleanup).
It also records the count and the total and max time of each kind of
Drive call and applied op, how many items each stage handled, and the
slowest folder listing on Drive.

The trace is logged as "sync: pass trace" when a pass ends, is cut
short or runs longer than 30 s. The running pass and the last pass
over each folder go out in SyncEngineState::traces, which
`pdfs diagnostics` prints.

The new sim test found that a file uploaded by a pass gets a baseline
row without a revision id: Drive does not list the node at once, and
the upload returns only its uid. Since B294, the next pass reads such
a file in full once and records the id.
2026-11-25 14:52:56 +01:00
nvrl ae24b7179b fix(fuse,core): keep a mirror folder too large for one run from starving the rest (B294)
Issue #53: two folders sat at a month-old `error` while their passes were
cut short at every restart, and the folder after the large one never got
a turn.

- The remote walk stores the revision ids it confirms after each listing,
  so a cut-short pass no longer makes the next walk unlock every key again.
- A burst runs named folders first, then the rest smallest baseline first.
- A removal asks the running pass to stop at its next checkpoint and waits
  up to a minute instead of blocking a control handler for hours.
- Listing folders copies the progress map instead of holding its lock
  across database queries.
- The engine resets folders left `syncing` by a killed daemon to `error`.
- A pass logs a heartbeat every five minutes, its progress when cut short,
  and its first failed step when it ends in `error`.
2026-11-25 14:27:00 +01:00
nvrl ed164df7cc Merge branch 'main' into feat/gui-file-manager-dnd 2026-11-25 13:35:22 +01:00
nvrl 78a807e53e Merge pull request #129 from narrrl/fix/mount-key-recovery
fix(fuse,cli): wait for key recovery after a cold mount fails
2026-11-25 11:02:54 +01:00
nvrl ece7372e17 Merge branch 'main' into feat/gui-file-manager-dnd 2026-11-25 02:15:52 +01:00
nvrl 506ff32d08 Merge branch 'main' into fix/mount-key-recovery 2026-11-25 02:10:22 +01:00
nvrl 7c70995eb7 Merge pull request #128 from narrrl/fix/sign-in-block
fix(auth): clarify blocked sign-in without upgrade advice
2026-11-25 02:09:55 +01:00
nvrl 28daffa2b3 Merge pull request #127 from narrrl/fix/immutable-install
fix(packaging): check tarball compatibility before installation
2026-11-25 02:09:39 +01:00
nvrl b920c1730f fix(gui): copy-only drag out, copy for outside drops into the mount
Offer only COPY when dragging rows out, so a file manager can never move
a file out of the mount and delete it from Drive. Decide move or copy
from where the drag came from: rows of this app move, files from a file
manager browsing the mount are copied. Leave out each source that cannot
go to the target instead of failing the batch, skip paths with .., stat
dropped files off the main thread, skip symlinks the daemon does not
upload, restart the placeholder grace while transfers run, and keep
placeholder rows out of share lookups.
2026-11-25 02:06:27 +01:00
nvrl 45a41d4e5c fix(core,fuse): keep the mount failure file readable after a downgrade, test the key wait
Mark the wait for key recovery with a separate awaiting_keys field instead
of a null next_attempt, which an older daemon cannot parse. Pin the
missing-key match against a real rpgp decrypt failure, including the
try-every-key path, and test that a parked daemon pings the watchdog until
it is stopped.
2026-11-25 02:00:33 +01:00
nvrl eb60c8a95b fix(packaging): test a failing ldd, warn about a package in --check 2026-11-25 01:36:24 +01:00
nvrl ba426dcb3f fix(i18n): wrap the code 2028 catalog entries, match German imperative style 2026-11-25 01:32:11 +01:00
nvrl b15f6db802 fix(fuse,cli): wait for key recovery after a cold mount fails 2026-11-24 21:19:52 +01:00
nvrl e10cc13901 fix(auth): clarify blocked sign-in without upgrade advice 2026-11-24 21:18:16 +01:00
nvrl 73e2d1ec53 fix(packaging): check tarball compatibility before installation 2026-11-24 21:11:52 +01:00
Ryan BeckettandClaude Opus 5.5 9da34f62d6 feat(gui): drag files to and from file managers, show uploads in place
My files did not take part in drag and drop with the rest of the desktop:

- A row dragged out carried an app-internal path string, so a file manager
  or any other app got nothing it could use.
- On Wayland a file manager's drag reaches the drop target as MOVE alone
  (the action the compositor picked so far, not every action the source
  offers). The page answered only to COPY, so the drop was refused with no
  message and nothing uploaded.
- Every row took string drops, and a file manager's drag carries text too,
  so a drop onto a row was taken by the row and rejected.

Now a row (or the whole selection) drags as a file list under the
mountpoint. Rows decline drops unless they are folders, which take them;
anything else falls through to the page. A drop sorts the dropped paths:
ones inside the mount move through the daemon, the rest upload into that
folder. Outside drags are always answered with COPY, which makes the
compositor pick the copy, so a source never deletes what it handed over.
The Name cell fills its column, so the whole column is the drop zone.

Uploads (dropped, or through Upload Files / Upload Folder) show in their
folder at once as faded placeholder rows until a listing has the real
entry. A placeholder that never arrives goes once nothing is transferring
and it is past a short grace period. Placeholders carry a reserved uid and
cannot be opened, dragged, dropped onto, right-clicked or bulk-selected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 15:59:27 +00:00
Nils Pukropp 0ee4734b33 chore(aur): update packages to 3.10.0 2026-11-22 12:59:38 +00:00
nvrl 5ffaa2c437 Merge pull request #125 from narrrl/chore/release-3.10.0
chore(release): 3.10.0
2026-11-22 13:42:23 +01:00
nvrl 3694551158 chore(release): 3.10.0 2026-11-22 13:41:34 +01:00
nvrl a38829aace Merge pull request #124 from narrrl/fix/trash-listing
fix(trash): list a large trash, empty it, and browse it by folder
2026-11-22 13:23:13 +01:00
nvrl 3c6ebfb705 build: require proton-sdk and proton-drive-rs 0.12.6
0.12.6 treats the HTTP 202 answer to emptying the trash as success, so
Empty Trash no longer reports an error after it worked.
2026-11-22 13:03:30 +01:00
nvrl 4aa34cf8ce build: require proton-sdk and proton-drive-rs 0.12.5 2026-11-22 12:56:56 +01:00
nvrl d0f9681593 fix(trash): list a large trash, empty it, and browse it by folder
A large trash never finished listing, so the Trash page kept the rows of
the last refresh that got anywhere, and Empty Trash listed the trash before
sending the delete and hung there (B293). The paging fix is in
proton-drive-rs 0.12.5.

- The refresh reads only nodes it has not stored yet, without unlocking
  file keys, keeps the time the server says each was trashed, and drops
  rows only once the whole listing is in.
- Empty Trash sends the delete at once under the trash call time limit
  and clears the stored listing. Restore and Delete Permanently drop their
  rows right away.
- Schema v47 indexes trash.parent_uid and drops the stored rows once, so
  they are read again with real deletion times.
- The Trash page groups items by the folder they were deleted from, opens
  deleted folders through the new ListTrashedFolder request, and has a
  search box and a switch back to one list. Restore and Delete Permanently
  on a folder row act on everything deleted from it.
- pdfs trash takes --by-folder and --folder UID.
2026-11-22 02:38:48 +01:00
nvrl f141d88d97 Merge pull request #123 from narrrl/feat/offline-basemap
feat(gui): offline basemap under the Places map
2026-11-22 01:06:31 +01:00
nvrl 795dd7edb0 feat(gui): offline basemap under the Places map
Places now draws the proton-map-rs basemap that Proton Gallery uses: seas by
depth, lakes, rivers, built-up areas, borders and town names, in light and
dark. Tiles render on two worker threads into the existing tile layer, so
caching, ancestor stand-ins and density restarts work as before. Opening
Places sends no request.

The OpenFreeMap street map stays opt-in and replaces the basemap while it
is turned on. Without the basemap file the map falls back to the coarse
Natural Earth outlines.

scripts/fetch-basemap.sh downloads basemap-v1.pmtiles and checks it against
a pinned SHA-256. The deb, rpm, tarball, local and AUR PKGBUILDs, COPR spec
and Nix package install it to /usr/share/proton-drive-linux. PDFS_BASEMAP
points the app at another copy.

The new credit and preference text is translated in every catalog.
2026-11-22 00:44:14 +01:00
nvrl 7be4c7db1e Merge pull request #122 from narrrl/feat/protect-queued-changes
feat: protect queued changes at shutdown and sign-out (B66)
2026-11-21 23:46:37 +01:00
nvrl 2b5d6f2436 feat: protect queued changes at shutdown and sign-out (B66)
While the queue holds changes the drain can send, the daemon holds a logind
shutdown inhibitor through systemd-inhibit, so desktops show why a power-off
is held up. Parked transient files and changes that need the user never hold
it. pdfs sync flush retries failed changes and waits for the queue, exiting 3
when what is left needs the user and 4 on timeout. Signing out, in the app or
with pdfs logout, says how many changes are not on Proton Drive yet.
2026-11-21 23:42:54 +01:00
nvrl ff8ee9d997 Merge pull request #121 from narrrl/perf/takeout-parallel
perf(fuse): upload two Takeout photos at once
2026-11-21 23:07:35 +01:00
nvrl aa26a8e1aa Merge branch 'main' into perf/takeout-parallel 2026-11-21 23:07:08 +01:00
nvrl 9027a1465f perf(fuse): upload two Takeout photos at once
The import uploaded one photo at a time, leaving the link idle while each
upload waited on Proton between blocks. Staged photos now go to two upload
workers while the import thread reads the next one out of its archive. A
round ends only when its uploads have landed, so a live pair's video still
finds its still's uid. Photos without a thumbnail still stream straight from
the archive on the import thread. Warnings no longer name the photo.
2026-11-21 23:04:28 +01:00
nvrl 66b634e4a1 Merge pull request #120 from narrrl/chore/sdk-0.12.4
chore(deps): proton-sdk 0.12.4
2026-11-21 22:51:29 +01:00
nvrl ae46e1e544 chore(deps): proton-sdk 0.12.4 2026-11-21 22:49:27 +01:00
nvrl 2c4c95812f Merge pull request #119 from narrrl/chore/sdk-0.12.3
chore(deps): proton-sdk 0.12.3 and proton-gallery-rs 0.1.5
2026-11-21 17:12:11 +01:00
nvrl 2bf1622793 chore(deps): proton-sdk 0.12.3 and proton-gallery-rs 0.1.5
SDK 0.12.3 fetches a thumbnail with fewer round trips and caches the
thumbnail target per revision. proton-gallery-rs 0.1.5 advances the
Photos revision only when an album changed.
2026-11-21 17:08:41 +01:00
nvrl 2ea189f1d9 Merge pull request #118 from narrrl/chore/gallery-rs-0.1.3
perf(gui): cluster Places markers with proton-gallery-rs 0.1.3
2026-11-20 22:12:51 +01:00
nvrl 8af671d8ed perf(gui): cluster Places markers with proton-gallery-rs 0.1.3
The map kept its own copy of the marker clustering, identical to the one
in proton-gallery-rs. 0.1.3 makes that one fast (a grid of cells instead
of a scan of every bubble so far, same results), so the map now uses it.
2026-11-20 22:09:04 +01:00
nvrl 9047bdd741 Merge pull request #117 from narrrl/perf/photos-main-thread
perf(gui): keep Photos decoding and file access off the main thread
2026-11-20 21:48:52 +01:00
nvrl ca20e5ed22 perf(gui): keep Takeout staging file access off the main thread
The Import page read and wrote its remembered archive list, checked each
dropped path and stat'ed every staged archive on the GTK thread. Do all
of it on gio's blocking pool. Nothing is saved until the remembered list
has been read back, so it can't be overwritten by the empty list shown
meanwhile, and a late save never overwrites a newer one.
2026-11-20 20:47:47 +01:00
nvrl 10bc9a6a37 perf(gui): cap the Places map's photo marker covers
Every photo cover the map was shown while zooming around stayed in
memory for as long as the map existed. Keep at most 1024 and drop the
ones drawn longest ago, never a town's cover or one drawn this frame,
and ask for a dropped cover again when its marker returns.
2026-11-20 20:43:44 +01:00
nvrl 890adbc189 perf(gui): debounce the Drive gallery re-flow on resize
The Drive gallery rebuilt its whole row model on every frame the width
changed, so dragging the window edge rebuilt it dozens of times a
second. Lay out the first width at once as before, and wait for a resize
to settle (80 ms, like the timeline) before rebuilding.
2026-11-20 20:41:59 +01:00
nvrl 960c6afe2d perf(gui): decode Drive gallery thumbnails off the main thread
Drive gallery tiles and the hidden-album preview decoded the base64
reply and the image itself on the GTK thread. Do both on gio's blocking
pool, then re-check the request generation and lock state before
painting, as before.
2026-11-20 20:37:22 +01:00
nvrl 1b545ba369 perf(gui): look Drive gallery thumbnails up by key
The Drive gallery's thumbnail cache was a queue searched linearly on
every tile bind. Keep it in the shared LRU cache instead, still capped at
256 thumbnails, so a lookup and its touch no longer scan the queue.
2026-11-20 20:36:12 +01:00
nvrl b854c1e819 perf(gui): decode timeline thumbnails off the main thread
The Photos timeline decoded up to four thumbnails per idle pass on the
GTK thread, which stuttered a fast scroll. Decode each batch on gio's
blocking pool instead and only paint the results on the main thread.
Results from before a timeline reset are dropped, and tiles that were
unbound or rebound meanwhile are no longer waiting, so they are not
painted.
2026-11-20 20:34:41 +01:00
nvrl 3fbe651f94 perf(gui): budget the Photos texture cache by bytes
The timeline kept up to 1500 decoded thumbnails regardless of their size,
and marking one as used scanned the whole eviction order on every tile
bind. Replace it with an LRU cache keyed on decoded pixel bytes (512 MiB,
about 900 ordinary 512 px thumbnails) whose touch is logarithmic.
2026-11-20 20:32:59 +01:00
nvrl 61b992cb48 Merge pull request #115 from narrrl/fix/drive-gallery-header
fix(gui): give Drive galleries room under their header
2026-11-20 20:04:38 +01:00
nvrl 08e0e80f34 fix(gui): give Drive galleries room under their header
An open Drive gallery kept Add This Folder, Unlock and its options button
in a row of their own above the grid. The row took height from the photos
and left the options button touching the first row of tiles. They now sit
in the page's header bar, where the timeline keeps its own menu.

Rows in a Drive gallery also lose their extra side inset and use the
timeline's tile gap vertically too, and the options menu no longer lists
Refresh twice while hidden albums are locked.
2026-11-20 19:27:57 +01:00
nvrl 0488ccd5f6 Merge pull request #114 from narrrl/refactor/sdk-login
refactor(core): sign in through proton_sdk::login
2026-11-20 17:53:42 +01:00
nvrl 62d16e03cf refactor(core): sign in through proton_sdk::login
The sign-in sequence moved from proton_auth_rs::session into proton-sdk
0.12.2. Same stored session, same messages; pdfs-core keeps only the
keyring feature of proton-auth-rs.
2026-11-20 17:37:54 +01:00
nvrl c92f78b5c8 Merge pull request #113 from narrrl/refactor/shared-sign-in
refactor(core): sign in through proton_auth_rs::session
2026-11-20 15:52:58 +01:00
nvrl b034e1d4e3 Merge pull request #112 from narrrl/fix/po-catalogs
fix(i18n): bring every catalog up to date with the sources
2026-11-20 15:52:49 +01:00
nvrl e15e1dcc76 refactor(core): sign in through proton_auth_rs::session
The sign-in steps are now the sequence Proton Gallery and Proton Stream
share. The stored session, the lock/unlock choice for two-password
accounts, the three mailbox-password tries and the errors front-ends
word themselves are unchanged. An account whose only second factor is
a security key now gets a clear message instead of a code prompt that
could only fail.
2026-11-20 15:43:31 +01:00
nvrl 43b76d4791 fix(i18n): bring every catalog up to date with the sources
The Drive galleries, hidden albums and move-recovery strings had been
added without regenerating po/, so 11 were untranslated and 17 fell back
to unrelated fuzzy matches ("Hidden albums" showed as "No albums").
Regenerated with po/update.sh and translated in all eight languages.
2026-11-20 15:37:46 +01:00
nvrl 734e9040fb Merge pull request #111 from narrrl/refactor/proton-media-rs
refactor(fuse): block fetch single flight from proton-media-rs
2026-11-20 13:28:42 +01:00
nvrl 01e3860741 refactor(fuse): block fetch single flight from proton-media-rs
BlockFlight is now proton_media_rs::SingleFlight joined with the typed
block result. Same semantics: one fetch per block, the key retires
before the result is published, and a waiter whose leader is cancelled
fetches the block itself.
2026-11-20 13:27:59 +01:00
nvrl 7a65e7011f Merge pull request #110 from narrrl/refactor/proton-base-rs
refactor(core): atomic file writes from proton-base-rs
2026-11-20 12:51:09 +01:00
nvrl 233d9e9e51 refactor(core): atomic file writes from proton-base-rs
Config, machine id and mount-failure files go through
proton_base_rs::atomic. Same modes as before (config 0600, the others
0644); the mount-failure file is now synced before its rename.
2026-11-20 12:16:32 +01:00
nvrl 73c4e1f6bf Merge pull request #107 from narrrl/refactor/proton-rs
refactor(photos): take the Gallery engine from crates.io
2026-11-20 12:10:34 +01:00
nvrl 26272cda6c refactor(core): take the keyring store from proton-auth-rs
The Secret Service connection that reconnects after the provider
restarts (B285) and the item replacement that oo7 before 0.7.0 needs
(B291) moved to proton-auth-rs, shared with Proton Gallery and Proton
Stream. pdfs-core keeps one KeyringStore per process; the session format,
service and user are unchanged. The two secretservice tests moved with
the code.
2026-11-20 12:01:50 +01:00
nvrl 370abd58dc refactor(photos): use the shared photo logic from proton-gallery-rs
RAW+JPEG grouping, Takeout reading, EXIF capture times, look-alike
hashes and the offline town lookup now come from proton-gallery-rs
0.1.1, shared with Proton Gallery. PhotoKind::classify delegates to the
shared MediaClass; the extension lists live there. No behaviour change.
2026-11-20 04:16:52 +01:00
nvrl 24594b24ae refactor(photos): take the Gallery engine from crates.io
Replace the git revision pin on Proton Gallery with proton-gallery-rs and
proton-gallery-app-rs 0.1.0 from the proton-rs workspace. This also moves
the engine from 858d244 to b171232. The Nix package no longer needs to
fetch from Git.
2026-11-20 02:44:22 +01:00
nvrl 04f0713012 Merge pull request #106 from narrrl/feat/shared-gallery
feat(photos): release Proton Drive 3.9.0
2026-11-19 21:31:16 +01:00
nvrl cc020bfb54 feat(photos): unlock hidden albums with system login 2026-11-19 20:55:26 +01:00
nvrl 1e6043d12a fix(photos): keep hidden albums open after unlock 2026-11-19 20:44:44 +01:00
nvrl 834684f6d7 chore(release): prepare Proton Drive 3.9.0 2026-11-19 18:15:54 +01:00
nvrl 1c2a66169f feat(photos): embed galleries and speed up zoom
Keep album browsing and private galleries inside Photos. Build GTK
tiles near the viewport and anchor relayouts on the visible photo.

Migrate the Photos cache to persist pending event work with its cursor.
Pin the published Gallery engine for scoped private album reads.
2026-11-19 17:56:32 +01:00
nvrl cb5ff8b8da feat(photos): integrate the shared Gallery engine
Share gallery settings and layout with Proton Gallery. Preserve Git
source mappings so COPR can resolve the dependency offline.
2026-11-19 11:42:47 +01:00
nvrl c57d98799a fix(sync): explain moves blocked by Trash
Keep blocked moves queued so they can land after a restore. Retain
simulation logs for intermittent conflicts and pick up the SDK fix for
uploads from machines with fast clocks.
2026-11-19 05:01:52 +01:00
nvrl 7d9d5850a4 Merge pull request #105 from narrrl/feat/branding
Feat/branding
2026-11-19 01:13:39 +01:00
nvrl a69ebbdd10 chore(version) 2026-11-19 00:57:31 +01:00
nvrl ddf7335894 fix(cache eviction) fixed a bug which didn't scan past pinned files and now reapplies at startup 2026-11-19 00:54:47 +01:00
nvrl 140bd2eee3 Merge pull request #104 from narrrl/feat/branding
feat(branding) added new icons and branding
2026-11-18 11:16:58 +01:00
nvrl 2462cb24bd fix(removed old logo) 2026-11-18 01:42:13 +01:00
nvrl a1dd2b5a9b feat(branding) added new icons and branding 2026-11-18 01:35:08 +01:00
Nils Pukropp e9d6d4a907 chore(aur): update packages to 3.8.0 2026-11-16 00:32:51 +00:00
nvrl 6fa91e83f1 Merge pull request #81 from narrrl/chore/release-3.8.0
chore(release): 3.8.0
2026-11-16 01:23:44 +01:00
nvrl f239dffbcc Merge pull request #103 from narrrl/feat/sync-exclusions
fix(gui): show Excluded Files on the Sync page when every folder is o…
2026-11-16 01:01:01 +01:00
nvrl e011a0d89f fix(gui): show Excluded Files on the Sync page when every folder is online only
The group was hidden without a folder set to Synced, so it could not be
found. It now always shows, with the patterns for all folders and Add
Pattern, and says that patterns apply only to folders kept on this
computer.
2026-11-16 00:40:30 +01:00
nvrl f2c4c05f27 Merge pull request #102 from narrrl/feat/sync-exclusions
feat(gui,cli,core): add excluded-file patterns from the Sync page, for all folders or one (#99)
2026-11-16 00:24:11 +01:00
nvrl 8598aff7dd feat(gui,cli,core): add excluded-file patterns from the Sync page, for all folders or one (#99)
The Sync page's Folders view gets an Excluded Files group under the
folder list: one row for the patterns of all synced folders (opens
Preferences → Sync) and one per folder kept on this computer with its
count of own patterns (opens that folder's .pdfsignore editor). Add
Pattern asks for a pattern and where it goes: all synced folders or one
of them.

pdfs-core gains add_folder_pattern/remove_folder_pattern, which edit a
folder's rules line by line and read them again when sync changed the
file in between, and AppDirs::change_ignore_patterns, now shared by the
CLI and Preferences. `pdfs sync ignore list|add|remove` take --folder.
Preferences → Sync repaints from the config each time it opens, so a
pattern added elsewhere shows there.
2026-11-16 00:21:01 +01:00
nvrl 38a8db0e3e Merge pull request #101 from narrrl/feat/tarball-install
feat(packaging): an installable release tarball for immutable distributions (#99)
2026-11-16 00:12:21 +01:00
nvrl db8c0cb382 fix(packaging): use an if for the icon cache update in install.sh (SC2015) 2026-11-15 23:57:01 +01:00
nvrl a7baf2313c feat(packaging): an installable release tarball for immutable distributions (#99)
The release .tar.gz held the four binaries and their translations only,
and the service unit pointed at /usr/bin/pdfs, so it was no install on
its own. It now carries a /usr-like tree (bin, share, the user unit, the
tray's autostart entry) and install.sh, which installs it into ~/.local
without root:

- checks the libraries with ldd and names the packages to install per
  distribution, and that fusermount3 is there and setuid;
- refuses to install next to a package of the client;
- rewrites Exec= and ExecStart= to absolute paths, since ~/.local/bin is
  often not on a session's PATH;
- keeps a manifest, removes what an older version left, restarts a
  running service on update, and --uninstall leaves settings alone.

packaging/tarball/build.sh lays the tarball out and test.sh installs,
updates and uninstalls it in a throwaway home; the release job runs
both, CI runs shellcheck on them. The app looks for its translations in
share/locale beside its own bin directory and starts the tray from there,
so nothing needs PDFS_LOCALEDIR or the PATH. The -bin AUR package takes
every file from the new tarball instead of raw.githubusercontent.com.

INSTALL.md documents the tarball and layering the COPR package on Fedora
Atomic.
2026-11-15 23:57:01 +01:00
nvrl 7e0d7d020e Merge pull request #100 from narrrl/feat/settings-editor
feat(gui,core,cli): edit excluded files, open-with rules and the launcher in Preferences (#99)
2026-11-15 23:56:16 +01:00
nvrl 0df4b3c5f9 feat(gui,core,cli): edit excluded files, open-with rules and the launcher in Preferences (#99)
Preferences gains two pages for the config.json settings that had no
place in the app:

- Sync: the patterns every synced folder leaves out (own patterns, and
  each built-in one on or off), and what the conflict sweep may do.
- Apps: which program opens which kind of file (open_with), and how the
  search launcher opens (prompt).

Each synced folder kept on this computer gets "Excluded Files…" in its
menu for its own .pdfsignore: checked as typed, "Check a path" says
which rule decides, and a version changed elsewhere is never written
over without asking. `pdfs sync ignore list|add|remove|reset|check` does
the same from a terminal, and `--page preferences-sync` (and -apps,
-storage) opens Preferences at a page.

Every writer of config.json now goes through AppDirs::update_config,
which reads, changes and writes under an flock on config.json.lock, so
the app, the tray and the daemon no longer undo each other's change
(B292). The opener reads its rules on each open, so a new rule applies
without a restart.

The built-in ignore list also leaves out what Nextcloud, Dropbox and
Syncthing leave out: desktop.ini, .directory, trash folders, NFS/FUSE
leftovers, partial downloads, Kate swap and office lock files.
2026-11-15 23:03:58 +01:00
nvrl 14b9e0fe64 Merge pull request #98 from narrrl/fix/78-keyring-replace
fix(core): save the session by replacing its keyring item (#78, B291)
2026-11-15 20:46:39 +01:00
nvrl 64864562ef fix(core): save the session by replacing its keyring item (#78, B291)
Fedora 45 and 46 ship oo7-daemon 0.7.0~beta^1.e91b98a, which applies
SetSecret only in memory (fixed upstream in 7fb11dd, after that
snapshot). Every token rotation saved there was lost at the next
reboot, and the next start found a spent refresh token.

An existing entry is now written with CreateItem and replace, in the
old item's collection with its label and attributes, which that build
persists. A duplicate left behind is removed; the first save, a locked
item, ambiguity or any failure fall back to SetSecret. No prompt is
ever shown on this path.

The daemon also logs a short fingerprint of the refresh token at each
resume and each save, so a log across a reboot shows whether the
keyring returned the last token saved.
2026-11-15 20:31:43 +01:00
nvrl ce3bfa217d Merge pull request #97 from narrrl/fix/db-lock-fork-race
fix(core): retry the database lock briefly before calling it another daemon (B290)
2026-11-15 19:44:24 +01:00
nvrl 593df5c401 fix(core): retry the database lock briefly before calling it another daemon (B290)
A child spawned by another thread holds a copy of the lock descriptor
between its fork and its exec, so a reopen right after a drop could be
refused. Seen once in CI in
what_a_create_sent_outlives_a_newer_blob_its_trash_and_a_restart.
2026-11-15 19:42:22 +01:00
nvrl fd6b2d3e85 Merge pull request #96 from narrrl/chore/screenshots
chore: retake the screenshots from a demo account, by script
2026-11-15 19:20:45 +01:00
nvrl 34902390f3 chore: retake the screenshots from a demo account, by script
scripts/screenshots.sh builds the app and runs it in a headless cage
compositor against crates/pdfs-core/examples/demo_daemon.rs, a stand-in
daemon that answers the control socket with an invented account. HOME,
the XDG directories, the session bus and the keyring are throwaway ones,
and the demo daemon refuses to run outside them.

The old screenshots showed real folder names, paths and photo places.
All nine are retaken from the demo data.

pdfs-app --page also takes albums, places, places-map and sync-folders,
which the script uses to reach those views.
2026-11-15 19:20:07 +01:00
nvrl 1dcf7c84ca Merge pull request #95 from narrrl/fix/takeout-import-94
fix(fuse,core,gui,cli): resumable, robust Google Photos import (#94)
2026-11-15 17:25:39 +01:00
nvrl a05772aa13 docs: keep the SDK 0.12.0 review out of the wiki 2026-11-15 17:23:45 +01:00
nvrl 2f2fe96cdf fix(fuse,core,gui,cli): resumable, robust Google Photos import (#94)
A Takeout import cut short by a restart could never be resumed: the
duplicate check failed on the draft the interrupted upload left behind
("invalid type: null, expected a string"). SDK 0.12.0 skips such drafts,
lets the import replace them across logins, and removes the draft of a
failed upload (B285, B286).

The import keeps its archives and outcome in the state directory, so a
run the service did not finish is reported as interrupted and can be
resumed from the app or with `pdfs import-google-photos --resume`. An
unreadable archive is left out instead of failing the scan, a failure
keeps its counts and still files albums, and a cancel or shutdown is
only reported when work was left undone (B287).

ImportStatus carries the phase, its progress, the running counts and
what can be resumed; the summary says dry_run, to_upload and
error_kind. The app shows these in the user's language, and --wait
prints progress. An empty gallery waits for a timeline refresh already
running instead of starting a second one.

The scan imports only the Photos service of an export, reads geoData
into the photo's Location, pairs live and motion photos (.MOV, .MP) with
their stills, and dates a photo by name and EXIF before Google's upload
time (B288).
2026-11-15 17:17:47 +01:00
nvrl 2ec3b7ff62 Merge pull request #93 from narrrl/fix/78-reconnect-secret-service
fix(core): reconnect to the Secret Service after it restarts
2026-11-15 16:23:54 +01:00
nvrl 38bd282d3a fix(core): reconnect to the Secret Service after it restarts
The keyring store keeps one D-Bus connection and one Secret Service
session for the whole process, and was installed once. The session lives
only in the provider's memory, so after the provider restarts every read
and write on it fails with NoSession until the process restarts. oo7,
the provider on Fedora 45, restarts on failure and can be replaced. A
daemon that met this kept every later token refresh only in memory and
the kernel keyring, and the next cold boot found the spent refresh token
(issue #78, B285).

Every keyring call now goes through with_keyring_entry. A platform
failure drops the store, unless another thread already replaced it, and
the call is made once more on a new connection. A locked keyring, a
dismissed prompt and a missing entry come back unchanged.

Reproduced against gnome-keyring 51.1 and oo7 0.7.1 restarted with
--replace in a throwaway session bus; the ignored test
real_secret_service_survives_a_provider_restart passes against both.

Refs #78
2026-11-14 19:17:11 +01:00
nvrl d773ba15d3 Merge pull request #92 from narrrl/feat/audio-cover-thumbnails
feat(gui,fuse,core): album covers for songs, thumbnails that appear live
2026-11-14 17:44:22 +01:00
nvrl d93982baa9 feat(gui,fuse,core): album covers as song thumbnails
A song in a listing showed a generic icon, and the player a music note.
Both now show the song's cover: the picture in its tags, read with
lofty, or else a cover, folder, front or album image in its folder.

Only the tags are downloaded. A song up to 4 MiB comes whole. A larger
one brings the ID3v2 tag or the FLAC metadata blocks at its start, an
M4A's moov box, the first 4 MiB of an Ogg file, and the last 4 MiB for
formats that keep their tags at the end. The parts are laid out in a
sparse staging file at their own offsets, as video samples are.

A folder cover comes from that image's cached thumbnail, the thumbnail
its uploader attached, or the image itself. It is stored under the song.
Uploads of songs carry their embedded cover as the Drive thumbnail.
2026-11-14 16:48:08 +01:00
nvrl 3f5001b2d2 fix(gui,fuse,core): fill in thumbnails without reopening the folder
Build thumbnails cancelled the requests of the tiles on screen, and those
tiles stayed blank until the folder was opened again, or the whole
recursive build ended.

The daemon now publishes a new Topic::Thumbnails whenever a batch made
at least one thumbnail. The app keeps the tiles still showing their icon
across a cancel, and asks for them again on that event, whatever page is
open. Older front-ends read the topic as Unknown, and older daemons never
send it.
2026-11-14 16:27:57 +01:00
nvrl 2308021aa2 Merge pull request #91 from narrrl/feat/media-player
feat(gui): play videos and music in the app
2026-11-14 15:58:17 +01:00
nvrl 602f1c9577 feat(gui): play videos and music in the app
Opening a video or a song in My files, by a double-click or Open, now
plays it in an in-app player window, streamed from the mount as before.
Open With… is the way to another player, and the separate Play item is
gone. A file GStreamer can't play shows the error with Open With….

Both that player and the Photos lightbox share the new widgets/player.rs:
a fullscreen button, fullscreen on a double-click, Repeat in the ⋮ menu,
K to play and pause, J/L or Shift+arrows to jump 10 seconds, M to mute,
and a volume that carries over between videos. The lightbox's thumbnail
strip stays off a video, where it covered the seek bar.
2026-11-14 15:57:10 +01:00
nvrl 9132c7ebd5 Merge pull request #90 from narrrl/feat/photos-drag-out
feat(gui): drag photos out of the timeline, upload progress bar
2026-11-14 15:44:55 +01:00
nvrl 94304ccc1a Merge pull request #89 from narrrl/fix/78-retain-unsaved-session-tokens
fix(core): retain unsaved session tokens
2026-11-14 15:37:44 +01:00
nvrl 74cd6fd2a9 fix(gui): keep paging the timeline when zoomed out onto one screen
Zoomed all the way out, a 200-photo page fits on one screen. With
nothing to scroll, the scroll handler never asked for the next page and
the timeline stopped after the first rows. Ask for more whenever the
content no longer fills a screen and a half, also after a zoom step or
a resize, not only when a page lands.
2026-11-14 15:33:41 +01:00
nvrl 4b669168ee feat(gui): drag photos out of the timeline, upload progress bar
- A drag that starts on a selected tile carries the selection out as a
  text/uri-list. PhotoDrag, a gdk::ContentProvider, downloads the photos
  only when the receiver reads the list, and hands over hard links (or
  copies) under their Drive names in the user cache; copies older than
  a day are pruned. Drag-select steps aside for such a drag, and the
  timeline's own drop target ignores drags from inside the app.
- Uploading several photos shows "Uploading 3 of 12 items…" with a
  progress bar under the Photos header, replacing the start toast.
  Photo uploads report no byte progress from the daemon, so the bar
  counts files; per-tile rings would need that first.
2026-11-14 15:25:26 +01:00
nvrl ba5b6a8bf2 fix(core): retain unsaved session tokens
Retry token persistence when the keyring reports a missing session.
oo7 can hide locked entries, so discarding the pending rotation leaves
a spent refresh token in the saved session.

Refs #78
2026-11-14 15:18:27 +01:00
nvrl 3295eda1f0 Merge pull request #88 from narrrl/feat/photos-drag-upload
Feat/photos drag upload
2026-11-14 14:38:24 +01:00
nvrl 41212efdf3 feat(gui,fuse,core): share photos, copy image, thumbnail strip in the viewer
- Share… in the grid's photo menu and the viewer's ⋮ menu opens the Share
  dialog by uid. The daemon accepts a uid from the Photos timeline for
  sharing (resolve_shareable), since the photos volume is in no mount.
  Photos in an album someone else shared are not offered.
- Copy Image (Ctrl+C) puts the shown still on the clipboard. The viewer
  has its own toast overlay, so this and Save a Copy confirm over it
  instead of behind it.
- A thumbnail strip along the viewer's bottom edge, on the gallery model,
  marks the shown photo and jumps on click. Several pictures can now
  wait for one thumbnail, so the strip and the grid tile don't steal it
  from each other.
- PhotoItem carries place_id (serde default); the line under the
  viewer's title reads "Berlin · 12 of 340".
2026-11-14 13:58:25 +01:00
nvrl 5f0b15fe70 fix(gui): a photo viewer bar that reads on any photo
The bar's white-on-translucent-white buttons vanished over a bright photo,
and eight look-alike icons, a floppy disk and an open-document glyph among
them, left the user guessing. The bar now holds the favorite, the details
and a menu with Slideshow, Save a Copy, Open With, Add to Album, Show on
Map and Move to Trash, on dark discs that read over white and black
alike.

A shot stored as more than one file shows a labelled pill ("RAW", "Live",
"2 of 3") instead of a paged icon, lit while the second file is shown.
The title is the localized full date instead of a raw timestamp.

Delete asks first, as the grid does: the dialog opens over the viewer,
and the album prompts can open there too. Alt+Left closes the viewer and
F10 opens the menu; the shortcuts window lists F5, F10 and Alt+Left.
2026-11-14 13:37:50 +01:00
nvrl 033c8d3d71 Merge pull request #86 from narrrl/fix/keep-place-when-navigating
fix(gui): keep the user's place when navigating
2026-11-14 12:57:35 +01:00
nvrl 5c184013f1 feat(gui): restore folder places and add keyboard Back
Back, Forward and Up in My files restore the folder's scroll offset and
selection as they were when it was left; opening a folder any other way
still starts at the top.

Closing the photo viewer scrolls the grid to the photo it showed last.

Alt+Left and Backspace go back a level in Shared with me and Computers
and leave an open album or place; Escape leaves an album or place too,
after ending selection mode. The shortcuts window lists it.

A fresh Photos load, or leaving the grid for Albums or Places, ends a
scrubber jump that was still paging.
2026-11-14 12:53:27 +01:00
nvrl 6be8a8f9bc fix(gui): keep the user's place when navigating
A folder opened in My files, Shared with me or Computers kept the scroll
offset of the folder before it, because the rows are swapped in place to
keep a refresh steady. Another folder, a new search and a fresh Photos
load (filter, album, place) now start at the top; a refresh still keeps
its place.

Closing a photo opened from the Places map returns to the map instead of
leaving the town's timeline behind, and the pending open is dropped when
the user leaves the town before it loads.

load_gallery no longer swaps Albums or Places for the timeline when a
page lands late (viewer paging, upload, trash Undo); the timeline is
marked stale and read when the user switches back. Coming back to Photos
reuses the timeline unless it is stale, and the timeline returns
filtered the way the kind tabs and date show after an album or place.

A search in My files is no longer replaced by the folder listing on file
changes, F5 or returning to the page. A favorite set in the viewer shows
on its tile at once.
2026-11-14 12:53:04 +01:00
nvrl 7d445bb02c Merge pull request #84 from narrrl/feat/video-thumbnails
feat(gui,fuse,core): video thumbnails in file views
2026-11-14 03:43:36 +01:00
nvrl 57acb0b849 chore(po): refresh source references after the merges 2026-11-14 03:08:17 +01:00
nvrl 68ff8c9e80 Merge remote-tracking branch 'origin/feat/photos-redesign' into release-prep
# Conflicts:
#	docs/BUGS.md
#	docs/CHANGELOG.md
2026-11-14 02:57:11 +01:00
nvrl 4552093c53 Merge remote-tracking branch 'origin/main' into release-prep
# Conflicts:
#	docs/CHANGELOG.md
2026-11-14 02:55:06 +01:00
nvrl f2a9a0f64b feat(gui): Ctrl+scroll changes the icon size in My files
Scrolling with Ctrl held over the icon grid steps the icon size, as it
does in Photos. Touchpad deltas add up to a whole notch before each
step, so a small swipe does not jump through every size.
2026-11-14 02:49:41 +01:00
nvrl e571f22d5d feat(gui,core): larger icon sizes in My files
The icon grid's size slider stops at 256 px instead of 144 px, which is
big enough to tell photos apart by their thumbnail. Thumbnails are
512 px, so they stay sharp at that size on a 2x screen. Names may wrap
wider on the larger tiles.

Ctrl+plus, Ctrl+minus and Ctrl+0 step and reset the size while the grid
is shown, as they do in Photos. The size is saved in the config as
files_view.icon_size once the slider rests; configs without it keep the
72 px default.
2026-11-14 02:48:29 +01:00
nvrl 1c50797772 feat(gui,core): modern Photos layout
Lay the timeline out in justified rows. Each photo keeps its own shape,
clamped between 1:2 and 5:2, and every row but a section's last spans
the width to the pixel. "Square Tiles" in the page menu restores the
even grid, and the Year zoom stays square. The zoom level and the
tile shape persist in a new `photos_view` config section.

Move Timeline/Albums/Places into the header as an icon-and-label
switch that shows only icons in a narrow window. The filters take a
single row whose kind tabs scroll sideways.

Selection mode follows GNOME apps:
- the header shows "N selected" and Cancel;
- an ActionBar along the bottom offers Favorite (or unfavorite), Add
  to Album, Remove from Album, Save Copies and Move to Trash;
- each section heading gets a check that selects the whole section.
One function, sync_header, decides the header for the page, an open
album or place, and selection mode.

The heading of the section at the top of the grid floats over the
grid. Favorites get a star badge, and video placeholders a video
glyph. New bundled icons: pdfs-photos, pdfs-album and pdfs-slideshow.

Upload takes several photos and videos at once, and files dropped on
the timeline upload too. The media type comes from the MIME database,
except that a recording-sized .ts counts as video.

The viewer's details panel moves into an OverlaySplitView that lies
over the photo below 800sp.
2026-11-14 02:40:38 +01:00
nvrl 0183f17435 feat(gui,fuse,core): video thumbnails in file views
My files, Shared, Trash and the launcher now ask the daemon for video
thumbnails, not only image ones. Grid tiles with a video thumbnail show
a small play badge.

A `.ts` file is a video from 1 MiB up and a TypeScript source below
that. One rule in pdfs-core (`is_video_file_name`) decides it for the
file icon, the thumbnail gate, the launcher icon and preview, and the
opener's `@media` / `@text` classes. The daemon also checks the MPEG-TS
sync byte before it runs ffmpeg, so a large TypeScript bundle gets no
retries.

A video thumbnail no longer downloads the whole file into memory (B283):
- the server thumbnail is tried first, at no content cost;
- files up to 24 MiB come whole;
- larger ones bring a 16 MiB head, plus the MP4/MOV `moov` box when it
  lies past the head, into a sparse staging file that ffmpeg reads.
The 256 MiB cap is gone. Without ffmpeg, a video answers "no thumbnail"
at once. The folder thumbnail build includes videos.
2026-11-14 02:17:18 +01:00
nvrl 14a663cee9 fix(fuse): keep pinned files on disk through remote changes
A remote change to a pinned file called `ContentCache::evict`, which does
not check pins, and only the pin request itself ever downloaded anything.
An edit from another device, or even a rename, left the file listed as kept
offline with no copy, so the next read downloaded it or failed without a
network. A file added to a pinned folder elsewhere was never downloaded,
and a folder pin whose downloads failed while offline never retried them.

A remote change no longer evicts a pinned file's copy. The copy is checked
against the revision's (mtime, size), so a newer revision does not read
it, and a rename keeps the mtime (B123), so the copy stays valid. A new
pdfs-pin-keeper thread checks pins again and downloads files that are
missing or stale:

- the pins a batch of remote events changed, after the batch's listings
  are dropped, including a pinned folder that gets a new file;
- every pin at startup, when the link returns, and after the event feed
  loses continuity;
- a file whose version is restored.

Failed downloads retry with a backoff of 30 s to 30 min. Pinning and the
keeper settle a provisional size first: a copy stored under the
ciphertext size never matched the plaintext it holds.

Fixes B282.
2026-11-14 00:20:06 +01:00
nvrl 3f45e89391 fix(fuse): keep files offline in on-demand synced folders
`pdfs pin` and `pdfs unpin` resolved every path against the primary mount
with `rel_to_mount`. An absolute path in an on-demand synced folder such as
~/Pictures was refused as "not under the mountpoint", and a relative path
named a file in My files instead. A synced folder's file is a different
Drive node from a same-named file in My files, so keeping one offline did
nothing for the other, and every program reading the synced copy
downloaded it.

Pin and unpin now route through `route_to_mount`, like ls, refresh, rm and
mv since B86, and run on the mount that owns the path. A path in a mirror
folder gets an error saying its files are already on this computer. A pin
made through an on-demand folder records the absolute local path, so
`pdfs pins`, the prompt and the HUD open the file where it was kept; pins
under the primary mount still record the mount-relative path.

Fixes B281.
2026-11-14 00:20:06 +01:00
nvrl b49631e18f Merge pull request #82 from narrrl/feat/shell-completions
feat(cli,core): shell completions with live values from the service
2026-11-12 11:48:12 +01:00
nvrl ad648ab5cc feat(cli,core): shell completions with live values from the service
`pdfs completions <shell>` prints a completion script for bash, zsh, fish,
elvish or PowerShell, built on clap_complete's dynamic engine: on Tab the
shell calls `pdfs` back, which completes commands and options and also the
values the running service knows, each with a description: paths in My
files, synced-folder and queue ids, computers, trash, albums, items shared
with me, invitations, bookmarks, conflict copies, and a file's versions or
a share's members and public link once its path is typed.

A completer that gets no answer from the service within two seconds offers
nothing rather than hanging the prompt. Listings that ask Proton are kept
for 30 s in $XDG_RUNTIME_DIR (0600), so repeated Tabs do not wait again.
Completion is triggered by PDFS_COMPLETE rather than clap's generic
COMPLETE, because the same binary runs the daemon.

Share roles are now checked by the CLI before the request. The package
recipes install the bash, zsh and fish scripts via packaging/completions.sh.
2026-11-12 11:47:29 +01:00
nvrl f25c2459a0 feat(cli,core): shell completions with live values from the service
`pdfs completions <shell>` prints a completion script for bash, zsh, fish,
elvish or PowerShell, built on clap_complete's dynamic engine: on Tab the
shell calls `pdfs` back, which completes commands and options and also the
values the running service knows, each with a description: paths in My
files, synced-folder and queue ids, computers, trash, albums, items shared
with me, invitations, bookmarks, conflict copies, and a file's versions or
a share's members and public link once its path is typed.

A completer that gets no answer from the service within two seconds offers
nothing rather than hanging the prompt. Listings that ask Proton are kept
for 30 s in $XDG_RUNTIME_DIR (0600), so repeated Tabs do not wait again.
Completion is triggered by PDFS_COMPLETE rather than clap's generic
COMPLETE, because the same binary runs the daemon.

Share roles are now checked by the CLI before the request. The package
recipes install the bash, zsh and fish scripts via packaging/completions.sh.
2026-11-12 11:43:53 +01:00
nvrl ce35a83a04 Merge pull request #79 from narrrl/chore/sdk-0.11.0
build(sdk): bump to 0.11.0
2026-11-12 10:25:00 +01:00
nvrl 762d06765e Merge pull request #80 from narrrl/fix/stale-mount-watchdog-startup
fix(fuse,cli): recover the mount after a watchdog kill and bound thumbnail memory
2026-11-12 10:24:43 +01:00
nvrl 2b95708260 chore(release): 3.8.0 2026-11-12 10:22:04 +01:00
nvrl c78bb529bc fix(fuse): bound memory held by thumbnail decodes
Every image upload decodes the whole file to build its thumbnail, and
nothing limited how many decodes ran at once. With a queue of large
photos all 16 drain workers decoded together; 100-megapixel JPEGs held
about 9 GiB, swapped the machine, and the watchdog killed the daemon on
every restart.

Each decode now takes a share of a process-wide 512 MiB budget, sized
from the encoded length and the header's pixel count. Phone photos still
decode side by side; a photo larger than the budget waits and runs alone.

Records B280.
2026-11-12 00:55:19 +01:00
nvrl 8d824af656 fix(fuse,cli): recover the mount after a watchdog kill
A daemon killed by the watchdog left its FUSE mounts dead. A dead mount
answers ENOTCONN, which create_dir_all took for an absent directory, so
every restart failed with EEXIST and retried forever without reaching the
code that clears stale mounts. mount_once now goes through
prepare_mountpoint, which clears a dead mount first.

Startup on a large account (70 s hydrating 48k nodes) plus the supervisor's
first ping one full period later outlasted WatchdogSec=120, so a restart
that did mount was aborted again. The daemon now asks for a 10-minute
watchdog before startup, the supervisor pings on its first tick, and the
unit's own timeout is restored once the control socket answers.

Records B279.
2026-11-12 00:38:50 +01:00
nvrl a0ab243be6 Merge branch 'main' into chore/sdk-0.11.0 2026-11-09 14:36:49 +01:00
nvrl c77c548d7e Merge pull request #77 from danielebrox/feat/sync-attach-my-files
feat(sync): attach local folders to existing My files folders
2026-11-06 22:58:16 +01:00
nvrl 2930b457d4 fix(docs): exclude SDK review from wiki 2026-11-05 19:18:18 +01:00
nvrl d9da0e2263 build(sdk): bump to 0.11.0 2026-11-05 19:12:21 +01:00
nvrl d4a14a17a8 fix(sync): isolate My files attachments
Schema 45 separates attachments from device backups so stopping sync or
changing mode cannot trash My files folders or evict their local data.
Exclude attachments from device profiles and validate device restores.

Verify attached roots before each pass and cover both local views,
concurrent edits, removal guards, and root loss across daemon restarts.

Refs #77
2026-11-05 17:11:57 +01:00
danielebrox 5ca0272f15 feat(sync): attach local folders to existing My files folders 2026-11-02 19:23:49 +01:00
Nils Pukropp 800705ccb0 chore(aur): update packages to 3.7.0 2026-11-02 15:16:31 +00:00
nvrl 7ab14bb8f7 Merge pull request #76 from narrrl/chore/release-3.7.0
chore(release): 3.7.0
2026-11-02 15:34:08 +01:00
nvrl 9c8b6680a7 chore(release): 3.7.0 2026-11-02 15:18:39 +01:00
nvrl bbd913b87d fix(cli): show the last sync as a time in sync list and devices list
`pdfs sync list` and `pdfs devices list` printed the last sync as epoch
seconds, such as `synced: 1793570850` in issue #46. Both columns now go
through `last_synced`, which formats it like `pdfs activity` and prints
`never` for a folder that never synced. `--json` output is unchanged
(B278).
2026-11-02 15:18:31 +01:00
nvrl 04f4610e4d Merge pull request #75 from narrrl/fix/footer-cant-open
fix(gui): say "Can't open your Drive" in the sidebar while a mount keeps failing
2026-11-01 18:09:25 +01:00
nvrl 0a5afd0b6a Merge pull request #74 from narrrl/docs/verify-3.7.0-run
docs(bugs): mark B276 and B258 checked by the 3.7.0 account run
2026-11-01 18:01:43 +01:00
nvrl 163c54a1e9 fix(gui): say "Can't open your Drive" in the sidebar while a mount keeps failing
The service can run while its mount fails on every try, for example over
a folder with files in it (B277). The page then said "Can't open your
Drive", but the sidebar status read "Not connected / Proton Drive isn't
running", which was wrong. paint_disconnected now reads the same failure
record the pages read, once the service is known to be running, and
shows "Can't open your Drive" with the reason. A reply from the daemon
that lands while it looks wins.
2026-11-01 17:55:52 +01:00
nvrl 0d7c6e7bae docs(bugs): mark B276 and B258 checked by the 3.7.0 account run
The account run of `scripts/fuse-acceptance.sh --journal-check --durability`
on 2026-11-01, against a build of main, passed 464 cases with 103 skipped.
Its eight daemon restarts left no panic in the journal (B276), and
`journalctl -p warning` listed every WARN line the run logged (B258).
2026-11-01 17:47:23 +01:00
nvrl 10252fa84b Merge pull request #73 from narrrl/docs/changelog-3.7.0
docs(changelog): record the changes merged since 3.6.0
2026-11-01 16:33:55 +01:00
nvrl bf9ec0862a docs(changelog): record the changes merged since 3.6.0
Entries for #55 to #65 and #70, which merged without one.
2026-11-01 16:20:18 +01:00
nvrl d0d0c73a51 Merge pull request #72 from narrrl/fix/wipe-guard-majority
fix(fuse): stop a sync pass when nearly all of a large folder vanishes
2026-11-01 16:19:54 +01:00
nvrl 129ad1a50d fix(fuse): stop a sync pass when nearly all of a large folder vanishes
The wipe guards refused a pass only when every synced path was missing
on one side. One surviving file cleared them, so a half-mounted disk,
a restored backup that brought back one file, or a script that emptied
the folder and wrote one back made the next pass trash everything else
on Drive, and on every computer syncing the folder (B270).

Both guards now also refuse when nine in ten or more of the tracked
paths of a folder with at least 20 are missing at once. A smaller
folder still stops only on a total loss, since an ordinary cleanup can
delete most of it. The reason now gives the count.

B270 stays partly fixed: a smaller loss still goes through, and the
app does not yet offer to confirm the deletions.
2026-11-01 16:06:08 +01:00
nvrl 506a610273 Merge pull request #71 from narrrl/fix/refuse-non-empty-mountpoint
fix(core,fuse,cli,gui): refuse to mount My files over a folder with files in it
2026-11-01 16:05:38 +01:00
nvrl 5048492a83 fix(core,fuse,cli,gui): refuse to mount My files over a folder with files in it
FUSE mounts over a non-empty folder without complaint, so files already
in the My files folder were hidden under the mount: not uploaded, and
back only once the service stopped, so they looked deleted (#67, B277).

- pdfs-core: new `mountpoint` module. `not_empty` lists what is in a
  folder (hidden entries count); `mounted_fs_type` moves here from the
  CLI so the daemon can use it. `MountFailure` gains an optional
  `not_empty` field, which older readers ignore.
- pdfs-fuse: `mount_with` checks the folder before the root fetch and
  before any worker starts. A dead mount is cleared first; one of our
  own live mounts is left to `spawn_session`, as before.
- pdfs-cli: `cmd_daemon` records the folder in the failure record. The
  refusal backs off and retries like any mount failure, so emptying the
  folder is enough.
- pdfs-gui: the status pages explain the refusal, and a dialog offers
  to open the folder or choose another one, once per run of failures.
  The folder picker refuses a folder with files in it.

Translated in all catalogs. Docs: BUGS (B277), CHANGELOG, FAQ,
TROUBLESHOOTING, CONFIGURATION.
2026-11-01 15:30:28 +01:00
nvrl 321547fb77 Merge pull request #70 from narrrl/chore/deps-2026-11
chore(deps): update dependencies, bump parking_lot, rusqlite, gettext-rs
2026-11-01 15:11:09 +01:00
nvrl a06a8150fb chore(deps): update dependencies, bump parking_lot, rusqlite, gettext-rs
Refresh Cargo.lock to the newest compatible versions and move three
crates to their next minor release:

- parking_lot 0.12 -> 0.13
- rusqlite 0.40 -> 0.41 (newer bundled SQLite)
- gettext-rs 0.7 -> 0.8

gettext-rs 0.8 marks setlocale as unsafe; the three calls in i18n.rs
run before any thread starts, the same precondition the set_var calls
next to them already state.

rustc 1.99 deprecates AtomicX::fetch_update in favour of try_update
(stable since 1.95, below the 1.96 minimum), which failed
`clippy -D warnings` on main. Rename the two uses so clippy passes
without `-A deprecated`.

The open Dependabot alerts for zip (< 9.0.5) and rustls (< 0.23.46)
are already resolved on main by #69 (zip 9.2.0, rustls 0.23.46).
2026-11-01 13:55:32 +01:00
nvrl c4bce50d35 Merge pull request #52 from narrrl/fix/create-landing-counted
fix(fuse,core): count a new file's landing until its bytes are cached
2026-11-01 12:06:39 +01:00
nvrl d2b5916b99 Merge remote-tracking branch 'origin/main' into fix/create-landing-counted 2026-11-01 11:28:03 +01:00
nvrl 4626ce17a7 Merge pull request #69 from narrrl/dependabot/cargo/cargo-f3dd2e6b0d
build(deps): bump the cargo group across 1 directory with 2 updates
2026-11-01 11:27:45 +01:00
nvrl 630f316fe6 Merge pull request #65 from narrrl/fix/clean-stop-runtime
fix(cli): leave the runtime running on a stop so stragglers cannot panic
2026-11-01 11:27:41 +01:00
nvrl 801681f747 Merge remote-tracking branch 'origin/main' into fix/create-landing-counted
# Conflicts:
#	docs/BUGS.md
2026-11-01 11:14:15 +01:00
nvrl e7382f2c7e test(core): name zip's options type the way zip 9 accepts 2026-11-01 11:12:17 +01:00
dependabot[bot] 7046f0f3ef build(deps): bump the cargo group across 1 directory with 2 updates
Bumps the cargo group with 2 updates in the / directory: [zip](https://github.com/zip-rs/zip2) and [rustls](https://github.com/rustls/rustls).


Updates `zip` from 8.6.0 to 9.0.5
- [Release notes](https://github.com/zip-rs/zip2/releases)
- [Changelog](https://github.com/zip-rs/zip2/blob/master/CHANGELOG.md)
- [Commits](https://github.com/zip-rs/zip2/compare/v8.6.0...v9.0.5)

Updates `rustls` from 0.23.45 to 0.23.46
- [Release notes](https://github.com/rustls/rustls/releases)
- [Changelog](https://github.com/rustls/rustls/blob/main/CHANGELOG.md)
- [Commits](https://github.com/rustls/rustls/compare/v/0.23.45...v/0.23.46)

---
updated-dependencies:
- dependency-name: zip
  dependency-version: 9.0.5
  dependency-type: direct:production
  dependency-group: cargo
- dependency-name: rustls
  dependency-version: 0.23.46
  dependency-type: indirect
  dependency-group: cargo
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-31 23:39:08 +00:00
nvrl 37e8dae61b Merge pull request #54 from narrrl/docs/bugs-issue-audit
docs(bugs): record the audit of issues #53, #46, #40 and #38
2026-10-31 19:44:18 +01:00
nvrl c52f2098f2 Merge pull request #64 from narrrl/chore/sdk-0.10.1
chore(deps): bump proton-sdk and proton-drive-rs to 0.10.1
2026-10-31 19:40:34 +01:00
nvrl f4a2674b9c Merge pull request #63 from narrrl/fix/sim-flakes-and-open-race
fix(fuse): retry a write open whose queued revision landed under the copy
2026-10-31 19:40:24 +01:00
nvrl 347861bbc1 Merge pull request #62 from narrrl/fix/restore-outcome-and-walk-gaps
fix(fuse,cli): keep a pass going past a failed listing, report skipped restores
2026-10-31 19:40:14 +01:00
nvrl c57763b07f Merge pull request #61 from narrrl/fix/diagnose-coverage
fix(cli): have diagnose report failing writes, a pause and folders in error
2026-10-31 19:40:04 +01:00
nvrl 846dfd8d14 Merge pull request #60 from narrrl/fix/db-errors-not-offline
fix(core): read database errors handed to from_api as internal, not offline
2026-10-31 19:39:53 +01:00
nvrl 2ae99de844 Merge pull request #59 from narrrl/fix/mount-failure-surfaced
fix(cli,core,fuse,gui): say why the mount keeps failing, and back off
2026-10-31 19:39:44 +01:00
nvrl 69ff216e7d Merge pull request #58 from narrrl/fix/never-synced-label
fix(gui): say a folder is waiting for its first sync, not up to date
2026-10-31 19:39:34 +01:00
nvrl 639ca359fa fix(fuse,core): count a new file's landing until its bytes are cached
A create that carries a file's bytes retired its op, then cached the
bytes and gave the tree the real uid. Nothing counted that window, so
`pdfs status` read empty while it ran, which B119 promises means the
file reads without the network.

A delete in that window found the placeholder uid in the tree and
trashed the node by its real uid. `queue_trash` asked the tree whether
that uid was open, found no entry, and dropped the cached bytes the open
handle reads. If the cache store ran at the same moment, its tag was
written after the eviction and never removed. CI caught that as a
stray .meta file.

The create's landing is now counted like an upload's, from the op's
retirement until the tree has the real uid. The delete and the replace
pass whether they found the file open. Opening the cache removes a tag
whose bytes are gone, which also covers a crash between an eviction's
two removals. The simulations wait for `Daemon::drained`, which counts
the landing, before they go offline.

B255 and B256 move to fixed: the account run checked both.
2026-10-27 14:44:34 +01:00
262 changed files with 71025 additions and 66634 deletions

No files matched your search

+11 -5
View File
@@ -44,6 +44,9 @@ jobs:
- name: Formatting
run: cargo fmt --all -- --check
- name: Shell scripts of the release tarball
run: shellcheck packaging/tarball/*.sh
- name: Lints
run: cargo clippy --workspace --all-targets --locked -- -D warnings
@@ -102,14 +105,17 @@ jobs:
- name: Simulation runs
run: 'cargo test -p pdfs-fuse --lib --locked sim:: -- --ignored --test-threads=1'
# A hung step writes every daemon thread's stack next to the run's
# state; without them a hang that does not replay cannot be told apart.
- name: Keep the stacks of a hung run
# Retain the operation trace and daemon logs for the failing seed, plus
# every daemon thread's stack if the watchdog caught a hang.
- name: Keep simulation failure diagnostics
if: failure()
uses: actions/upload-artifact@v7
with:
name: simulation-stacks
path: /tmp/pdfs-sim-*/stacks.txt
name: simulation-diagnostics
path: |
/tmp/pdfs-sim-*/steps.log
/tmp/pdfs-sim-*/daemon.log
/tmp/pdfs-sim-*/stacks.txt
if-no-files-found: ignore
# Keeps the release-profile dependencies cached on main, where the release
+19 -13
View File
@@ -119,23 +119,22 @@ jobs:
echo "VERSION=$VERSION" >> $GITHUB_ENV
echo "Building version: $VERSION"
- name: Package raw binaries (.tar.gz)
# Binaries plus everything around them, with install.sh for a home
# directory install (immutable distributions, anything without a package).
- name: Package the installable tarball (.tar.gz)
run: |
mkdir -p dist/binaries
cp target/release/pdfs dist/binaries/
cp target/release/pdfs-tray dist/binaries/
cp target/release/pdfs-app dist/binaries/
cp target/release/pdfs-prompt dist/binaries/
po/build.sh dist/binaries/locale
# Create tarball
tar -czf proton-drive-linux-${{ env.VERSION }}-x86_64.tar.gz -C dist/binaries .
tarball=$(packaging/tarball/build.sh target/release "${{ env.VERSION }}" .)
packaging/tarball/test.sh "$tarball"
# Every crate the build needs, so COPR can build the spec without network.
- name: Package vendored crates (.tar.xz)
run: |
cargo vendor --locked dist/vendor > /dev/null
tar -cJf proton-drive-linux-vendor-${{ env.VERSION }}.tar.xz -C dist vendor
mkdir -p dist/.cargo
(
cd dist
cargo vendor --locked --manifest-path ../Cargo.toml vendor > .cargo/config.toml
)
tar -cJf proton-drive-linux-vendor-${{ env.VERSION }}.tar.xz -C dist vendor .cargo/config.toml
- name: Package Debian package (.deb)
run: |
@@ -157,9 +156,14 @@ jobs:
cp packaging/io.narl.proton-drive-linux.desktop deb/usr/share/applications/
cp packaging/io.narl.proton-drive-linux-tray.desktop deb/etc/xdg/autostart/
cp packaging/io.narl.proton-drive-linux.svg deb/usr/share/icons/hicolor/scalable/apps/
install -Dm644 packaging/io.narl.proton-drive-linux.policy deb/usr/share/polkit-1/actions/io.narl.proton-drive-linux.policy
cp packaging/proton-drive.service deb/usr/lib/systemd/user/
cp LICENSE deb/usr/share/licenses/proton-drive-linux/
# The offline Places basemap, already fetched for the tarball.
scripts/fetch-basemap.sh
install -Dm644 data/basemap-v1.pmtiles deb/usr/share/proton-drive-linux/basemap-v1.pmtiles
po/build.sh deb/usr/share/locale
packaging/completions.sh target/release/pdfs deb/usr/share
# Stops the running daemon before removal, so the mount stops mirroring deletes
install -m755 packaging/deb/prerm deb/DEBIAN/prerm
@@ -175,7 +179,7 @@ jobs:
Priority: optional
Architecture: amd64
Maintainer: Nils Pukropp <contact@narl.io>
Depends: fuse3, libgtk-4-1 (>= 4.12.0), libadwaita-1-0 (>= 1.5.0), libsecret-1-0, libwebkitgtk-6.0-4, libimage-exiftool-perl
Depends: polkitd, fuse3, libgtk-4-1 (>= 4.12.0), libadwaita-1-0 (>= 1.5.0), libsecret-1-0, libwebkitgtk-6.0-4, libimage-exiftool-perl
Installed-Size: ${INSTALLED_SIZE}
Homepage: https://proton-drive.narl.io
Description: Unofficial Proton Drive client for Linux
@@ -190,6 +194,8 @@ jobs:
- name: Package Fedora package (.rpm)
run: |
# The in-tree spec build installs the basemap from data/.
scripts/fetch-basemap.sh
# Sanitize version (replace hyphens with dots for RPM compatibility)
RPM_VERSION=$(echo "${{ env.VERSION }}" | tr '-' '.')
+1
View File
@@ -65,6 +65,7 @@ jobs:
git config --global --add safe.directory "$GITHUB_WORKSPACE"
VERSION=$(grep -m1 '^version' Cargo.toml | cut -d'"' -f2)
SHORT=${GITHUB_SHA::7}
scripts/fetch-basemap.sh
mkdir -p rpmbuild/{BUILD,RPMS,SOURCES,SPECS,SRPMS,BUILDROOT,db}
rpmbuild -bb \
--nodeps \
+1
View File
@@ -5,3 +5,4 @@
/rpmbuild
/result
/result-*
/data/*.pmtiles
+1 -1
View File
@@ -48,7 +48,7 @@ runs are destructive: use a dedicated test account, never one holding data you c
- **Keep shared logic in `pdfs-core`.** The CLI and GUI never touch the database or the network;
they speak the control protocol to the daemon.
- **The SQLite schema is forward-only.** Never edit a shipped migration — add a new one and bump
`SCHEMA_VERSION` in `crates/pdfs-core/src/db/migrations.rs`.
`SCHEMA_VERSION` in `crates/pdfs-store/src/db/migrations.rs`.
- **Typed errors and `?` over panics** on runtime paths. Blocking filesystem, keyring, or
control-socket work stays off GTK's main thread.
- **`staging/` and `recovery/` may hold the only copy of user data.** Nothing may clear or purge
Generated
+773 -412
View File
File diff suppressed because it is too large. Load diff
+32 -7
View File
@@ -1,9 +1,9 @@
[workspace]
resolver = "2"
members = ["crates/pdfs-core", "crates/pdfs-fuse", "crates/pdfs-cli", "crates/pdfs-gui"]
members = ["crates/pdfs-core", "crates/pdfs-store", "crates/pdfs-drive", "crates/pdfs-sync", "crates/pdfs-fuse", "crates/pdfs-daemon", "crates/pdfs-cli", "crates/pdfs-gui"]
[workspace.package]
version = "3.6.0"
version = "3.10.0"
edition = "2024"
license = "MIT"
authors = ["Nils Pukropp <contact@narl.io>"]
@@ -15,12 +15,20 @@ keywords = ["proton", "drive", "fuse", "sync", "linux"]
categories = ["filesystem", "command-line-utilities"]
[workspace.dependencies]
proton-sdk = { version = "0.10.1" }
proton-drive-rs = { version = "0.10.1" }
proton-sdk = { version = "0.12.6" }
proton-drive-rs = { version = "0.12.6" }
proton-gallery-app-rs = "0.1.0"
proton-gallery-rs = "0.1.5"
proton-map-rs = "0.1.0"
chrono = { version = "0.4", default-features = false, features = ["std"] }
# Internal crates.
pdfs-core = { path = "crates/pdfs-core" }
pdfs-store = { path = "crates/pdfs-store" }
pdfs-drive = { path = "crates/pdfs-drive" }
pdfs-sync = { path = "crates/pdfs-sync" }
pdfs-fuse = { path = "crates/pdfs-fuse" }
pdfs-daemon = { path = "crates/pdfs-daemon" }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "fs", "io-util", "time", "signal"] }
serde = { version = "1", features = ["derive"] }
@@ -33,15 +41,17 @@ anyhow = "1"
# wedge every later acquisition of it: `Workers` catches the unwind to keep the
# pool alive, and `std::sync::Mutex` would defeat that by poisoning the state
# the recovered worker needs.
parking_lot = "0.12"
parking_lot = "0.13"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
directories = "6"
ignore = "0.4"
# Command lines typed into Preferences, split and shown the way a shell would.
shell-words = "1"
sha2 = "0.11"
# Google Takeout exports are zip sets; the importer reads their central
# directories and streams entries out without extracting to disk first.
zip = { version = "8", default-features = false, features = ["deflate"] }
zip = { version = "9", default-features = false, features = ["deflate"] }
# Proton's photo duplicate detection is keyed on the plaintext SHA-1, so an
# import has to speak SHA-1 whatever its age.
sha1 = "0.11"
@@ -49,13 +59,28 @@ sha1 = "0.11"
# formats a camera or phone actually produces — the rest of the crate's codecs
# would be dead weight in the daemon.
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp", "gif", "tiff", "bmp", "rayon"] }
rusqlite = { version = "0.40", features = ["bundled"] }
# Cover pictures of songs, read from their tags (ID3, FLAC, Ogg, MP4, APE) for
# the song's thumbnail. Its default feature is required: 0.25 does not build
# without it.
lofty = "0.25"
rusqlite = { version = "0.41", features = ["bundled"] }
# keyring 4 split into `keyring-core` plus per-platform stores. The libdbus
# Secret Service store is the one keyring 3's `sync-secret-service` wrapped, and
# with no `target` it matches items v3 wrote, so existing logins survive.
keyring-core = "1"
# The keyring store all three apps share: reconnects after a Secret Service
# restart (B285) and replaces items instead of editing them (B291).
proton-auth-rs = "0.1.1"
proton-base-rs = "0.1"
proton-media-rs = "0.1.1"
dbus-secret-service-keyring-store = { version = "1", features = ["crypto-rust"] }
# The same Secret Service client the store wraps, used directly to replace an
# item instead of editing it, which oo7 before 0.7.0 kept only in memory (B291).
dbus-secret-service = { version = "4.1", features = ["crypto-rust"] }
clap = { version = "4", features = ["derive"] }
# `unstable-dynamic`: Tab calls `pdfs` back, so arguments complete from the
# running service. Only `pdfs-cli/src/complete.rs` uses it.
clap_complete = { version = "4.6", features = ["unstable-dynamic"] }
rpassword = "7"
async-trait = "0.1"
futures = "0.3"
+6 -4
View File
@@ -1,6 +1,6 @@
<div align="center">
<img src="images/logo.svg" alt="" width="112" height="112">
<a href="images/logo.svg"><img src="images/logo.svg" alt="Proton Drive for Linux icon" width="128" height="128"></a>
# Proton Drive for Linux
@@ -77,7 +77,8 @@ scriptable CLI.
| Arch Linux | [`proton-drive-for-linux`](https://aur.archlinux.org/packages/proton-drive-for-linux) (also `-bin` and `-git`) in the AUR |
| Debian, Ubuntu 24.04 or newer | `.deb` from the [latest release](https://github.com/narrrl/proton-drive-linux/releases/latest) |
| NixOS | The flake in this repository: see [Installation → NixOS](docs/INSTALL.md#nixos-flake) |
| Anything else | [Build from source](docs/INSTALL.md#build-from-source) |
| Fedora Atomic (Silverblue, Kinoite, Bazzite, Bluefin) | A home-directory tarball or a COPR package layered with `rpm-ostree`. See [Installation → Fedora Atomic](docs/INSTALL.md#fedora-atomic-silverblue-kinoite-bazzite-bluefin) |
| Anything else, immutable ones included | `.tar.gz` from the [latest release](https://github.com/narrrl/proton-drive-linux/releases/latest), installed into your home folder by its `install.sh`: see [Installation → Other distributions](docs/INSTALL.md#other-distributions), or [build from source](docs/INSTALL.md#build-from-source) |
**Fedora**
@@ -125,7 +126,7 @@ The documentation is in [`docs/`](docs/README.md) and on the
| [Getting started](docs/GETTING_STARTED.md) | From installing to your first synced folder |
| [User guide](docs/USER_GUIDE.md) | Everything the app, tray and launcher do |
| [FAQ](docs/FAQ.md) | Short answers to common questions |
| [Command-line reference](docs/CLI.md) | Every `pdfs` command and scripting with `--json` |
| [Command-line reference](docs/CLI.md) | Every `pdfs` command, Tab completion and scripting with `--json` |
| [Configuration](docs/CONFIGURATION.md) | `config.json`, file locations, environment variables, the service |
| [Troubleshooting](docs/TROUBLESHOOTING.md) | Diagnosing problems and fixing common ones |
| [Recovering on a new computer](docs/RECOVERY.md) | Getting your synced folders back after a reinstall or a lost machine |
@@ -192,7 +193,8 @@ Proton Drive Linux is free and built in spare time. If it saves you a few headac
Released under the [MIT License](LICENSE).
The Places map uses [GeoNames](https://www.geonames.org/) data (CC BY 4.0) and
[Natural Earth](https://www.naturalearthdata.com/) outlines (public domain). The optional street
[Natural Earth](https://www.naturalearthdata.com/) land, water and borders (public domain), drawn
through [proton-map-rs](https://github.com/narrrl/proton-rs). The optional street
map comes from [OpenFreeMap](https://openfreemap.org/), © [OpenStreetMap](https://www.openstreetmap.org/copyright)
contributors.
+3
View File
@@ -15,12 +15,15 @@ path = "src/main.rs"
[dependencies]
pdfs-core.workspace = true
pdfs-store.workspace = true
pdfs-fuse.workspace = true
pdfs-daemon.workspace = true
tokio.workspace = true
anyhow.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
clap.workspace = true
clap_complete.workspace = true
rpassword.workspace = true
serde_json.workspace = true
zeroize.workspace = true
+187
View File
@@ -0,0 +1,187 @@
//! The account: login, unlock, lock and logout.
use super::*;
/// Read a line from stdin with a prompt (echoed).
pub(super) fn prompt_line(label: &str) -> Result<String> {
print!("{label}: ");
std::io::stdout().flush()?;
let mut line = String::new();
std::io::stdin().read_line(&mut line)?;
Ok(line.trim().to_owned())
}
pub(super) fn cmd_login(username: Option<String>, remember: bool) -> Result<()> {
let username = match username {
Some(u) => u,
None => prompt_line("Proton email")?,
};
let password = rpassword::prompt_password("Password: ").context("read password")?;
// The 2FA prompt fires lazily — only if the account actually requires it.
let get_totp = || -> pdfs_core::Result<String> {
prompt_line("2FA code").map_err(|e| pdfs_core::Error::Other(format!("read 2FA code: {e}")))
};
// Only a two-password account is ever asked for this.
let get_mailbox = |attempt: u32| prompt_mailbox(attempt, remember);
// Proton may ask for a CAPTCHA first, usually on a VPN. The CLI has no
// browser engine, so the user solves the page in their own browser and says
// when they are done; the retry then carries the challenge token.
let get_hv = |hv: pdfs_core::proton_sdk::api::HumanVerification| {
println!(
"Proton is asking for a CAPTCHA before it will accept this sign-in.\n\
Open this page in your browser and complete it:\n\n {}\n",
auth::browser_verification_url(&hv)
);
prompt_line("Press Enter once the page says you are verified")
.map_err(|e| pdfs_core::Error::Other(format!("read verification answer: {e}")))?;
Ok(auth::browser_verified(&hv))
};
let rt = tokio::runtime::Runtime::new()?;
rt.block_on(auth::login_interactive(
&username,
&password,
get_totp,
get_mailbox,
get_hv,
))
.map_err(login_failure)?;
// A daemon that is already up is parked in `wait_for_session`, sleeping
// between keyring checks; restart it so the mount appears now instead of
// whenever the next poll fires. Only when it is already active — `pdfs
// login` deliberately does not enable the unit the way the GUI does, so a
// headless user driving `pdfs daemon` by hand keeps that setup.
if service::is_active() {
service::restart();
}
println!("Logged in as {username}. Session stored in the system keyring.");
report_key_state();
Ok(())
}
pub(super) fn login_failure(error: pdfs_core::Error) -> anyhow::Error {
if matches!(&error, pdfs_core::Error::Proton(e) if pdfs_core::error::sign_in_blocked(e)) {
// The SDK logs the response code at debug level. Its server text
// would give contradictory instructions in the displayed cause chain.
anyhow::anyhow!(
"Proton declined this sign-in (code 2028). Wait before trying again. If it persists, try signing in on the web and mention code 2028 when contacting Proton support."
)
} else {
anyhow::Error::new(error).context("login failed")
}
}
/// Ask for the mailbox password of a two-password account, without echo.
pub(super) fn prompt_mailbox(attempt: u32, remember: bool) -> pdfs_core::Result<auth::Mailbox> {
if attempt == 0 {
eprintln!("This account has a separate mailbox password.");
} else {
eprintln!("That mailbox password did not unlock the account. Try again.");
}
let password = rpassword::prompt_password("Mailbox password: ")
.map_err(|e| pdfs_core::Error::Other(format!("read mailbox password: {e}")))?;
Ok(auth::Mailbox {
password: zeroize::Zeroizing::new(password),
remember,
})
}
/// Say where the account's keys are held, and what that means for the next login.
pub(super) fn report_key_state() {
match auth::key_state() {
Ok(auth::KeyState::Session) => println!(
"Unlocked for this login session only. After you log out or reboot, run `pdfs unlock`."
),
Ok(auth::KeyState::Locked) => println!("The account is locked. Run `pdfs unlock`."),
_ => {}
}
}
pub(super) fn cmd_unlock(remember: bool) -> Result<()> {
auth::load().context("not logged in (run `pdfs login` first)")?;
let rt = tokio::runtime::Runtime::new()?;
// Bounded like the login prompt: three wrong answers end the command.
let mut attempt = 0;
loop {
let mailbox = prompt_mailbox(attempt, remember)?;
match rt.block_on(auth::unlock(&mailbox.password, remember)) {
Ok(()) => break,
Err(pdfs_core::Error::WrongMailboxPassword) if attempt < 2 => attempt += 1,
Err(e) => return Err(anyhow::Error::new(e).context("unlock failed")),
}
}
// A daemon parked on the locked account would otherwise notice on its next
// poll; restarting it makes the mount appear now, as after `pdfs login`.
if service::is_active() {
service::restart();
}
println!("Unlocked.");
report_key_state();
Ok(())
}
pub(super) fn cmd_lock(forget: bool) -> Result<()> {
auth::lock(forget)?;
println!(
"Locked. {}",
if forget {
"Unlock removed from memory and keyring."
} else {
"Run `pdfs unlock` to unlock again."
}
);
// The running daemon keeps its keys until it restarts; say so, since
// "locked" would otherwise suggest the mount stopped.
if service::is_active() {
println!(
"The running daemon keeps its keys until it restarts: `systemctl --user restart proton-drive`."
);
}
Ok(())
}
/// `stored`, `session` or `locked`: where the account's keys are held.
pub(super) fn key_state_name() -> &'static str {
match auth::key_state() {
Ok(auth::KeyState::Stored) => "stored",
Ok(auth::KeyState::Session) => "session",
_ => "locked",
}
}
pub(super) fn cmd_logout(yes: bool) -> Result<()> {
// Queued changes stay staged on this computer and are sent after the next
// sign-in, but until then they exist nowhere else. Without a running
// daemon there is no count to show.
if !yes
&& let Ok(CtlResponse::Status {
pending_uploads,
pending_changes,
parked_uploads,
..
}) = control_request(CtlRequest::Status)
{
let queued = pending_uploads + pending_changes + parked_uploads;
if queued > 0 {
println!(
"{queued} change(s) are not on Proton Drive yet. They stay on this computer and are \
sent after you sign in again. Run `pdfs sync flush` first to send them now."
);
confirm("Sign out anyway?")?;
}
}
if auth::logout()? {
println!("Signed out: the session is ended on Proton and cleared here.");
} else {
println!(
"Stored session cleared. Proton could not be reached to end the session; \
it stays valid until it expires or is signed out in your account's security settings."
);
}
Ok(())
}
+731
View File
@@ -0,0 +1,731 @@
//! Shell completion for `pdfs`.
//!
//! Built on clap_complete's dynamic engine: the script a shell loads is a thin
//! stub that calls `pdfs` back on every Tab with the words typed so far, and
//! `pdfs` answers from its own clap definition. That lets an argument complete
//! from the running service as well as from the command tree — `pdfs sync rm
//! <Tab>` offers the synced-folder ids with their paths, `pdfs pin Doc<Tab>`
//! walks My files.
//!
//! Every value that comes from the service is best effort. With no service, a
//! slow one or an error, a completer offers nothing: a Tab that hangs or prints
//! an error into the prompt is worse than one that does nothing.
//!
//! The engine sits behind clap_complete's `unstable-dynamic` feature, so all of
//! this crate's use of it is kept to this module.
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::time::Duration;
use clap::CommandFactory;
use clap_complete::engine::{CompletionCandidate, PathCompleter, ValueCompleter};
use clap_complete::env::{Bash, CompleteEnv, Elvish, EnvCompleter, Fish, Powershell, Zsh};
use pdfs_core::control::{
AlbumInfo, BookmarkInfo, ConflictInfo, DeviceInfo, DirEntry, InvitationInfo, PendingOpInfo,
PublicLinkInfo, Request, Response, RevisionInfo, ShareEntry, ShareEntryKind, SyncFolderInfo,
};
/// The environment variable that turns a run of `pdfs` into a completion
/// request. Not clap's generic `COMPLETE`: the same binary is the systemd
/// daemon, and an unrelated `COMPLETE` in its environment must not stop it.
pub const VAR: &str = "PDFS_COMPLETE";
/// How long a completer waits for the service. A Tab is interactive, so a
/// listing the service cannot give soon is better skipped. Long enough for the
/// listings that ask Proton (computers take over a second).
const SERVICE_TIMEOUT: Duration = Duration::from_secs(2);
/// How long a listing that asks Proton is reused. Every Tab is a new `pdfs`, so
/// without it `pdfs devices rm <Tab>`, a letter and another Tab would wait for
/// Proton twice. A uid that went away in the meantime only fails the command.
const CACHE_TTL: Duration = Duration::from_secs(30);
/// Answer a completion request and exit, if this run is one. Must run before
/// anything writes to stdout.
pub fn handle_request() {
CompleteEnv::with_factory(crate::Cli::command)
.var(VAR)
.complete();
}
/// The shells `pdfs completions` writes a script for.
#[derive(Clone, Copy, clap::ValueEnum)]
pub enum ShellArg {
Bash,
Zsh,
Fish,
Elvish,
Powershell,
}
impl ShellArg {
fn completer(self) -> &'static dyn EnvCompleter {
match self {
ShellArg::Bash => &Bash,
ShellArg::Zsh => &Zsh,
ShellArg::Fish => &Fish,
ShellArg::Elvish => &Elvish,
ShellArg::Powershell => &Powershell,
}
}
}
/// Write the script that registers `pdfs` completion with `shell`.
///
/// The script calls `pdfs` from `PATH`, not this binary's path, so one written
/// at packaging time keeps working once installed.
pub fn write_script(shell: ShellArg, out: &mut dyn std::io::Write) -> std::io::Result<()> {
shell
.completer()
.write_registration(VAR, "pdfs", "pdfs", "pdfs", out)?;
if let ShellArg::Zsh = shell {
// Installed as `_pdfs` in site-functions, the script is autoloaded as
// that function's body on the first Tab. The body above only defines
// and registers the completer, so this line also runs it, or the first
// Tab would complete nothing. Sourced, `funcstack` names no `_pdfs`.
writeln!(
out,
"if [ \"$funcstack[1]\" = \"_pdfs\" ]; then\n _clap_dynamic_completer_pdfs \"$@\"\nfi"
)?;
}
Ok(())
}
// ---------------------------------------------------------------------------
// Talking to the service
/// One request to the service, or `None` if there is no answer worth showing.
fn ask(request: Request) -> Option<Response> {
let socket = pdfs_core::config::AppDirs::new().ok()?.control_socket();
ask_at(&socket, &request)
}
fn ask_at(socket: &Path, request: &Request) -> Option<Response> {
match pdfs_core::control::send_with_timeout(socket, request, SERVICE_TIMEOUT) {
Ok(Response::Error { .. }) | Err(_) => None,
Ok(response) => Some(response),
}
}
/// [`ask`] for a listing that comes from Proton rather than the local
/// database, reusing an answer younger than [`CACHE_TTL`]. `key` names the
/// listing's cache file.
fn ask_cached(key: &str, request: Request) -> Option<Response> {
let file = cache_file(key);
if let Some(hit) = file.as_deref().and_then(read_fresh) {
return Some(hit);
}
let response = ask(request)?;
if let Some(file) = &file {
write_cache(file, &response);
}
Some(response)
}
/// In `$XDG_RUNTIME_DIR`: private to the user, in memory and gone at logout,
/// which suits names from the account. With no runtime dir, nothing is cached.
fn cache_file(key: &str) -> Option<PathBuf> {
let runtime = PathBuf::from(std::env::var_os("XDG_RUNTIME_DIR")?);
Some(
runtime
.join(pdfs_core::config::app_dir_name())
.join(format!("completion-{key}.json")),
)
}
fn read_fresh(file: &Path) -> Option<Response> {
let age = std::fs::metadata(file)
.ok()?
.modified()
.ok()?
.elapsed()
.ok()?;
if age > CACHE_TTL {
return None;
}
serde_json::from_slice(&std::fs::read(file).ok()?).ok()
}
/// Best effort: a cache that cannot be written only costs the next Tab a wait.
fn write_cache(file: &Path, response: &Response) {
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
let (Some(dir), Ok(json)) = (file.parent(), serde_json::to_vec(response)) else {
return;
};
let _ = std::fs::DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(dir);
let staging = file.with_extension(format!("{}.tmp", std::process::id()));
let written = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&staging)
.and_then(|mut f| std::io::Write::write_all(&mut f, &json));
if written.is_err() || std::fs::rename(&staging, file).is_err() {
let _ = std::fs::remove_file(&staging);
}
}
fn candidate(value: impl Into<OsString>, help: impl Into<String>) -> CompletionCandidate {
let help = help.into();
let candidate = CompletionCandidate::new(value);
if help.is_empty() {
candidate
} else {
candidate.help(Some(help.into()))
}
}
// ---------------------------------------------------------------------------
// Paths in Proton Drive
/// A path in the mount: an absolute path completes from the local filesystem
/// (through the mount), anything else from the service's listing of My files,
/// which is what the commands resolve a relative path against.
pub fn drive_path(current: &OsStr) -> Vec<CompletionCandidate> {
complete_drive(current, false)
}
/// [`drive_path`] for an argument that must be a folder.
pub fn drive_dir(current: &OsStr) -> Vec<CompletionCandidate> {
complete_drive(current, true)
}
/// `pdfs refresh`: a folder, or one of the two named caches.
pub fn refresh_target(current: &OsStr) -> Vec<CompletionCandidate> {
let typed = current.to_string_lossy();
let mut candidates: Vec<_> = [
("trash", "the trash listing"),
("photos", "the photos timeline"),
]
.into_iter()
.filter(|(name, _)| name.starts_with(typed.as_ref()))
.map(|(name, help)| candidate(name, help))
.collect();
candidates.extend(drive_dir(current));
candidates
}
fn complete_drive(current: &OsStr, dirs_only: bool) -> Vec<CompletionCandidate> {
let Some(word) = current.to_str() else {
return Vec::new();
};
if word.starts_with('/') || word.starts_with('~') {
let local = if dirs_only {
PathCompleter::dir()
} else {
PathCompleter::any()
};
return local.complete(current);
}
let (parent, prefix) = split_drive_word(word);
let listing = Request::ListDir {
path: parent.trim_end_matches('/').to_owned(),
};
match ask(listing) {
Some(Response::Entries { entries }) => {
drive_candidates(parent, prefix, &entries, dirs_only)
}
_ => Vec::new(),
}
}
/// Split a typed drive path into the folder to list (with its trailing `/`)
/// and the start of the name being completed in it.
fn split_drive_word(word: &str) -> (&str, &str) {
match word.rfind('/') {
Some(at) => word.split_at(at + 1),
None => ("", word),
}
}
/// The entries of `parent` whose name starts with `prefix`. A folder ends in
/// `/`, which tells every shell not to add a space after it, so the next Tab
/// goes on into it.
fn drive_candidates(
parent: &str,
prefix: &str,
entries: &[DirEntry],
dirs_only: bool,
) -> Vec<CompletionCandidate> {
entries
.iter()
.filter(|e| e.name.starts_with(prefix) && (e.is_dir || !dirs_only))
.map(|e| {
let slash = if e.is_dir { "/" } else { "" };
CompletionCandidate::new(format!("{parent}{}{slash}", e.name))
.hide(e.name.starts_with('.') && !prefix.starts_with('.'))
})
.collect()
}
// ---------------------------------------------------------------------------
// Ids and uids from the service's listings
pub fn sync_folder_id() -> Vec<CompletionCandidate> {
match ask(Request::ListSyncFolders) {
Some(Response::SyncFolders { items }) => sync_folder_candidates(&items),
_ => Vec::new(),
}
}
fn sync_folder_candidates(items: &[SyncFolderInfo]) -> Vec<CompletionCandidate> {
items
.iter()
.map(|f| candidate(f.id.to_string(), format!("{} ({})", f.local_path, f.mode)))
.collect()
}
pub fn queue_id() -> Vec<CompletionCandidate> {
match ask(Request::ListPendingOps) {
Some(Response::PendingOps { items }) => queue_candidates(&items),
_ => Vec::new(),
}
}
fn queue_candidates(items: &[PendingOpInfo]) -> Vec<CompletionCandidate> {
items
.iter()
.map(|op| candidate(op.id.to_string(), format!("{} {}", op.kind, op.path)))
.collect()
}
pub fn device_uid() -> Vec<CompletionCandidate> {
match ask_cached("devices", Request::ListDevices) {
Some(Response::Devices { items }) => device_candidates(&items),
_ => Vec::new(),
}
}
fn device_candidates(items: &[DeviceInfo]) -> Vec<CompletionCandidate> {
items
.iter()
.map(|d| {
let this = if d.this_device {
" (this computer)"
} else {
""
};
candidate(d.uid.as_str(), format!("{}{this}", d.name))
})
.collect()
}
pub fn trash_uid() -> Vec<CompletionCandidate> {
match ask_cached("trash", Request::ListTrash) {
Some(Response::Entries { entries }) => trash_candidates(&entries),
_ => Vec::new(),
}
}
fn trash_candidates(entries: &[DirEntry]) -> Vec<CompletionCandidate> {
entries
.iter()
.map(|e| {
let help = match e.trashed_from.as_deref() {
Some(from) if !from.is_empty() => format!("{} (from {from})", e.name),
_ => e.name.clone(),
};
candidate(e.uid.as_str(), help)
})
.collect()
}
pub fn album_uid() -> Vec<CompletionCandidate> {
match ask_cached("albums", Request::PhotoAlbums) {
Some(Response::Albums { items, .. }) => album_candidates(&items),
_ => Vec::new(),
}
}
fn album_candidates(items: &[AlbumInfo]) -> Vec<CompletionCandidate> {
items
.iter()
.map(|a| candidate(a.uid.as_str(), a.name.as_str()))
.collect()
}
pub fn shared_uid() -> Vec<CompletionCandidate> {
match ask_cached("shared-with-me", Request::ListSharedWithMe) {
Some(Response::Entries { entries }) => shared_candidates(&entries),
_ => Vec::new(),
}
}
fn shared_candidates(entries: &[DirEntry]) -> Vec<CompletionCandidate> {
entries
.iter()
.map(|e| {
let help = if e.shared_by.is_empty() {
e.name.clone()
} else {
format!("{} (from {})", e.name, e.shared_by)
};
candidate(e.uid.as_str(), help)
})
.collect()
}
pub fn invitation_id() -> Vec<CompletionCandidate> {
match ask_cached("invitations", Request::ListInvitations) {
Some(Response::Invitations { items }) => invitation_candidates(&items),
_ => Vec::new(),
}
}
fn invitation_candidates(items: &[InvitationInfo]) -> Vec<CompletionCandidate> {
items
.iter()
.map(|i| {
let help = match i.name.as_deref() {
Some(name) => format!("{name} from {}", i.inviter_email),
None => format!("from {}", i.inviter_email),
};
candidate(i.id.as_str(), help)
})
.collect()
}
pub fn bookmark_token() -> Vec<CompletionCandidate> {
match ask_cached("bookmarks", Request::ListBookmarks) {
Some(Response::Bookmarks { items }) => bookmark_candidates(&items),
_ => Vec::new(),
}
}
fn bookmark_candidates(items: &[BookmarkInfo]) -> Vec<CompletionCandidate> {
items
.iter()
.map(|b| candidate(b.token.as_str(), b.name.as_deref().unwrap_or(&b.url)))
.collect()
}
pub fn conflict_path() -> Vec<CompletionCandidate> {
match ask(Request::ListConflicts) {
Some(Response::Conflicts { items }) => conflict_candidates(&items),
_ => Vec::new(),
}
}
fn conflict_candidates(items: &[ConflictInfo]) -> Vec<CompletionCandidate> {
items
.iter()
.map(|c| candidate(c.path.as_str(), format!("copy of {}", c.original_path)))
.collect()
}
// ---------------------------------------------------------------------------
// Ids that belong to the path typed before them
/// A version of the file named earlier on the line (`pdfs versions restore
/// <path> <Tab>`).
pub fn version_id(current: &OsStr) -> Vec<CompletionCandidate> {
let Some(path) = typed_path() else {
return Vec::new();
};
match ask(Request::ListRevisions { path }) {
Some(Response::Revisions { items }) => starting_with(current, revision_candidates(&items)),
_ => Vec::new(),
}
}
fn revision_candidates(items: &[RevisionInfo]) -> Vec<CompletionCandidate> {
items
.iter()
.map(|r| {
let current = if r.is_active { ", current" } else { "" };
let size = r.claimed_size.unwrap_or(r.size_on_storage).max(0);
candidate(
r.id.as_str(),
format!(
"{}, {}{current}",
crate::format_epoch_utc(r.created),
crate::human_bytes(size as u64)
),
)
})
.collect()
}
/// A member or invitation on the share of the path typed earlier on the line.
pub fn share_entry_id(current: &OsStr) -> Vec<CompletionCandidate> {
match share_of_typed_path() {
Some((entries, _)) => starting_with(current, share_entry_candidates(&entries)),
None => Vec::new(),
}
}
fn share_entry_candidates(entries: &[ShareEntry]) -> Vec<CompletionCandidate> {
entries
.iter()
.map(|e| {
// The kind is the next argument, so the help names it in the words
// that argument takes.
let kind = match e.kind {
ShareEntryKind::Member => "member",
ShareEntryKind::ProtonInvite => "proton",
ShareEntryKind::ExternalInvite => "external",
};
candidate(e.id.as_str(), format!("{} ({}, {kind})", e.email, e.role))
})
.collect()
}
/// The public link of the path typed earlier on the line.
pub fn public_link_id(current: &OsStr) -> Vec<CompletionCandidate> {
match share_of_typed_path() {
Some((_, Some(link))) => starting_with(current, vec![public_link_candidate(&link)]),
_ => Vec::new(),
}
}
/// Described without its URL: the fragment is the link's password, and a Tab
/// menu is on screen for anyone watching.
fn public_link_candidate(link: &PublicLinkInfo) -> CompletionCandidate {
let help = match link.expires {
Some(expires) => format!(
"{} link, expires {}",
link.role,
crate::format_epoch_utc(expires)
),
None => format!("{} link", link.role),
};
candidate(link.id.as_str(), help)
}
fn share_of_typed_path() -> Option<(Vec<ShareEntry>, Option<PublicLinkInfo>)> {
match ask(Request::ListShare {
path: typed_path()?,
})? {
Response::Share { entries, link } => Some((entries, link)),
_ => None,
}
}
/// [`clap_complete::engine::ArgValueCompleter`] candidates are not filtered by
/// the engine, unlike [`clap_complete::engine::ArgValueCandidates`].
fn starting_with(
current: &OsStr,
candidates: Vec<CompletionCandidate>,
) -> Vec<CompletionCandidate> {
let typed = current.to_string_lossy();
candidates
.into_iter()
.filter(|c| c.get_value().to_string_lossy().starts_with(typed.as_ref()))
.collect()
}
/// The `path` argument of the command being completed, as the service takes
/// it. A completer only receives the word under the cursor, so this reads the
/// line from the process arguments, where the shell's stub passes it.
fn typed_path() -> Option<String> {
let args: Vec<OsString> = std::env::args_os().collect();
let index = std::env::var("_CLAP_COMPLETE_INDEX")
.ok()
.and_then(|i| i.parse().ok());
path_in(words_before_cursor(&args, index))
}
/// The words of the line before the one being completed. The stub runs
/// `pdfs -- <words>`; bash, zsh and elvish say which word the cursor is on,
/// fish and PowerShell pass the line cut at the cursor, so it is the last.
fn words_before_cursor(args: &[OsString], index: Option<usize>) -> Vec<OsString> {
let start = args
.iter()
.position(|a| a == "--")
.map_or(args.len(), |at| at + 1);
let mut words = args[start..].to_vec();
let index = index.unwrap_or(words.len().saturating_sub(1));
words.truncate(index);
words
}
/// Parse `words` as far as they go and take the innermost command's `path`.
fn path_in(words: Vec<OsString>) -> Option<String> {
let matches = crate::Cli::command()
.ignore_errors(true)
.try_get_matches_from(words)
.ok()?;
let mut leaf = &matches;
while let Some((_, sub)) = leaf.subcommand() {
leaf = sub;
}
let path = leaf.try_get_one::<PathBuf>("path").ok().flatten()?;
crate::path_arg(path).ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn values(candidates: &[CompletionCandidate]) -> Vec<String> {
candidates
.iter()
.map(|c| c.get_value().to_string_lossy().into_owned())
.collect()
}
fn help(candidate: &CompletionCandidate) -> String {
candidate
.get_help()
.map(ToString::to_string)
.unwrap_or_default()
}
fn entry(name: &str, is_dir: bool) -> DirEntry {
serde_json::from_value(serde_json::json!({
"name": name,
"is_dir": is_dir,
"size": 0,
"modified": 0,
"pinned": false,
"uid": format!("vol~{name}"),
}))
.unwrap()
}
fn words(line: &[&str]) -> Vec<OsString> {
line.iter().map(OsString::from).collect()
}
#[test]
fn the_command_definition_is_valid() {
crate::Cli::command().debug_assert();
}
#[test]
fn completions_script_is_written_for_every_shell() {
for shell in [
ShellArg::Bash,
ShellArg::Zsh,
ShellArg::Fish,
ShellArg::Elvish,
ShellArg::Powershell,
] {
let mut script = Vec::new();
write_script(shell, &mut script).unwrap();
let script = String::from_utf8(script).unwrap();
assert!(script.contains(VAR), "{script}");
assert!(script.contains("pdfs"), "{script}");
}
}
#[test]
fn drive_path_splits_parent_and_prefix() {
assert_eq!(split_drive_word(""), ("", ""));
assert_eq!(split_drive_word("Doc"), ("", "Doc"));
assert_eq!(split_drive_word("Documents/"), ("Documents/", ""));
assert_eq!(split_drive_word("Documents/Rep"), ("Documents/", "Rep"));
assert_eq!(split_drive_word("a/b/c"), ("a/b/", "c"));
}
#[test]
fn drive_dirs_end_in_a_slash() {
let entries = [
entry("Reports", true),
entry("Receipt.pdf", false),
entry("Other", true),
];
let all = drive_candidates("Documents/", "Re", &entries, false);
assert_eq!(
values(&all),
["Documents/Reports/", "Documents/Receipt.pdf"]
);
let dirs = drive_candidates("Documents/", "", &entries, true);
assert_eq!(values(&dirs), ["Documents/Reports/", "Documents/Other/"]);
}
#[test]
fn hidden_drive_entries_need_a_typed_dot() {
let entries = [entry(".git", true)];
assert!(drive_candidates("", "", &entries, false)[0].is_hide_set());
assert!(!drive_candidates("", ".", &entries, false)[0].is_hide_set());
}
#[test]
fn sync_folder_ids_complete_with_their_local_path() {
let folders: Vec<SyncFolderInfo> = serde_json::from_value(serde_json::json!([{
"id": 3,
"local_path": "/home/me/Documents",
"remote_uid": "vol~docs",
"mode": "mirror",
"state": "idle",
"last_sync": 0,
}]))
.unwrap();
let candidates = sync_folder_candidates(&folders);
assert_eq!(values(&candidates), ["3"]);
assert_eq!(help(&candidates[0]), "/home/me/Documents (mirror)");
}
#[test]
fn trash_uids_complete_with_their_name() {
let mut from_docs = entry("a.pdf", false);
from_docs.trashed_from = Some("Documents".into());
let candidates = trash_candidates(&[from_docs, entry("b", true)]);
assert_eq!(values(&candidates), ["vol~a.pdf", "vol~b"]);
assert_eq!(help(&candidates[0]), "a.pdf (from Documents)");
assert_eq!(help(&candidates[1]), "b");
}
#[test]
fn completer_without_a_service_offers_nothing() {
let dir = std::env::temp_dir().join(format!("pdfs-complete-{}", std::process::id()));
let socket = dir.join("control.sock");
assert!(ask_at(&socket, &Request::ListSyncFolders).is_none());
}
#[test]
fn cached_listing_is_reused_until_it_is_stale() {
let dir = std::env::temp_dir().join(format!("pdfs-complete-cache-{}", std::process::id()));
let file = dir.join("completion-devices.json");
write_cache(&file, &Response::Devices { items: Vec::new() });
assert!(matches!(read_fresh(&file), Some(Response::Devices { .. })));
let mode = std::os::unix::fs::PermissionsExt::mode(
&std::fs::metadata(&file).unwrap().permissions(),
);
assert_eq!(mode & 0o777, 0o600);
let stale = std::time::SystemTime::now() - CACHE_TTL - Duration::from_secs(1);
std::fs::File::options()
.write(true)
.open(&file)
.unwrap()
.set_modified(stale)
.unwrap();
assert!(read_fresh(&file).is_none());
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn words_before_cursor_stop_at_the_cursor() {
let args = words(&[
"pdfs", "--", "pdfs", "versions", "restore", "a.txt", "", "x",
]);
assert_eq!(
words_before_cursor(&args, Some(4)),
words(&["pdfs", "versions", "restore", "a.txt"])
);
// fish: the line arrives cut at the cursor, the current word last.
let fish = words(&["pdfs", "--", "pdfs", "versions", "restore", "a.txt", "ab"]);
assert_eq!(
words_before_cursor(&fish, None),
words(&["pdfs", "versions", "restore", "a.txt"])
);
}
#[test]
fn completing_words_finds_the_path_before_the_id() {
let line = words(&["pdfs", "versions", "restore", "Documents/a.txt"]);
assert_eq!(path_in(line).as_deref(), Some("Documents/a.txt"));
let line = words(&["pdfs", "--json", "share-role", "Shared/x"]);
assert_eq!(path_in(line).as_deref(), Some("Shared/x"));
let line = words(&["pdfs", "public-link", "update", "--role", "editor", "a"]);
assert_eq!(path_in(line).as_deref(), Some("a"));
assert_eq!(path_in(words(&["pdfs", "versions", "restore"])), None);
}
}
+538
View File
@@ -0,0 +1,538 @@
//! `pdfs diagnose`: checks of this computer that need no running daemon.
use super::*;
#[derive(Default)]
pub(super) struct DiagnoseReport {
warnings: usize,
failures: usize,
}
impl DiagnoseReport {
pub(super) fn finding(&mut self, level: DiagnoseLevel, label: &str, detail: impl AsRef<str>) {
let mark = match level {
DiagnoseLevel::Ok => "ok ",
DiagnoseLevel::Warn => {
self.warnings += 1;
"WARN"
}
DiagnoseLevel::Fail => {
self.failures += 1;
"FAIL"
}
};
let detail = detail.as_ref();
if detail.is_empty() {
println!("[{mark}] {label}");
} else {
println!("[{mark}] {label}: {detail}");
}
}
pub(super) fn check(&mut self, label: &str, ok: bool, detail: impl AsRef<str>) {
self.finding(
if ok {
DiagnoseLevel::Ok
} else {
DiagnoseLevel::Fail
},
label,
detail,
);
}
}
#[derive(Clone, Copy)]
pub(super) enum DiagnoseLevel {
Ok,
Warn,
Fail,
}
pub(super) fn executable_on_path(name: &str) -> bool {
std::env::var_os("PATH").is_some_and(|paths| {
std::env::split_paths(&paths)
.any(|dir| std::fs::metadata(dir.join(name)).is_ok_and(|m| m.is_file()))
})
}
/// Create, sync, and remove a new file without ever replacing an existing one.
pub(super) fn writable_probe(dir: &Path) -> std::io::Result<()> {
let name = format!(".pdfs-diagnose-probe-{}", std::process::id());
let path = dir.join(name);
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)?;
let result = (|| {
file.write_all(b"probe")?;
file.sync_all()
})();
drop(file);
let remove = std::fs::remove_file(path);
result.and(remove)
}
/// Self-check the installation, reporting each finding and exiting non-zero if
/// any check failed.
///
/// Every check is written to work with no daemon running, because that is the
/// situation a user runs this in. A missing daemon is reported as a finding,
/// not an error that aborts the rest of the report.
pub(super) fn cmd_diagnose() -> Result<()> {
let mut report = DiagnoseReport::default();
let dirs = AppDirs::new().context("resolve application directories")?;
let config = dirs.load_config();
println!("Paths");
let state = dirs.state_dir();
report.check(
" state dir",
state.is_dir(),
format!("{}", state.display()),
);
let cache_dir = dirs.cache_dir();
report.check(
" cache dir",
cache_dir.is_dir(),
format!("{}", cache_dir.display()),
);
// Writability is checked by actually writing: permission bits do not
// account for a full disk, a read-only remount, or an immutable flag.
match writable_probe(&state) {
Ok(()) => report.finding(
DiagnoseLevel::Ok,
" state dir writable",
"write and fsync succeeded",
),
Err(e) => report.finding(DiagnoseLevel::Fail, " state dir writable", e.to_string()),
}
let db_path = dirs.db_path();
if db_path.exists() {
let db_size = std::fs::metadata(&db_path).map(|m| m.len()).unwrap_or(0);
report.check(
" database",
db_path.is_file(),
format!("{} ({})", db_path.display(), human_bytes(db_size)),
);
} else {
// The daemon creates it on its first start, which waits for a sign-in,
// so a fresh install has none yet (issue #39 read this as the fault).
report.finding(
DiagnoseLevel::Warn,
" database",
format!(
"{} not created yet (the daemon creates it on first start)",
db_path.display()
),
);
}
println!("\nFUSE");
let fuse = Path::new("/dev/fuse");
report.check(" /dev/fuse", fuse.exists(), fuse.display().to_string());
let has_fusermount = executable_on_path("fusermount3") || executable_on_path("fusermount");
report.check(
" unmount helper",
has_fusermount,
"fusermount3 or fusermount on PATH",
);
println!("\nAccount");
let mut keys_unlocked = false;
match pdfs_core::auth::load() {
Ok(session) => {
report.finding(DiagnoseLevel::Ok, " keyring session", session.username);
let key_state = key_state_name();
keys_unlocked = key_state != "locked";
match key_state {
"locked" => report.finding(
DiagnoseLevel::Fail,
" account keys",
"locked — run `pdfs unlock` (the daemon waits for it)",
),
"session" => report.finding(
DiagnoseLevel::Ok,
" account keys",
"unlocked for this login session",
),
_ => report.finding(DiagnoseLevel::Ok, " account keys", "stored in the keyring"),
}
}
Err(e) => {
// A locked keyring and an absent login look the same from here, so
// the detail carries the distinction rather than the verdict.
report.finding(DiagnoseLevel::Fail, " keyring session", format!("{e}"));
}
}
println!("\nDaemon");
let socket = dirs.control_socket();
let socket_exists = socket.exists();
let socket_kind_ok =
std::fs::symlink_metadata(&socket).is_ok_and(|m| m.file_type().is_socket());
// A stale socket file with no listener is the common failure, so the reply
// is what decides this rather than the file's existence.
let status = control_request(CtlRequest::Status);
report.finding(
if socket_exists && !socket_kind_ok {
DiagnoseLevel::Fail
} else if socket_exists && status.is_ok() {
DiagnoseLevel::Ok
} else {
DiagnoseLevel::Warn
},
" control socket",
if socket_exists && socket_kind_ok && status.is_err() {
format!("{} (left over; nothing listens on it)", socket.display())
} else {
socket.display().to_string()
},
);
let mut daemon_responding = false;
match status {
Ok(CtlResponse::Status {
mountpoint,
online,
session_expired,
tokens_unsaved,
pending_uploads,
pending_changes,
failing_ops,
failing_error,
staged_bytes,
staged_oldest_secs,
paused,
paused_until,
version,
..
}) => {
daemon_responding = true;
report.finding(DiagnoseLevel::Ok, " daemon responding", "");
if daemon_outdated(&version) {
report.finding(
DiagnoseLevel::Warn,
" daemon version",
outdated_daemon_note(&version),
);
}
let live_type = pdfs_core::mountpoint::mounted_fs_type(Path::new(&mountpoint));
let is_fuse = live_type
.as_deref()
.is_some_and(|kind| kind.starts_with("fuse"));
report.finding(
if is_fuse {
DiagnoseLevel::Ok
} else {
DiagnoseLevel::Fail
},
" active mount",
live_type.map_or_else(
|| format!("{mountpoint} is not mounted"),
|kind| format!("{mountpoint} ({kind})"),
),
);
// The keyring check above read the blob, which still holds the
// tokens the daemon could not replace.
if tokens_unsaved {
report.finding(
DiagnoseLevel::Warn,
" session tokens",
"the keyring refuses the refreshed ones; unlock it, or a reboot needs `pdfs login`",
);
}
// A refused session reads as offline too, but no connection will
// bring it back, and the keyring check above cannot tell.
if session_expired {
report.finding(
DiagnoseLevel::Fail,
" session",
"Proton refused it (expired or revoked) — run `pdfs login`",
);
} else {
report.finding(
if online {
DiagnoseLevel::Ok
} else {
DiagnoseLevel::Warn
},
" network",
if online {
"online"
} else {
"offline; cached data remains available"
},
);
}
let pending = pending_uploads + pending_changes;
report.finding(
if pending == 0 {
DiagnoseLevel::Ok
} else {
DiagnoseLevel::Warn
},
" queued writes",
if pending == 0 {
"none".to_string()
} else {
format!("{pending} waiting to upload")
},
);
// The rest of the daemon's state that the report used to drop:
// writes that keep failing, a pause, a folder in error. Each of
// them stops changes from reaching Drive while everything above
// reads as fine (`docs/BUGS.md` B268).
for (level, check, detail) in sync_health(
failing_ops,
failing_error.as_deref(),
staged_bytes,
staged_oldest_secs,
paused,
paused_until.map(|until| until - unix_now()),
) {
report.finding(level, check, detail);
}
if let Ok(CtlResponse::SyncFolders { items }) =
control_request(CtlRequest::ListSyncFolders)
{
for (level, check, detail) in folder_health(&items) {
report.finding(level, &check, detail);
}
}
match await_integrity_check() {
Ok(CtlResponse::CacheReport {
integrity_problems,
integrity_checked: true,
..
}) if integrity_problems.is_empty() => report.finding(
DiagnoseLevel::Ok,
" database integrity",
"SQLite integrity_check passed",
),
Ok(CtlResponse::CacheReport {
integrity_checked: false,
..
}) => report.finding(
DiagnoseLevel::Warn,
" database integrity",
"still checking — run `pdfs cache inspect --deep` for the result",
),
Ok(CtlResponse::CacheReport {
integrity_problems, ..
}) => report.finding(
DiagnoseLevel::Fail,
" database integrity",
format!(
"{} problem(s): {}",
integrity_problems.len(),
integrity_problems.join("; ")
),
),
Ok(other) => report.finding(
DiagnoseLevel::Fail,
" database integrity",
format!("unexpected: {other:?}"),
),
Err(e) => report.finding(
DiagnoseLevel::Fail,
" database integrity",
format!("check failed: {e:#}"),
),
}
}
Ok(other) => {
report.finding(
DiagnoseLevel::Fail,
" daemon responding",
format!("unexpected: {other:?}"),
);
}
Err(e) => {
// Not a failure of the installation: a stopped daemon is a normal
// state, and the rest of the report is still worth printing.
report.finding(
DiagnoseLevel::Warn,
" daemon responding",
format!("stopped or unreachable: {e:#}"),
);
match pdfs_core::mountfail::read(&dirs.state_dir()) {
// A daemon whose mount keeps failing never opens the socket,
// so this is the only place its reason shows (B263).
Some(failure) => report.finding(
DiagnoseLevel::Fail,
" mount",
format!(
"failing for {}, {} attempt(s): {}",
human_secs(unix_now().saturating_sub(failure.since).max(0) as u64),
failure.attempts,
if failure.awaiting_keys {
format!("{} — after recovering your account keys, restart proton-drive.service", failure.error)
} else {
failure.error
}
),
),
None => println!(
" (start it with `systemctl --user start proton-drive.service`)"
),
}
}
}
let mountpoint = dirs.resolved_mountpoint(&config);
report.finding(
if mountpoint.is_dir() {
DiagnoseLevel::Ok
} else {
DiagnoseLevel::Warn
},
" configured mountpoint",
mountpoint.display().to_string(),
);
// The daemon opens its control socket only once My Files is mounted, so a
// daemon that answers has the keys it needs. One that does not may be stuck
// on a key that does not open (#40); only then is Proton asked.
if keys_unlocked && !daemon_responding {
println!("\nKeys");
diagnose_keys(&mut report);
}
if report.failures == 0 {
if report.warnings == 0 {
println!("\nNo problems found.");
} else {
println!(
"\nNo critical problems found; {} warning(s) need attention.",
report.warnings
);
}
Ok(())
} else {
bail!(
"{} check(s) failed and {} warning(s) were reported; see above",
report.failures,
report.warnings
)
}
}
/// Ask Proton which account and address keys open, and which of them the My
/// Files share needs. The findings hold key IDs and no secrets.
pub(super) fn diagnose_keys(report: &mut DiagnoseReport) {
use pdfs_core::keycheck::{self, Level};
let checked = tokio::runtime::Runtime::new()
.map_err(anyhow::Error::from)
.and_then(|rt| {
rt.block_on(async {
tokio::time::timeout(std::time::Duration::from_secs(30), keycheck::run())
.await
.map_err(|_| anyhow!("Proton did not answer within 30 seconds"))?
.map_err(anyhow::Error::from)
})
});
let (keys, share) = match checked {
Ok(checked) => checked,
Err(e) => {
report.finding(DiagnoseLevel::Warn, " key check", format!("{e:#}"));
return;
}
};
let findings = keycheck::findings(&keys, &share);
let any_failed = findings.iter().any(|f| f.level != Level::Ok);
for finding in findings {
let level = match finding.level {
Level::Ok => DiagnoseLevel::Ok,
Level::Warn => DiagnoseLevel::Warn,
Level::Fail => DiagnoseLevel::Fail,
};
report.finding(level, &format!(" {}", finding.label), finding.detail);
}
if any_failed {
println!(" (key IDs are not secret; include this section when you report it)");
}
}
#[cfg(test)]
mod diagnose_tests {
use super::*;
/// A healthy queue says nothing; writes that keep failing, an old unsent
/// write and a pause each say so (`docs/BUGS.md` B268).
#[test]
fn a_stuck_queue_or_a_pause_is_reported() {
assert!(sync_health(0, None, 0, 0, false, None).is_empty());
assert!(sync_health(0, None, 4096, STAGED_STALE_SECS - 1, false, None).is_empty());
let checks: Vec<&str> = sync_health(
2,
Some("upload a.txt: quota"),
4096,
STAGED_STALE_SECS,
true,
Some(600),
)
.into_iter()
.map(|(level, check, _)| {
assert!(matches!(level, DiagnoseLevel::Warn));
check.trim()
})
.collect();
assert_eq!(checks, ["failing writes", "oldest unsent write", "sync"]);
}
/// Issue #53: a folder that would not sync, and `diagnose` found nothing.
#[test]
fn a_synced_folder_in_error_is_reported() {
let folder = |id: i64, state: &str| pdfs_core::control::SyncFolderInfo {
kind: "device".into(),
id,
local_path: format!("/home/u/f{id}"),
remote_uid: "vol~link".into(),
mode: "mirror".into(),
state: state.into(),
last_sync: 0,
pending_mode: None,
progress: None,
paused: false,
};
let findings =
folder_health(&[folder(1, "idle"), folder(2, "error"), folder(3, "syncing")]);
assert_eq!(findings.len(), 1);
assert_eq!(findings[0].1.trim(), "synced folder [2]");
assert!(findings[0].2.starts_with("/home/u/f2: sync error"));
}
#[test]
fn finding_severity_is_counted_centrally() {
let mut report = DiagnoseReport::default();
report.finding(DiagnoseLevel::Ok, "ok", "");
report.finding(DiagnoseLevel::Warn, "warn", "");
report.finding(DiagnoseLevel::Fail, "fail", "");
assert_eq!(report.warnings, 1);
assert_eq!(report.failures, 1);
}
#[test]
fn writable_probe_never_replaces_an_existing_file() {
let dir = std::env::temp_dir().join(format!(
"pdfs-diagnose-test-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
std::fs::create_dir_all(&dir).unwrap();
let collision = dir.join(format!(".pdfs-diagnose-probe-{}", std::process::id()));
std::fs::write(&collision, b"keep me").unwrap();
assert_eq!(
writable_probe(&dir).unwrap_err().kind(),
std::io::ErrorKind::AlreadyExists
);
assert_eq!(std::fs::read(&collision).unwrap(), b"keep me");
std::fs::remove_file(collision).unwrap();
std::fs::remove_dir(dir).unwrap();
}
}
+474
View File
@@ -0,0 +1,474 @@
//! Files on the drive: mount, pins, listing, search, moves and copies,
//! versions, trash, new folders and uploads.
use super::*;
pub(super) fn cmd_versions(action: VersionCmd) -> Result<()> {
match action {
VersionCmd::List { path } => {
let response = control_request(CtlRequest::ListRevisions {
path: path_arg(&path)?,
})?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Revisions { items } if items.is_empty() => {
println!("No versions.");
}
CtlResponse::Revisions { items } => {
for r in items {
// The claimed plaintext size is what the user recognises;
// the storage size is ciphertext and always larger.
let size = r
.claimed_size
.filter(|size| *size >= 0)
.unwrap_or(r.size_on_storage)
.max(0) as u64;
let mark = if r.is_active { "*" } else { " " };
let by = r
.signed_by
.map(|email| format!(" {email}"))
.unwrap_or_default();
println!(
"{mark} {:<20} {:>10} {}{by}",
r.id,
human_bytes(size),
format_epoch(r.created),
);
}
println!("(* = current)");
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
VersionCmd::Restore { path, id } => {
ok_or_bail(control_request(CtlRequest::RestoreRevision {
path: path_arg(&path)?,
revision_id: id,
})?)
}
VersionCmd::Save { path, id, dest } => {
// The daemon writes the file, so it needs a path that means the same
// thing in its process as in this one.
let dest = std::path::absolute(&dest)
.with_context(|| format!("resolve {}", dest.display()))?;
ok_or_bail(control_request(CtlRequest::SaveRevisionAs {
path: path_arg(&path)?,
revision_id: id,
dest: dest.to_string_lossy().into_owned(),
})?)
}
VersionCmd::Rm { path, id } => ok_or_bail(control_request(CtlRequest::DeleteRevision {
path: path_arg(&path)?,
revision_id: id,
})?),
}
}
pub(super) fn cmd_mount(mountpoint: Option<PathBuf>) -> Result<()> {
pdfs_daemon::mount_once(mountpoint)?;
Ok(())
}
pub(super) fn cmd_pin(path: PathBuf) -> Result<()> {
match control_request(CtlRequest::Pin {
path: path_arg(&path)?,
})? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_unpin(path: PathBuf) -> Result<()> {
match control_request(CtlRequest::Unpin {
path: path_arg(&path)?,
})? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_transfers() -> Result<()> {
use pdfs_core::control::TransferDirection;
let response = control_request(CtlRequest::GetQueueStatus)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Transfers { items, jobs } if items.is_empty() && jobs.is_empty() => {
println!("Nothing in progress.")
}
CtlResponse::Transfers { items, jobs } => {
// Jobs first: they are the context for the transfers under them ("of
// 40 files", "still scanning") rather than a separate list.
for j in jobs {
let count = if j.total > 0 {
format!("{} of {}", j.done, j.total)
} else {
"—".to_string()
};
let detail = if j.detail.is_empty() {
String::new()
} else {
format!(" — {}", j.detail)
};
println!("… {:>9} {}{detail}", count, j.title);
}
for t in items {
let arrow = match t.direction {
TransferDirection::Download => "↓",
TransferDirection::Upload => "↑",
};
let pct = if t.bytes_total > 0 {
format!(
"{:.0}%",
100.0 * t.bytes_completed as f64 / t.bytes_total as f64
)
} else {
"—".to_string()
};
let speed = t.speed_bytes_sec as f64 / 1_048_576.0;
println!(
"{arrow} {:>4} {:>8} / {:>8} {speed:>6.2} MiB/s {}",
pct, t.bytes_completed, t.bytes_total, t.name
);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_pins() -> Result<()> {
let response = control_request(CtlRequest::ListPins)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Pins { pins } if pins.is_empty() => println!("No pinned files."),
CtlResponse::Pins { pins } => {
for p in pins {
println!("{}", p.path);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_ls(path: Option<PathBuf>) -> Result<()> {
let path = match path {
Some(p) => path_arg(&p)?,
None => String::new(),
};
let response = control_request(CtlRequest::ListDir { path })?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Entries { entries } if entries.is_empty() => println!("(empty)"),
CtlResponse::Entries { entries } => {
for e in entries {
let kind = if e.is_dir { "d" } else { "-" };
let pin = if e.pinned { "*" } else { " " };
println!("{kind}{pin} {:>12} {} [{}]", e.size, e.name, e.uid);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_search(query: String, limit: usize, scope: Option<PathBuf>) -> Result<()> {
let scope = scope.map(|p| path_arg(&p)).transpose()?;
match control_request(CtlRequest::Search {
query,
limit,
scope,
})? {
CtlResponse::SearchResults { hits } if hits.is_empty() => println!("(no matches)"),
CtlResponse::SearchResults { hits } => {
for h in hits {
let kind = if h.is_dir { "d" } else { "-" };
let pin = if h.pinned { "*" } else { " " };
println!("{kind}{pin} {:>12} {}", h.size, h.path);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_rename(path: PathBuf, new_name: String) -> Result<()> {
match control_request(CtlRequest::Rename {
path: path_arg(&path)?,
new_name,
})? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// Move each of `sources` into `new_parent`, one request each. A refusal names
/// its source and the rest still move; the command fails if any did not.
pub(super) fn cmd_move(sources: Vec<PathBuf>, new_parent: PathBuf) -> Result<()> {
let new_parent = path_arg(&new_parent)?;
let mut failed = 0;
for source in &sources {
let outcome = path_arg(source).and_then(|path| {
match control_request(CtlRequest::Move {
path,
new_parent: new_parent.clone(),
})? {
CtlResponse::Ok { message } => Ok(message),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
});
match outcome {
Ok(message) => println!("{message}"),
Err(e) if sources.len() == 1 => return Err(e),
Err(e) => {
eprintln!("{}: {e:#}", source.display());
failed += 1;
}
}
}
if failed > 0 {
bail!("{failed} of {} could not be moved", sources.len());
}
Ok(())
}
pub(super) fn cmd_copy(sources: Vec<PathBuf>, new_parent: PathBuf) -> Result<()> {
let new_parent = path_arg(&new_parent)?;
let mut failed = 0;
for source in &sources {
let outcome = path_arg(source).and_then(|path| {
match control_request(CtlRequest::Copy {
path,
new_parent: new_parent.clone(),
})? {
CtlResponse::Ok { message } => Ok(message),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
});
match outcome {
Ok(message) => println!("{message}"),
Err(e) if sources.len() == 1 => return Err(e),
Err(e) => {
eprintln!("{}: {e:#}", source.display());
failed += 1;
}
}
}
if failed > 0 {
bail!("{failed} of {} could not be copied", sources.len());
}
Ok(())
}
pub(super) fn cmd_du(path: PathBuf) -> Result<()> {
let response = control_request(CtlRequest::FolderSize {
path: path_arg(&path)?,
})?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::FolderSize { size, items } => {
let noun = if items == 1 { "item" } else { "items" };
println!(
"{} in {items} {noun} (on Proton Drive, trash included)",
human_bytes(size)
);
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_rm(path: PathBuf) -> Result<()> {
match control_request(CtlRequest::Delete {
path: path_arg(&path)?,
})? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_trash(by_folder: bool, folder: Option<String>) -> Result<()> {
let request = match folder {
Some(uid) => CtlRequest::ListTrashedFolder { uid },
None => CtlRequest::ListTrash,
};
let response = control_request(request)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Entries { entries } if entries.is_empty() => println!("(nothing here)"),
CtlResponse::Entries { entries } if by_folder => {
let mut groups: BTreeMap<String, Vec<&pdfs_core::control::DirEntry>> = BTreeMap::new();
for e in entries.iter().filter(|e| e.trashed_parent.is_none()) {
let folder = match e.trashed_from.as_deref() {
None => "(unknown folder)".to_string(),
Some("") => "/".to_string(),
Some(path) => format!("/{path}"),
};
groups.entry(folder).or_default().push(e);
}
for (folder, items) in groups {
println!("{folder} ({} item(s))", items.len());
for e in items {
print_trashed(e, " ");
}
}
}
CtlResponse::Entries { entries } => {
for e in &entries {
print_trashed(e, "");
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn print_trashed(e: &pdfs_core::control::DirEntry, indent: &str) {
let kind = if e.is_dir { "d" } else { "-" };
println!("{indent}{kind} {:>12} {} [{}]", e.size, e.name, e.uid);
}
pub(super) fn cmd_restore(uids: Vec<String>) -> Result<()> {
match control_request(CtlRequest::Restore { uids })? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_delete_forever(uids: Vec<String>) -> Result<()> {
confirm(&format!(
"Permanently delete {} item(s)? This cannot be undone.",
uids.len()
))?;
match control_request(CtlRequest::DeleteForever { uids })? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_empty_trash() -> Result<()> {
confirm("Permanently delete everything in the trash? This cannot be undone.")?;
match control_request(CtlRequest::EmptyTrash)? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// Drop a cached listing. `trash` and `photos` name those two listings; anything
/// else is read as a folder path, so a folder actually called "trash" is still
/// reachable as `./trash`.
pub(super) fn cmd_refresh(target: Option<String>, full: bool) -> Result<()> {
let scope = match target.as_deref() {
Some("trash") => RefreshScope::Trash,
Some("photos") => RefreshScope::Photos { full },
path => RefreshScope::Dir {
path: path.unwrap_or("").to_string(),
},
};
let photos = matches!(scope, RefreshScope::Photos { .. });
match control_request(CtlRequest::Refresh { scope })? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
if photos {
wait_for_photos_refresh()?;
}
Ok(())
}
/// How often [`wait_for_photos_refresh`] asks the daemon whether the timeline
/// refresh it started is done.
pub(super) const PHOTOS_REFRESH_POLL: std::time::Duration = std::time::Duration::from_secs(2);
/// Block until the daemon's timeline refresh has finished.
///
/// The daemon answers `Refresh { Photos }` as soon as the refresh is running,
/// because re-reading a large library takes minutes and a control reply may not.
/// `pdfs refresh photos` means "the timeline is up to date when I return", so
/// the waiting happens here, where no socket read bound applies.
pub(super) fn wait_for_photos_refresh() -> Result<()> {
loop {
std::thread::sleep(PHOTOS_REFRESH_POLL);
match control_request(CtlRequest::PhotosRefreshStatus)? {
CtlResponse::PhotosRefresh { running: true } => continue,
CtlResponse::PhotosRefresh { running: false } => {
println!("refreshed");
return Ok(());
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
}
}
pub(super) fn cmd_mkdir(parent: PathBuf, name: String) -> Result<()> {
match control_request(CtlRequest::CreateFolder {
parent: path_arg(&parent)?,
name,
})? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_upload(sources: Vec<PathBuf>, parent: PathBuf) -> Result<()> {
// The daemon reads the sources off its own (local) filesystem, so send it
// absolute, canonicalized paths.
let mut abs = Vec::with_capacity(sources.len());
for src in &sources {
let p = std::fs::canonicalize(src).with_context(|| format!("resolve {}", src.display()))?;
abs.push(
p.to_str()
.ok_or_else(|| anyhow!("path is not valid UTF-8: {}", p.display()))?
.to_owned(),
);
}
match control_request(CtlRequest::UploadPaths {
parent: path_arg(&parent)?,
sources: abs,
})? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
+314 -3231
View File
File diff suppressed because it is too large. Load diff
+470
View File
@@ -0,0 +1,470 @@
//! Photos: the timeline, favorites, albums, the Google Photos import and
//! re-dating.
use super::*;
pub(super) fn cmd_photos(limit: usize, offset: usize, favorites: bool) -> Result<()> {
match control_request(CtlRequest::PhotosTimeline {
offset,
limit,
kind: None,
range: None,
favorites,
not_in_album: false,
})? {
CtlResponse::Photos {
available: false, ..
} => {
println!("This account has no photos volume.")
}
CtlResponse::Photos { items, .. } if items.is_empty() => println!("No photos."),
CtlResponse::Photos { items, .. } => print_photo_page(items)?,
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// Print one page of photos as `capture-time uid thumbnail-path`.
///
/// A timeline or album reply only carries thumbnails already in the cache, so
/// the rest of the page's are pulled in one batch rather than left blank.
pub(super) fn cmd_favorite(uid: String, remove: bool) -> Result<()> {
ok_or_bail(control_request(CtlRequest::SetPhotoFavorite {
uid,
favorite: !remove,
})?)
}
pub(super) fn print_photo_page(items: Vec<pdfs_core::control::PhotoItem>) -> Result<()> {
let uids: Vec<String> = items.iter().map(|p| p.uid.clone()).collect();
let thumbs: HashMap<String, Option<String>> =
match control_request(CtlRequest::PhotoThumbs { uids })? {
CtlResponse::Thumbs { items } => items.into_iter().map(|t| (t.uid, t.path)).collect(),
_ => HashMap::new(),
};
for p in items {
let thumb = thumbs
.get(&p.uid)
.and_then(|p| p.as_deref())
.or(p.thumb_path.as_deref())
.unwrap_or("(no thumbnail)");
let fav = if p.favorite { "*" } else { " " };
println!("{fav} {} {} {thumb}", p.capture_time, p.uid);
}
Ok(())
}
pub(super) fn cmd_albums() -> Result<()> {
match control_request(CtlRequest::PhotoAlbums)? {
CtlResponse::Albums {
available: false, ..
} => println!("This account has no photos volume."),
CtlResponse::Albums { items, .. } if items.is_empty() => println!("No albums."),
CtlResponse::Albums { items, .. } => {
for album in items {
let shared = if album.shared {
" (shared with me)"
} else {
""
};
println!(
"{:>6} {} {}{shared}",
album.photo_count, album.uid, album.name
);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_new_album(name: String) -> Result<()> {
match control_request(CtlRequest::CreateAlbum { name })? {
CtlResponse::AlbumCreated { uid } => println!("{uid}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// Send an album add or remove and report it per photo; any failed photo
/// fails the command.
pub(super) fn cmd_album_change(request: CtlRequest, verb: &str) -> Result<()> {
match control_request(request)? {
CtlResponse::AlbumChanged { changed, failed } => {
println!("{} {verb}", photo_count(changed.len()));
for failure in &failed {
eprintln!("{}: {}", failure.uid, failure.message);
}
if !failed.is_empty() {
bail!("{} failed", photo_count(failed.len()));
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn photo_count(n: usize) -> String {
if n == 1 {
"1 photo".to_string()
} else {
format!("{n} photos")
}
}
pub(super) fn cmd_import_google_photos(
archives: Vec<PathBuf>,
dry_run: bool,
resume: bool,
wait: bool,
) -> Result<()> {
let request = if resume {
CtlRequest::ResumeImport
} else {
// The daemon opens the archives itself off the shared filesystem, so it
// gets absolute paths — the same arrangement `pdfs upload` uses.
let mut absolute = Vec::with_capacity(archives.len());
for archive in &archives {
let path = std::fs::canonicalize(archive)
.with_context(|| format!("resolve {}", archive.display()))?;
absolute.push(
path.to_str()
.ok_or_else(|| anyhow!("path is not valid UTF-8: {}", path.display()))?
.to_owned(),
);
}
CtlRequest::ImportTakeout {
archives: absolute,
dry_run,
}
};
match control_request(request)? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
if !wait {
println!("Run `pdfs import-status` to follow it.");
return Ok(());
}
// Poll rather than stream: the control protocol is request/response, and an
// import runs for hours — a held-open socket would be the only long-lived
// connection the daemon has. A line is printed when the step changes and
// every few percent of it, not on every poll.
let mut last_line = String::new();
let mut last_printed = std::time::Instant::now();
loop {
std::thread::sleep(std::time::Duration::from_secs(2));
match control_request(CtlRequest::ImportStatus)? {
CtlResponse::ImportStatus {
running: true,
progress,
..
} => {
let line = progress.as_ref().map(progress_line).unwrap_or_default();
let step_changed = line.split(':').next() != last_line.split(':').next();
if !line.is_empty()
&& line != last_line
&& (step_changed || last_printed.elapsed().as_secs() >= 30)
{
println!("{line}");
last_line = line;
last_printed = std::time::Instant::now();
}
}
CtlResponse::ImportStatus {
summary, resumable, ..
} => {
print_import_summary(summary.as_ref(), &resumable);
return import_outcome(summary.as_ref());
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
}
}
/// One line saying where a running import is.
pub(super) fn progress_line(progress: &pdfs_core::control::ImportProgress) -> String {
use pdfs_core::control::ImportPhase;
let step = match progress.phase {
ImportPhase::Scanning => "Reading archives",
ImportPhase::Checking => "Checking for photos already on Proton",
ImportPhase::Uploading => "Uploading",
ImportPhase::Albums => "Filing photos into albums",
};
match (progress.total, &progress.current) {
(0, _) => format!("{step}…"),
(total, Some(name)) => format!("{step}: {} of {total} ({name})", progress.done),
(total, None) => format!("{step}: {} of {total}", progress.done),
}
}
/// How an import `--wait` followed ended, as the exit status: an error unless
/// it did everything it set out to do, so a script can tell.
pub(super) fn import_outcome(summary: Option<&pdfs_core::control::ImportSummary>) -> Result<()> {
let Some(summary) = summary else {
bail!("the import ended without a result; the service may have restarted");
};
if let Some(error) = &summary.error {
bail!("the import failed: {error}");
}
if summary.interrupted {
bail!("the import was interrupted; run `pdfs import-google-photos --resume` to continue");
}
if summary.cancelled {
bail!("the import was cancelled");
}
if summary.failed > 0 || !summary.unreadable_archives.is_empty() {
bail!(
"the import finished, but {} photo(s) and {} archive(s) failed",
summary.failed,
summary.unreadable_archives.len()
);
}
Ok(())
}
pub(super) fn cmd_redate_photos(
dry_run: bool,
limit: Option<usize>,
from: Option<String>,
to: Option<String>,
wait: bool,
) -> Result<()> {
let range = match (from.as_deref(), to.as_deref()) {
(None, None) => None,
(from, to) => Some((
from.map(parse_day).transpose()?.unwrap_or(i64::MIN),
to.map(parse_day).transpose()?.unwrap_or(i64::MAX),
)),
};
match control_request(CtlRequest::RedatePhotos {
dry_run,
limit,
range,
})? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
if !wait {
println!("Run `pdfs redate-status` to follow it.");
return Ok(());
}
// Polled for the same reason the import is: request/response protocol, and a
// run over a whole library is a download plus an upload per photo.
loop {
std::thread::sleep(std::time::Duration::from_secs(2));
match control_request(CtlRequest::RedateStatus)? {
CtlResponse::RedateStatus { running: true, .. } => continue,
CtlResponse::RedateStatus { summary, .. } => {
print_redate_summary(summary.as_ref());
return finished_run(
"the re-date",
summary.map(|s| (s.failed, s.cancelled, s.error)),
);
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
}
}
/// How a run `--wait` followed ended, as the exit status: an error when it
/// failed, was cancelled, or left photos failed, so a script can tell.
/// `outcome` is `(failed, cancelled, error)`; `None` when the daemon has no
/// result, which happens when it restarted during the run.
pub(super) fn finished_run(
what: &str,
outcome: Option<(usize, bool, Option<String>)>,
) -> Result<()> {
match outcome {
None => bail!("{what} ended without a result; the service may have restarted"),
Some((_, _, Some(error))) => bail!("{what} failed: {error}"),
Some((_, true, None)) => bail!("{what} was cancelled"),
Some((failed, false, None)) if failed > 0 => {
bail!("{what} finished, but {failed} photo(s) failed")
}
Some(_) => Ok(()),
}
}
/// A `YYYY-MM-DD` day as epoch seconds at UTC midnight. Reuses the Takeout
/// scanner's date reader, which already accepts exactly this spelling.
pub(super) fn parse_day(day: &str) -> Result<i64> {
pdfs_core::takeout::capture_time_from_name(day)
.ok_or_else(|| anyhow!("not a date (expected YYYY-MM-DD): {day}"))
}
pub(super) fn cmd_redate_status() -> Result<()> {
match control_request(CtlRequest::RedateStatus)? {
CtlResponse::RedateStatus { running, summary } => {
if running {
println!("Re-date running. `pdfs transfers` shows its progress.");
}
print_redate_summary(summary.as_ref());
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_cancel_redate() -> Result<()> {
match control_request(CtlRequest::CancelRedate)? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn print_redate_summary(summary: Option<&pdfs_core::control::RedateSummary>) {
let Some(summary) = summary else {
println!("No re-date has run yet.");
return;
};
if let Some(error) = &summary.error {
println!("Failed : {error}");
return;
}
println!("Photos examined : {}", summary.examined);
println!("Mis-dated : {}", summary.candidates);
if summary.dry_run {
println!("(dry run — nothing was uploaded or trashed)");
} else {
println!("Re-dated : {}", summary.redated);
if summary.album_links > 0 {
println!("Albums refiled : {}", summary.album_links);
}
if summary.failed > 0 {
println!("Failed : {}", summary.failed);
}
if summary.bytes > 0 {
println!("Uploaded bytes : {}", summary.bytes);
}
}
for (name, stored, wanted) in &summary.samples {
// Epoch seconds, as `pdfs photos` prints capture times.
println!(" {name}: {stored} -> {wanted}");
}
if summary.candidates > summary.samples.len() {
println!(
" … and {} more",
summary.candidates - summary.samples.len()
);
}
if summary.cancelled {
println!("Run was cancelled before it finished.");
}
}
pub(super) fn cmd_import_status() -> Result<()> {
match control_request(CtlRequest::ImportStatus)? {
CtlResponse::ImportStatus {
running,
summary,
progress,
resumable,
} => {
if running {
match progress.as_ref() {
Some(progress) => println!("Import running. {}", progress_line(progress)),
None => println!("Import running."),
}
}
print_import_summary(summary.as_ref(), &resumable);
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_cancel_import() -> Result<()> {
match control_request(CtlRequest::CancelImport)? {
CtlResponse::Ok { message } => println!("{message}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn print_import_summary(
summary: Option<&pdfs_core::control::ImportSummary>,
resumable: &[String],
) {
let Some(summary) = summary else {
println!("No import has run yet.");
return;
};
if summary.dry_run {
println!("Scan only; nothing was uploaded.");
}
if let Some(error) = &summary.error {
println!("Stopped by : {error}");
}
println!("Photos in export : {}", summary.found);
if summary.dry_run {
println!("Would upload : {}", summary.to_upload);
println!("Bytes to upload : {}", summary.to_upload_bytes);
} else {
println!("Uploaded : {}", summary.uploaded);
}
println!("Already on Proton: {}", summary.duplicates);
if summary.live_photos > 0 {
println!("Live photos : {}", summary.live_photos);
}
if summary.skipped_trashed > 0 {
println!("Skipped (trash) : {}", summary.skipped_trashed);
}
if summary.albums_created > 0 || summary.album_links > 0 {
println!(
"Albums : {} created, {} photos filed",
summary.albums_created, summary.album_links
);
}
if summary.failed > 0 {
println!("Failed : {}", summary.failed);
}
for archive in &summary.unreadable_archives {
println!("Unreadable : {archive}");
}
if summary.bytes > 0 {
println!("Uploaded bytes : {}", summary.bytes);
}
if summary.interrupted {
println!("The service stopped before the import finished.");
} else if summary.cancelled {
println!("Import was cancelled before it finished.");
}
if !resumable.is_empty() {
println!("Run `pdfs import-google-photos --resume` to continue it.");
}
}
pub(super) fn cmd_album(uid: String, limit: usize, offset: usize) -> Result<()> {
match control_request(CtlRequest::AlbumPhotos { uid, offset, limit })? {
CtlResponse::Photos { items, .. } if items.is_empty() => println!("No photos."),
CtlResponse::Photos { items, .. } => print_photo_page(items)?,
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_open_photo(uid: String) -> Result<()> {
match control_request(CtlRequest::OpenPhoto { uid })? {
CtlResponse::FilePath { path } => println!("{path}"),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
+389
View File
@@ -0,0 +1,389 @@
//! Sharing: members and roles, public links, what is shared with you,
//! invitations and bookmarks.
use super::*;
pub(super) fn cmd_members(path: PathBuf) -> Result<()> {
let response = control_request(CtlRequest::ListShare {
path: path_arg(&path)?,
})?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Share { entries, link } => {
if entries.is_empty() {
println!("No members or pending invitations.");
}
for e in entries {
let kind = match e.kind {
ShareEntryKind::Member => "member",
ShareEntryKind::ProtonInvite => "invited (proton)",
ShareEntryKind::ExternalInvite => "invited (external)",
};
println!("{:<18} {:<8} {} [{}]", kind, e.role, e.email, e.id);
}
match link {
Some(l) => {
let url = l.url.as_deref().unwrap_or("(url hidden)");
let pw = if l.has_password { " +password" } else { "" };
let expiry = l
.expires
.map(|at| format!(", expires {}", format_epoch_utc(at)))
.unwrap_or_default();
println!("public link ({}{pw}{expiry}): {url} [{}]", l.role, l.id);
}
None => println!("public link: none"),
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_share_role(
path: PathBuf,
id: String,
kind: ShareKindArg,
role: String,
) -> Result<()> {
ok_or_bail(control_request(CtlRequest::UpdateShareRole {
path: path_arg(&path)?,
id,
kind: kind.to_kind(),
role,
})?)
}
pub(super) fn cmd_unshare(
path: PathBuf,
id: Option<String>,
kind: Option<ShareKindArg>,
) -> Result<()> {
let path = path_arg(&path)?;
let request = match (id, kind) {
(Some(id), Some(kind)) => CtlRequest::RemoveShareEntry {
path,
id,
kind: kind.to_kind(),
},
_ => CtlRequest::StopSharing { path },
};
ok_or_bail(control_request(request)?)
}
pub(super) fn cmd_public_link(action: PublicLinkCmd) -> Result<()> {
match action {
PublicLinkCmd::Create {
path,
role,
password,
expires,
} => match control_request(CtlRequest::CreatePublicLink {
path: path_arg(&path)?,
role,
password,
expires,
})? {
response if emit_json(&response)? => {}
CtlResponse::PublicLink { link } => {
println!("{}", link.url.as_deref().unwrap_or("(no url returned)"));
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
},
PublicLinkCmd::Update {
path,
id,
role,
password,
no_password,
expires,
no_expiry,
} => match control_request(CtlRequest::UpdatePublicLink {
path: path_arg(&path)?,
id,
role,
password: link_change(password, no_password),
expires: link_change(expires, no_expiry),
})? {
response if emit_json(&response)? => {}
CtlResponse::PublicLink { link } => {
println!("{}", link.url.as_deref().unwrap_or("(no url returned)"));
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
},
PublicLinkCmd::Remove { path, id } => {
ok_or_bail(control_request(CtlRequest::RemovePublicLink {
path: path_arg(&path)?,
id,
})?)?
}
}
Ok(())
}
/// A `--x VALUE` / `--no-x` flag pair as one link option change.
pub(super) fn link_change<T>(value: Option<T>, remove: bool) -> LinkChange<T> {
match (value, remove) {
(Some(value), _) => LinkChange::Set(value),
(None, true) => LinkChange::Remove,
(None, false) => LinkChange::Keep,
}
}
pub(super) fn cmd_shared() -> Result<()> {
match control_request(CtlRequest::ListSharedByMe)? {
CtlResponse::SharedByMe { items } if items.is_empty() => {
println!("You haven't shared anything.")
}
CtlResponse::SharedByMe { items } => {
for it in items {
let kind = if it.is_dir { "d" } else { "-" };
let mut tags = Vec::new();
if it.member_count > 0 {
tags.push(format!("{} member(s)", it.member_count));
}
if it.invite_count > 0 {
tags.push(format!("{} pending", it.invite_count));
}
if let Some(link) = &it.link {
tags.push(match &link.url {
Some(url) => format!("link: {url}"),
None => "link".to_string(),
});
}
let tags = if tags.is_empty() {
String::new()
} else {
format!(" ({})", tags.join(", "))
};
println!("{kind} {}{tags} [{}]", it.name, it.uid);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// List what is shared with me, or — given a folder uid — that folder's
/// children. Shared items have no path in the mount, so a uid is the only handle
/// there is: every row prints one, and it is what the next level down (or
/// `shared-get`) is addressed with.
pub(super) fn cmd_shared_with_me(uid: Option<String>) -> Result<()> {
let request = match uid {
Some(uid) => CtlRequest::ListSharedFolder { uid },
None => CtlRequest::ListSharedWithMe,
};
let response = control_request(request)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Entries { entries } if entries.is_empty() => {
println!("Nothing shared with you.")
}
CtlResponse::Entries { entries } => {
for e in entries {
let kind = if e.is_dir { "d" } else { "-" };
// My role decides whether this is writable at all, so it is
// printed whenever the API reported one; an empty role prints
// nothing rather than a guess.
let role = if e.role.is_empty() {
String::new()
} else {
format!(" ({})", e.role)
};
println!("{kind} {:>12} {}{role} [{}]", e.size, e.name, e.uid);
if let Some(line) = shared_by_line(&e) {
println!("{:>15}{line}", "");
}
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// Who shared an entry with me, and when, as a line printed under it — `None`
/// when the invitation said nothing (owned content, or a node inside a shared
/// folder rather than its root). An inviter whose signature did not verify is
/// said to be claimed, not stated: the name may be forged.
pub(super) fn shared_by_line(entry: &pdfs_core::control::DirEntry) -> Option<String> {
if entry.shared_by.is_empty() {
return None;
}
let mut line = format!("shared by {}", entry.shared_by);
if entry.shared_at > 0 {
line.push_str(&format!(" at {}", format_epoch_utc(entry.shared_at)));
}
if entry.shared_by_unverified {
line.push_str(" WARNING: invitation signature did not verify; the sender may be forged");
}
Some(line)
}
/// Download a file shared with me. The daemon puts the plaintext in its content
/// cache and replies with that path; with a `dest` we copy it out, so the caller
/// gets a file it owns rather than one the cache may later evict.
pub(super) fn cmd_shared_get(uid: String, dest: Option<PathBuf>) -> Result<()> {
let path = match control_request(CtlRequest::OpenSharedFile { uid })? {
CtlResponse::FilePath { path } => PathBuf::from(path),
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
};
match dest {
Some(dest) => {
std::fs::copy(&path, &dest).with_context(|| format!("writing {}", dest.display()))?;
println!("{}", dest.display());
}
None => println!("{}", path.display()),
}
Ok(())
}
pub(super) fn cmd_quota() -> Result<()> {
let response = control_request(CtlRequest::AccountQuota)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::AccountQuota {
max_space,
used_space,
} => {
let used = used_space.max(0) as u64;
if max_space > 0 {
let total = max_space as u64;
let pct = (used as f64 / total as f64 * 100.0).round() as u64;
println!(
"{} of {} used ({pct}%)",
human_bytes(used),
human_bytes(total)
);
} else {
println!("{} used", human_bytes(used));
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_activity(limit: usize) -> Result<()> {
let response = control_request(CtlRequest::ListActivity { limit })?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Activity { items } if items.is_empty() => println!("No recent activity."),
CtlResponse::Activity { items } => {
for a in items {
let when = format_epoch(a.time);
let verb = activity_verb(a.kind);
let mark = if a.ok { " " } else { "!" };
let detail = if a.detail.is_empty() {
String::new()
} else {
format!(" {}", a.detail)
};
println!("{mark} {when} {verb:<8} {}{detail}", a.target);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// A short verb for an activity kind, for the CLI's one-line-per-event feed.
pub(super) fn activity_verb(kind: pdfs_core::control::ActivityKind) -> &'static str {
use pdfs_core::control::ActivityKind::*;
match kind {
Upload => "upload",
Download => "download",
Sync => "sync",
Rename => "rename",
Move => "move",
Copy => "copy",
CreateFolder => "mkdir",
Trash => "trash",
Restore => "restore",
DeleteForever => "delete",
EmptyTrash => "empty",
Share => "share",
PublicLink => "link",
Unshare => "unshare",
Conflict => "conflict",
}
}
/// The `synced:` column of `sync list` and `devices list`: when the last pass
/// finished, or `never`. The daemon reports 0 for a folder that never synced.
pub(super) fn last_synced(secs: Option<i64>) -> String {
match secs {
Some(secs) if secs > 0 => format_epoch(secs),
_ => "never".to_string(),
}
}
pub(super) fn cmd_leave(uid: String) -> Result<()> {
ok_or_bail(control_request(CtlRequest::LeaveShared { uid })?)
}
pub(super) fn cmd_invitations(action: InvitationCmd) -> Result<()> {
match action {
InvitationCmd::List => match control_request(CtlRequest::ListInvitations)? {
CtlResponse::Invitations { items } if items.is_empty() => {
println!("No pending invitations.")
}
CtlResponse::Invitations { items } => {
for i in items {
let kind = if i.is_dir { "folder" } else { "file" };
let name = i.name.as_deref().unwrap_or("(name hidden)");
println!("{} shared {kind} \"{name}\" [{}]", i.inviter_email, i.id);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
},
InvitationCmd::Accept { id } => {
ok_or_bail(control_request(CtlRequest::AcceptInvitation { id })?)?
}
InvitationCmd::Reject { id } => {
ok_or_bail(control_request(CtlRequest::RejectInvitation { id })?)?
}
}
Ok(())
}
pub(super) fn cmd_bookmarks(action: BookmarkCmd) -> Result<()> {
match action {
BookmarkCmd::List => match control_request(CtlRequest::ListBookmarks)? {
CtlResponse::Bookmarks { items } if items.is_empty() => println!("No bookmarks."),
CtlResponse::Bookmarks { items } => {
for b in items {
let name = b.name.as_deref().unwrap_or("(name hidden)");
println!("{name} {} [{}]", b.url, b.token);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
},
BookmarkCmd::Add { url, password } => {
ok_or_bail(control_request(CtlRequest::CreateBookmark {
url,
password,
})?)?
}
BookmarkCmd::Rm { token } => {
ok_or_bail(control_request(CtlRequest::DeleteBookmark { token })?)?
}
}
Ok(())
}
+474
View File
@@ -0,0 +1,474 @@
//! What the daemon reports: status, locations, devices, diagnostics and the
//! content cache.
use super::*;
pub(super) fn cmd_devices(action: DeviceCmd) -> Result<()> {
match action {
DeviceCmd::List => {
let response = control_request(CtlRequest::ListDevices)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Devices { items } if items.is_empty() => println!("No devices."),
CtlResponse::Devices { items } => {
for d in items {
let sync = last_synced(d.last_sync);
let tag = match (d.adopted, d.this_device) {
(true, _) => " *adopted*",
(false, true) => " *this machine*",
_ => "",
};
println!(
"{} {} (synced: {sync}) [{}]{tag}",
d.device_type, d.name, d.uid
);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
}
DeviceCmd::Rename { uid, name } => {
ok_or_bail(control_request(CtlRequest::RenameDevice { uid, name })?)?
}
DeviceCmd::Rm { uid } => ok_or_bail(control_request(CtlRequest::DeleteDevice { uid })?)?,
DeviceCmd::Adopt { uid, clear } => {
if uid.is_none() && !clear {
bail!("give a device uid (see `pdfs devices list`), or --clear");
}
let uid = if clear { None } else { uid };
ok_or_bail(control_request(CtlRequest::AdoptDevice { uid })?)?
}
DeviceCmd::Join { uid, yes } => {
if !yes {
println!(
"This computer syncs into that device alongside it. Its folders are kept\n\
in step on both computers: an edit or a deletion on one reaches the other.\n\
New synced folders here go under that device too. Folders already synced\n\
here stay where they are."
);
confirm("Sync with it?")?;
}
let response = control_request(CtlRequest::AdoptDevice { uid: Some(uid) })?;
// A script gets the one reply and runs `sync restore` itself.
if emit_json(&response)? {
return Ok(());
}
ok_or_bail(response)?;
// The device is this machine's now, so the plain restore offers its
// folders.
cmd_sync_restore(yes, None)?
}
DeviceCmd::Migrate { uid, yes } => {
if !yes {
println!(
"Every folder that device backs up moves into this computer's backup.\n\
The device stays registered, without those folders. Stop Proton Drive\n\
on that computer first, or it sees its folders disappear."
);
confirm("Move them here?")?;
}
let response = control_request(CtlRequest::MigrateDevice { uid })?;
// A script gets the one reply and runs `sync restore` itself.
if emit_json(&response)? {
return Ok(());
}
ok_or_bail(response)?;
// The folders are this device's now, so the plain restore offers them.
cmd_sync_restore(yes, None)?
}
}
Ok(())
}
pub(super) fn cmd_status() -> Result<()> {
// `status` is the one query that merges two sources — the local keyring and
// the daemon — so its JSON is composed here rather than being a daemon reply
// passed through. A script asking for status wants both halves in one
// object, including the "logged in but no daemon" case that has no reply at
// all.
if json_enabled() {
let session = match auth::load() {
Ok(s) => Some(s),
Err(pdfs_core::Error::NotLoggedIn) => None,
Err(e) => return Err(e.into()),
};
let mount = match control_request(CtlRequest::Status) {
Ok(r @ CtlResponse::Status { .. }) => response_payload(&r)?,
_ => serde_json::Value::Null,
};
let out = serde_json::json!({
"logged_in": session.is_some(),
"username": session.as_ref().map(|s| s.username.clone()),
"user_id": session.as_ref().map(|s| s.user_id.clone()),
"scopes": session.as_ref().map(|s| s.scopes.clone()),
"keys": session.as_ref().map(|_| key_state_name()),
"mount": mount,
});
println!("{}", serde_json::to_string_pretty(&out)?);
return Ok(());
}
match auth::load() {
Ok(s) => {
println!("Logged in as {} (user {})", s.username, s.user_id);
println!("Scopes: {}", s.scopes.join(", "));
match key_state_name() {
"locked" => println!("Keys: locked — run `pdfs unlock`"),
"session" => println!("Keys: unlocked for this login session"),
_ => {}
}
}
Err(pdfs_core::Error::NotLoggedIn) => {
println!("Not logged in. Run `pdfs login`.");
return Ok(());
}
Err(e) => return Err(e.into()),
}
// If a mount daemon is running, report live status from its control socket.
match control_request(CtlRequest::Status) {
Ok(CtlResponse::Status {
mountpoint,
pinned,
online,
pending_uploads,
pending_changes,
parked_uploads,
failing_ops,
failing_error,
staged_bytes,
staged_oldest_secs,
paused,
paused_until,
session_expired,
tokens_unsaved,
version,
..
}) => {
let state = match (online, paused) {
_ if session_expired => ", session expired: run `pdfs login`",
(_, true) => ", sync paused",
(false, false) => ", offline",
(true, false) => "",
};
let queued = match pending_summary(pending_uploads, pending_changes) {
Some(s) => format!(", {s}"),
None => String::new(),
};
println!("Mounted at {mountpoint} ({pinned} pinned{state}{queued})");
// Everything below is a queue that is not making progress on its
// own. Printed only when it exists, because in the ordinary case
// there is nothing to say.
if staged_bytes > 0 {
println!(
"Staged {} not yet uploaded (oldest {})",
human_bytes(staged_bytes),
human_age(staged_oldest_secs),
);
}
if let Some(until) = paused_until {
let left = until.saturating_sub(unix_now()).max(0) as u64;
println!("Paused sync resumes in {}", human_age(left.max(1)));
}
if parked_uploads > 0 {
println!("Parked {parked_uploads} upload(s) waiting for a final filename");
}
if failing_ops > 0 {
println!(
"Stuck {failing_ops} queued operation(s) keep failing: {}",
failing_error.as_deref().unwrap_or("no error recorded"),
);
}
if tokens_unsaved {
println!(
"Keyring refuses the refreshed sign-in; unlock it, or a reboot needs `pdfs login`"
);
}
if daemon_outdated(&version) {
println!("Daemon {}", outdated_daemon_note(&version));
}
}
Ok(other) => println!("Mount: unexpected response {other:?}"),
Err(_) => println!("Mount: not running."),
}
Ok(())
}
/// What `pdfs status` and `pdfs diagnose` say about a daemon still running
/// an older release than this CLI.
pub(super) fn outdated_daemon_note(version: &str) -> String {
let running = if version.is_empty() {
"an older release".to_string()
} else {
version.to_string()
};
format!(
"still runs {running}, this is {}; run `systemctl --user restart proton-drive` to finish the update",
env!("CARGO_PKG_VERSION"),
)
}
pub(super) fn cmd_locations() -> Result<()> {
let response = control_request(CtlRequest::ListLocations)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Locations { items } if items.is_empty() => {
println!("No Proton Drive locations.");
}
CtlResponse::Locations { items } => {
for location in items {
let kind = match &location.kind {
MountKind::MyFiles => "My Files".to_string(),
MountKind::Device { sync_folder_id } => {
format!("Device folder {sync_folder_id}")
}
MountKind::Attached { sync_folder_id } => {
format!("My files mirror {sync_folder_id}")
}
MountKind::Shared { .. } => "Shared folder".to_string(),
};
let mode = match location.pending_mode {
Some(pending) => format!("{} -> {pending}", location.mode),
None => location.mode.to_string(),
};
let mounted = if location.mounted {
"mounted"
} else {
"not mounted"
};
println!(
"{kind}: {} ({mode}, {}, {}, {mounted})",
location.local_path, location.access, location.state
);
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// The sync engine's line in `pdfs diagnostics`: whether it runs, and which
/// folder's pass it is on.
pub(super) fn sync_engine_line(sync: &pdfs_core::control::SyncEngineState) -> String {
let mut line = match (sync.running, sync.pass_folder) {
(false, _) => "STOPPED; synced folders do not sync until the daemon restarts".to_string(),
(true, None) => "idle".to_string(),
(true, Some(folder)) => format!(
"pass on folder {folder} for {}, last progress {} ago",
human_secs(sync.pass_age_secs),
human_secs(sync.pass_idle_secs),
),
};
if sync.panics > 0 {
line.push_str(&format!("; {} pass(es) panicked", sync.panics));
}
line
}
pub(super) fn cmd_diagnostics() -> Result<()> {
let response = control_request(CtlRequest::Diagnostics)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Diagnostics { diagnostics: d } => {
println!(
"uptime {} rss {} pending ops {}",
human_secs(d.uptime_secs),
human_bytes(d.rss_bytes),
d.pending_ops
.map_or_else(|| "unknown (database busy)".to_owned(), |n| n.to_string()),
);
println!(
"control handlers {}/{}",
d.control_handlers, d.control_handler_limit,
);
println!(
"queued: meta {} (done {}), transfer {} (done {})",
d.meta_queued, d.meta_completed, d.transfer_queued, d.transfer_completed,
);
println!("workers:");
for worker in &d.workers {
let what = if worker.busy {
worker.label.as_str()
} else {
"idle"
};
println!(
" {:<20} {:<12} {}",
worker.name,
what,
human_secs(worker.age_secs)
);
}
if !d.services.is_empty() {
let ended: Vec<&str> = d
.services
.iter()
.filter(|service| !service.running)
.map(|service| service.name.as_str())
.collect();
if ended.is_empty() {
println!("services: {} running", d.services.len());
} else {
println!(
"services: {} running, ended: {}",
d.services.len() - ended.len(),
ended.join(", ")
);
}
}
if let Some(sync) = &d.sync {
println!("sync engine: {}", sync_engine_line(sync));
for trace in &sync.traces {
let how = if trace.ended.is_empty() {
"running"
} else {
trace.ended.as_str()
};
println!(
" folder {} pass ({how}, {}): {trace}",
trace.folder_id,
human_secs(trace.elapsed_ms / 1000),
);
}
}
if !d.drive_calls.is_empty() {
println!("calls to Drive since start:");
for call in &d.drive_calls {
println!(
" {:<38} {:>7} calls {:>5} failed {:>9} ms total {:>7} ms longest",
call.call, call.count, call.errors, call.total_ms, call.longest_ms,
);
}
}
if d.inflight.is_empty() {
println!("in-flight requests: none");
} else {
println!("in-flight requests (oldest first):");
for request in &d.inflight {
println!(" {:<20} {}", request.kind, human_secs(request.age_secs));
}
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
pub(super) fn cmd_cache(action: CacheCmd) -> Result<()> {
match action {
CacheCmd::Inspect { deep } => cmd_cache_inspect(deep),
CacheCmd::Vacuum => match control_request(CtlRequest::CacheVacuum)? {
CtlResponse::Ok { message } => {
println!("{message}");
Ok(())
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
},
CacheCmd::Clear => match control_request(CtlRequest::PurgeCache)? {
CtlResponse::Ok { message } => {
println!("{message}");
Ok(())
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
},
}
}
/// Ask for a deep integrity check and wait for it to finish.
///
/// The daemon answers the request immediately and runs the check on a thread —
/// it holds the single database connection for as long as it takes, which would
/// otherwise stall the mount — so a caller that needs the verdict polls for it.
/// `pdfs doctor` is that caller: it is a diagnostic the user is watching, so
/// waiting is right, and the bound is generous enough for a large database
/// without hanging forever if the daemon never finishes.
pub(super) fn await_integrity_check() -> Result<CtlResponse> {
const POLL: std::time::Duration = std::time::Duration::from_secs(1);
const GIVE_UP_AFTER: std::time::Duration = std::time::Duration::from_secs(120);
let started = std::time::Instant::now();
loop {
let response = control_request(CtlRequest::CacheInspect { deep: true })?;
match &response {
CtlResponse::CacheReport {
integrity_running: true,
integrity_checked: false,
..
} if started.elapsed() < GIVE_UP_AFTER => std::thread::sleep(POLL),
_ => return Ok(response),
}
}
}
pub(super) fn cmd_cache_inspect(deep: bool) -> Result<()> {
let response = control_request(CtlRequest::CacheInspect { deep })?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::CacheReport {
schema_version,
db_bytes,
db_reclaimable_bytes,
tables,
cache_used,
cache_budget,
integrity_problems,
integrity_checked,
integrity_running,
} => {
println!(
"Database schema v{schema_version}, {}",
human_bytes(db_bytes)
);
if db_reclaimable_bytes > 0 {
println!(
" {} reclaimable — run `pdfs cache vacuum`",
human_bytes(db_reclaimable_bytes)
);
}
let budget = if cache_budget == 0 {
"unlimited".to_string()
} else {
human_bytes(cache_budget)
};
println!("Content {} cached of {budget}", human_bytes(cache_used));
println!("\nRows");
for (name, count) in tables {
println!(" {name:<16} {count:>10}");
}
if integrity_checked {
if integrity_problems.is_empty() {
println!("\nIntegrity ok");
} else {
println!("\nIntegrity {} problem(s):", integrity_problems.len());
for problem in integrity_problems {
println!(" {problem}");
}
}
} else if integrity_running {
// The daemon runs the check on a thread rather than holding its
// only database connection for the length of it, so the answer
// belongs to a later request.
println!("\nIntegrity checking in the background — run this again for the result");
} else {
println!("\nIntegrity not checked (pass --deep)");
}
Ok(())
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
}
+780
View File
@@ -0,0 +1,780 @@
//! `pdfs sync`: synced folders, their queue, issues, limits and ignore rules,
//! and `pdfs conflicts`.
use super::*;
pub(super) fn cmd_sync(action: SyncCmd) -> Result<()> {
match action {
SyncCmd::Add { path } => {
let abs = std::fs::canonicalize(&path)
.with_context(|| format!("resolve {}", path.display()))?;
let local_path = abs
.to_str()
.ok_or_else(|| anyhow!("path is not valid UTF-8"))?
.to_string();
ok_or_bail(control_request(CtlRequest::AddSyncFolder { local_path })?)?
}
SyncCmd::Attach { path, to } => {
let abs = std::fs::canonicalize(&path)
.with_context(|| format!("resolve {}", path.display()))?;
let local_path = abs
.to_str()
.ok_or_else(|| anyhow!("path is not valid UTF-8"))?
.to_owned();
let remote_path = to
.to_str()
.ok_or_else(|| anyhow!("remote path is not valid UTF-8"))?
.to_owned();
ok_or_bail(control_request(CtlRequest::AttachSyncFolder {
local_path,
remote_path,
})?)?
}
SyncCmd::List => {
let response = control_request(CtlRequest::ListSyncFolders)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::SyncFolders { items } if items.is_empty() => {
println!("No synced folders.")
}
CtlResponse::SyncFolders { items } => {
for f in items {
let sync = last_synced(Some(f.last_sync));
// A queued switch is reported as the mode the folder is moving
// to, so `sync list` never reads as if the request was dropped.
let mode = match &f.pending_mode {
Some(pending) => format!("{} → {pending}", f.mode),
None => f.mode.clone(),
};
let mode = match f.paused {
true => format!("{mode}, paused"),
false => mode,
};
println!(
"[{}] {} ({mode}, {}, synced: {sync})",
f.id, f.local_path, f.state
);
// A pass in flight says what it is doing, indented under it.
if let Some(p) = &f.progress {
match p.phase {
SyncPhase::Scanning if p.total == 0 && p.done == 0 => {
println!(" scanning…")
}
// A first pass has no estimate yet; the count alone
// shows a long first scan is moving.
SyncPhase::Scanning if p.total == 0 => {
println!(" scanning: {} checked", p.done)
}
SyncPhase::Scanning => {
println!(
" scanning: {} of {}",
p.done,
p.total.max(p.done)
)
}
SyncPhase::Applying => println!(
" {} of {} {}",
p.done + 1,
p.total.max(p.done + 1),
p.current
),
}
}
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
}
SyncCmd::Rm { id, delete_remote } => {
ok_or_bail(control_request(CtlRequest::RemoveSyncFolder {
id,
delete_remote,
})?)?
}
SyncCmd::Now { id } => ok_or_bail(control_request(CtlRequest::SyncNow { id })?)?,
SyncCmd::Reset { id } => ok_or_bail(control_request(CtlRequest::ResetSyncFolder { id })?)?,
SyncCmd::Pause {
folder: Some(id), ..
} => ok_or_bail(control_request(CtlRequest::SetSyncFolderPaused {
id,
paused: true,
})?)?,
SyncCmd::Resume { folder: Some(id) } => {
ok_or_bail(control_request(CtlRequest::SetSyncFolderPaused {
id,
paused: false,
})?)?
}
SyncCmd::Pause {
duration,
folder: None,
} => {
let until = duration.map(|secs| unix_now().saturating_add(secs as i64));
ok_or_bail(control_request(CtlRequest::SetSyncPaused {
paused: true,
until,
})?)?
}
SyncCmd::Queue => return cmd_sync_queue(),
SyncCmd::Flush { timeout } => return cmd_sync_flush(timeout),
SyncCmd::Issues => return cmd_sync_issues(),
SyncCmd::Export { id, dest } => return cmd_sync_export(id, &dest),
SyncCmd::Limit { up, down } => return cmd_sync_limit(up, down),
SyncCmd::Ignore { action } => return cmd_sync_ignore(action),
SyncCmd::Discard { id, yes } => {
if !yes {
confirm(&format!(
"Discard queued change {id} and undo it here? Content not exported is lost."
))?;
}
ok_or_bail(control_request(CtlRequest::DiscardPendingOp { id })?)?
}
SyncCmd::Retry { id } => ok_or_bail(control_request(CtlRequest::RetryPendingOp { id })?)?,
SyncCmd::Resume { folder: None } => {
ok_or_bail(control_request(CtlRequest::SetSyncPaused {
paused: false,
until: None,
})?)?
}
SyncCmd::Mode { id, mode } => {
ok_or_bail(control_request(CtlRequest::SetSyncFolderMode { id, mode })?)?
}
SyncCmd::Restore { yes, device } => return cmd_sync_restore(yes, device),
}
Ok(())
}
/// `pdfs conflicts`: list conflict copies, or resolve one.
pub(super) fn cmd_conflicts(action: Option<ConflictCmd>) -> Result<()> {
if let Some(ConflictCmd::Resolve { path, keep, name }) = action {
let keep = match keep.as_str() {
"original" => ConflictKeep::Original,
"copy" => ConflictKeep::Copy,
_ => ConflictKeep::Both {
name: name.unwrap_or_default(),
},
};
let path = path_arg(&path)?;
return ok_or_bail(control_request(CtlRequest::ResolveConflict { path, keep })?);
}
let response = control_request(CtlRequest::ListConflicts)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::Conflicts { items } if items.is_empty() => println!("No conflicts."),
CtlResponse::Conflicts { items } => {
for c in items {
println!("{}", c.path);
let verdict = match (c.original_exists, c.identical) {
(false, _) => "original is gone".to_string(),
(true, true) => format!("identical to {}", c.original_path),
(true, false) => format!(
"differs from {} ({} vs {})",
c.original_path,
human_bytes(c.size),
human_bytes(c.original_size.unwrap_or_default()),
),
};
println!(" {verdict}");
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// `pdfs sync queue`: what has not reached Proton Drive yet, and why.
pub(super) fn cmd_sync_queue() -> Result<()> {
let response = control_request(CtlRequest::ListPendingOps)?;
if emit_json(&response)? {
return Ok(());
}
match response {
CtlResponse::PendingOps { items } if items.is_empty() => {
println!("Nothing queued: everything is on Proton Drive.");
}
CtlResponse::PendingOps { items } => {
let now = unix_now();
for op in items {
let state = match (op.parked, op.next_attempt_at) {
(true, _) => "waiting for its final name".to_string(),
(false, Some(at)) if at > now => {
format!("next try in {}", human_age((at - now) as u64))
}
(false, _) => "due now".to_string(),
};
println!("[{}] {} {} ({state})", op.id, op.kind, op.path);
if let Some(issue) = op.issue {
println!(" needs attention: {}", issue_text(issue));
}
if let Some(error) = &op.last_error {
println!(" failed {} time(s): {error}", op.attempts);
}
}
}
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
}
Ok(())
}
/// `pdfs sync flush`: wait for the queue to drain.
///
/// Failed changes are retried at once rather than after their backoff. The
/// wait ends early, with exit code 3, when everything left is waiting on the
/// user: refused by Drive, failing again and again, or a temporary file
/// waiting for its final name. Paused or offline, it keeps waiting and says
/// why.
pub(super) fn cmd_sync_flush(timeout: Option<u64>) -> Result<()> {
const POLL: std::time::Duration = std::time::Duration::from_secs(1);
let deadline =
timeout.map(|secs| std::time::Instant::now() + std::time::Duration::from_secs(secs));
ok_or_bail(control_request(CtlRequest::RetryPendingOp { id: None })?)?;
let mut last_line = String::new();
loop {
let items = match control_request(CtlRequest::ListPendingOps)? {
CtlResponse::PendingOps { items } => items,
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
};
let waiting = items
.iter()
.filter(|op| !op.parked && !op.failing && op.issue.is_none())
.count();
if items.is_empty() {
finish_line(&last_line);
println!("Everything is on Proton Drive.");
return Ok(());
}
if waiting == 0 {
finish_line(&last_line);
eprintln!(
"{} queued change(s) need you before they can be sent. See `pdfs sync issues`.",
items.len()
);
std::process::exit(3);
}
let reason = match control_request(CtlRequest::Status)? {
CtlResponse::Status { paused: true, .. } => " (sync is paused; `pdfs sync resume`)",
CtlResponse::Status { online: false, .. } => " (offline; waiting for Proton Drive)",
_ => "",
};
let line = format!("{waiting} change(s) left to send{reason}");
if line != last_line {
if !last_line.is_empty() {
print!("\r\x1b[2K");
}
print!("{line}");
last_line = line;
}
if deadline.is_some_and(|deadline| std::time::Instant::now() >= deadline) {
finish_line(&last_line);
eprintln!("Timed out with {waiting} change(s) still queued.");
std::process::exit(4);
}
std::thread::sleep(POLL);
}
}
/// End a progress line so the next message starts on its own.
pub(super) fn finish_line(last_line: &str) {
if !last_line.is_empty() {
println!();
}
}
/// `pdfs sync issues`: the queued changes that need the user, and what to do.
pub(super) fn cmd_sync_issues() -> Result<()> {
let response = control_request(CtlRequest::ListPendingOps)?;
let items = match response {
CtlResponse::PendingOps { items } => items,
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
};
let issues: Vec<_> = items.into_iter().filter(|op| op.failing).collect();
if json_enabled() {
println!("{}", serde_json::to_string_pretty(&issues)?);
return Ok(());
}
if issues.is_empty() {
println!("No sync issues.");
return Ok(());
}
for op in issues {
println!("[{}] {} {}", op.id, op.kind, op.path);
match op.issue {
Some(issue) => println!(" {}", issue_text(issue)),
None => println!(" keeps failing; it is retried."),
}
if let Some(error) = &op.last_error {
println!(" last error: {error}");
}
if op.exportable {
println!(
" save a copy: pdfs sync export {} <file or folder>",
op.id
);
}
}
Ok(())
}
/// What a sync issue means, and what the user can do about it.
pub(super) fn issue_text(issue: SyncIssue) -> &'static str {
match issue {
SyncIssue::Quota => {
"Proton Drive storage is full. Free up space or upgrade; the change is retried."
}
SyncIssue::Access => {
"you can no longer change this on Proton Drive, for example because a share was \
revoked. Save a copy to keep the content."
}
SyncIssue::Trashed => "restore the item or folder from Trash, then retry the move.",
SyncIssue::Missing => {
"the file or its folder is gone from Proton Drive. Save a copy to keep the content."
}
SyncIssue::Limit => {
"the folder holds too many items or is nested too deep. Move the file to another \
folder."
}
SyncIssue::Rejected => {
"Proton Drive rejected the change, for example the name. Rename the file."
}
SyncIssue::Unknown => "Proton Drive refused the change.",
}
}
/// `pdfs sync export`: save a queued upload's content. A folder as `dest`
/// gets the file under its own name.
pub(super) fn cmd_sync_export(id: i64, dest: &Path) -> Result<()> {
let mut dest =
std::path::absolute(dest).with_context(|| format!("resolving {}", dest.display()))?;
if dest.is_dir() {
let items = match control_request(CtlRequest::ListPendingOps)? {
CtlResponse::PendingOps { items } => items,
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
};
let Some(op) = items.iter().find(|op| op.id == id) else {
bail!("no queued change {id}; see `pdfs sync queue`");
};
let name = Path::new(&op.path)
.file_name()
.with_context(|| format!("{} has no file name", op.path))?;
dest.push(name);
}
ok_or_bail(control_request(CtlRequest::ExportPendingOp {
id,
dest: dest.display().to_string(),
})?)
}
/// `pdfs sync restore`: list what this machine's device holds, confirm where
/// each folder should land, then hand the mapping to the daemon.
///
/// The daemon only ever *proposes* local paths — a path recorded by another
/// machine may name a home directory that does not exist here — so the default
/// flow is propose-and-confirm. `--yes` accepts the proposals for scripting.
pub(super) fn cmd_sync_restore(yes: bool, device: Option<String>) -> Result<()> {
let response = control_request(match &device {
Some(device) => CtlRequest::ListDeviceRestorableFolders {
device: device.clone(),
},
None => CtlRequest::ListRestorableFolders,
})?;
if emit_json(&response)? {
return Ok(());
}
let items = match response {
CtlResponse::RestorableFolders { items } => items,
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected response: {other:?}"),
};
let candidates: Vec<_> = items.into_iter().filter(|f| !f.already_synced).collect();
if candidates.is_empty() {
println!("Nothing to restore: this device has no folders that aren't already synced here.");
return Ok(());
}
let mut chosen: Vec<CtlRestoreItem> = Vec::new();
for f in candidates {
if yes {
println!("{} -> {} [{}]", f.name, f.local_path, f.mode);
chosen.push(CtlRestoreItem {
remote_uid: f.remote_uid,
local_path: f.local_path,
mode: f.mode,
});
continue;
}
// Empty answer takes the proposal, `n` skips, anything else is read as
// the path to use instead — the three things a user wants here.
let answer = prompt_line(&format!(
"{} [{}] -> {} (Enter to accept, 'n' to skip, or a path)",
f.name, f.mode, f.local_path
))?;
match answer.as_str() {
"n" | "N" => continue,
"" => chosen.push(CtlRestoreItem {
remote_uid: f.remote_uid,
local_path: f.local_path,
mode: f.mode,
}),
path => chosen.push(CtlRestoreItem {
remote_uid: f.remote_uid,
local_path: expand_tilde(path),
mode: f.mode,
}),
}
}
if chosen.is_empty() {
println!("Nothing selected.");
return Ok(());
}
ok_or_bail(control_request(match device {
Some(device) => CtlRequest::RestoreDeviceFolders {
device,
items: chosen,
},
None => CtlRequest::RestoreSyncFolders { items: chosen },
})?)?;
// The daemon acks before it works, so the outcome, and any folder it had
// to skip, only shows up later.
println!("Run `pdfs activity` to see which folders were restored.");
Ok(())
}
/// Expand a leading `~` in a hand-typed path. The daemon requires an absolute
/// path, and a shell is not always the one doing the typing here.
pub(super) fn expand_tilde(path: &str) -> String {
match path.strip_prefix("~/") {
Some(rest) => match std::env::var_os("HOME") {
Some(home) => PathBuf::from(home)
.join(rest)
.to_string_lossy()
.into_owned(),
None => path.to_string(),
},
None => path.to_string(),
}
}
pub(super) fn cmd_share(
path: PathBuf,
emails: Vec<String>,
role: String,
message: Option<String>,
) -> Result<()> {
ok_or_bail(control_request(CtlRequest::ShareNode {
path: path_arg(&path)?,
emails,
role,
message,
})?)
}
/// Format an age in seconds for a report line, coarsely — the point of the
/// number is whether it is minutes or weeks.
/// Parse a `sync pause --for` duration: a whole number followed by `m`, `h` or
/// `d`. Returns seconds.
pub(super) fn parse_pause_duration(text: &str) -> Result<u64, String> {
let text = text.trim();
let split = text.char_indices().last().map_or(0, |(at, _)| at);
let (number, unit) = text.split_at(split);
let per_unit: u64 = match unit {
"m" => 60,
"h" => 3600,
"d" => 86_400,
_ => return Err("use a number followed by m, h or d, e.g. 30m".to_string()),
};
match number.parse::<u64>() {
Ok(n) if n > 0 => Ok(n.saturating_mul(per_unit)),
_ => Err("use a positive whole number, e.g. 30m".to_string()),
}
}
/// Read a bytes-per-second rate: a whole number with an optional `K`, `M` or
/// `G` suffix in the same binary units `human_bytes` prints.
pub(super) fn parse_rate(text: &str) -> Result<u64, String> {
let text = text.trim();
let (number, scale) = match text.char_indices().last() {
Some((at, 'K' | 'k')) => (&text[..at], 1024),
Some((at, 'M' | 'm')) => (&text[..at], 1_048_576),
Some((at, 'G' | 'g')) => (&text[..at], 1_073_741_824),
_ => (text, 1),
};
number
.parse::<u64>()
.map(|n| n.saturating_mul(scale))
.map_err(|_| "use a whole number with an optional K, M or G, e.g. 2M".to_string())
}
pub(super) fn human_rate(rate: u64) -> String {
if rate == 0 {
"unlimited".to_string()
} else {
format!("{}/s", human_bytes(rate))
}
}
/// `pdfs sync limit`: set the bandwidth caps, keeping whichever one is not
/// given, or print both when neither is.
pub(super) fn cmd_sync_limit(up: Option<u64>, down: Option<u64>) -> Result<()> {
let config = AppDirs::new()?.load_config();
let upload = up.or(config.upload_limit).unwrap_or(0);
let download = down.or(config.download_limit).unwrap_or(0);
if up.is_none() && down.is_none() {
println!("Upload {}", human_rate(upload));
println!("Download {}", human_rate(download));
return Ok(());
}
ok_or_bail(control_request(CtlRequest::SetBandwidthLimits {
upload,
download,
})?)
}
pub(super) fn cmd_sync_ignore(action: IgnoreCmd) -> Result<()> {
use pdfs_core::syncignore::{
DEFAULT_IGNORE_PATTERNS, FolderRules, IgnoreRules, RuleSource, Verdict, add_folder_pattern,
check_pattern, remove_folder_pattern,
};
let dirs = AppDirs::new()?;
let change = |edit: &dyn Fn(&mut Vec<String>)| -> Result<()> {
dirs.change_ignore_patterns(edit)?;
// The next pass picks the change up anyway; this only hurries it.
let _ = control_request(CtlRequest::SyncNow { id: None });
Ok(())
};
let valid = |pattern: &str| -> Result<String> {
let pattern = pattern.trim();
if pattern.is_empty() || pattern.starts_with('#') {
bail!("not a pattern: `{pattern}`");
}
check_pattern(pattern).map_err(|e| anyhow!("not a valid pattern: {e}"))?;
Ok(pattern.to_string())
};
match action {
IgnoreCmd::List { folder: None } => {
let config = dirs.load_config();
let list = config.resolved_ignore_patterns();
if list.is_empty() {
println!("No patterns: every file is synced.");
}
for pattern in list {
if DEFAULT_IGNORE_PATTERNS.contains(&pattern.as_str()) {
println!("{pattern} (built in)");
} else {
println!("{pattern}");
}
}
}
IgnoreCmd::List {
folder: Some(folder),
} => {
let (_, root) = mirror_folder_of(&folder)?;
let rules = FolderRules::read(&root)?;
let patterns = rules.patterns();
if patterns.is_empty() {
println!(
"{} has no own patterns; the ones for all synced folders apply.",
root.display()
);
}
for pattern in patterns {
println!("{pattern}");
}
}
IgnoreCmd::Add {
pattern,
folder: None,
} => {
let pattern = valid(&pattern)?;
change(&|list| {
if !list.contains(&pattern) {
list.push(pattern.clone());
}
})?;
}
IgnoreCmd::Add {
pattern,
folder: Some(folder),
} => {
let pattern = valid(&pattern)?;
let (id, root) = mirror_folder_of(&folder)?;
if add_folder_pattern(&root, &pattern)? {
let _ = control_request(CtlRequest::SyncNow { id: Some(id) });
} else {
println!("`{pattern}` is already in {}/.pdfsignore.", root.display());
}
}
IgnoreCmd::Remove {
pattern,
folder: None,
} => {
let pattern = pattern.trim().to_string();
let list = dirs.load_config().resolved_ignore_patterns();
if !list.contains(&pattern) {
bail!("`{pattern}` is not in the list; see `pdfs sync ignore list`");
}
change(&|list| list.retain(|p| *p != pattern))?;
}
IgnoreCmd::Remove {
pattern,
folder: Some(folder),
} => {
let (id, root) = mirror_folder_of(&folder)?;
if !remove_folder_pattern(&root, &pattern)? {
bail!(
"`{}` is not among the own patterns of {}; see `pdfs sync ignore list --folder {}`",
pattern.trim(),
root.display(),
root.display()
);
}
let _ = control_request(CtlRequest::SyncNow { id: Some(id) });
}
IgnoreCmd::Reset => change(&|list| {
*list = DEFAULT_IGNORE_PATTERNS
.iter()
.map(|p| (*p).to_string())
.collect()
})?,
IgnoreCmd::Check { path } => {
let path = std::path::absolute(&path)?;
let folder = synced_folder_of(&path)?;
if folder.mode != "mirror" {
println!(
"{} is online only; patterns apply only to folders kept on this computer.",
folder.local_path
);
return Ok(());
}
let root = PathBuf::from(&folder.local_path);
let rel = path.strip_prefix(&root).unwrap_or(&path).to_string_lossy();
let globals = dirs.load_config().resolved_ignore_patterns();
let rules = IgnoreRules::load(&root, &globals);
let source = |source: &RuleSource| match source {
RuleSource::AllFolders => "the patterns for all synced folders".to_string(),
RuleSource::ThisFolder => format!("{}/.pdfsignore", root.display()),
};
match rules.explain(&rel, path.is_dir()) {
Verdict::Synced => println!("Synced: no pattern matches it."),
Verdict::Excluded { pattern, source: s } => {
println!("Not synced: excluded by `{pattern}` in {}.", source(&s))
}
Verdict::Included { pattern, source: s } => {
println!("Synced: `{pattern}` in {} includes it again.", source(&s))
}
}
}
}
Ok(())
}
/// The synced folder holding `path`: the innermost one, as the daemon lists
/// them.
pub(super) fn synced_folder_of(path: &Path) -> Result<SyncFolderInfo> {
let path = std::path::absolute(path)?;
let folders = match control_request(CtlRequest::ListSyncFolders)? {
CtlResponse::SyncFolders { items } => items,
CtlResponse::Error { message, kind } => bail!("{}", cli_error(kind, &message)),
other => bail!("unexpected reply: {other:?}"),
};
folders
.into_iter()
.filter(|f| path.starts_with(&f.local_path))
.max_by_key(|f| f.local_path.len())
.ok_or_else(|| anyhow!("{} is not in a synced folder", path.display()))
}
/// The id and root of the synced folder kept on this computer that holds
/// `path`. Own patterns mean nothing to an online-only folder.
pub(super) fn mirror_folder_of(path: &Path) -> Result<(i64, PathBuf)> {
let folder = synced_folder_of(path)?;
if folder.mode != "mirror" {
bail!(
"{} is online only; patterns apply only to folders kept on this computer",
folder.local_path
);
}
Ok((folder.id, PathBuf::from(folder.local_path)))
}
/// How long the oldest write may wait to upload before `diagnose` calls it
/// out. Under a day it is a slow link or a big file; past it, something is
/// holding the queue.
pub(super) const STAGED_STALE_SECS: u64 = 86_400;
/// `diagnose` findings for the queue and the pause, from the `Status` reply.
/// `paused_for` is how long a timed pause still runs, in seconds.
pub(super) fn sync_health(
failing_ops: u64,
failing_error: Option<&str>,
staged_bytes: u64,
staged_oldest_secs: u64,
paused: bool,
paused_for: Option<i64>,
) -> Vec<(DiagnoseLevel, &'static str, String)> {
let mut findings = Vec::new();
if failing_ops > 0 {
findings.push((
DiagnoseLevel::Warn,
" failing writes",
match failing_error {
Some(error) => format!("{failing_ops} keep failing; the last error: {error}"),
None => format!("{failing_ops} keep failing"),
},
));
}
if staged_bytes > 0 && staged_oldest_secs >= STAGED_STALE_SECS {
findings.push((
DiagnoseLevel::Warn,
" oldest unsent write",
format!(
"{} old, {} only on this computer",
human_secs(staged_oldest_secs),
human_bytes(staged_bytes)
),
));
}
if paused {
findings.push((
DiagnoseLevel::Warn,
" sync",
match paused_for {
Some(left) if left > 0 => {
format!("paused for another {}", human_secs(left as u64))
}
_ => "paused until resumed (`pdfs sync resume`)".to_string(),
},
));
}
findings
}
/// `diagnose` findings for the synced folders that need someone to look.
pub(super) fn folder_health(
folders: &[pdfs_core::control::SyncFolderInfo],
) -> Vec<(DiagnoseLevel, String, String)> {
folders
.iter()
.filter_map(|folder| {
let what = match folder.state.as_str() {
"error" => "sync error; `pdfs sync list` and the activity feed say more",
"conflict" => "conflict copies to look at",
_ => return None,
};
Some((
DiagnoseLevel::Warn,
format!(" synced folder [{}]", folder.id),
format!("{}: {what}", folder.local_path),
))
})
.collect()
}
+6 -3
View File
@@ -12,6 +12,8 @@ description = "Core auth/session/config for the Proton Drive Linux client"
[dependencies]
proton-sdk.workspace = true
proton-drive-rs.workspace = true
proton-gallery-rs.workspace = true
chrono.workspace = true
tokio.workspace = true
serde.workspace = true
serde_json.workspace = true
@@ -19,15 +21,16 @@ thiserror.workspace = true
tracing.workspace = true
directories.workspace = true
ignore.workspace = true
shell-words.workspace = true
sha2.workspace = true
sha1.workspace = true
zip.workspace = true
rusqlite.workspace = true
keyring-core.workspace = true
proton-auth-rs = { workspace = true, features = ["keyring"] }
proton-base-rs.workspace = true
dbus-secret-service-keyring-store.workspace = true
dbus-secret-service.workspace = true
parking_lot.workspace = true
async-trait.workspace = true
libc.workspace = true
zeroize.workspace = true
base64.workspace = true
exif = { version = "0.6", package = "kamadak-exif" }
File diff suppressed because it is too large. Load diff
-250
View File
@@ -1,250 +0,0 @@
AD Andorra
AE United Arab Emirates
AF Afghanistan
AG Antigua and Barbuda
AI Anguilla
AL Albania
AM Armenia
AO Angola
AQ Antarctica
AR Argentina
AS American Samoa
AT Austria
AU Australia
AW Aruba
AX Åland Islands
AZ Azerbaijan
BA Bosnia and Herzegovina
BB Barbados
BD Bangladesh
BE Belgium
BF Burkina Faso
BG Bulgaria
BH Bahrain
BI Burundi
BJ Benin
BL Saint Barthélemy
BM Bermuda
BN Brunei Darussalam
BO Bolivia, Plurinational State of
BQ Bonaire, Sint Eustatius and Saba
BR Brazil
BS Bahamas
BT Bhutan
BV Bouvet Island
BW Botswana
BY Belarus
BZ Belize
CA Canada
CC Cocos (Keeling) Islands
CD Congo, The Democratic Republic of the
CF Central African Republic
CG Congo
CH Switzerland
CI Côte d'Ivoire
CK Cook Islands
CL Chile
CM Cameroon
CN China
CO Colombia
CR Costa Rica
CU Cuba
CV Cabo Verde
CW Curaçao
CX Christmas Island
CY Cyprus
CZ Czechia
DE Germany
DJ Djibouti
DK Denmark
DM Dominica
DO Dominican Republic
DZ Algeria
EC Ecuador
EE Estonia
EG Egypt
EH Western Sahara
ER Eritrea
ES Spain
ET Ethiopia
FI Finland
FJ Fiji
FK Falkland Islands (Malvinas)
FM Micronesia, Federated States of
FO Faroe Islands
FR France
GA Gabon
GB United Kingdom
GD Grenada
GE Georgia
GF French Guiana
GG Guernsey
GH Ghana
GI Gibraltar
GL Greenland
GM Gambia
GN Guinea
GP Guadeloupe
GQ Equatorial Guinea
GR Greece
GS South Georgia and the South Sandwich Islands
GT Guatemala
GU Guam
GW Guinea-Bissau
GY Guyana
HK Hong Kong
HM Heard Island and McDonald Islands
HN Honduras
HR Croatia
HT Haiti
HU Hungary
ID Indonesia
IE Ireland
IL Israel
IM Isle of Man
IN India
IO British Indian Ocean Territory
IQ Iraq
IR Iran, Islamic Republic of
IS Iceland
IT Italy
JE Jersey
JM Jamaica
JO Jordan
JP Japan
KE Kenya
KG Kyrgyzstan
KH Cambodia
KI Kiribati
KM Comoros
KN Saint Kitts and Nevis
KP Korea, Democratic People's Republic of
KR Korea, Republic of
KW Kuwait
KY Cayman Islands
KZ Kazakhstan
LA Lao People's Democratic Republic
LB Lebanon
LC Saint Lucia
LI Liechtenstein
LK Sri Lanka
LR Liberia
LS Lesotho
LT Lithuania
LU Luxembourg
LV Latvia
LY Libya
MA Morocco
MC Monaco
MD Moldova, Republic of
ME Montenegro
MF Saint Martin (French part)
MG Madagascar
MH Marshall Islands
MK North Macedonia
ML Mali
MM Myanmar
MN Mongolia
MO Macao
MP Northern Mariana Islands
MQ Martinique
MR Mauritania
MS Montserrat
MT Malta
MU Mauritius
MV Maldives
MW Malawi
MX Mexico
MY Malaysia
MZ Mozambique
NA Namibia
NC New Caledonia
NE Niger
NF Norfolk Island
NG Nigeria
NI Nicaragua
NL Netherlands
NO Norway
NP Nepal
NR Nauru
NU Niue
NZ New Zealand
OM Oman
PA Panama
PE Peru
PF French Polynesia
PG Papua New Guinea
PH Philippines
PK Pakistan
PL Poland
PM Saint Pierre and Miquelon
PN Pitcairn
PR Puerto Rico
PS Palestine, State of
PT Portugal
PW Palau
PY Paraguay
QA Qatar
RE Réunion
RO Romania
RS Serbia
RU Russian Federation
RW Rwanda
SA Saudi Arabia
SB Solomon Islands
SC Seychelles
SD Sudan
SE Sweden
SG Singapore
SH Saint Helena, Ascension and Tristan da Cunha
SI Slovenia
SJ Svalbard and Jan Mayen
SK Slovakia
SL Sierra Leone
SM San Marino
SN Senegal
SO Somalia
SR Suriname
SS South Sudan
ST Sao Tome and Principe
SV El Salvador
SX Sint Maarten (Dutch part)
SY Syrian Arab Republic
SZ Eswatini
TC Turks and Caicos Islands
TD Chad
TF French Southern Territories
TG Togo
TH Thailand
TJ Tajikistan
TK Tokelau
TL Timor-Leste
TM Turkmenistan
TN Tunisia
TO Tonga
TR Türkiye
TT Trinidad and Tobago
TV Tuvalu
TW Taiwan, Province of China
TZ Tanzania, United Republic of
UA Ukraine
UG Uganda
UM United States Minor Outlying Islands
US United States
UY Uruguay
UZ Uzbekistan
VA Holy See (Vatican City State)
VC Saint Vincent and the Grenadines
VE Venezuela, Bolivarian Republic of
VG Virgin Islands, British
VI Virgin Islands, U.S.
VN Viet Nam
VU Vanuatu
WF Wallis and Futuna
WS Samoa
XK Kosovo
YE Yemen
YT Mayotte
ZA South Africa
ZM Zambia
ZW Zimbabwe
1 AD Andorra
2 AE United Arab Emirates
3 AF Afghanistan
4 AG Antigua and Barbuda
5 AI Anguilla
6 AL Albania
7 AM Armenia
8 AO Angola
9 AQ Antarctica
10 AR Argentina
11 AS American Samoa
12 AT Austria
13 AU Australia
14 AW Aruba
15 AX Åland Islands
16 AZ Azerbaijan
17 BA Bosnia and Herzegovina
18 BB Barbados
19 BD Bangladesh
20 BE Belgium
21 BF Burkina Faso
22 BG Bulgaria
23 BH Bahrain
24 BI Burundi
25 BJ Benin
26 BL Saint Barthélemy
27 BM Bermuda
28 BN Brunei Darussalam
29 BO Bolivia, Plurinational State of
30 BQ Bonaire, Sint Eustatius and Saba
31 BR Brazil
32 BS Bahamas
33 BT Bhutan
34 BV Bouvet Island
35 BW Botswana
36 BY Belarus
37 BZ Belize
38 CA Canada
39 CC Cocos (Keeling) Islands
40 CD Congo, The Democratic Republic of the
41 CF Central African Republic
42 CG Congo
43 CH Switzerland
44 CI Côte d'Ivoire
45 CK Cook Islands
46 CL Chile
47 CM Cameroon
48 CN China
49 CO Colombia
50 CR Costa Rica
51 CU Cuba
52 CV Cabo Verde
53 CW Curaçao
54 CX Christmas Island
55 CY Cyprus
56 CZ Czechia
57 DE Germany
58 DJ Djibouti
59 DK Denmark
60 DM Dominica
61 DO Dominican Republic
62 DZ Algeria
63 EC Ecuador
64 EE Estonia
65 EG Egypt
66 EH Western Sahara
67 ER Eritrea
68 ES Spain
69 ET Ethiopia
70 FI Finland
71 FJ Fiji
72 FK Falkland Islands (Malvinas)
73 FM Micronesia, Federated States of
74 FO Faroe Islands
75 FR France
76 GA Gabon
77 GB United Kingdom
78 GD Grenada
79 GE Georgia
80 GF French Guiana
81 GG Guernsey
82 GH Ghana
83 GI Gibraltar
84 GL Greenland
85 GM Gambia
86 GN Guinea
87 GP Guadeloupe
88 GQ Equatorial Guinea
89 GR Greece
90 GS South Georgia and the South Sandwich Islands
91 GT Guatemala
92 GU Guam
93 GW Guinea-Bissau
94 GY Guyana
95 HK Hong Kong
96 HM Heard Island and McDonald Islands
97 HN Honduras
98 HR Croatia
99 HT Haiti
100 HU Hungary
101 ID Indonesia
102 IE Ireland
103 IL Israel
104 IM Isle of Man
105 IN India
106 IO British Indian Ocean Territory
107 IQ Iraq
108 IR Iran, Islamic Republic of
109 IS Iceland
110 IT Italy
111 JE Jersey
112 JM Jamaica
113 JO Jordan
114 JP Japan
115 KE Kenya
116 KG Kyrgyzstan
117 KH Cambodia
118 KI Kiribati
119 KM Comoros
120 KN Saint Kitts and Nevis
121 KP Korea, Democratic People's Republic of
122 KR Korea, Republic of
123 KW Kuwait
124 KY Cayman Islands
125 KZ Kazakhstan
126 LA Lao People's Democratic Republic
127 LB Lebanon
128 LC Saint Lucia
129 LI Liechtenstein
130 LK Sri Lanka
131 LR Liberia
132 LS Lesotho
133 LT Lithuania
134 LU Luxembourg
135 LV Latvia
136 LY Libya
137 MA Morocco
138 MC Monaco
139 MD Moldova, Republic of
140 ME Montenegro
141 MF Saint Martin (French part)
142 MG Madagascar
143 MH Marshall Islands
144 MK North Macedonia
145 ML Mali
146 MM Myanmar
147 MN Mongolia
148 MO Macao
149 MP Northern Mariana Islands
150 MQ Martinique
151 MR Mauritania
152 MS Montserrat
153 MT Malta
154 MU Mauritius
155 MV Maldives
156 MW Malawi
157 MX Mexico
158 MY Malaysia
159 MZ Mozambique
160 NA Namibia
161 NC New Caledonia
162 NE Niger
163 NF Norfolk Island
164 NG Nigeria
165 NI Nicaragua
166 NL Netherlands
167 NO Norway
168 NP Nepal
169 NR Nauru
170 NU Niue
171 NZ New Zealand
172 OM Oman
173 PA Panama
174 PE Peru
175 PF French Polynesia
176 PG Papua New Guinea
177 PH Philippines
178 PK Pakistan
179 PL Poland
180 PM Saint Pierre and Miquelon
181 PN Pitcairn
182 PR Puerto Rico
183 PS Palestine, State of
184 PT Portugal
185 PW Palau
186 PY Paraguay
187 QA Qatar
188 RE Réunion
189 RO Romania
190 RS Serbia
191 RU Russian Federation
192 RW Rwanda
193 SA Saudi Arabia
194 SB Solomon Islands
195 SC Seychelles
196 SD Sudan
197 SE Sweden
198 SG Singapore
199 SH Saint Helena, Ascension and Tristan da Cunha
200 SI Slovenia
201 SJ Svalbard and Jan Mayen
202 SK Slovakia
203 SL Sierra Leone
204 SM San Marino
205 SN Senegal
206 SO Somalia
207 SR Suriname
208 SS South Sudan
209 ST Sao Tome and Principe
210 SV El Salvador
211 SX Sint Maarten (Dutch part)
212 SY Syrian Arab Republic
213 SZ Eswatini
214 TC Turks and Caicos Islands
215 TD Chad
216 TF French Southern Territories
217 TG Togo
218 TH Thailand
219 TJ Tajikistan
220 TK Tokelau
221 TL Timor-Leste
222 TM Turkmenistan
223 TN Tunisia
224 TO Tonga
225 TR Türkiye
226 TT Trinidad and Tobago
227 TV Tuvalu
228 TW Taiwan, Province of China
229 TZ Tanzania, United Republic of
230 UA Ukraine
231 UG Uganda
232 UM United States Minor Outlying Islands
233 US United States
234 UY Uruguay
235 UZ Uzbekistan
236 VA Holy See (Vatican City State)
237 VC Saint Vincent and the Grenadines
238 VE Venezuela, Bolivarian Republic of
239 VG Virgin Islands, British
240 VI Virgin Islands, U.S.
241 VN Viet Nam
242 VU Vanuatu
243 WF Wallis and Futuna
244 WS Samoa
245 XK Kosovo
246 YE Yemen
247 YT Mayotte
248 ZA South Africa
249 ZM Zambia
250 ZW Zimbabwe
+984
View File
@@ -0,0 +1,984 @@
//! A stand-in daemon that serves made-up data, for the README screenshots.
//!
//! `scripts/screenshots.sh` runs it; see `docs/DEVELOPMENT.md`. It answers the
//! control socket the way the real daemon does, for the requests the captured
//! pages send, with an invented account: no Proton login, no FUSE mount and
//! nothing private. Every name, place and number below is made up.
//!
//! ```text
//! demo_daemon serve <photos-dir> answer the control socket until killed
//! demo_daemon seed-keyring store a fake session, so the app signs in
//! ```
//!
//! Both refuse to run outside a throwaway environment: `PDFS_DEMO_ROOT` must be
//! set and every XDG directory must lie inside it, so the real daemon's socket
//! is never touched (`HOME` may instead name a folder that does not exist, the
//! demo user's, so paths read as theirs), and `seed-keyring` refuses the session bus the script was
//! started on (`PDFS_DEMO_OUTER_BUS`), so the fake session only ever lands in a
//! private keyring.
use std::collections::BTreeMap;
use std::io::{BufRead, BufReader, Write};
use std::os::unix::fs::PermissionsExt;
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use chrono::{Datelike, Local, TimeZone};
use pdfs_core::config::AppDirs;
use pdfs_core::control::Pin;
use pdfs_core::control::{
ActivityEntry, ActivityKind, AlbumInfo, DeviceInfo, DirEntry, Event, LocalHit, PhotoItem,
PhotoKind, PhotoLocation, PhotoMonth, PhotoThumb, PlaceInfo, Request, Response, SearchHit,
SyncFolderInfo, Topic,
};
use pdfs_core::mounts::{MountAccess, MountKind, MountMode, MountSpec};
const USERNAME: &str = "alex.example";
const MOUNTPOINT: &str = "/home/alex/ProtonDrive";
const GIB: u64 = 1 << 30;
const DAY: i64 = 86_400;
/// How many photos the timeline holds. The demo pictures repeat, but not
/// within a screen.
const PHOTOS: usize = 1_840;
fn main() {
if let Err(e) = run() {
eprintln!("demo_daemon: {e}");
std::process::exit(1);
}
}
fn run() -> Result<(), String> {
check_sandbox()?;
let args: Vec<String> = std::env::args().skip(1).collect();
match args.iter().map(String::as_str).collect::<Vec<_>>()[..] {
["serve", photos] => serve(Path::new(photos)),
["seed-keyring"] => seed_keyring(),
_ => Err("usage: demo_daemon serve <photos-dir> | seed-keyring".into()),
}
}
/// Refuse to run anywhere but inside the throwaway root the script made.
fn check_sandbox() -> Result<(), String> {
let root = std::env::var_os("PDFS_DEMO_ROOT")
.map(PathBuf::from)
.ok_or("PDFS_DEMO_ROOT is not set; run scripts/screenshots.sh")?;
let home = std::env::var_os("HOME").map(PathBuf::from);
if home.is_none_or(|home| home.exists() && !home.starts_with(&root)) {
return Err("HOME must lie inside PDFS_DEMO_ROOT or not exist".into());
}
for var in [
"XDG_CONFIG_HOME",
"XDG_STATE_HOME",
"XDG_CACHE_HOME",
"XDG_DATA_HOME",
] {
let inside = std::env::var_os(var)
.map(PathBuf::from)
.is_some_and(|dir| dir.starts_with(&root));
if !inside {
return Err(format!("{var} must lie inside PDFS_DEMO_ROOT"));
}
}
Ok(())
}
/// Store a made-up session where the app looks for one. Its keys "unlock"
/// without a prompt; nothing ever uses them against Proton.
fn seed_keyring() -> Result<(), String> {
let bus = std::env::var("DBUS_SESSION_BUS_ADDRESS").unwrap_or_default();
let outer =
std::env::var("PDFS_DEMO_OUTER_BUS").map_err(|_| "PDFS_DEMO_OUTER_BUS is not set")?;
if bus.is_empty() || bus == outer {
return Err("refusing to write a fake session to your own keyring".into());
}
let session = serde_json::json!({
"session_id": "demo-session",
"username": USERNAME,
"user_id": "demo-user",
"access_token": "demo",
"refresh_token": "demo",
"scopes": ["full", "self", "drive"],
"password_mode": 1,
"key_passphrases": { "demo-key": "ZGVtbw==" },
});
let store: Arc<keyring_core::CredentialStore> =
dbus_secret_service_keyring_store::Store::new().map_err(|e| e.to_string())?;
keyring_core::set_default_store(store);
keyring_core::Entry::new(pdfs_core::config::keyring_service(), "session")
.and_then(|entry| entry.set_password(&session.to_string()))
.map_err(|e| e.to_string())
}
fn serve(photos: &Path) -> Result<(), String> {
let demo = Arc::new(Demo::new(photos)?);
let dirs = AppDirs::new().map_err(|e| e.to_string())?;
dirs.ensure().map_err(|e| e.to_string())?;
let socket = dirs.control_socket();
let _ = std::fs::remove_file(&socket);
let listener = UnixListener::bind(&socket).map_err(|e| format!("{}: {e}", socket.display()))?;
std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600))
.map_err(|e| e.to_string())?;
eprintln!("demo_daemon: serving {}", socket.display());
for stream in listener.incoming().flatten() {
let demo = Arc::clone(&demo);
std::thread::spawn(move || {
if let Err(e) = connection(&demo, stream) {
eprintln!("demo_daemon: {e}");
}
});
}
Ok(())
}
fn connection(demo: &Demo, stream: UnixStream) -> std::io::Result<()> {
let mut reader = BufReader::new(stream.try_clone()?);
let mut line = String::new();
reader.read_line(&mut line)?;
let request: Request = match serde_json::from_str(line.trim()) {
Ok(request) => request,
Err(e) => {
eprintln!("demo_daemon: unreadable request: {e}");
return Ok(());
}
};
let mut out = stream;
if matches!(request, Request::Subscribe) {
return subscription(demo, &mut out);
}
send(&mut out, &demo.answer(&request))
}
/// What the real daemon sends a new subscriber, then a heartbeat now and then
/// so the window never counts the daemon as gone.
fn subscription(demo: &Demo, out: &mut UnixStream) -> std::io::Result<()> {
send(out, &Event::Status(Box::new(demo.status())))?;
send(
out,
&Event::Transfers {
items: Vec::new(),
jobs: Vec::new(),
},
)?;
send(
out,
&Event::Changed {
topics: Topic::ALL.to_vec(),
},
)?;
loop {
std::thread::sleep(Duration::from_secs(10));
send(out, &Event::Heartbeat)?;
}
}
fn send(out: &mut UnixStream, value: &impl serde::Serialize) -> std::io::Result<()> {
let mut line = serde_json::to_vec(value)?;
line.push(b'\n');
out.write_all(&line)?;
out.flush()
}
/// One invented account.
struct Demo {
now: i64,
pictures: Vec<PathBuf>,
photos: Vec<PhotoItem>,
/// Each photo's place, by index into [`PLACES`].
place_of: Vec<Option<usize>>,
}
/// Towns the photos were "taken" in: name, ISO country, latitude, longitude.
const PLACES: &[(&str, &str, f64, f64)] = &[
("Lisbon", "PT", 38.7223, -9.1393),
("Porto", "PT", 41.1579, -8.6291),
("Barcelona", "ES", 41.3874, 2.1686),
("Paris", "FR", 48.8566, 2.3522),
("Amsterdam", "NL", 52.3676, 4.9041),
("Copenhagen", "DK", 55.6761, 12.5683),
("Berlin", "DE", 52.5200, 13.4050),
("Prague", "CZ", 50.0755, 14.4378),
("Vienna", "AT", 48.2082, 16.3738),
("Florence", "IT", 43.7696, 11.2558),
("Rome", "IT", 41.9028, 12.4964),
("Thira", "GR", 36.4166, 25.4318),
];
const ALBUMS: &[&str] = &[
"Summer in Portugal",
"Family",
"Hiking",
"Food",
"City trips",
"Best of 2025",
];
impl Demo {
fn new(dir: &Path) -> Result<Self, String> {
let mut pictures: Vec<PathBuf> = std::fs::read_dir(dir)
.map_err(|e| format!("{}: {e}", dir.display()))?
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|ext| ext == "jpg"))
.collect();
pictures.sort();
if pictures.is_empty() {
return Err(format!("no .jpg pictures in {}", dir.display()));
}
let now = Local::now().timestamp();
let mut demo = Demo {
now,
pictures,
photos: Vec::new(),
place_of: Vec::new(),
};
demo.make_photos();
Ok(demo)
}
/// The timeline: newest first, a few a week back three years, plus a
/// photo on this day in each of the last three years.
fn make_photos(&mut self) {
let mut seed = 0x5eed_u64;
let mut next = move || {
seed = seed
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
(seed >> 33) as i64
};
let today = Local::now().date_naive();
let noon = |years_back: i32| {
let day = today
.with_year(today.year() - years_back)
.unwrap_or(today - chrono::Days::new(365 * years_back as u64));
Local
.from_local_datetime(&day.and_hms_opt(11, 30, 0).unwrap_or_default())
.single()
.map_or(0, |t| t.timestamp())
};
// Three years, so a few a day.
let step = 3 * 365 * DAY / PHOTOS as i64;
let mut times: Vec<i64> = (0..PHOTOS as i64)
.map(|i| self.now - 3 * 3600 - i * step - next() % step)
.collect();
times.extend([noon(1), noon(2), noon(3)]);
times.sort_unstable_by(|a, b| b.cmp(a));
for (i, time) in times.into_iter().enumerate() {
let picture = &self.pictures[i % self.pictures.len()];
let kind = match i % 23 {
7 | 15 => PhotoKind::Video,
19 => PhotoKind::Raw,
_ => PhotoKind::Photo,
};
let place = (i % 5 != 4).then_some((i / 7) % PLACES.len());
self.photos.push(PhotoItem {
uid: format!("demo-photos~{i}"),
capture_time: time,
thumb_path: Some(picture.display().to_string()),
name: Some(format!(
"IMG_{}.{}",
20_000 + i,
if kind == PhotoKind::Video {
"MP4"
} else {
"JPG"
}
)),
ratio: Some(if picture.to_string_lossy().ends_with("-p.jpg") {
2.0 / 3.0
} else {
1.5
}),
no_thumb: false,
kind,
favorite: i % 11 == 3,
group_size: 0,
has_raw: kind == PhotoKind::Raw,
place_id: place.map(|p| p as u32 + 1),
});
self.place_of.push(place);
}
}
fn status(&self) -> Response {
Response::Status {
username: USERNAME.into(),
mountpoint: MOUNTPOINT.into(),
pinned: 3,
used: 6 * GIB + 300 * (1 << 20),
budget: 20 * GIB,
pins: self.pins(),
online: true,
pending_uploads: 0,
pending_changes: 0,
parked_uploads: 0,
failing_ops: 0,
failing_error: None,
staged_bytes: 0,
staged_oldest_secs: 0,
paused: false,
paused_until: None,
session_expired: false,
tokens_unsaved: false,
version: env!("CARGO_PKG_VERSION").into(),
}
}
fn answer(&self, request: &Request) -> Response {
match request {
Request::Status => self.status(),
Request::AccountQuota => Response::AccountQuota {
max_space: 500 * GIB as i64,
used_space: 137 * GIB as i64,
},
Request::ListDir { path } => Response::Entries {
entries: self.dir(path),
},
Request::ListTrash => Response::Entries {
entries: self.trash(),
},
Request::ListTrashedFolder { uid } => Response::Entries {
entries: self.trashed_folder(uid),
},
Request::ReserveFileThumbGeneration => Response::FileThumbGeneration { generation: 1 },
Request::FileThumbs { items, .. } => Response::Thumbs {
items: items
.iter()
.map(|item| PhotoThumb {
uid: item.uid.clone(),
path: self.file_picture(&item.uid),
pending: false,
})
.collect(),
},
Request::PhotosTimeline {
offset,
limit,
kind,
favorites,
..
} => {
let items: Vec<PhotoItem> = self
.photos
.iter()
.filter(|p| kind.is_none_or(|k| p.kind == k))
.filter(|p| !favorites || p.favorite)
.skip(*offset)
.take(*limit)
.cloned()
.collect();
Response::Photos {
available: true,
items,
counts: Some(self.counts()),
}
}
Request::PhotoMonths { kind } => Response::PhotoMonths {
months: self.months(*kind),
},
Request::PhotosOnThisDay { .. } => {
let today = Local::now();
let items = self
.photos
.iter()
.filter(|p| {
let at = Local.timestamp_opt(p.capture_time, 0).single();
at.is_some_and(|at| {
at.year() < today.year()
&& at.month() == today.month()
&& at.day() == today.day()
})
})
.cloned()
.collect();
Response::Photos {
available: true,
items,
counts: None,
}
}
Request::PhotoThumbs { uids } => Response::Thumbs {
items: uids
.iter()
.map(|uid| PhotoThumb {
uid: uid.clone(),
path: self
.photos
.iter()
.find(|p| &p.uid == uid)
.and_then(|p| p.thumb_path.clone()),
pending: false,
})
.collect(),
},
Request::PhotoAlbums => Response::Albums {
available: true,
items: self.albums(),
},
Request::AlbumPhotos { uid, offset, limit } => {
let index: usize = uid
.rsplit('~')
.next()
.and_then(|n| n.parse().ok())
.unwrap_or(0);
Response::Photos {
available: true,
items: self
.album_photos(index)
.skip(*offset)
.take(*limit)
.cloned()
.collect(),
counts: None,
}
}
Request::PhotoPlaces => Response::Places {
items: self.places(),
mapping: None,
},
Request::PlaceLocations { id } => Response::PhotoLocations {
items: self.place_locations(*id),
},
Request::PlacePhotos { id, offset, limit } => Response::Photos {
available: true,
items: self
.in_place(*id)
.map(|(_, p)| p)
.skip(*offset)
.take(*limit)
.cloned()
.collect(),
counts: None,
},
Request::ListDevices => Response::Devices {
items: self.devices(),
},
Request::ListSyncFolders => Response::SyncFolders {
items: self.sync_folders(),
},
Request::ListLocations => Response::Locations {
items: self.locations(),
},
// Every conflict in the history is resolved: an open one would
// badge every page.
Request::ListConflicts => Response::Conflicts { items: Vec::new() },
Request::ListPendingOps => Response::PendingOps { items: Vec::new() },
Request::ListActivity { limit } => Response::Activity {
items: self.activity().into_iter().take(*limit).collect(),
},
Request::ListInvitations => Response::Invitations { items: Vec::new() },
Request::ListBookmarks => Response::Bookmarks { items: Vec::new() },
Request::GetQueueStatus => Response::Transfers {
items: Vec::new(),
jobs: Vec::new(),
},
Request::ListPins => Response::Pins { pins: self.pins() },
Request::SearchV2 { query, limit, .. } => Response::SearchResultsV2 {
drive_hits: self.search(query, *limit),
local_hits: self.local_search(query),
local_indexing: false,
},
Request::Search { query, limit, .. } => Response::SearchResults {
hits: self.search(query, *limit),
},
Request::ImportStatus => Response::ImportStatus {
running: false,
summary: None,
progress: None,
resumable: Vec::new(),
},
Request::PhotosRefreshStatus => Response::PhotosRefresh { running: false },
other => {
eprintln!("demo_daemon: no demo answer for {}", request_name(other));
Response::Ok {
message: String::new(),
}
}
}
}
fn counts(&self) -> (usize, usize, usize) {
let of = |kind| self.photos.iter().filter(|p| p.kind == kind).count();
(
of(PhotoKind::Photo),
of(PhotoKind::Video),
of(PhotoKind::Raw),
)
}
fn months(&self, kind: Option<PhotoKind>) -> Vec<PhotoMonth> {
let mut months: BTreeMap<(i32, i32), usize> = BTreeMap::new();
for photo in self
.photos
.iter()
.filter(|p| kind.is_none_or(|k| p.kind == k))
{
if let Some(at) = Local.timestamp_opt(photo.capture_time, 0).single() {
*months.entry((at.year(), at.month() as i32)).or_default() += 1;
}
}
months
.into_iter()
.rev()
.map(|((year, month), count)| PhotoMonth { year, month, count })
.collect()
}
fn albums(&self) -> Vec<AlbumInfo> {
ALBUMS
.iter()
.enumerate()
.map(|(i, name)| AlbumInfo {
uid: format!("demo-album~{i}"),
name: (*name).into(),
photo_count: self.album_photos(i).count(),
cover_uid: self.album_photos(i).next().map(|p| p.uid.clone()),
last_activity: Some(self.now - (i as i64 * 9 + 2) * DAY),
shared: i == 1,
})
.collect()
}
fn album_photos(&self, album: usize) -> impl Iterator<Item = &PhotoItem> {
let stride = 3 + album;
self.photos
.iter()
.skip(album * 2)
.step_by(stride)
.take(40 + album * 17)
}
fn in_place(&self, id: u32) -> impl Iterator<Item = (usize, &PhotoItem)> {
self.photos
.iter()
.enumerate()
.filter(move |(i, _)| self.place_of[*i].is_some_and(|p| p as u32 + 1 == id))
}
fn places(&self) -> Vec<PlaceInfo> {
PLACES
.iter()
.enumerate()
.filter_map(|(i, (name, country, latitude, longitude))| {
let id = i as u32 + 1;
let count = self.in_place(id).count();
let cover = self.in_place(id).next()?.1.clone();
Some(PlaceInfo {
id,
name: (*name).into(),
country: (*country).into(),
latitude: *latitude,
longitude: *longitude,
photo_count: count,
cover,
})
})
.collect()
}
fn place_locations(&self, id: u32) -> Vec<PhotoLocation> {
let Some((_, _, latitude, longitude)) = PLACES.get(id as usize - 1) else {
return Vec::new();
};
self.in_place(id)
.map(|(i, photo)| {
// Spread around the centre, the same way on every run.
let angle = i as f64 * 2.399;
let reach = 0.004 + (i % 9) as f64 * 0.003;
PhotoLocation {
photo: photo.clone(),
latitude: latitude + reach * angle.sin(),
longitude: longitude + reach * angle.cos(),
}
})
.collect()
}
/// The trash: things deleted from a few folders, and a deleted folder with
/// a file deleted from it before it went.
fn trash(&self) -> Vec<DirEntry> {
let item = |name: &str, size: u64, hours: i64, from: &str| DirEntry {
name: name.into(),
is_dir: size == 0,
size,
modified: self.now - 40 * DAY,
uid: format!("demo-trash~{from}/{name}"),
trashed_at: self.now - hours * 3600,
trashed_from: Some(from.into()),
..Default::default()
};
let mut inside = item("Draft 3.odt", 48_120, 30, "");
inside.uid = "demo-trash~Old drafts/Draft 3.odt".into();
inside.trashed_from = None;
inside.trashed_parent = Some("demo-trash~Work/Old drafts".into());
vec![
item("Budget 2025.ods", 51_200, 2, "Documents"),
item("Scan 0042.pdf", 1_204_331, 5, "Documents"),
item("Scan 0043.pdf", 1_198_002, 5, "Documents"),
item("IMG_2041.jpg", 3_402_112, 20, "Pictures/Lisbon"),
item("IMG_2042.jpg", 3_311_870, 20, "Pictures/Lisbon"),
item("IMG_2043.jpg", 3_587_004, 20, "Pictures/Lisbon"),
item("Old drafts", 0, 26, "Work"),
item("Meeting notes (copy).md", 6_120, 50, ""),
item("Invoice 118.pdf", 88_341, 80, "Taxes/2025"),
inside,
]
}
/// What the deleted folder in [`Self::trash`] holds.
fn trashed_folder(&self, uid: &str) -> Vec<DirEntry> {
if uid != "demo-trash~Work/Old drafts" {
return Vec::new();
}
let file = |name: &str, size: u64| DirEntry {
name: name.into(),
size,
modified: self.now - 50 * DAY,
uid: format!("demo-trash~Old drafts/{name}"),
trashed_parent: Some(uid.into()),
..Default::default()
};
let mut gone = file("Draft 3.odt", 48_120);
gone.trashed_at = self.now - 30 * 3600;
vec![
file("Draft 1.odt", 41_002),
file("Draft 2.odt", 44_870),
gone,
]
}
/// My files: folders first, then a few files, some of them pictures with
/// thumbnails. Any folder below the root holds the same few documents.
fn dir(&self, path: &str) -> Vec<DirEntry> {
let folder = |name: &str, days: i64| DirEntry {
name: name.into(),
is_dir: true,
modified: self.now - days * DAY,
uid: format!("demo-files~{path}/{name}"),
path: join(path, name),
..Default::default()
};
let file = |name: &str, size: u64, days: i64| DirEntry {
name: name.into(),
is_dir: false,
size,
modified: self.now - days * DAY - 4000,
uid: format!("demo-files~{path}/{name}"),
path: join(path, name),
..Default::default()
};
if !path.trim_matches('/').is_empty() {
return vec![
file("Notes.md", 4_812, 1),
file("Overview.pdf", 912_384, 6),
file("Budget.ods", 38_112, 12),
];
}
let mut entries = vec![
folder("Documents", 1),
folder("Music", 30),
folder("Pictures", 2),
folder("Projects", 4),
folder("Recipes", 60),
folder("Taxes", 120),
folder("Videos", 14),
folder("Work", 3),
];
let mut pinned = file("Lisbon sunset.jpg", 4_218_112, 20);
pinned.pinned = true;
pinned.cached = true;
entries.extend([
file("Apartment lease.pdf", 1_482_011, 40),
file("Budget 2026.ods", 52_340, 2),
file("Cliffs.jpg", 3_844_201, 33),
file("Garden.jpg", 2_904_877, 9),
pinned,
file("Meeting notes.md", 6_120, 0),
file("Mountain lake.jpg", 5_120_330, 61),
file("Packing list.txt", 1_204, 5),
file("Road trip.jpg", 3_211_008, 75),
file("Thesis draft.odt", 812_448, 18),
]);
entries
}
/// The picture behind a demo file, for its thumbnail.
fn file_picture(&self, uid: &str) -> Option<String> {
let name = uid.rsplit('/').next()?;
if !name.ends_with(".jpg") {
return None;
}
let index = name.bytes().map(usize::from).sum::<usize>() % self.pictures.len();
Some(self.pictures[index].display().to_string())
}
fn pins(&self) -> Vec<Pin> {
[
("Documents", true),
("Work/Quarterly report.odt", false),
("Lisbon sunset.jpg", false),
]
.into_iter()
.map(|(path, dir)| Pin {
uid: format!("demo-files~/{path}"),
path: (*path).into(),
recursive: dir,
is_dir: Some(dir),
cached: true,
})
.collect()
}
fn devices(&self) -> Vec<DeviceInfo> {
vec![
DeviceInfo {
uid: "demo-devices~1".into(),
name: "alex-laptop".into(),
device_type: "Linux".into(),
last_sync: Some(self.now - 240),
this_device: true,
adopted: true,
},
DeviceInfo {
uid: "demo-devices~2".into(),
name: "studio-desktop".into(),
device_type: "Windows".into(),
last_sync: Some(self.now - 2 * DAY - 3 * 3600),
this_device: false,
adopted: false,
},
DeviceInfo {
uid: "demo-devices~3".into(),
name: "old-macbook".into(),
device_type: "MacOs".into(),
last_sync: Some(self.now - 210 * DAY),
this_device: false,
adopted: false,
},
]
}
/// This computer's synced folders: mirrors, and one kept online only.
const FOLDERS: &[(&str, &str)] = &[
("/home/alex/Documents", "mirror"),
("/home/alex/Pictures/Camera", "mirror"),
("/home/alex/Music", "ondemand"),
("/home/alex/Projects", "mirror"),
];
fn sync_folders(&self) -> Vec<SyncFolderInfo> {
Self::FOLDERS
.iter()
.enumerate()
.map(|(i, (path, mode))| SyncFolderInfo {
id: i as i64 + 1,
kind: "device".into(),
local_path: (*path).into(),
remote_uid: format!("demo-sync~{i}"),
mode: (*mode).into(),
pending_mode: None,
state: "idle".into(),
last_sync: self.now - 240 - i as i64 * 60,
progress: None,
paused: false,
})
.collect()
}
fn locations(&self) -> Vec<MountSpec> {
let mut items = vec![MountSpec {
id: 1,
kind: MountKind::MyFiles,
local_path: MOUNTPOINT.into(),
root_uid: "demo-files~".into(),
root_share_id: String::new(),
mode: MountMode::OnDemand,
access: MountAccess::Rw,
state: "idle".into(),
last_sync: self.now - 60,
pending_mode: None,
mounted: true,
progress: None,
paused: false,
}];
items.extend(
Self::FOLDERS
.iter()
.enumerate()
.map(|(i, (path, mode))| MountSpec {
id: i as i64 + 2,
kind: MountKind::Device {
sync_folder_id: i as i64 + 1,
},
local_path: (*path).into(),
root_uid: format!("demo-sync~{i}"),
root_share_id: String::new(),
mode: MountMode::from(*mode),
access: MountAccess::Rw,
state: "idle".into(),
last_sync: self.now - 240 - i as i64 * 60,
pending_mode: None,
mounted: *mode == "ondemand",
progress: None,
paused: false,
}),
);
items
}
fn activity(&self) -> Vec<ActivityEntry> {
let at = |minutes: i64| self.now - minutes * 60;
let entry = |time, kind, target: &str, detail: &str, ok| ActivityEntry {
time,
kind,
target: target.into(),
detail: detail.into(),
ok,
};
let conflict = |time, name: &str, ext: &str| {
entry(
time,
ActivityKind::Conflict,
&format!("{name} (sync-conflict {time}).{ext}"),
&format!("differs from {name}.{ext}"),
false,
)
};
vec![
entry(at(2), ActivityKind::Upload, "Meeting notes.md", "", true),
entry(
at(14),
ActivityKind::Share,
"Budget 2026.ods",
"1 recipient(s) as editor",
true,
),
entry(
at(38),
ActivityKind::Upload,
"Pictures/Camera/IMG_20481.JPG",
"",
true,
),
entry(
at(39),
ActivityKind::Upload,
"Pictures/Camera/IMG_20480.JPG",
"",
true,
),
entry(
at(52),
ActivityKind::Rename,
"Thesis draft.odt",
"was thesis-v3.odt",
true,
),
conflict(at(180), "Quarterly report", "odt"),
entry(
at(240),
ActivityKind::Move,
"Taxes/2025",
"from Documents",
true,
),
entry(
at(26 * 60),
ActivityKind::PublicLink,
"Road trip.jpg",
"",
true,
),
conflict(at(26 * 60 + 5), "Packing list", "txt"),
entry(at(27 * 60), ActivityKind::CreateFolder, "Recipes", "", true),
conflict(at(28 * 60), "Garden plan", "svg"),
entry(at(29 * 60), ActivityKind::Trash, "Old invoices", "", true),
entry(
at(30 * 60),
ActivityKind::Restore,
"Apartment lease.pdf",
"",
true,
),
entry(
at(50 * 60),
ActivityKind::Upload,
"Videos/Harbour at dusk.mp4",
"",
true,
),
]
}
/// Hits for the search launcher: every demo file whose name holds the
/// query, or a few to show when nothing does.
fn search(&self, query: &str, limit: usize) -> Vec<SearchHit> {
let names = [
("Work/Quarterly report.odt", false, 180_912),
("Work/Quarterly report 2025.pdf", false, 1_204_334),
("Work/Reports", true, 0),
("Documents/Expense report March.ods", false, 44_201),
("Documents/Lab report.pdf", false, 2_301_442),
("Projects/Annual report draft.md", false, 18_400),
("Taxes/2025/Tax report.pdf", false, 640_008),
("Pictures/Report cover.jpg", false, 2_801_220),
];
let needle = query.to_lowercase();
names
.iter()
.filter(|(path, _, _)| needle.is_empty() || path.to_lowercase().contains(&needle))
.take(limit)
.enumerate()
.map(|(i, (path, is_dir, size))| SearchHit {
name: path.rsplit('/').next().unwrap_or(path).into(),
path: (*path).into(),
is_dir: *is_dir,
size: *size,
modified: self.now - (i as i64 * 5 + 1) * DAY,
pinned: i == 0,
cached: i == 0,
uid: format!("demo-files~/{path}"),
mounted_path: Some(format!("{MOUNTPOINT}/{path}")),
score: 100 - i as i64,
})
.collect()
}
fn local_search(&self, query: &str) -> Vec<LocalHit> {
let needle = query.to_lowercase();
[("/home/alex/Downloads/report-template.ott", 22_018)]
.iter()
.filter(|(path, _)| path.to_lowercase().contains(&needle))
.map(|(path, size)| LocalHit {
name: path.rsplit('/').next().unwrap_or(path).into(),
path: (*path).into(),
is_dir: false,
size: *size,
modified: self.now - 4 * DAY,
score: 10,
})
.collect()
}
}
fn join(dir: &str, name: &str) -> String {
let dir = dir.trim_matches('/');
if dir.is_empty() {
name.into()
} else {
format!("{dir}/{name}")
}
}
/// The variant name of `request`, for the log of requests the demo ignores.
fn request_name(request: &Request) -> String {
let json = serde_json::to_string(request).unwrap_or_default();
json.trim_start_matches(['{', '"'])
.split('"')
.next()
.unwrap_or_default()
.to_string()
}
+2 -2
View File
@@ -16,7 +16,7 @@ impl Access {
matches!(self, Self::Owner | Self::Editor)
}
pub(crate) fn as_db_str(self) -> &'static str {
pub fn as_db_str(self) -> &'static str {
match self {
Self::Owner => "owner",
Self::Editor => "editor",
@@ -25,7 +25,7 @@ impl Access {
}
}
pub(crate) fn from_db_str(value: &str) -> Option<Self> {
pub fn from_db_str(value: &str) -> Option<Self> {
match value {
"owner" => Some(Self::Owner),
"editor" => Some(Self::Editor),
+352 -108
View File
@@ -28,6 +28,7 @@ use std::time::Duration;
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64;
use keyring_core::Entry;
use proton_auth_rs::{KeyringStore, SecretStore};
use proton_drive_rs::{KeySalt, ProtonDriveClient};
use proton_sdk::account::KeyPassphrases;
use proton_sdk::api::{HumanVerification, HumanVerificationCredential};
@@ -35,12 +36,13 @@ use proton_sdk::cache::EncryptedCacheRepository;
use proton_sdk::config::ProtonClientConfiguration;
use proton_sdk::error::ProtonError;
use proton_sdk::http::Tokens;
use proton_sdk::login::{self, LoginError, Step};
use proton_sdk::session::{PasswordMode, ProtonApiSession, ResumeParameters};
use proton_sdk::telemetry::TracingTelemetry;
use serde::{Deserialize, Serialize};
use zeroize::Zeroizing;
use crate::config::{APP_VERSION, AppDirs, KEYRING_SERVICE, USER_AGENT};
use crate::config::{APP_VERSION, AppDirs, USER_AGENT};
use crate::error::{Error, Result};
use crate::kernelkey;
@@ -123,13 +125,33 @@ fn client_config() -> ProtonClientConfiguration {
ProtonClientConfiguration::new(app_version).with_user_agent(user_agent)
}
fn keyring_entry() -> Result<Entry> {
// Installed lazily rather than once at startup so a session bus that was not
// up yet on the first attempt is retried on the next one.
if keyring_core::get_default_store().is_none() {
keyring_core::set_default_store(dbus_secret_service_keyring_store::Store::new()?);
}
Ok(Entry::new(KEYRING_SERVICE, KEYRING_USER)?)
/// Run `op` on the session's keyring entry.
fn with_keyring<T>(op: impl Fn(&Entry) -> keyring_core::Result<T>) -> Result<T> {
Ok(keyring().with_entry(KEYRING_USER, op)?)
}
/// The process's keyring, connected on first use.
///
/// One connection for the whole process; when the Secret Service fails it
/// (a restarted provider forgets the session, `docs/BUGS.md` B285), the call
/// reconnects and is made once more. A changed session replaces its item
/// instead of editing it (B291). Both live in `proton-auth-rs`.
fn keyring() -> &'static KeyringStore {
static STORE: std::sync::OnceLock<KeyringStore> = std::sync::OnceLock::new();
STORE.get_or_init(|| {
#[cfg(not(test))]
{
KeyringStore::new(crate::config::keyring_service())
}
#[cfg(test)]
{
KeyringStore::with_connector(
crate::config::KEYRING_SERVICE,
Arc::new(tests::connect_keyring_store),
)
.replace_items(|| tests::MOCK_STORE.lock().is_none())
}
})
}
/// What the user answered when asked for the mailbox password.
@@ -261,74 +283,56 @@ pub async fn login_verified(
get_totp: impl Fn() -> Result<String>,
get_mailbox: impl Fn(u32) -> Result<Mailbox>,
) -> Result<()> {
let password = Zeroizing::new(password.to_owned());
let session = ProtonApiSession::begin_verified(
client_config(),
username,
password.as_bytes(),
verification,
)
.await
.map_err(classify_verification_gate);
let mut session = session?;
if session.is_waiting_for_second_factor() {
let code = get_totp()?;
session.apply_second_factor_code(code.trim()).await?;
}
// Grab the key salts while this access token still has the `locked` scope:
// after its first refresh it never will again, and without them no later
// resume can unlock the key chain. See `StoredSession::key_salts`.
let key_salts = ProtonDriveClient::new(&session, Vec::new())
.account()
.key_salts()
.await?;
// A single-password account's mailbox password is the login password. A
// two-password one has a second secret the user must type, and it is checked
// against the account now — a typo found at login is a retry, found later it
// is a daemon that never mounts.
let (passphrases, remember) = match session.password_mode() {
PasswordMode::Single => (
derive_verified(&session, password.as_bytes(), key_salts.clone()).await?,
true,
),
PasswordMode::Dual => {
let mut attempt = 0;
loop {
let mailbox = get_mailbox(attempt)?;
match derive_verified(&session, mailbox.password.as_bytes(), key_salts.clone())
.await
{
Ok(passphrases) => break (passphrases, mailbox.remember),
Err(Error::WrongMailboxPassword) if attempt + 1 < MAILBOX_ATTEMPTS => {
attempt += 1;
}
Err(e) => return Err(e),
}
// The sequence is `proton_sdk::login`, shared with the other Proton
// apps. It reads the key salts before unlocking, while this access token
// still has the `locked` scope: after its first refresh it never will
// again, and without them no later resume can unlock the key chain. See
// `StoredSession::key_salts`.
let mut step = login::begin(client_config(), username, password, verification)
.await
.map_err(sign_in_error)?;
let (unlocked, remember) = loop {
step = match step {
Step::SecondFactor(pending) => {
let code = get_totp()?;
pending.second_factor(&code).await.map_err(sign_in_error)?
}
}
// A single-password account's mailbox password is the login password.
Step::Unlock(pending) => break (pending.unlock().await.map_err(sign_in_error)?, true),
// A two-password one has a second secret the user must type, and it is
// checked against the account now — a typo found at login is a retry,
// found later it is a daemon that never mounts.
Step::MailboxPassword(pending) => {
let mut attempt = 0;
break loop {
let mailbox = get_mailbox(attempt)?;
match pending.mailbox_password(&mailbox.password).await {
Ok(unlocked) => break (unlocked, mailbox.remember),
Err(LoginError::WrongMailboxPassword) if attempt + 1 < MAILBOX_ATTEMPTS => {
attempt += 1;
}
Err(e) => return Err(sign_in_error(e)),
}
};
}
};
};
let tokens = session.current_tokens().await;
register_refresh_handler(&session, tokens.refresh_token.clone());
let tokens = unlocked.resume_parameters().await;
register_refresh_handler(&unlocked.session, tokens.refresh_token.clone());
let stored = StoredSession {
session_id: session.session_id().as_str().to_owned(),
username: session.username().to_owned(),
user_id: session.user_id().as_str().to_owned(),
session_id: tokens.session_id.as_str().to_owned(),
username: tokens.username,
user_id: tokens.user_id.as_str().to_owned(),
access_token: tokens.access_token,
refresh_token: tokens.refresh_token,
scopes: session.scopes().to_vec(),
password_mode: match session.password_mode() {
PasswordMode::Single => 1,
PasswordMode::Dual => 2,
},
scopes: tokens.scopes,
password_mode: tokens.password_mode.to_wire() as u8,
mailbox_password: String::new(),
key_salts,
key_salts: unlocked.key_salts,
key_passphrases: None,
};
keep_passphrases(stored, &passphrases, remember)
keep_passphrases(stored, &unlocked.key_passphrases, remember)
}
/// Derive the key passphrases from `mailbox` and prove they unlock the account.
@@ -402,36 +406,53 @@ fn decode_secret(secret: &[u8]) -> Option<KeyPassphrases> {
decode(&serde_json::from_slice(secret).ok()?)
}
/// Lift a human-verification gate out of the generic API error into the typed
/// variant a front-end can act on.
/// A failed sign-in step as this crate's error.
///
/// Only a gate that names a solvable method is converted. A `9001` with no
/// `Details`, or one offering only `email`/`sms`, stays a plain API error:
/// promoting it would send the UI to open a verification page it cannot
/// complete, which reads to the user as a hang rather than a refusal.
fn classify_verification_gate(e: ProtonError) -> Error {
let ProtonError::Api(api) = &e else {
return e.into();
};
match api.human_verification() {
Some(hv) if hv.supports_captcha() => Error::HumanVerificationRequired(Box::new(hv)),
_ => e.into(),
/// A blocked, refused or wrong-code attempt goes back to the Proton error it
/// came from, which is what the front-ends word themselves. Only a gate that
/// names a solvable method is a [`Error::HumanVerificationRequired`]: one that
/// offers only `email`/`sms` stays a plain API error, because sending the UI to
/// open a page it cannot complete reads as a hang rather than a refusal.
fn sign_in_error(e: LoginError) -> Error {
match e {
LoginError::HumanVerification(hv) => Error::HumanVerificationRequired(hv),
LoginError::SecurityKeyOnly => Error::SecurityKeyOnly,
LoginError::Blocked(api) | LoginError::Rejected(api) | LoginError::WrongCode(api) => {
Error::Proton(ProtonError::Api(api))
}
LoginError::WrongMailboxPassword => Error::WrongMailboxPassword,
LoginError::Proton(e) => e.into(),
other => Error::Other(other.to_string()),
}
}
/// Save `stored` to the keyring.
///
/// Save the session. An existing entry is replaced by a new item rather than
/// edited, because oo7 before 0.7.0 keeps an edit only in memory and a reboot
/// brings the spent refresh token back (`docs/BUGS.md` B291).
fn write_stored(stored: &StoredSession) -> Result<()> {
let json = Zeroizing::new(serde_json::to_string(stored)?);
keyring_entry()?.set_password(&json)?;
Ok(())
Ok(keyring().set(KEYRING_USER, &json)?)
}
/// A short, one-way tag for a refresh token, for the log: enough to tell
/// whether the token a start finds is the one the last save wrote, and
/// nothing that helps anyone use it.
fn fingerprint(token: &str) -> String {
use sha2::{Digest, Sha256};
Sha256::digest(token.as_bytes())[..4]
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
/// Load the persisted session blob, or `Error::NotLoggedIn` if absent.
pub fn load() -> Result<StoredSession> {
let entry = keyring_entry()?;
match entry.get_password() {
match with_keyring(|entry| entry.get_password()) {
Ok(json) => Ok(serde_json::from_str(&json)?),
Err(keyring_core::Error::NoEntry) => Err(Error::NotLoggedIn),
Err(e) => Err(e.into()),
Err(Error::Keyring(keyring_core::Error::NoEntry)) => Err(Error::NotLoggedIn),
Err(e) => Err(e),
}
}
@@ -589,9 +610,9 @@ pub fn logout() -> Result<bool> {
tracing::warn!(error = %e, "clearing the kernel-keyring unlock on logout failed");
}
let _ = kernelkey::UNSAVED_TOKENS.clear();
match keyring_entry()?.delete_credential() {
Ok(()) | Err(keyring_core::Error::NoEntry) => Ok(ended),
Err(e) => Err(e.into()),
match with_keyring(|entry| entry.delete_credential()) {
Ok(()) | Err(Error::Keyring(keyring_core::Error::NoEntry)) => Ok(ended),
Err(e) => Err(e),
}
}
@@ -634,6 +655,10 @@ fn resume_stored(stored: &StoredSession) -> Result<ProtonApiSession> {
resumed.access_token = tokens.access_token.clone();
resumed.refresh_token = tokens.refresh_token.clone();
}
tracing::info!(
refresh = %fingerprint(&resumed.refresh_token),
"resuming the stored session"
);
let session = ProtonApiSession::resume(client_config(), resumed.to_params())?;
let sink = register_refresh_handler(&session, stored.refresh_token.clone());
if let Some(tokens) = unsaved {
@@ -996,21 +1021,15 @@ impl TokenSink {
}
}
/// Write the unsaved rotation, if there is one. A blob that moved on, or
/// is gone with a logout, drops it: there is nothing it may still go into.
/// Write the unsaved rotation, if there is one. A blob that moved on drops
/// it. A missing blob is retried: some Secret Service providers also report
/// locked or temporarily hidden items as absent. Never recreate it here.
fn flush(&self) -> Result<()> {
let mut state = self.state.lock();
let Some(tokens) = state.unsaved.clone() else {
return Ok(());
};
let mut stored = match load() {
Ok(stored) => stored,
Err(Error::NotLoggedIn) => {
state.settle();
return Ok(());
}
Err(e) => return Err(e),
};
let mut stored = load()?;
match take_rotation(
&mut stored,
&self.session_id,
@@ -1019,8 +1038,11 @@ impl TokenSink {
) {
Rotation::Taken => {
write_stored(&stored)?;
tracing::info!(
refresh = %fingerprint(&tokens.refresh_token),
"successfully auto-persisted refreshed tokens in keyring"
);
state.stored_refresh = tokens.refresh_token;
tracing::info!("successfully auto-persisted refreshed tokens in keyring");
}
Rotation::MovedOn => {
tracing::info!(
@@ -1213,12 +1235,203 @@ mod tests {
/// The keyring is one store per process, so the tests that use it,
/// through `keyring-core`'s in-memory store, take turns.
fn mock_keyring() -> parking_lot::MutexGuard<'static, ()> {
static KEYRING: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
let turn = KEYRING.lock();
keyring_core::set_default_store(keyring_core::mock::Store::new().unwrap());
let store: Arc<keyring_core::CredentialStore> = keyring_core::mock::Store::new().unwrap();
*MOCK_STORE.lock() = Some(Arc::clone(&store));
keyring_core::set_default_store(store);
keyring().disconnect();
turn
}
/// The tests' in-memory store when they set one, so a reconnect finds the
/// same entries; the real Secret Service otherwise.
pub(super) fn connect_keyring_store() -> keyring_core::Result<Arc<keyring_core::CredentialStore>>
{
KEYRING_CONNECTS.fetch_add(1, Ordering::SeqCst);
match MOCK_STORE.lock().clone() {
Some(store) => Ok(store),
None => Ok(dbus_secret_service_keyring_store::Store::new()?),
}
}
/// Run `op` on the entry `service`/`user` of the real Secret Service.
fn with_keyring_entry<T>(
store: &KeyringStore,
user: &str,
op: impl Fn(&Entry) -> keyring_core::Result<T>,
) -> Result<T> {
Ok(store.with_entry(user, op)?)
}
static KEYRING: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
/// The in-memory store a reconnect hands out, so it finds the same
/// entries; `None` connects to the real Secret Service.
pub(super) static MOCK_STORE: parking_lot::Mutex<Option<Arc<keyring_core::CredentialStore>>> =
parking_lot::Mutex::new(None);
/// How many times a store was connected.
pub(super) static KEYRING_CONNECTS: std::sync::atomic::AtomicUsize =
std::sync::atomic::AtomicUsize::new(0);
/// The session's entry, to make its next call fail.
fn keyring_entry() -> Entry {
Entry::new(crate::config::KEYRING_SERVICE, KEYRING_USER).unwrap()
}
/// Make the session entry's next call fail with `error`.
fn fail_next(error: keyring_core::Error) {
keyring_entry()
.as_any()
.downcast_ref::<keyring_core::mock::Cred>()
.unwrap()
.set_error(error);
}
fn no_session() -> keyring_core::Error {
keyring_core::Error::PlatformFailure(
std::io::Error::other("The session does not exist (NoSession)").into(),
)
}
/// B285: a restarted Secret Service no longer knows the process's
/// session, and every call on it failed until the process restarted.
#[test]
fn a_dropped_secret_service_session_is_reconnected_and_retried() {
let _turn = mock_keyring();
write_stored(&stored_with("r")).unwrap();
let connects = KEYRING_CONNECTS.load(Ordering::SeqCst);
fail_next(no_session());
assert_eq!(load().unwrap().refresh_token, "r");
assert_eq!(KEYRING_CONNECTS.load(Ordering::SeqCst), connects + 1);
fail_next(no_session());
write_stored(&stored_with("r2")).unwrap();
assert_eq!(load().unwrap().refresh_token, "r2");
assert_eq!(KEYRING_CONNECTS.load(Ordering::SeqCst), connects + 2);
}
#[test]
fn a_rotation_lands_at_once_after_the_keyring_restarts() {
let _turn = mock_keyring();
write_stored(&stored_with("r")).unwrap();
let sink = Arc::new(TokenSink::new("s", "r".into()));
fail_next(no_session());
sink.rotated(tokens("a2", "r2")).unwrap();
assert_eq!(load().unwrap().refresh_token, "r2");
assert!(sink.state.lock().unsaved.is_none());
}
/// A locked keyring or a dismissed prompt is no fault of the connection.
#[test]
fn a_locked_keyring_is_not_reconnected() {
let _turn = mock_keyring();
write_stored(&stored_with("r")).unwrap();
let connects = KEYRING_CONNECTS.load(Ordering::SeqCst);
fail_next(keyring_core::Error::NoStorageAccess(
std::io::Error::other("locked").into(),
));
assert!(matches!(
load(),
Err(Error::Keyring(keyring_core::Error::NoStorageAccess(_)))
));
assert_eq!(KEYRING_CONNECTS.load(Ordering::SeqCst), connects);
assert_eq!(load().unwrap().refresh_token, "r");
}
/// The real Secret Service, restarted between two calls on one store.
///
/// Run inside a throwaway session bus, never against the desktop's
/// keyring. With gnome-keyring:
///
/// ```sh
/// echo -n pw | gnome-keyring-daemon --unlock --components=secrets
/// PDFS_SECRET_SERVICE_RESTART_TEST=1 \
/// PDFS_RESTART_PROVIDER='echo -n pw | gnome-keyring-daemon --replace --unlock --components=secrets' \
/// cargo test -p pdfs-core real_secret_service -- --ignored
/// ```
#[test]
#[ignore = "needs a throwaway Secret Service; see the doc comment"]
fn real_secret_service_survives_a_provider_restart() {
if std::env::var_os("PDFS_SECRET_SERVICE_RESTART_TEST").is_none() {
return;
}
let restart = std::env::var("PDFS_RESTART_PROVIDER").expect("PDFS_RESTART_PROVIDER");
let _turn = KEYRING.lock();
*MOCK_STORE.lock() = None;
keyring_core::unset_default_store();
let user = "restart";
let service = &KeyringStore::with_connector("pdfs-test", Arc::new(connect_keyring_store));
with_keyring_entry(service, user, |e| e.set_password("before")).unwrap();
let status = std::process::Command::new("sh")
.args(["-c", &restart])
.status()
.unwrap();
assert!(status.success(), "restarting the provider failed");
std::thread::sleep(Duration::from_secs(1));
let connects = KEYRING_CONNECTS.load(Ordering::SeqCst);
let read = with_keyring_entry(service, user, |e| e.get_password()).unwrap();
assert_eq!(read, "before");
assert_eq!(
KEYRING_CONNECTS.load(Ordering::SeqCst),
connects + 1,
"the provider kept the old session, so nothing was tested"
);
with_keyring_entry(service, user, |e| e.set_password("after")).unwrap();
let read = with_keyring_entry(service, user, |e| e.get_password()).unwrap();
assert_eq!(read, "after");
with_keyring_entry(service, user, |e| e.delete_credential()).unwrap();
keyring_core::unset_default_store();
}
/// B291: every save after the first replaces the keyring item, so a
/// provider that keeps an edited secret only in memory (oo7 before 0.7.0)
/// still has the last one after a restart, and only one item is left.
///
/// Run like [`real_secret_service_survives_a_provider_restart`], in a
/// throwaway session bus only.
#[test]
#[ignore = "needs a throwaway Secret Service; see real_secret_service_survives_a_provider_restart"]
fn real_secret_service_keeps_the_last_save_across_a_provider_restart() {
if std::env::var_os("PDFS_SECRET_SERVICE_RESTART_TEST").is_none() {
return;
}
let restart = std::env::var("PDFS_RESTART_PROVIDER").expect("PDFS_RESTART_PROVIDER");
let _turn = KEYRING.lock();
*MOCK_STORE.lock() = None;
keyring_core::unset_default_store();
keyring().disconnect();
for refresh in ["r1", "r2", "r3"] {
write_stored(&stored_with(refresh)).unwrap();
}
let status = std::process::Command::new("sh")
.args(["-c", &restart])
.status()
.unwrap();
assert!(status.success(), "restarting the provider failed");
std::thread::sleep(Duration::from_secs(1));
assert_eq!(load().unwrap().refresh_token, "r3");
let ss =
dbus_secret_service::SecretService::connect(dbus_secret_service::EncryptionType::Plain)
.unwrap();
let found = ss
.search_items(std::collections::HashMap::from([
("service", crate::config::KEYRING_SERVICE),
("username", KEYRING_USER),
]))
.unwrap();
assert_eq!(found.unlocked.len() + found.locked.len(), 1);
with_keyring(|e| e.delete_credential()).unwrap();
keyring_core::unset_default_store();
}
fn stored_with(refresh: &str) -> StoredSession {
serde_json::from_str(&blob("").replace(r#""r""#, &format!("{refresh:?}"))).unwrap()
}
@@ -1273,12 +1486,7 @@ mod tests {
write_stored(&stored_with("r")).unwrap();
let sink = Arc::new(TokenSink::new("s", "r".into()));
let entry = keyring_entry().unwrap();
let cred = entry
.as_any()
.downcast_ref::<keyring_core::mock::Cred>()
.unwrap();
cred.set_error(keyring_core::Error::NoStorageAccess(
fail_next(keyring_core::Error::NoStorageAccess(
std::io::Error::other("locked").into(),
));
assert!(sink.rotated(tokens("a2", "r2")).is_err());
@@ -1306,6 +1514,42 @@ mod tests {
}
}
/// oo7 0.7.0 reports a locked collection's items as absent (upstream #614).
/// Treating that as logout loses the only live tokens (B284, issue #78).
#[test]
fn a_temporarily_missing_session_does_not_discard_a_rotation() {
let _turn = mock_keyring();
write_stored(&stored_with("r")).unwrap();
let sink = Arc::new(TokenSink::new("s", "r".into()));
fail_next(keyring_core::Error::NoEntry);
assert!(sink.rotated(tokens("a2", "r2")).is_err());
assert!(sink.state.lock().unsaved.is_some());
assert_eq!(load().unwrap().refresh_token, "r");
sink.flush().unwrap();
assert_eq!(load().unwrap().refresh_token, "r2");
assert!(sink.state.lock().unsaved.is_none());
}
#[test]
fn retrying_a_missing_session_never_recreates_it_or_overwrites_a_new_login() {
let _turn = mock_keyring();
let sink = TokenSink::new("s", "r".into());
sink.state.lock().unsaved = Some(tokens("a2", "r2"));
assert!(matches!(sink.flush(), Err(Error::NotLoggedIn)));
assert!(matches!(load(), Err(Error::NotLoggedIn)));
assert!(sink.state.lock().unsaved.is_some());
let mut login = stored_with("fresh");
login.session_id = "new".into();
write_stored(&login).unwrap();
sink.flush().unwrap();
assert!(sink.state.lock().unsaved.is_none());
assert_eq!(load().unwrap().refresh_token, "fresh");
}
#[test]
fn an_unsaved_rotation_goes_only_into_the_blob_it_was_refused_for() {
let unsaved = UnsavedRotation {
+387 -69
View File
@@ -26,11 +26,95 @@ pub const USER_AGENT: &str = concat!("proton-drive-linux/", env!("CARGO_PKG_VERS
const LEGACY_APP_VERSION: &str = "external-drive-linux@0.1.0-alpha";
const LEGACY_USER_AGENT: &str = "proton-drive-linux/0.1.0";
/// Keyring service name; one entry per credential kind keyed by username.
/// Keyring service name of the default instance; see [`keyring_service`].
pub const KEYRING_SERVICE: &str = "proton-drive-linux";
/// Environment variable that names a separate instance of the client.
///
/// Unset, everything is as it always was. Set to a name, every place the client
/// keeps an account apart is suffixed with it: the XDG config, state and cache
/// directories (and with them the database, the control socket and the
/// machine id), the Secret Service entry, the kernel keys and the default
/// mountpoint. A second daemon can then run on another account next to the
/// user's own, and neither sees the other's session. The test tooling uses it
/// to run against a test account without signing the user out.
///
/// The systemd unit belongs to the default instance only: with an instance
/// set, the `service` calls do nothing, so a `pdfs login` for a test account
/// never restarts the user's daemon. Start that instance's `pdfs daemon` by
/// hand.
pub const INSTANCE_ENV: &str = "PDFS_INSTANCE";
/// Base name of the client's directories and Secret Service entry.
const APP_NAME: &str = "proton-drive-linux";
/// The instance named by [`INSTANCE_ENV`], read once per process. `None` for
/// the default instance.
///
/// # Panics
///
/// When the name is not 1 to 32 lowercase ASCII letters, digits or `-`. A name
/// that was ignored instead would fall back to the default instance and touch
/// the user's own account. Front ends call [`check_instance`] first to report
/// it as an error.
pub fn instance() -> Option<&'static str> {
match parsed_instance() {
Ok(instance) => *instance,
Err(message) => panic!("{message}"),
}
}
/// Fails when [`INSTANCE_ENV`] is set to a name [`instance`] would refuse.
pub fn check_instance() -> Result<()> {
match parsed_instance() {
Ok(_) => Ok(()),
Err(message) => Err(Error::Other(message.clone())),
}
}
fn parsed_instance() -> &'static std::result::Result<Option<&'static str>, String> {
static INSTANCE: std::sync::OnceLock<std::result::Result<Option<&'static str>, String>> =
std::sync::OnceLock::new();
INSTANCE.get_or_init(|| match std::env::var(INSTANCE_ENV) {
Err(std::env::VarError::NotPresent) => Ok(None),
Ok(name) if name.is_empty() => Ok(None),
Ok(name) if is_instance_name(&name) => Ok(Some(Box::leak(name.into_boxed_str()))),
_ => Err(format!(
"{INSTANCE_ENV} must be 1 to 32 lowercase letters, digits or '-'"
)),
})
}
fn is_instance_name(name: &str) -> bool {
(1..=32).contains(&name.len())
&& name
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
/// `base`, or `base` and the instance name joined by `separator`.
pub fn instance_suffixed(base: &str, separator: char) -> String {
match instance() {
Some(name) => format!("{base}{separator}{name}"),
None => base.to_string(),
}
}
/// The Secret Service name the session is stored under: [`KEYRING_SERVICE`],
/// suffixed with the [`instance`] when one is set.
pub fn keyring_service() -> &'static str {
static SERVICE: std::sync::OnceLock<String> = std::sync::OnceLock::new();
SERVICE.get_or_init(|| instance_suffixed(KEYRING_SERVICE, '-'))
}
/// The directory name under each XDG base directory: `proton-drive-linux`,
/// suffixed with the [`instance`] when one is set.
pub fn app_dir_name() -> String {
instance_suffixed(APP_NAME, '-')
}
/// Default soft cap on the on-disk content cache (5 GiB). LRU-evicts unpinned
/// blobs back under this; pinned files are exempt. See [`crate::cache`].
/// blobs back under this; pinned files are exempt. See `pdfs_store::cache`.
pub const DEFAULT_CACHE_BUDGET_BYTES: u64 = 5 * 1024 * 1024 * 1024;
/// Environment override for [`AppConfig::resolved_conflict_sweep`]. Exists so a
@@ -163,6 +247,10 @@ pub struct AppConfig {
/// Defaulted for configs predating the field.
#[serde(default)]
pub files_view: FilesView,
/// How the desktop app's Photos page lays out its grid. Defaulted for
/// configs predating the field.
#[serde(default)]
pub photos_view: PhotosView,
/// The desktop app's main window size, remembered between runs. Defaulted
/// for configs predating the field.
#[serde(default)]
@@ -220,6 +308,10 @@ pub struct FilesView {
pub descending: bool,
/// Folders ahead of files, whatever the sort.
pub folders_first: bool,
/// The icon grid's thumbnail edge in logical pixels. `None` means the
/// app's default.
#[serde(skip_serializing_if = "Option::is_none")]
pub icon_size: Option<i32>,
}
impl Default for FilesView {
@@ -229,10 +321,23 @@ impl Default for FilesView {
sort: FileSort::Name,
descending: false,
folders_first: true,
icon_size: None,
}
}
}
/// The Photos page's grid choices, remembered between runs.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
#[serde(default)]
pub struct PhotosView {
/// The zoom level: the row height the grid aims for, in logical pixels.
/// `None` means the app's default.
pub row_height: Option<i32>,
/// Crop every photo to a square tile instead of showing it at its own
/// shape.
pub square: bool,
}
/// The desktop app's main window, as it was when it last closed.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
#[serde(default)]
@@ -370,6 +475,27 @@ impl AppConfig {
}
}
/// Apply `edit` to the ignore patterns in effect in the config at `path`,
/// under the config lock, and return the saved config. A list equal to the
/// built-in one is stored as unset, so it follows the built-in list in later
/// releases.
pub fn change_ignore_patterns_at(
path: &Path,
edit: impl FnOnce(&mut Vec<String>),
) -> Result<AppConfig> {
update_config_at(path, |config| {
let mut list = config.resolved_ignore_patterns();
edit(&mut list);
let builtin = list.len() == DEFAULT_IGNORE_PATTERNS.len()
&& list
.iter()
.zip(DEFAULT_IGNORE_PATTERNS)
.all(|(a, b)| a == b);
config.ignore_patterns = (!builtin).then_some(list);
config.clone()
})
}
/// Fail when the config file at `path` exists but does not parse, so that
/// [`AppDirs::save_config`] never writes over settings it could not read.
fn refuse_to_replace_unreadable(path: &Path) -> Result<()> {
@@ -386,6 +512,97 @@ fn refuse_to_replace_unreadable(path: &Path) -> Result<()> {
}
}
/// [`AppDirs::load_config`] for the file at `path`.
fn load_config_at(path: &Path) -> AppConfig {
if path.exists() {
match std::fs::read_to_string(path)
.map_err(Error::from)
.and_then(|content| serde_json::from_str::<AppConfig>(&content).map_err(Error::from))
{
Ok(config) => return config,
Err(e) => {
// Preserve the original bytes for diagnosis/recovery. In
// particular, never replace a truncated config with defaults
// and silently lose mount, device, or ignore settings.
// `save_config` refuses to write over it for the same reason.
tracing::error!(path = %path.display(), error = %e, "config is unreadable; using in-memory defaults without overwriting it");
return AppConfig::default();
}
}
}
let default_config = AppConfig::default();
if let Err(e) = save_config_at(path, &default_config) {
tracing::warn!(path = %path.display(), error = %e, "could not write the default config");
}
default_config
}
/// [`AppDirs::save_config`] for the file at `path`.
fn save_config_at(path: &Path, config: &AppConfig) -> Result<()> {
refuse_to_replace_unreadable(path)?;
proton_base_rs::atomic::write(path, &serde_json::to_vec_pretty(config)?)?;
Ok(())
}
/// [`AppDirs::update_config`] for the file at `path`.
fn update_config_at<R>(path: &Path, change: impl FnOnce(&mut AppConfig) -> R) -> Result<R> {
let _lock = lock_config(path)?;
// Refuse before reading: an unreadable file loads as defaults, and the
// change must not be applied to those.
refuse_to_replace_unreadable(path)?;
let mut config = load_config_at(path);
let out = change(&mut config);
save_config_at(path, &config)?;
Ok(out)
}
/// How long [`lock_config`] waits for another writer. A change holds the lock
/// for one small read and write; anything longer is a stuck process, and the
/// setting is better reported as not saved than waited on forever.
const CONFIG_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
/// Take the lock that orders changes to the config file at `path`, held until
/// the returned file is dropped.
///
/// A separate `config.json.lock`, never the config file itself: that file is
/// replaced by a rename on every save, so a lock on it would guard a file
/// nobody reads any more.
fn lock_config(path: &Path) -> Result<std::fs::File> {
use std::os::fd::AsRawFd as _;
use std::os::unix::fs::OpenOptionsExt as _;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let mut name = path.as_os_str().to_owned();
name.push(".lock");
let file = std::fs::OpenOptions::new()
.create(true)
.read(true)
.write(true)
.truncate(false)
.mode(0o600)
.open(PathBuf::from(name))?;
let deadline = std::time::Instant::now() + CONFIG_LOCK_WAIT;
loop {
// SAFETY: `file` owns the descriptor and outlives the call.
if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 {
return Ok(file);
}
let e = std::io::Error::last_os_error();
if e.raw_os_error() != Some(libc::EWOULDBLOCK) {
return Err(Error::Io(e));
}
if std::time::Instant::now() >= deadline {
return Err(Error::Other(format!(
"{} is being changed by another process; try again",
path.display()
)));
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
}
/// Resolved XDG locations for state, cache, and the default mountpoint.
pub struct AppDirs {
dirs: ProjectDirs,
@@ -393,7 +610,7 @@ pub struct AppDirs {
impl AppDirs {
pub fn new() -> Result<Self> {
let dirs = ProjectDirs::from("io", "narl", "proton-drive-linux")
let dirs = ProjectDirs::from("io", "narl", &app_dir_name())
.ok_or_else(|| Error::Other("cannot resolve home directory".into()))?;
Ok(Self { dirs })
}
@@ -405,65 +622,40 @@ impl AppDirs {
/// Load config from disk, creating default if missing.
pub fn load_config(&self) -> AppConfig {
let path = self.config_path();
if path.exists() {
match std::fs::read_to_string(&path)
.map_err(Error::from)
.and_then(|content| {
serde_json::from_str::<AppConfig>(&content).map_err(Error::from)
}) {
Ok(config) => return config,
Err(e) => {
// Preserve the original bytes for diagnosis/recovery. In
// particular, never replace a truncated config with defaults
// and silently lose mount, device, or ignore settings.
// `save_config` refuses to write over it for the same reason.
tracing::error!(path = %path.display(), error = %e, "config is unreadable; using in-memory defaults without overwriting it");
return AppConfig::default();
}
}
}
let default_config = AppConfig::default();
if let Err(e) = self.save_config(&default_config) {
tracing::warn!(path = %path.display(), error = %e, "could not write the default config");
}
default_config
load_config_at(&self.config_path())
}
/// Persist `config` to [`config_path`](Self::config_path), creating the
/// config dir if missing. The Settings page calls this after editing the
/// cache budget or mountpoint; the daemon re-reads the file on its next mount.
/// config dir if missing.
///
/// Refuses while the file on disk does not parse. Every caller loads,
/// changes one field and saves, and [`load_config`](Self::load_config)
/// gives defaults for a file it cannot read, so the first change after
/// the file was damaged wrote defaults over the mountpoint, the device and
/// the ignore rules the user had (`docs/BUGS.md` B223).
/// Refuses while the file on disk does not parse: [`load_config`](Self::load_config)
/// gives defaults for a file it cannot read, so the first change after the
/// file was damaged would write defaults over the mountpoint, the device
/// and the ignore rules the user had (`docs/BUGS.md` B223).
///
/// Writes the whole file. To change a setting, use
/// [`update_config`](Self::update_config), which does not lose another
/// process's change.
pub fn save_config(&self, config: &AppConfig) -> Result<()> {
let path = self.config_path();
refuse_to_replace_unreadable(&path)?;
let parent = path
.parent()
.ok_or_else(|| Error::Other("configuration path has no parent".into()))?;
std::fs::create_dir_all(parent)?;
let nonce = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|duration| duration.as_nanos())
.unwrap_or(0);
let tmp = path.with_extension(format!("json.tmp-{}-{nonce}", std::process::id()));
use std::os::unix::fs::OpenOptionsExt as _;
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&tmp)?;
use std::io::Write as _;
file.write_all(&serde_json::to_vec_pretty(config)?)?;
file.sync_all()?;
std::fs::rename(&tmp, &path)?;
std::fs::File::open(parent)?.sync_all()?;
Ok(())
save_config_at(&self.config_path(), config)
}
/// Change settings in place: read the file, apply `change`, write it back,
/// all under a lock, and return what `change` returned.
///
/// The app, the tray and the daemon each write the file. Without the lock,
/// two of them changing different settings at once both read the old file,
/// and the one that wrote last undid the other's change (`docs/BUGS.md`
/// B292).
pub fn update_config<R>(&self, change: impl FnOnce(&mut AppConfig) -> R) -> Result<R> {
update_config_at(&self.config_path(), change)
}
/// Apply `edit` to the ignore patterns in effect for every synced folder
/// and save them, returning the saved config. See
/// [`change_ignore_patterns_at`].
pub fn change_ignore_patterns(&self, edit: impl FnOnce(&mut Vec<String>)) -> Result<AppConfig> {
change_ignore_patterns_at(&self.config_path(), edit)
}
/// This machine's id (e.g. ~/.config/proton-drive-linux/machine-id). See
@@ -494,15 +686,8 @@ impl AppDirs {
use std::io::Read as _;
std::fs::File::open("/dev/urandom")?.read_exact(&mut bytes)?;
let id: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
let parent = path
.parent()
.ok_or_else(|| Error::Other("machine id path has no parent".into()))?;
std::fs::create_dir_all(parent)?;
let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
std::fs::write(&tmp, format!("{id}\n"))?;
std::fs::File::open(&tmp)?.sync_all()?;
std::fs::rename(&tmp, &path)?;
std::fs::File::open(parent)?.sync_all()?;
// Not secret, and other tools may read it; keep it world-readable.
proton_base_rs::atomic::write_with_mode(&path, format!("{id}\n").as_bytes(), 0o644)?;
Ok(id)
}
@@ -541,6 +726,12 @@ impl AppDirs {
self.state_dir().join("control.sock")
}
/// The Google Photos import's last run: its archives and how it ended, so
/// an import cut short by a restart can be resumed.
pub fn takeout_import_path(&self) -> PathBuf {
self.state_dir().join("takeout-import.json")
}
/// Unix domain socket the tray uses to ensure single instance.
pub fn tray_socket(&self) -> PathBuf {
self.state_dir().join("tray.sock")
@@ -552,11 +743,13 @@ impl AppDirs {
directories::UserDirs::new().map(|u| u.home_dir().to_path_buf())
}
/// Default mountpoint when the user does not pass one explicitly.
/// Default mountpoint when the user does not pass one explicitly:
/// `~/ProtonDrive`, or `~/ProtonDrive-<instance>` for a named [`instance`].
pub fn default_mountpoint(&self) -> PathBuf {
let name = instance_suffixed("ProtonDrive", '-');
directories::UserDirs::new()
.map(|u| u.home_dir().join("ProtonDrive"))
.unwrap_or_else(|| PathBuf::from("/tmp/ProtonDrive"))
.map(|u| u.home_dir().join(&name))
.unwrap_or_else(|| PathBuf::from("/tmp").join(&name))
}
/// The effective mountpoint: the config's explicit path, or
@@ -655,6 +848,114 @@ mod tests {
std::fs::metadata(p).unwrap().permissions().mode() & 0o777
}
#[test]
fn an_instance_name_is_short_lowercase_ascii() {
for good in ["test", "bench-1", "a", &"x".repeat(32)] {
assert!(is_instance_name(good), "{good:?}");
}
for bad in ["", "Test", "a/b", "../x", "a b", "ü", &"x".repeat(33)] {
assert!(!is_instance_name(bad), "{bad:?}");
}
}
/// The test process has no `PDFS_INSTANCE`, so it is the default instance
/// and every name is the one releases before 4.0 used.
#[test]
fn the_default_instance_keeps_the_old_names() {
assert_eq!(instance(), None);
assert_eq!(keyring_service(), "proton-drive-linux");
assert_eq!(app_dir_name(), "proton-drive-linux");
assert!(
AppDirs::new()
.unwrap()
.default_mountpoint()
.ends_with("ProtonDrive")
);
}
/// Two writers changing different settings at once both keep their change
/// (`docs/BUGS.md` B292).
#[test]
fn concurrent_changes_to_different_settings_are_all_kept() {
let dir = std::env::temp_dir().join(format!(
"pdfs-cfg-race-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("config.json");
let a = {
let path = path.clone();
std::thread::spawn(move || {
for i in 1..=100u64 {
update_config_at(&path, |c| c.upload_limit = Some(i)).unwrap();
}
})
};
let b = {
let path = path.clone();
std::thread::spawn(move || {
for i in 1..=100u64 {
update_config_at(&path, |c| c.download_limit = Some(i)).unwrap();
}
})
};
a.join().unwrap();
b.join().unwrap();
let config = load_config_at(&path);
assert_eq!(config.upload_limit, Some(100));
assert_eq!(config.download_limit, Some(100));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn ignore_patterns_back_at_the_built_in_list_are_stored_as_unset() {
let dir = std::env::temp_dir().join(format!(
"pdfs-cfg-ignore-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("config.json");
let config = change_ignore_patterns_at(&path, |list| list.push("*.db".into())).unwrap();
assert_eq!(
config.ignore_patterns.as_ref().unwrap().last().unwrap(),
"*.db"
);
let config = change_ignore_patterns_at(&path, |list| list.retain(|p| p != "*.db")).unwrap();
assert_eq!(config.ignore_patterns, None);
assert_eq!(load_config_at(&path).ignore_patterns, None);
// An empty list is a choice, not the built-in one.
let config = change_ignore_patterns_at(&path, Vec::clear).unwrap();
assert_eq!(config.ignore_patterns, Some(Vec::new()));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_change_is_never_applied_over_an_unreadable_config() {
let dir = std::env::temp_dir().join(format!(
"pdfs-cfg-update-guard-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("config.json");
std::fs::write(&path, br#"{"mountpoint": "/home/me/Pro"#).unwrap();
assert!(update_config_at(&path, |c| c.tray_hidden = true).is_err());
assert_eq!(
std::fs::read(&path).unwrap(),
br#"{"mountpoint": "/home/me/Pro"#
);
let _ = std::fs::remove_dir_all(&dir);
}
/// A damaged config must not be replaced by defaults the next time a
/// setting changes (`docs/BUGS.md` B223).
#[test]
@@ -761,6 +1062,11 @@ mod tests {
sort: FileSort::Modified,
descending: true,
folders_first: false,
icon_size: Some(192),
},
photos_view: PhotosView {
row_height: Some(240),
square: true,
},
window: WindowState {
width: 1200,
@@ -792,6 +1098,7 @@ mod tests {
assert_eq!(decoded.upload_limit, Some(500_000));
assert_eq!(decoded.download_limit, None);
assert_eq!(decoded.files_view, config.files_view);
assert_eq!(decoded.photos_view, config.photos_view);
assert_eq!(decoded.window, config.window);
}
@@ -835,6 +1142,17 @@ mod tests {
let partial: FilesView = serde_json::from_str(r#"{"sort":"size"}"#).unwrap();
assert_eq!(partial.sort, FileSort::Size);
assert!(partial.folders_first);
assert_eq!(partial.icon_size, None);
}
#[test]
fn a_config_without_a_photos_view_gets_the_default() {
let decoded: AppConfig =
serde_json::from_str(r#"{"app_version":"a","user_agent":"b"}"#).unwrap();
assert_eq!(decoded.photos_view, PhotosView::default());
let partial: PhotosView = serde_json::from_str(r#"{"square":true}"#).unwrap();
assert!(partial.square);
assert_eq!(partial.row_height, None);
}
#[test]
File diff suppressed because it is too large. Load diff
-379
View File
@@ -1,379 +0,0 @@
//! Folder-sync bookkeeping: the folders this device mirrors, and the per-file
//! state each pass reconciles against.
use rusqlite::{OptionalExtension, params};
use super::Db;
use crate::Result;
use std::collections::HashMap;
pub struct StoredSyncFolder {
pub id: i64,
pub local_path: String,
pub remote_uid: String,
pub remote_share_id: String,
/// `mirror` (full local copy, two-way synced) or `ondemand` (FUSE mount).
pub mode: String,
/// A mode the user asked for that could not be applied on the spot — the
/// folder was mid-pass, or had un-uploaded changes. The engine applies it
/// once the folder is safe to switch, so the request is queued rather than
/// rejected. `None` when the folder is where the user wants it.
pub pending_mode: Option<String>,
/// `idle` | `syncing` | `error` | `conflict`.
pub state: String,
pub last_sync: i64,
}
/// One per-file sync baseline row: what a path looked like on both sides at the
/// last successful sync, so the next reconcile can tell which side changed.
/// `remote_rev`/`remote_hash` hold the remote signature —
/// its modification time and size as strings — since no cheap content hash is
/// exposed; change detection is `(mtime, size)` on each side.
#[derive(Clone, Debug, PartialEq)]
pub struct StoredSyncEntry {
pub rel_path: String,
pub remote_uid: Option<String>,
pub local_mtime: i64,
pub local_size: i64,
/// The same modification time to nanosecond precision, when it is known.
///
/// `local_mtime` alone cannot tell an edit that landed inside the same
/// second as the last sync — and left the file the same length — from no
/// edit at all, so those never uploaded (`docs/BUGS.md` B25). `None` on a row
/// written before schema 28, which the comparison reads as "compare whole
/// seconds", so upgrading does not make an entire mirror look changed.
pub local_mtime_ns: Option<i64>,
pub remote_rev: Option<String>,
pub remote_hash: Option<String>,
/// The id of the remote revision this row was synced at. A mirror upload
/// checks it before it supersedes what Drive holds, because another client
/// may have committed a revision since (`docs/BUGS.md` B249). `None` on a
/// row written before schema 44, or by a pass that did not learn it; the
/// check then falls back to `remote_rev` and `remote_hash`.
pub remote_revision_id: Option<String>,
}
impl Db {
pub fn sync_folder_add(
&self,
local_path: &str,
remote_uid: &str,
remote_share_id: &str,
) -> Result<i64> {
let conn = self.conn.lock();
conn.execute(
"INSERT INTO sync_folder (local_path, remote_uid, remote_share_id)
VALUES (?1, ?2, ?3)",
params![local_path, remote_uid, remote_share_id],
)?;
Ok(conn.last_insert_rowid())
}
/// Every synced folder, oldest first.
pub fn sync_folder_list(&self) -> Result<Vec<StoredSyncFolder>> {
let conn = self.read();
let mut stmt = conn.prepare(
"SELECT id, local_path, remote_uid, remote_share_id, mode, pending_mode, state, last_sync
FROM sync_folder ORDER BY id",
)?;
let rows = stmt.query_map([], |r| {
Ok(StoredSyncFolder {
id: r.get(0)?,
local_path: r.get(1)?,
remote_uid: r.get(2)?,
remote_share_id: r.get(3)?,
mode: r.get(4)?,
pending_mode: r.get(5)?,
state: r.get(6)?,
last_sync: r.get(7)?,
})
})?;
let mut items = Vec::new();
for row in rows {
items.push(row?);
}
Ok(items)
}
/// Look up one synced folder by id.
pub fn sync_folder_get(&self, id: i64) -> Result<Option<StoredSyncFolder>> {
let conn = self.read();
conn.query_row(
"SELECT id, local_path, remote_uid, remote_share_id, mode, pending_mode, state, last_sync
FROM sync_folder WHERE id = ?1",
params![id],
|r| {
Ok(StoredSyncFolder {
id: r.get(0)?,
local_path: r.get(1)?,
remote_uid: r.get(2)?,
remote_share_id: r.get(3)?,
mode: r.get(4)?,
pending_mode: r.get(5)?,
state: r.get(6)?,
last_sync: r.get(7)?,
})
},
)
.optional()
.map_err(Into::into)
}
/// Remove a synced folder and its per-file baseline.
pub fn sync_folder_remove(&self, id: i64) -> Result<bool> {
let mut conn = self.conn.lock();
let tx = conn.transaction()?;
tx.execute("DELETE FROM sync_entry WHERE folder_id = ?1", params![id])?;
let n = tx.execute("DELETE FROM sync_folder WHERE id = ?1", params![id])?;
tx.commit()?;
Ok(n > 0)
}
/// Update a synced folder's mode (`mirror`/`ondemand`). A queued request for
/// that mode is satisfied and cleared in the same write. An opposite pending
/// mode arrived after this transition started, so preserve it as the newer
/// last-request intent.
pub fn sync_folder_set_mode(&self, id: i64, mode: &str) -> Result<()> {
let conn = self.conn.lock();
conn.execute(
"UPDATE sync_folder
SET mode = ?2,
pending_mode = CASE WHEN pending_mode = ?2 THEN NULL ELSE pending_mode END
WHERE id = ?1",
params![id, mode],
)?;
Ok(())
}
/// Re-point a synced folder at the share that now holds its remote folder,
/// after the folder moved to another device without changing its uid.
pub fn sync_folder_set_share(&self, id: i64, share_id: &str) -> Result<()> {
let conn = self.conn.lock();
conn.execute(
"UPDATE sync_folder SET remote_share_id = ?2 WHERE id = ?1",
params![id, share_id],
)?;
Ok(())
}
/// Queue (or, with `None`, withdraw) a mode the folder should move to once it
/// is safe to switch.
pub fn sync_folder_set_pending_mode(&self, id: i64, mode: Option<&str>) -> Result<()> {
let conn = self.conn.lock();
conn.execute(
"UPDATE sync_folder SET pending_mode = ?2 WHERE id = ?1",
params![id, mode],
)?;
Ok(())
}
/// Withdraw a queued mode only if it is still the intent the caller
/// inspected. A newer request must survive an older settlement attempt.
pub fn sync_folder_clear_pending_mode_if(&self, id: i64, expected: &str) -> Result<bool> {
let conn = self.conn.lock();
let changed = conn.execute(
"UPDATE sync_folder SET pending_mode = NULL
WHERE id = ?1 AND pending_mode = ?2",
params![id, expected],
)?;
Ok(changed > 0)
}
/// Update a synced folder's state and stamp `last_sync` to now.
pub fn sync_folder_set_state(&self, id: i64, state: &str, last_sync: i64) -> Result<()> {
let conn = self.conn.lock();
conn.execute(
"UPDATE sync_folder SET state = ?2, last_sync = ?3 WHERE id = ?1",
params![id, state, last_sync],
)?;
Ok(())
}
/// The whole per-file sync baseline for a folder, keyed by relative path.
pub fn sync_entries(&self, folder_id: i64) -> Result<HashMap<String, StoredSyncEntry>> {
let conn = self.read();
let mut stmt = conn.prepare(
"SELECT rel_path, remote_uid, local_mtime, local_size, remote_rev, remote_hash,
local_mtime_ns, remote_revision_id
FROM sync_entry WHERE folder_id = ?1",
)?;
let rows = stmt.query_map(params![folder_id], |r| {
Ok(StoredSyncEntry {
rel_path: r.get(0)?,
remote_uid: r.get(1)?,
local_mtime: r.get(2)?,
local_size: r.get(3)?,
remote_rev: r.get(4)?,
remote_hash: r.get(5)?,
local_mtime_ns: r.get(6)?,
remote_revision_id: r.get(7)?,
})
})?;
let mut map = HashMap::new();
for row in rows {
let e = row?;
map.insert(e.rel_path.clone(), e);
}
Ok(map)
}
/// Whether `uid` is represented by a mirror location.
///
/// An on-demand location proves residency through its live inode state.
/// Mirror locations have no FUSE state, so their folder root comes from
/// `sync_folder` and descendants come from the last successful
/// `sync_entry` baseline.
pub fn mirror_contains_uid(&self, uid: &str) -> Result<bool> {
let conn = self.read();
conn.query_row(
"SELECT EXISTS(
SELECT 1
FROM sync_folder AS folder
LEFT JOIN sync_entry AS entry ON entry.folder_id = folder.id
WHERE folder.mode = 'mirror'
AND (folder.remote_uid = ?1 OR entry.remote_uid = ?1)
)",
params![uid],
|row| row.get(0),
)
.map_err(Into::into)
}
/// Insert or replace one baseline row.
pub fn sync_entry_upsert(&self, folder_id: i64, e: &StoredSyncEntry) -> Result<()> {
let conn = self.conn.lock();
conn.execute(
"INSERT INTO sync_entry
(folder_id, rel_path, remote_uid, local_mtime, local_size, remote_rev,
remote_hash, local_mtime_ns, remote_revision_id)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
ON CONFLICT(folder_id, rel_path) DO UPDATE SET
remote_uid = excluded.remote_uid,
local_mtime = excluded.local_mtime,
local_size = excluded.local_size,
remote_rev = excluded.remote_rev,
remote_hash = excluded.remote_hash,
local_mtime_ns = excluded.local_mtime_ns,
remote_revision_id = excluded.remote_revision_id",
params![
folder_id,
e.rel_path,
e.remote_uid,
e.local_mtime,
e.local_size,
e.remote_rev,
e.remote_hash,
e.local_mtime_ns,
e.remote_revision_id,
],
)?;
Ok(())
}
/// Drop one baseline row (a path that left the sync set on both sides).
pub fn sync_entry_remove(&self, folder_id: i64, rel_path: &str) -> Result<()> {
let conn = self.conn.lock();
conn.execute(
"DELETE FROM sync_entry WHERE folder_id = ?1 AND rel_path = ?2",
params![folder_id, rel_path],
)?;
Ok(())
}
/// Drop the baseline rows of `rel_path` and everything under it.
///
/// Used when a subtree leaves a mirror folder through a move on Drive: its
/// local copy is about to be removed, and rows left behind would read as
/// "deleted locally" and trash the moved nodes at their new place.
pub fn sync_entries_remove_subtree(&self, folder_id: i64, rel_path: &str) -> Result<()> {
let conn = self.conn.lock();
conn.execute(
"DELETE FROM sync_entry
WHERE folder_id = ?1
AND (rel_path = ?2 OR substr(rel_path, 1, length(?2) + 1) = ?2 || '/')",
params![folder_id, rel_path],
)?;
Ok(())
}
/// Move the baseline rows of `from_rel` and everything under it to `to_rel`
/// in folder `to_folder`, in one transaction.
///
/// Used when a move on Drive took a mirror subtree along with its local
/// copy: the rows still describe both sides correctly, only under a new
/// path, so the next pass on either folder has nothing to do. The two
/// folders may be the same one.
pub fn sync_entries_move(
&self,
from_folder: i64,
from_rel: &str,
to_folder: i64,
to_rel: &str,
) -> Result<()> {
let mut conn = self.conn.lock();
let tx = conn.transaction()?;
{
let mut select = tx.prepare(
"SELECT rel_path, remote_uid, local_mtime, local_size, remote_rev, remote_hash,
local_mtime_ns, remote_revision_id
FROM sync_entry
WHERE folder_id = ?1
AND (rel_path = ?2 OR substr(rel_path, 1, length(?2) + 1) = ?2 || '/')",
)?;
let rows = select
.query_map(params![from_folder, from_rel], |r| {
Ok(StoredSyncEntry {
rel_path: r.get(0)?,
remote_uid: r.get(1)?,
local_mtime: r.get(2)?,
local_size: r.get(3)?,
remote_rev: r.get(4)?,
remote_hash: r.get(5)?,
local_mtime_ns: r.get(6)?,
remote_revision_id: r.get(7)?,
})
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
let mut delete =
tx.prepare("DELETE FROM sync_entry WHERE folder_id = ?1 AND rel_path = ?2")?;
for row in &rows {
delete.execute(params![from_folder, row.rel_path])?;
}
let mut insert = tx.prepare(
"INSERT OR REPLACE INTO sync_entry
(folder_id, rel_path, remote_uid, local_mtime, local_size, remote_rev,
remote_hash, local_mtime_ns, remote_revision_id)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
)?;
for row in rows {
let rel = format!("{to_rel}{}", &row.rel_path[from_rel.len()..]);
insert.execute(params![
to_folder,
rel,
row.remote_uid,
row.local_mtime,
row.local_size,
row.remote_rev,
row.remote_hash,
row.local_mtime_ns,
row.remote_revision_id,
])?;
}
}
tx.commit()?;
Ok(())
}
/// Drop the entire baseline for a folder. Used when flipping ondemand→mirror:
/// the local tree was evicted, so the old baseline is stale and would make the
/// next reconcile mistake "locally deleted" for "must re-download". Clearing it
/// leaves an empty baseline + full remote = pure download.
pub fn sync_entries_clear(&self, folder_id: i64) -> Result<()> {
let conn = self.conn.lock();
conn.execute(
"DELETE FROM sync_entry WHERE folder_id = ?1",
params![folder_id],
)?;
Ok(())
}
}
+17
View File
@@ -42,6 +42,13 @@ pub enum Error {
#[error("that mailbox password does not unlock your account")]
WrongMailboxPassword,
/// The account's only second factor is a security key, which needs
/// WebAuthn. Asking for a code would only fail as a wrong one.
#[error(
"this account's only second factor is a security key, which pdfs cannot use yet — add an authenticator app in your Proton account settings"
)]
SecurityKeyOnly,
/// The login was gated behind human verification. Not a failure the user can
/// fix by retrying: the challenge has to be solved and the login restarted
/// with the resulting token (see [`auth::login_verified`](crate::auth::login_verified)).
@@ -220,6 +227,7 @@ fn core_kind(e: &Error) -> ErrorKind {
| Error::ReloginRequired
| Error::Locked
| Error::WrongMailboxPassword
| Error::SecurityKeyOnly
| Error::HumanVerificationRequired(_) => ErrorKind::Denied,
Error::Proton(proton) => proton_kind(proton),
_ => ErrorKind::Internal,
@@ -347,6 +355,15 @@ pub fn sign_in_blocked(e: &proton_sdk::ProtonError) -> bool {
/// The result every request-serving method in the daemon returns.
pub type CoreResult<T> = std::result::Result<T, CoreError>;
impl From<proton_auth_rs::Error> for Error {
fn from(error: proton_auth_rs::Error) -> Self {
match error {
proton_auth_rs::Error::Keyring(error) => Self::Keyring(error),
other => Self::Other(other.to_string()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
-133
View File
@@ -1,133 +0,0 @@
//! When a photo was taken, as its own EXIF tags say.
//!
//! The fallback for a photo nothing else dates: a Takeout photo without a
//! sidecar or a date in its name, and a photo uploaded from the app. Without
//! it the first was filed under the moment of the import and the second under
//! the file's modification time, which a copy resets.
use std::io::{BufRead, Seek};
use std::path::Path;
use crate::takeout::days_from_civil;
/// The capture time in the EXIF of the file at `path`, in epoch seconds.
pub fn capture_time_of(path: &Path) -> Option<i64> {
let file = std::fs::File::open(path).ok()?;
capture_time(&mut std::io::BufReader::new(file))
}
/// The capture time in the EXIF `reader` holds: `DateTimeOriginal`, then
/// `DateTimeDigitized`, each adjusted by its `OffsetTime…` tag when the camera
/// wrote one. Without an offset the time is read as UTC, as a date in a file
/// name is (`takeout::capture_time_from_name`).
pub fn capture_time(reader: &mut (impl BufRead + Seek)) -> Option<i64> {
let exif = exif::Reader::new().read_from_container(reader).ok()?;
let ascii = |tag: exif::Tag| -> Option<String> {
let field = exif.get_field(tag, exif::In::PRIMARY)?;
match &field.value {
exif::Value::Ascii(parts) => parts.first().map(|part| {
String::from_utf8_lossy(part)
.trim_matches('\0')
.trim()
.to_string()
}),
_ => None,
}
};
[
(exif::Tag::DateTimeOriginal, exif::Tag::OffsetTimeOriginal),
(exif::Tag::DateTimeDigitized, exif::Tag::OffsetTimeDigitized),
]
.into_iter()
.find_map(|(time, offset)| {
let local = parse_exif_time(&ascii(time)?)?;
let offset = ascii(offset).and_then(|o| parse_offset(&o)).unwrap_or(0);
Some(local - offset)
})
}
/// `YYYY:MM:DD HH:MM:SS` as epoch seconds, read as UTC. `None` for the
/// all-zero or blank value cameras write when they do not know.
fn parse_exif_time(text: &str) -> Option<i64> {
let bytes = text.as_bytes();
if bytes.len() < 19 || bytes[4] != b':' || bytes[7] != b':' || bytes[13] != b':' {
return None;
}
let number = |range: std::ops::Range<usize>| text.get(range)?.parse::<i64>().ok();
let (year, month, day) = (number(0..4)?, number(5..7)?, number(8..10)?);
let (hour, minute, second) = (number(11..13)?, number(14..16)?, number(17..19)?);
if !(1800..=9999).contains(&year)
|| !(1..=12).contains(&month)
|| !(1..=31).contains(&day)
|| hour > 23
|| minute > 59
|| second > 60
{
return None;
}
Some(days_from_civil(year, month, day) * 86_400 + hour * 3600 + minute * 60 + second)
}
/// `+HH:MM` or `-HH:MM` as seconds east of UTC.
fn parse_offset(text: &str) -> Option<i64> {
let sign = match text.as_bytes().first()? {
b'+' => 1,
b'-' => -1,
_ => return None,
};
let (hours, minutes) = text.get(1..)?.split_once(':')?;
let (hours, minutes) = (hours.parse::<i64>().ok()?, minutes.parse::<i64>().ok()?);
(hours <= 14 && minutes < 60).then_some(sign * (hours * 3600 + minutes * 60))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_exif_time_reads_as_utc_and_its_offset_moves_it() {
// 2023-06-01 12:00:00 UTC.
let noon = 1_685_620_800;
assert_eq!(parse_exif_time("2023:06:01 12:00:00"), Some(noon));
assert_eq!(parse_offset("+02:00"), Some(7200));
assert_eq!(parse_offset("-05:30"), Some(-19_800));
assert_eq!(
parse_exif_time("2023:06:01 14:00:00").map(|t| t - parse_offset("+02:00").unwrap()),
Some(noon)
);
}
#[test]
fn an_unknown_exif_time_is_no_time() {
assert_eq!(parse_exif_time("0000:00:00 00:00:00"), None);
assert_eq!(parse_exif_time(" : : : : "), None);
assert_eq!(parse_exif_time(""), None);
assert_eq!(parse_offset("02:00"), None);
}
#[test]
fn a_photo_is_dated_by_its_original_time_and_offset() {
let ascii = |tag, text: &str| exif::Field {
tag,
ifd_num: exif::In::PRIMARY,
value: exif::Value::Ascii(vec![text.as_bytes().to_vec()]),
};
let taken = ascii(exif::Tag::DateTimeOriginal, "2023:06:01 14:00:00");
let offset = ascii(exif::Tag::OffsetTimeOriginal, "+02:00");
let digitized = ascii(exif::Tag::DateTimeDigitized, "2024:01:01 00:00:00");
let mut writer = exif::experimental::Writer::new();
writer.push_field(&taken);
writer.push_field(&offset);
writer.push_field(&digitized);
let mut tiff = std::io::Cursor::new(Vec::new());
writer.write(&mut tiff, false).unwrap();
tiff.set_position(0);
assert_eq!(capture_time(&mut tiff), Some(1_685_620_800));
}
#[test]
fn a_file_without_exif_has_no_capture_time() {
let mut png = std::io::Cursor::new(b"\x89PNG\r\n\x1a\n".to_vec());
assert_eq!(capture_time(&mut png), None);
}
}
+20 -10
View File
@@ -18,36 +18,38 @@
//! `CONFIG_KEYS`); every operation then reports it as an error and the caller
//! falls back to asking again, never to storing the secret somewhere weaker.
use std::ffi::CString;
use std::io;
use zeroize::Zeroizing;
/// One secret in the user keyring, by its description. Descriptions are
/// namespaced so they cannot collide with another program's keys.
/// namespaced so they cannot collide with another program's keys, and carry
/// the [`crate::config::instance`] so a second instance keeps its own.
pub struct Key {
description: &'static [u8],
name: &'static str,
}
/// The account's key passphrases (see the module docs).
#[cfg(not(test))]
pub const PASSPHRASES: Key = Key {
description: b"pdfs:key-passphrases\0",
name: "pdfs:key-passphrases",
};
/// Tests must never touch a real unlock.
#[cfg(test)]
pub const PASSPHRASES: Key = Key {
description: b"pdfs:key-passphrases:test\0",
name: "pdfs:key-passphrases:test",
};
/// Session tokens the Secret Service refused to store, until it takes them.
/// A refresh token held only in a process's memory dies with the process.
#[cfg(not(test))]
pub const UNSAVED_TOKENS: Key = Key {
description: b"pdfs:unsaved-tokens\0",
name: "pdfs:unsaved-tokens",
};
#[cfg(test)]
pub const UNSAVED_TOKENS: Key = Key {
description: b"pdfs:unsaved-tokens:test\0",
name: "pdfs:unsaved-tokens:test",
};
const KEY_TYPE: &[u8] = b"user\0";
@@ -73,7 +75,7 @@ fn last_error<T>() -> io::Result<T> {
Err(io::Error::last_os_error())
}
fn find(description: &[u8]) -> io::Result<Option<libc::c_long>> {
fn find(description: &std::ffi::CStr) -> io::Result<Option<libc::c_long>> {
// SAFETY: both strings are NUL-terminated and outlive the call.
let id = unsafe {
libc::syscall(
@@ -108,15 +110,23 @@ pub fn forbid_dumps() {
}
impl Key {
/// The key's description: its name, suffixed with the instance when one
/// is set.
fn description(&self) -> CString {
CString::new(crate::config::instance_suffixed(self.name, ':'))
.expect("key names and instance names hold no NUL")
}
/// Store `secret`, replacing any earlier one.
pub fn store(&self, secret: &[u8]) -> io::Result<()> {
// SAFETY: strings are NUL-terminated; the payload pointer/length pair
// describes `secret`, which outlives the call.
let description = self.description();
let id = unsafe {
libc::syscall(
libc::SYS_add_key,
KEY_TYPE.as_ptr(),
self.description.as_ptr(),
description.as_ptr(),
secret.as_ptr(),
secret.len(),
KEY_SPEC_USER_KEYRING,
@@ -145,7 +155,7 @@ impl Key {
/// Read the stored secret, or `None` when there is none.
pub fn load(&self) -> io::Result<Option<Zeroizing<Vec<u8>>>> {
let Some(id) = find(self.description)? else {
let Some(id) = find(&self.description())? else {
return Ok(None);
};
// Size first, then read; retry if the key was replaced in between.
@@ -190,7 +200,7 @@ impl Key {
/// Remove the stored secret. Succeeds when there is none.
pub fn clear(&self) -> io::Result<()> {
let Some(id) = find(self.description)? else {
let Some(id) = find(&self.description())? else {
return Ok(());
};
// SAFETY: plain integer arguments.
+9 -6
View File
@@ -5,32 +5,35 @@
pub mod access;
pub mod auth;
pub mod batch;
pub mod cache;
pub mod config;
pub mod control;
pub mod db;
pub mod error;
pub mod exiftime;
pub mod kernelkey;
pub mod keycheck;
pub mod lifecycle;
pub mod localindex;
pub mod lockrank;
pub mod menu;
pub mod mountfail;
pub mod mountpoint;
pub mod mounts;
pub mod opener;
pub mod places;
pub mod profile;
pub mod sdkcache;
pub mod search;
pub mod service;
pub mod shell;
pub mod similar;
pub mod shutdown;
pub mod syncignore;
pub mod syncroot;
pub mod takeout;
pub mod timestamp;
pub mod transfers;
pub mod tray;
pub mod update;
// Photo logic shared with Proton Gallery through the proton-rs crates.
pub use proton_gallery_rs::{exiftime, places, similar, takeout};
pub use access::{Access, access_for, perm_bits};
pub use error::{CoreError, CoreResult, Error, Result};
+263
View File
@@ -0,0 +1,263 @@
//! The daemon's long-lived threads, started, watched and stopped in one place.
//!
//! Each long-lived thread used to be started on its own, with its own rules
//! for how it learns to stop, and the mount kept a bare list of join handles.
//! Waking a thread that blocks somewhere other than [`Shutdown::sleep`] (the
//! drain's condvar, the sync engine's channel, the control socket's `accept`)
//! was a separate list of calls far from the spawn, and nothing could say which
//! threads were still alive.
//!
//! [`Services`] keeps all of it together. Each thread is started with its name
//! and the call that wakes it, if it needs one. [`Services::stop`] stops them in
//! reverse start order: it signals [`Shutdown`], wakes each one, and joins each
//! one up to a shared deadline, naming any that is still running then.
//! [`ServiceBoard`] is the live view of the same threads, for diagnostics.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use parking_lot::Mutex;
use crate::shutdown::Shutdown;
/// Wakes a thread that blocks somewhere a [`Shutdown::stop`] alone does not reach.
pub type Wake = Box<dyn Fn() + Send + Sync>;
/// Whether one service thread is still running, for diagnostics.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServiceHealth {
/// The thread's name, such as `pdfs-sync`.
pub name: String,
pub running: bool,
/// How long ago the thread was started.
pub age: Duration,
}
/// The live view of the service threads: which ones were started, and which
/// are still running. Cheap to clone and to read; never blocks on a service.
#[derive(Clone, Default)]
pub struct ServiceBoard(Arc<Mutex<Vec<Entry>>>);
struct Entry {
name: String,
started: Instant,
running: Arc<AtomicBool>,
}
impl ServiceBoard {
/// Every service thread started so far, in start order.
pub fn health(&self) -> Vec<ServiceHealth> {
self.0
.lock()
.iter()
.map(|entry| ServiceHealth {
name: entry.name.clone(),
running: entry.running.load(Ordering::Relaxed),
age: entry.started.elapsed(),
})
.collect()
}
fn add(&self, name: &str) -> Arc<AtomicBool> {
let running = Arc::new(AtomicBool::new(true));
self.0.lock().push(Entry {
name: name.to_owned(),
started: Instant::now(),
running: running.clone(),
});
running
}
}
/// Clears a service's `running` flag when its thread ends, by return or by panic.
struct Running(Arc<AtomicBool>);
impl Drop for Running {
fn drop(&mut self) {
self.0.store(false, Ordering::Relaxed);
}
}
struct Service {
handle: JoinHandle<()>,
wake: Option<Wake>,
}
/// The service threads one mount started, and how to stop them.
pub struct Services {
board: ServiceBoard,
started: Vec<Service>,
}
impl Services {
/// Start an empty set whose threads show on `board`.
pub fn new(board: ServiceBoard) -> Self {
Self {
board,
started: Vec::new(),
}
}
/// Start `run` on a thread named `name`. `wake`, if given, is called on
/// [`stop`](Self::stop) after the [`Shutdown`] signal, for a thread that
/// blocks where that signal does not reach.
pub fn spawn<F>(&mut self, name: &str, wake: Option<Wake>, run: F) -> std::io::Result<()>
where
F: FnOnce() + Send + 'static,
{
let running = self.board.add(name);
let guard = Running(running.clone());
let spawned = std::thread::Builder::new()
.name(name.to_owned())
.spawn(move || {
let _guard = guard;
run();
});
match spawned {
Ok(handle) => {
self.started.push(Service { handle, wake });
Ok(())
}
Err(error) => {
// The closure, and the guard in it, are dropped with the error,
// so the board already shows the thread as not running.
Err(error)
}
}
}
/// How many threads were started.
pub fn len(&self) -> usize {
self.started.len()
}
/// Whether no thread was started.
pub fn is_empty(&self) -> bool {
self.started.is_empty()
}
/// Stop every thread: signal `shutdown`, wake each thread in reverse start
/// order, then join them in the same order until `deadline`. Returns the
/// names of the threads still running at the deadline; they are left
/// behind rather than waited for.
pub fn stop(self, shutdown: &Shutdown, deadline: Instant) -> Vec<String> {
shutdown.stop();
for service in self.started.iter().rev() {
if let Some(wake) = &service.wake {
wake();
}
}
join_until(
self.started.into_iter().rev().map(|service| service.handle),
deadline,
)
}
}
/// Join `handles` until `deadline`, and name the ones still running then.
///
/// A stop used to wait for each thread however long it took. The sync engine's
/// mirror pass waits on Drive with no deadline, and a stop that waited for it
/// was killed by systemd (`docs/BUGS.md` B165).
pub fn join_until(
handles: impl IntoIterator<Item = JoinHandle<()>>,
deadline: Instant,
) -> Vec<String> {
let mut running = Vec::new();
for handle in handles {
while !handle.is_finished() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
if !handle.is_finished() {
running.push(handle.thread().name().unwrap_or("unnamed").to_string());
} else if handle.join().is_err() {
tracing::warn!("a background worker panicked before shutdown");
}
}
running
}
#[cfg(test)]
mod tests {
use std::sync::mpsc;
use super::*;
#[test]
fn a_stop_wakes_in_reverse_order_and_names_what_is_still_running() {
let board = ServiceBoard::default();
let shutdown = Arc::new(Shutdown::default());
let mut services = Services::new(board.clone());
let woken = Arc::new(Mutex::new(Vec::new()));
// Ends on the shutdown signal alone.
let signalled = shutdown.clone();
services
.spawn("sleeper", None, move || {
while signalled.sleep(Duration::from_secs(3600)) {}
})
.unwrap();
// Blocks on a channel: only its wake ends it.
let (tx, rx) = mpsc::channel::<()>();
let order = woken.clone();
services
.spawn(
"listener",
Some(Box::new(move || {
order.lock().push("listener");
let _ = tx.send(());
})),
move || {
let _ = rx.recv();
},
)
.unwrap();
// Never ends within the deadline.
let (_hold, stuck) = mpsc::channel::<()>();
let order = woken.clone();
services
.spawn(
"stuck",
Some(Box::new(move || order.lock().push("stuck"))),
move || {
let _ = stuck.recv();
},
)
.unwrap();
assert_eq!(services.len(), 3);
assert!(board.health().iter().all(|service| service.running));
let left = services.stop(&shutdown, Instant::now() + Duration::from_millis(500));
assert_eq!(left, ["stuck"]);
assert_eq!(*woken.lock(), ["stuck", "listener"]);
let running: Vec<_> = board
.health()
.into_iter()
.map(|service| (service.name, service.running))
.collect();
assert_eq!(
running,
[
("sleeper".to_string(), false),
("listener".to_string(), false),
("stuck".to_string(), true),
]
);
}
#[test]
fn a_service_that_panics_shows_as_not_running() {
let board = ServiceBoard::default();
let mut services = Services::new(board.clone());
services.spawn("doomed", None, || panic!("boom")).unwrap();
let left = services.stop(
&Shutdown::default(),
Instant::now() + Duration::from_secs(5),
);
assert!(left.is_empty());
assert!(!board.health()[0].running);
}
}
+1 -1
View File
@@ -4,7 +4,7 @@
//! side. Drive names come from the `nodes` FTS index; local names come from the
//! `local_files` index this module feeds. The daemon runs [`scan`] on a
//! background thread — never on a FUSE or control-socket thread — and streams
//! batches into [`crate::db::Db::local_upsert_batch`].
//! batches into `pdfs_store::db::Db::local_upsert_batch`.
//!
//! Walking is deliberately shallow on cost: we stat each entry once (the walker
//! already has the `DirEntry` metadata) and skip the directories that dominate a
+244
View File
@@ -0,0 +1,244 @@
//! A mutex that knows where it sits in the daemon's lock order.
//!
//! Most of the daemon's deadlocks were two threads taking the same pair of
//! locks in opposite orders (`docs/BUGS.md` B110, the cold size upgrade, the
//! diagnostics threads behind the database writer). Each such order was
//! written down in a comment, and the next feature did not read it.
//!
//! A [`Ranked`] lock carries a [`Rank`]. In a debug build, a thread that blocks
//! on a lock while it holds one of a higher rank panics, naming both, at the
//! line that would deadlock under the wrong interleaving. Release builds keep
//! no record and check nothing.
//!
//! Locks of equal rank may be held together. The code that takes several of
//! them orders them itself (several synced folders, lowest id first). A
//! `try_lock` cannot wait, so it is never refused, but what it takes is
//! recorded like any other lock.
use std::ops::{Deref, DerefMut};
use std::time::Duration;
use parking_lot::{Mutex, MutexGuard};
/// Where a lock sits in the order. A thread takes locks in increasing rank.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Rank {
/// One synced folder's lock, held by its sync pass for as long as the pass
/// runs.
SyncFolder = 10,
/// Publishing a shared change to every mounted session.
SharedPublication = 20,
/// The inode tree.
State = 30,
/// The database's single write connection.
DbWriter = 40,
}
/// A mutex with a [`Rank`]; see the module documentation.
pub struct Ranked<T> {
rank: Rank,
inner: Mutex<T>,
}
impl<T> Ranked<T> {
pub const fn new(rank: Rank, value: T) -> Self {
Self {
rank,
inner: Mutex::new(value),
}
}
pub fn rank(&self) -> Rank {
self.rank
}
/// Block until the lock is free. In a debug build, panics when this
/// thread holds a lock of a higher rank.
pub fn lock(&self) -> RankedGuard<'_, T> {
held::check(self.rank);
RankedGuard::new(self.inner.lock(), self.rank)
}
/// Take the lock if it is free.
pub fn try_lock(&self) -> Option<RankedGuard<'_, T>> {
self.inner
.try_lock()
.map(|guard| RankedGuard::new(guard, self.rank))
}
/// Wait up to `timeout` for the lock. It waits, so it is checked as
/// [`Ranked::lock`] is.
pub fn try_lock_for(&self, timeout: Duration) -> Option<RankedGuard<'_, T>> {
held::check(self.rank);
self.inner
.try_lock_for(timeout)
.map(|guard| RankedGuard::new(guard, self.rank))
}
pub fn into_inner(self) -> T {
self.inner.into_inner()
}
pub fn get_mut(&mut self) -> &mut T {
self.inner.get_mut()
}
}
/// A held [`Ranked`] lock.
pub struct RankedGuard<'a, T> {
guard: MutexGuard<'a, T>,
_held: held::Held,
}
impl<'a, T> RankedGuard<'a, T> {
fn new(guard: MutexGuard<'a, T>, rank: Rank) -> Self {
Self {
guard,
_held: held::Held::new(rank),
}
}
}
impl<T> Deref for RankedGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
&self.guard
}
}
impl<T> DerefMut for RankedGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.guard
}
}
#[cfg(debug_assertions)]
mod held {
use std::cell::RefCell;
use super::Rank;
thread_local! {
/// The ranks this thread holds, in the order it took them.
static HELD: RefCell<Vec<Rank>> = const { RefCell::new(Vec::new()) };
}
pub(super) fn check(rank: Rank) {
HELD.with(|held| {
let held = held.borrow();
if let Some(higher) = held.iter().find(|&&other| other > rank) {
panic!(
"lock order: waiting on {rank:?} while holding {higher:?} \
(held: {held:?}); take {rank:?} first (see pdfs_core::lockrank)"
);
}
});
}
pub(super) struct Held(Rank);
impl Held {
pub(super) fn new(rank: Rank) -> Self {
HELD.with(|held| held.borrow_mut().push(rank));
Self(rank)
}
}
impl Drop for Held {
fn drop(&mut self) {
HELD.with(|held| {
let mut held = held.borrow_mut();
// Guards can drop out of order; forget the latest of this rank.
if let Some(at) = held.iter().rposition(|&rank| rank == self.0) {
held.remove(at);
}
});
}
}
}
#[cfg(not(debug_assertions))]
mod held {
use super::Rank;
#[inline]
pub(super) fn check(_: Rank) {}
pub(super) struct Held;
impl Held {
#[inline]
pub(super) fn new(_: Rank) -> Self {
Held
}
}
}
#[cfg(all(test, debug_assertions))]
mod tests {
use super::*;
#[test]
fn locks_taken_in_rank_order_are_allowed() {
let state = Ranked::new(Rank::State, 1);
let db = Ranked::new(Rank::DbWriter, 2);
let a = state.lock();
let b = db.lock();
assert_eq!(*a + *b, 3);
}
#[test]
#[should_panic(expected = "lock order: waiting on State while holding DbWriter")]
fn a_lower_rank_taken_under_a_higher_one_panics() {
let state = Ranked::new(Rank::State, ());
let db = Ranked::new(Rank::DbWriter, ());
let _db = db.lock();
let _state = state.lock();
}
#[test]
fn locks_of_equal_rank_may_be_held_together() {
let one = Ranked::new(Rank::SyncFolder, ());
let two = Ranked::new(Rank::SyncFolder, ());
let _one = one.lock();
let _two = two.lock();
}
#[test]
fn a_released_lock_no_longer_counts() {
let state = Ranked::new(Rank::State, ());
let db = Ranked::new(Rank::DbWriter, ());
drop(db.lock());
let _state = state.lock();
let _db = db.lock();
}
#[test]
fn guards_dropped_out_of_order_are_both_forgotten() {
let publication = Ranked::new(Rank::SharedPublication, ());
let state = Ranked::new(Rank::State, ());
let db = Ranked::new(Rank::DbWriter, ());
let p = publication.lock();
let s = state.lock();
drop(p);
drop(s);
let _db = db.lock();
drop(_db);
let _p = publication.lock();
}
#[test]
fn a_try_lock_is_never_refused_but_still_counts() {
let state = Ranked::new(Rank::State, ());
let db = Ranked::new(Rank::DbWriter, ());
let _db = db.lock();
let s = state.try_lock().expect("free");
drop(_db);
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _ = Ranked::new(Rank::SharedPublication, ()).lock();
}));
drop(s);
assert!(result.is_err(), "the try_lock'd State still counts as held");
}
}
+94 -4
View File
@@ -13,6 +13,25 @@ use serde::{Deserialize, Serialize};
/// The file's name inside the state directory.
const FILE_NAME: &str = "mount-failure.json";
/// Failure to fetch My Files on a cold start with no cached root.
#[derive(Debug, thiserror::Error)]
#[error("fetch My Files root: {0}")]
pub struct RootLookup(pub proton_sdk::ProtonError);
impl RootLookup {
pub fn needs_account_keys(&self) -> bool {
use proton_sdk::{ProtonError, crypto::CryptoError};
// SDK 0.12 carries rpgp's `MissingKey` as the text of Decrypt.
// `a_real_missing_key_failure_waits_for_keys` pins that wording, so
// an SDK or rpgp update that changes it fails the test instead of
// silently going back to the retry loop. Never park for an unrelated
// decryption error.
matches!(self.0, ProtonError::KeysLocked)
|| matches!(&self.0, ProtonError::Crypto(CryptoError::Decrypt(reason)) if reason == "missing key")
}
}
/// The last failed mount attempt.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct MountFailure {
@@ -22,8 +41,19 @@ pub struct MountFailure {
pub since: i64,
/// Failed attempts in a row.
pub attempts: u32,
/// Unix seconds of the next attempt.
/// Unix seconds of the next attempt. Meaningless while `awaiting_keys`.
pub next_attempt: i64,
/// The daemon stopped retrying because the account keys cannot open My
/// Files, and waits for a restart after key recovery. A separate field
/// rather than an optional `next_attempt`, so an older version reading
/// the file after a downgrade still understands it.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub awaiting_keys: bool,
/// Set when the mount was refused because the folder already has files in
/// it, so the app can explain that in the user's language. Absent in a
/// file an older daemon wrote.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub not_empty: Option<crate::mountpoint::NotEmpty>,
}
/// Where the failure is kept for the state directory `state_dir`.
@@ -35,9 +65,7 @@ pub fn path(state_dir: &Path) -> PathBuf {
/// and renamed, so a reader never sees half of it.
pub fn record(state_dir: &Path, failure: &MountFailure) -> std::io::Result<()> {
let json = serde_json::to_vec(failure).map_err(std::io::Error::other)?;
let tmp = state_dir.join(format!("{FILE_NAME}.tmp"));
std::fs::write(&tmp, json)?;
std::fs::rename(&tmp, path(state_dir))
proton_base_rs::atomic::write_with_mode(&path(state_dir), &json, 0o644)
}
/// Forget the failure: a mount is up, or a new daemon has started.
@@ -65,6 +93,8 @@ mod tests {
since: 1_700_000_000,
attempts: 3,
next_attempt: 1_700_000_040,
awaiting_keys: false,
not_empty: None,
};
record(&dir, &failure).unwrap();
assert_eq!(read(&dir), Some(failure));
@@ -72,4 +102,64 @@ mod tests {
assert_eq!(read(&dir), None);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_failure_an_older_daemon_wrote_still_reads() {
let old = r#"{"error":"missing key","since":1,"attempts":2,"next_attempt":3}"#;
let failure: MountFailure = serde_json::from_str(old).unwrap();
assert_eq!(failure.next_attempt, 3);
assert!(!failure.awaiting_keys);
assert_eq!(failure.not_empty, None);
assert_eq!(failure.attempts, 2);
}
/// An older daemon, after a downgrade, must still read what this one
/// writes while it waits for key recovery.
#[test]
fn a_key_wait_reads_as_a_plain_failure_without_the_new_field() {
#[derive(Deserialize)]
#[allow(dead_code)]
struct OlderFailure {
error: String,
since: i64,
attempts: u32,
next_attempt: i64,
}
let failure = MountFailure {
error: "fetch My Files root: missing key".into(),
since: 1,
attempts: 1,
next_attempt: 1,
awaiting_keys: true,
not_empty: None,
};
let json = serde_json::to_string(&failure).unwrap();
let older: OlderFailure = serde_json::from_str(&json).unwrap();
assert_eq!(older.next_attempt, 1);
let back: MountFailure = serde_json::from_str(&json).unwrap();
assert!(back.awaiting_keys);
}
/// The error a key that is not the message's recipient really produces,
/// not a hand-written payload.
#[test]
fn a_real_missing_key_failure_waits_for_keys() {
use proton_sdk::crypto::{PrivateKey, generate_node_key};
let unlock = |generated: proton_sdk::crypto::GeneratedNodeKey| {
PrivateKey::from_armored(&generated.locked_armored, &generated.passphrase).unwrap()
};
let recipient = unlock(generate_node_key().unwrap());
let stranger = unlock(generate_node_key().unwrap());
let message = recipient.encrypt(b"root share key").unwrap();
let single = stranger.decrypt_armored_message(&message).unwrap_err();
assert!(RootLookup(single.into()).needs_account_keys());
let any = proton_sdk::crypto::decrypt_armored_with_keys(&message, &[stranger]).unwrap_err();
assert!(RootLookup(any.into()).needs_account_keys());
assert!(
!RootLookup(proton_sdk::ProtonError::invalid_operation("missing key"))
.needs_account_keys()
);
}
}
+147
View File
@@ -0,0 +1,147 @@
//! Whether a folder can take the My files mount without hiding anything.
//!
//! FUSE mounts over a folder that already has files in it without a word. The
//! files then sit under the mount, out of sight: not uploaded, and back only
//! once the service stops, so they look deleted (`docs/BUGS.md` B277, #67).
//! The daemon refuses such a folder, and the app refuses it when it is picked.
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
/// The file system type the kernel reports for this client's own mounts.
pub const OWN_FS_TYPE: &str = "fuse.protondrive";
/// How many of a folder's entries an error names.
const NAMED_ENTRIES: usize = 3;
/// A folder that already has something in it.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct NotEmpty {
/// The folder.
pub path: PathBuf,
/// The first few names in it, sorted.
pub entries: Vec<String>,
/// How many entries it has in all.
pub count: usize,
}
impl std::fmt::Display for NotEmpty {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} is not empty (holds ", self.path.display())?;
write!(f, "{}", self.entries.join(", "))?;
let rest = self.count.saturating_sub(self.entries.len());
if rest > 0 {
write!(f, " and {rest} more")?;
}
write!(
f,
"); My files would hide those files. Move them out, or choose another folder for My files"
)
}
}
impl std::error::Error for NotEmpty {}
/// What is in `dir`, if anything. A folder that does not exist yet is empty.
/// Hidden entries count: a `.directory` or a `.Trash-1000` hidden under the
/// mount is as lost as any other file.
pub fn not_empty(dir: &Path) -> std::io::Result<Option<NotEmpty>> {
let read = match std::fs::read_dir(dir) {
Ok(read) => read,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e),
};
let mut names = read
.map(|entry| entry.map(|entry| entry.file_name().to_string_lossy().into_owned()))
.collect::<std::io::Result<Vec<_>>>()?;
if names.is_empty() {
return Ok(None);
}
names.sort();
let count = names.len();
names.truncate(NAMED_ENTRIES);
Ok(Some(NotEmpty {
path: dir.to_path_buf(),
entries: names,
count,
}))
}
/// The file system type mounted at `path`, as `/proc/self/mountinfo` names it
/// (`ext4`, `fuse.protondrive`, …), or `None` when nothing is mounted there.
pub fn mounted_fs_type(path: &Path) -> Option<String> {
let wanted = path.canonicalize().ok()?;
let mounts = std::fs::read_to_string("/proc/self/mountinfo").ok()?;
mounts
.lines()
.filter_map(|line| {
let fields: Vec<_> = line.split_whitespace().collect();
let separator = fields.iter().position(|field| *field == "-")?;
let encoded = *fields.get(4)?;
let decoded = encoded.replace("\\040", " ").replace("\\011", "\t");
let mountpoint = PathBuf::from(decoded);
if mountpoint.canonicalize().ok()? == wanted {
Some(fields.get(separator + 1)?.to_string())
} else {
None
}
})
.next()
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_dir(name: &str) -> PathBuf {
let dir =
std::env::temp_dir().join(format!("pdfs-mountpoint-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn an_empty_or_missing_folder_takes_the_mount() {
let dir = temp_dir("empty");
assert_eq!(not_empty(&dir).unwrap(), None);
assert_eq!(not_empty(&dir.join("missing")).unwrap(), None);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_folder_with_files_is_refused_and_named() {
let dir = temp_dir("files");
for name in ["report.pdf", "Notes", ".directory", "zeta.txt"] {
std::fs::write(dir.join(name), b"x").unwrap();
}
let found = not_empty(&dir).unwrap().expect("must refuse");
assert_eq!(found.count, 4);
assert_eq!(found.entries, [".directory", "Notes", "report.pdf"]);
let message = found.to_string();
assert!(message.contains("is not empty"), "{message}");
assert!(
message.contains(".directory, Notes, report.pdf and 1 more"),
"{message}"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_hidden_file_alone_is_enough_to_refuse() {
let dir = temp_dir("hidden");
std::fs::write(dir.join(".Trash-1000"), b"").unwrap();
let found = not_empty(&dir).unwrap().expect("must refuse");
assert_eq!(found.count, 1);
assert!(!found.to_string().contains("more"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_plain_folder_is_not_a_mount() {
let dir = temp_dir("plain");
assert_eq!(mounted_fs_type(&dir), None);
let _ = std::fs::remove_dir_all(&dir);
}
}
+4 -2
View File
@@ -81,6 +81,8 @@ pub enum MountKind {
MyFiles,
/// A folder owned by this machine's Proton Drive device.
Device { sync_folder_id: i64 },
/// A real local mirror of an existing My files folder.
Attached { sync_folder_id: i64 },
/// A future standalone mount rooted at a node shared with this account.
Shared { share_root_uid: String },
}
@@ -88,8 +90,8 @@ pub enum MountKind {
/// One local Proton Drive location as exposed over the control protocol.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct MountSpec {
/// Presentation-row id. Device actions use the `sync_folder_id` carried by
/// [`MountKind::Device`], not this id.
/// Presentation-row id. Synced-folder actions use the `sync_folder_id`
/// carried by [`MountKind::Device`] or [`MountKind::Attached`], not this id.
pub id: i64,
pub kind: MountKind,
pub local_path: String,
+126 -19
View File
@@ -27,6 +27,7 @@ use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::{Command, Stdio};
use crate::control::is_video_file_name;
use serde::{Deserialize, Serialize};
/// Environment override for the terminal used by `"terminal": true` rules.
@@ -108,11 +109,12 @@ impl OpenWith {
/// a Markdown file). The rules are about *what the user opened*, so the
/// caller passes that name and the argv still gets the real path.
pub fn command_for_named(&self, path: &Path, name: &str, is_dir: bool) -> Vec<String> {
let kind = Kind::of(path, name, is_dir);
for rule in &self.rules {
if rule.command.is_empty() {
continue;
}
if !rule.patterns.iter().any(|p| matches(p, name, is_dir)) {
if !rule.patterns.iter().any(|p| matches(p, name, kind)) {
continue;
}
let argv = expand(&rule.command, path);
@@ -204,26 +206,23 @@ pub fn reap(mut child: std::process::Child) {
});
}
/// [`open`] with the policy from the user's `config.json`, read once per
/// process. For callers that open the occasional path and have no reason to
/// carry a policy around; long-lived windows should hold their own copy.
/// [`open`] with the policy from the user's `config.json`, read again on
/// every call: the file is small, a path is opened by hand, and a rule changed
/// in Preferences then applies to the next file opened, without a restart.
pub fn open_default(path: &Path, is_dir: bool) {
open(default_policy(), path, is_dir);
open(&default_policy(), path, is_dir);
}
/// [`open_default`] matching the rules against `name` — see
/// [`OpenWith::command_for_named`].
pub fn open_default_named(path: &Path, name: &str, is_dir: bool) {
open_named(default_policy(), path, name, is_dir);
open_named(&default_policy(), path, name, is_dir);
}
fn default_policy() -> &'static OpenWith {
static POLICY: std::sync::OnceLock<OpenWith> = std::sync::OnceLock::new();
POLICY.get_or_init(|| {
crate::config::AppDirs::new()
.map(|dirs| dirs.load_config().resolved_open_with())
.unwrap_or_default()
})
fn default_policy() -> OpenWith {
crate::config::AppDirs::new()
.map(|dirs| dirs.load_config().resolved_open_with())
.unwrap_or_default()
}
/// `$PDFS_TERMINAL`, then `$TERMINAL`, then the first [`KNOWN_TERMINALS`] entry
@@ -264,6 +263,33 @@ fn with_exec_flag(program: &str) -> Vec<String> {
argv
}
/// Split a command line typed by the user into argv, the way a shell would:
/// quotes keep spaces, nothing is expanded. `None` for an unclosed quote.
pub fn parse_command(line: &str) -> Option<Vec<String>> {
shell_words::split(line).ok()
}
/// Show `argv` as one line that [`parse_command`] turns back into it.
pub fn format_command(argv: &[String]) -> String {
shell_words::join(argv)
}
/// Whether the program `argv` starts with can be found: an absolute or
/// relative path to a file, or a name on `PATH`. A `$VAR` program counts as
/// found, since it is looked up only when a file is opened.
pub fn command_available(argv: &[String]) -> bool {
let Some(program) = argv.first() else {
return false;
};
if program.starts_with('$') {
return true;
}
if program.contains('/') {
return Path::new(program).is_file();
}
on_path(program)
}
fn on_path(program: &str) -> bool {
let Some(path) = std::env::var_os("PATH") else {
return false;
@@ -325,16 +351,46 @@ fn expand_env(token: &str) -> Option<String> {
value.filter(|v| !v.is_empty())
}
/// What is being opened, as far as the `@class` patterns care.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
Dir,
Video,
File,
}
impl Kind {
/// `.ts` names TypeScript and MPEG transport streams alike, so for that
/// one extension the size on disk decides (see
/// [`is_video_file_name`](crate::control::is_video_file_name)). No other
/// name costs a `stat`.
fn of(path: &Path, name: &str, is_dir: bool) -> Kind {
if is_dir {
return Kind::Dir;
}
let size = extension(name)
.eq_ignore_ascii_case("ts")
.then(|| std::fs::metadata(path).ok().map(|meta| meta.len()))
.flatten();
if is_video_file_name(name, size) {
Kind::Video
} else {
Kind::File
}
}
}
/// Whether `pattern` — a glob or an `@class` — matches this name.
fn matches(pattern: &str, name: &str, is_dir: bool) -> bool {
fn matches(pattern: &str, name: &str, kind: Kind) -> bool {
let name_lower = name.to_lowercase();
let file = kind == Kind::File;
match pattern.to_lowercase().as_str() {
"@any" => true,
"@dir" => is_dir,
"@text" => !is_dir && class_text(&name_lower),
"@document" => !is_dir && class_document(&name_lower),
"@image" => !is_dir && class_image(&name_lower),
"@media" => !is_dir && class_media(&name_lower),
"@dir" => kind == Kind::Dir,
"@text" => file && class_text(&name_lower),
"@document" => file && class_document(&name_lower),
"@image" => file && class_image(&name_lower),
"@media" => kind == Kind::Video || (file && class_media(&name_lower)),
other if other.starts_with('@') => false,
other => glob_match(other, &name_lower),
}
@@ -533,6 +589,37 @@ mod tests {
);
}
#[test]
fn a_ts_file_opens_as_media_or_text_by_its_size() {
let policy = OpenWith {
terminal: Some(vec!["alacritty".into(), "-e".into()]),
default: None,
rules: vec![
rule(&["@text"], &["nvim"], true),
rule(&["@media"], &["mpv"], false),
],
};
let dir = std::env::temp_dir().join(format!("pdfs-opener-ts-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let source = dir.join("blob-source");
std::fs::write(&source, "export const answer = 42;\n").unwrap();
let recording = dir.join("blob-recording");
std::fs::File::create(&recording)
.unwrap()
.set_len(crate::control::TS_VIDEO_MIN_BYTES)
.unwrap();
let source_argv = policy.command_for_named(&source, "app.ts", false);
let recording_argv = policy.command_for_named(&recording, "recording.ts", false);
// A file that is not on this machine yet has no size to go by.
let unknown_argv = policy.command_for_named(&dir.join("missing"), "recording.ts", false);
std::fs::remove_dir_all(&dir).unwrap();
assert_eq!(source_argv[..3], ["alacritty", "-e", "nvim"]);
assert_eq!(recording_argv[0], "mpv");
assert_eq!(unknown_argv[0], "mpv");
}
#[test]
fn an_empty_policy_is_xdg_open() {
let policy = OpenWith::default();
@@ -640,4 +727,24 @@ mod tests {
// Unknown terminals get the near-universal `-e`.
assert_eq!(with_exec_flag("mystery-term"), vec!["mystery-term", "-e"]);
}
#[test]
fn a_typed_command_line_round_trips() {
let argv = parse_command("alacritty -e 'my editor' --flag").unwrap();
assert_eq!(argv, ["alacritty", "-e", "my editor", "--flag"]);
assert_eq!(parse_command(&format_command(&argv)).unwrap(), argv);
assert_eq!(parse_command("nvim 'unclosed"), None);
assert_eq!(parse_command(" ").unwrap(), Vec::<String>::new());
}
#[test]
fn a_command_is_available_when_its_program_is() {
assert!(command_available(&["sh".to_string()]));
assert!(command_available(&["$EDITOR".to_string()]));
assert!(!command_available(&[]));
assert!(!command_available(
&["pdfs-no-such-program-xyz".to_string()]
));
assert!(!command_available(&["/nonexistent/program".to_string()]));
}
}
-185
View File
@@ -1,185 +0,0 @@
//! Offline reverse geocoding: the town a photo was taken in, from its GPS
//! position, without asking any service.
//!
//! The towns are GeoNames' `cities15000` dump (every place with more than
//! 15,000 people), trimmed to id, name, position and country in
//! `data/cities15000.tsv` by `scripts/geonames-cities.py`. The script drops the
//! parts of a city, such as Kreuzberg or "Paris 15 Vaugirard", so that a photo
//! lands in the town people would name. GeoNames publishes the dump under
//! CC BY 4.0, which is why the About dialog credits it.
//!
//! `data/countries.tsv` maps each country code to its ISO 3166-1 English name,
//! as the `iso-codes` project spells it, so a front end can translate it
//! through that project's `iso_3166-1` gettext domain.
use std::collections::HashMap;
use std::sync::OnceLock;
/// How far from the nearest town a photo may be and still count as taken
/// there, in km. Farther out (at sea, in the wilderness) it has no place.
pub const MAX_DISTANCE_KM: f64 = 50.0;
/// Mean Earth radius in km, for the haversine distance.
const EARTH_RADIUS_KM: f64 = 6371.0;
const CITIES: &str = include_str!("../data/cities15000.tsv");
const COUNTRIES: &str = include_str!("../data/countries.tsv");
/// One town of the table.
#[derive(Debug, Clone, PartialEq)]
pub struct City {
/// The GeoNames id, stable across dumps.
pub id: u32,
pub name: &'static str,
pub latitude: f64,
pub longitude: f64,
/// ISO 3166-1 alpha-2 country code.
pub country: &'static str,
}
/// The towns, and an index of them by whole-degree cell.
struct Table {
cities: Vec<City>,
cells: HashMap<(i32, i32), Vec<usize>>,
}
fn table() -> &'static Table {
static TABLE: OnceLock<Table> = OnceLock::new();
TABLE.get_or_init(|| {
let cities: Vec<City> = CITIES.lines().filter_map(parse_city).collect();
let mut cells: HashMap<(i32, i32), Vec<usize>> = HashMap::new();
for (index, city) in cities.iter().enumerate() {
cells
.entry(cell(city.latitude, city.longitude))
.or_default()
.push(index);
}
Table { cities, cells }
})
}
fn parse_city(line: &'static str) -> Option<City> {
let mut fields = line.split('\t');
Some(City {
id: fields.next()?.parse().ok()?,
name: fields.next()?,
latitude: fields.next()?.parse().ok()?,
longitude: fields.next()?.parse().ok()?,
country: fields.next()?,
})
}
fn cell(latitude: f64, longitude: f64) -> (i32, i32) {
(latitude.floor() as i32, longitude.floor() as i32)
}
/// Great-circle distance between two positions, in km.
pub fn distance_km(a: (f64, f64), b: (f64, f64)) -> f64 {
let (lat1, lat2) = (a.0.to_radians(), b.0.to_radians());
let dlat = lat2 - lat1;
let dlon = (b.1 - a.1).to_radians();
let h = (dlat / 2.0).sin().powi(2) + lat1.cos() * lat2.cos() * (dlon / 2.0).sin().powi(2);
2.0 * EARTH_RADIUS_KM * h.sqrt().min(1.0).asin()
}
/// The town nearest to a position, if one lies within [`MAX_DISTANCE_KM`].
pub fn nearest(latitude: f64, longitude: f64) -> Option<&'static City> {
if !latitude.is_finite() || !longitude.is_finite() {
return None;
}
let table = table();
// A degree of latitude is about 111 km everywhere; a degree of longitude
// shrinks towards the poles, so more cells are needed to cover the radius.
let lat_span = (MAX_DISTANCE_KM / 111.0).ceil() as i32;
let lon_span = {
let scale = latitude.to_radians().cos().abs().max(0.01);
((MAX_DISTANCE_KM / (111.0 * scale)).ceil() as i32).min(180)
};
let (row, column) = cell(latitude, longitude);
let mut best: Option<(f64, &City)> = None;
for dlat in -lat_span..=lat_span {
for dlon in -lon_span..=lon_span {
// Longitude wraps at the antimeridian: -181 is 179.
let lon_cell = (column + dlon + 180).rem_euclid(360) - 180;
let Some(indices) = table.cells.get(&(row + dlat, lon_cell)) else {
continue;
};
for &index in indices {
let city = &table.cities[index];
let d = distance_km((latitude, longitude), (city.latitude, city.longitude));
if d <= MAX_DISTANCE_KM && best.is_none_or(|(bd, _)| d < bd) {
best = Some((d, city));
}
}
}
}
best.map(|(_, city)| city)
}
/// The town with this GeoNames id.
pub fn city(id: u32) -> Option<&'static City> {
let cities = &table().cities;
// The table is sorted by id.
cities
.binary_search_by_key(&id, |city| city.id)
.ok()
.map(|index| &cities[index])
}
/// The English ISO 3166-1 name of a country code, such as "Germany" for "DE".
pub fn country_name(code: &str) -> Option<&'static str> {
COUNTRIES.lines().find_map(|line| {
let (c, name) = line.split_once('\t')?;
(c == code).then_some(name)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_position_in_a_town_resolves_to_that_town() {
let berlin = nearest(52.52, 13.405).expect("Berlin is a town");
assert_eq!(berlin.name, "Berlin");
assert_eq!(berlin.country, "DE");
assert_eq!(city(berlin.id), Some(berlin));
}
#[test]
fn the_open_sea_has_no_town() {
assert_eq!(nearest(0.0, -30.0), None);
assert_eq!(nearest(f64::NAN, 0.0), None);
}
#[test]
fn a_town_across_the_antimeridian_is_still_found() {
// Just east of 180°, the nearest towns in Fiji are west of it.
let town = nearest(-16.8, 179.99);
assert!(town.is_none_or(|t| t.country == "FJ"));
let suva = nearest(-18.14, 178.44).expect("Suva is a town");
assert_eq!(suva.country, "FJ");
}
#[test]
fn every_town_has_a_named_country() {
for city in &table().cities {
assert!(
country_name(city.country).is_some(),
"{} has no country name for {}",
city.name,
city.country
);
}
assert_eq!(country_name("DE"), Some("Germany"));
}
#[test]
fn distances_are_great_circle_km() {
let d = distance_km((52.52, 13.405), (48.137, 11.575));
assert!(
(d - 504.0).abs() < 5.0,
"Berlin to Munich is about 504 km, got {d}"
);
}
}
+11
View File
@@ -16,7 +16,15 @@ pub const SERVICE: &str = "proton-drive.service";
/// Run one `systemctl --user <args> proton-drive.service`, returning whether it
/// succeeded. Output is suppressed; failures are logged.
///
/// The unit runs the default instance. With a named
/// [`crate::config::instance`], nothing is run and the answer is `false`, so a
/// test account's `pdfs login` never restarts the user's own daemon.
fn systemctl(args: &[&str]) -> bool {
if crate::config::instance().is_some() {
tracing::debug!(args = ?args, "not running systemctl for a named instance");
return false;
}
let ok = Command::new("systemctl")
.arg("--user")
.args(args)
@@ -36,6 +44,9 @@ fn systemctl(args: &[&str]) -> bool {
/// rather than a failure to log. For query verbs (`is-active`, `is-failed`)
/// where "no" is the normal, expected result.
fn systemctl_query(args: &[&str]) -> bool {
if crate::config::instance().is_some() {
return false;
}
Command::new("systemctl")
.arg("--user")
.args(args)
@@ -21,7 +21,7 @@ use parking_lot::{Condvar, Mutex};
/// The daemon's stop signal. Set once, never cleared: a `Core` that has been
/// told to stop belongs to a mount that is going away.
#[derive(Default)]
pub(crate) struct Shutdown {
pub struct Shutdown {
stopping: Mutex<bool>,
changed: Condvar,
}
@@ -29,14 +29,14 @@ pub(crate) struct Shutdown {
impl Shutdown {
/// Whether teardown has begun. Loops check this where they would otherwise
/// start another unit of work.
pub(crate) fn is_stopping(&self) -> bool {
pub fn is_stopping(&self) -> bool {
*self.stopping.lock()
}
/// Begin teardown and wake everything waiting in [`sleep`](Self::sleep).
/// Idempotent, because more than one path can reach teardown (a signal, the
/// kernel mount ending, a failed startup).
pub(crate) fn stop(&self) {
pub fn stop(&self) {
let mut stopping = self.stopping.lock();
*stopping = true;
self.changed.notify_all();
@@ -47,7 +47,7 @@ impl Shutdown {
/// Returns `false` if the daemon is stopping — including when it was already
/// stopping on entry, so `while shutdown.sleep(interval)` is a complete and
/// correct loop condition and no separate check is needed at the top.
pub(crate) fn sleep(&self, duration: Duration) -> bool {
pub fn sleep(&self, duration: Duration) -> bool {
let mut stopping = self.stopping.lock();
if !*stopping {
self.changed.wait_for(&mut stopping, duration);
-193
View File
@@ -1,193 +0,0 @@
//! Telling photos apart by what they show rather than by their bytes.
//!
//! The server's content hash only matches byte-identical files. A photo that
//! was resized, re-encoded or sent through a messenger is another file, so the
//! similar-photo finder hashes each thumbnail instead: a 64-bit difference
//! hash ("dHash"), which compares neighbouring brightness in a 9×8 grid. Two
//! copies of one picture land a few bits apart, and different pictures about
//! half of the bits apart.
/// Hashes this many bits apart or fewer show the same picture.
pub const SIMILAR_BITS: u32 = 6;
/// Stored for a photo whose thumbnail was looked at and gave no usable hash
/// (it couldn't be decoded, or is one flat colour), so it isn't looked at
/// again. A real hash is never 0: a picture that would hash to 0 has no
/// brightness changes, which [`difference_hash`] turns down as flat.
pub const NO_HASH: u64 = 0;
/// Samples of the grid that differ by less than this in brightness, all of
/// them, make a flat picture — a black frame, a blank page — whose hash is
/// noise and would match every other flat picture.
const FLAT: u8 = 8;
/// The difference hash of an 8-bit greyscale image `width` px wide, rows
/// stored one after another in `luma`. `None` for an empty or flat image.
pub fn difference_hash(width: usize, height: usize, luma: &[u8]) -> Option<u64> {
if width == 0 || height == 0 || luma.len() < width * height {
return None;
}
// Box-average down to 9×8, so every source pixel counts once and the hash
// doesn't depend on which pixels a nearest-neighbour pick happens to hit.
let mut grid = [[0u8; 9]; 8];
for (gy, row) in grid.iter_mut().enumerate() {
let (y0, y1) = span(gy, 8, height);
for (gx, cell) in row.iter_mut().enumerate() {
let (x0, x1) = span(gx, 9, width);
let mut sum = 0u64;
for y in y0..y1 {
sum += luma[y * width + x0..y * width + x1]
.iter()
.map(|&v| u64::from(v))
.sum::<u64>();
}
*cell = (sum / ((y1 - y0) * (x1 - x0)) as u64) as u8;
}
}
let (min, max) = grid
.iter()
.flatten()
.fold((u8::MAX, 0), |(min, max), &v| (min.min(v), max.max(v)));
if max - min < FLAT {
return None;
}
let mut hash = 0u64;
for row in &grid {
for pair in row.windows(2) {
hash = hash << 1 | u64::from(pair[0] < pair[1]);
}
}
(hash != NO_HASH).then_some(hash)
}
/// The source pixels `from..to` that cell `i` of `cells` covers along an edge
/// of `len` px; never empty, even for an edge shorter than the grid.
fn span(i: usize, cells: usize, len: usize) -> (usize, usize) {
let from = (i * len / cells).min(len - 1);
let to = ((i + 1) * len / cells).max(from + 1);
(from, to)
}
/// Whether two hashes show the same picture.
pub fn alike(a: u64, b: u64) -> bool {
(a ^ b).count_ones() <= SIMILAR_BITS
}
/// Group `hashes` into sets of alike ones, by index, each set in index order
/// and the sets by their first index. A hash alike to none other is in no
/// set. Alike is taken as catching: a burst of shots each a little different
/// from the last is one set.
pub fn sets(hashes: &[u64]) -> Vec<Vec<usize>> {
// Two hashes at most SIMILAR_BITS apart agree on at least one of their
// eight bytes, as long as SIMILAR_BITS < 8. So only hashes sharing some
// byte are compared, not every pair of the library.
const _: () = assert!(SIMILAR_BITS < 8);
let mut parent: Vec<usize> = (0..hashes.len()).collect();
fn root(parent: &mut [usize], mut i: usize) -> usize {
while parent[i] != i {
parent[i] = parent[parent[i]];
i = parent[i];
}
i
}
for byte in 0..8 {
let mut buckets: Vec<Vec<usize>> = vec![Vec::new(); 256];
for (i, &hash) in hashes.iter().enumerate() {
buckets[(hash >> (byte * 8)) as u8 as usize].push(i);
}
for bucket in &buckets {
for (n, &a) in bucket.iter().enumerate() {
for &b in &bucket[n + 1..] {
if alike(hashes[a], hashes[b]) {
let (ra, rb) = (root(&mut parent, a), root(&mut parent, b));
if ra != rb {
parent[ra.max(rb)] = ra.min(rb);
}
}
}
}
}
}
let mut by_root: std::collections::BTreeMap<usize, Vec<usize>> = Default::default();
for i in 0..hashes.len() {
let r = root(&mut parent, i);
by_root.entry(r).or_default().push(i);
}
by_root.into_values().filter(|set| set.len() > 1).collect()
}
#[cfg(test)]
mod tests {
use super::*;
/// A 90×80 picture: a bright disc on a gradient.
fn picture(width: usize, height: usize) -> Vec<u8> {
let mut luma = Vec::with_capacity(width * height);
for y in 0..height {
for x in 0..width {
let (fx, fy) = (x as f64 / width as f64, y as f64 / height as f64);
let disc = ((fx - 0.3).powi(2) + (fy - 0.6).powi(2)).sqrt() < 0.2;
let v = if disc { 240.0 } else { 40.0 + 120.0 * fx * fy };
luma.push(v as u8);
}
}
luma
}
#[test]
fn a_resized_copy_hashes_alike() {
let big = difference_hash(900, 800, &picture(900, 800)).unwrap();
let small = difference_hash(91, 79, &picture(91, 79)).unwrap();
assert!(
alike(big, small),
"{} bits apart",
(big ^ small).count_ones()
);
}
#[test]
fn a_different_picture_hashes_apart() {
let one = difference_hash(90, 80, &picture(90, 80)).unwrap();
let mirrored: Vec<u8> = picture(90, 80)
.chunks(90)
.flat_map(|row| row.iter().rev().copied().collect::<Vec<_>>())
.collect();
let other = difference_hash(90, 80, &mirrored).unwrap();
assert!(!alike(one, other));
}
#[test]
fn a_flat_picture_has_no_hash() {
assert_eq!(difference_hash(64, 64, &[17; 64 * 64]), None);
assert_eq!(difference_hash(0, 0, &[]), None);
assert_eq!(difference_hash(4, 4, &[0; 3]), None);
}
#[test]
fn a_picture_smaller_than_the_grid_still_hashes() {
let luma: Vec<u8> = (0..4 * 3).map(|i| (i * 20) as u8).collect();
assert!(difference_hash(4, 3, &luma).is_some());
}
#[test]
fn alike_hashes_form_sets_and_catch_on() {
let a = 0x0123_4567_89ab_cdef_u64;
let hashes = [
a,
!a,
a ^ 0b111,
a ^ 0b111 ^ (0b1111 << 40),
0x5555_0000_ffff_aaaa,
];
assert_eq!(sets(&hashes), vec![vec![0, 2, 3]]);
}
#[test]
fn hashes_apart_in_most_bytes_are_still_found() {
// One bit apart in each of six bytes: six bits in all, and only the
// top two bytes agree.
let a = 1u64 << 63;
let b = (0..6).fold(a, |h, byte| h | 1 << (byte * 8));
assert_eq!(sets(&[a, b]), vec![vec![0, 1]]);
}
}
+499 -1
View File
@@ -30,6 +30,11 @@ use ignore::gitignore::{Gitignore, GitignoreBuilder};
/// them. Version-control metadata, dependency and build trees, editor
/// leftovers, and OS turds — none of which belong on Drive, all of which are
/// large or rewritten constantly.
///
/// The second half is what Nextcloud, Dropbox and Syncthing leave out as well:
/// files a desktop, a file system or a program in the middle of a write leaves
/// behind, never anything a person made. Every one is in a test, next to a real
/// file of a similar name that must stay synced.
pub const DEFAULT_IGNORE_PATTERNS: &[&str] = &[
".git/",
".hg/",
@@ -43,6 +48,23 @@ pub const DEFAULT_IGNORE_PATTERNS: &[&str] = &[
"*.tmp",
".DS_Store",
"Thumbs.db",
// Folder settings of Windows and KDE's Dolphin.
"desktop.ini",
".directory",
// Trash folders and file-system leftovers: a file deleted while open on a
// FUSE or NFS mount lives on under one of these names until it is closed.
".Trash-*/",
".Trashes/",
".Spotlight-V100/",
".fuse_hidden*",
".nfs*",
// Downloads and saves still being written.
"*.part",
"*.crdownload",
"*.kate-swp",
// Office lock files: LibreOffice's `.~lock.<name>#`, Microsoft Office's `~$<name>`.
".~lock.*#",
"~$*",
];
/// Suffixes that mean a file is incomplete *by construction*: only the program
@@ -119,6 +141,225 @@ pub fn is_scratch_name(name: &str) -> bool {
/// Filenames accepted as a folder's ignore file, in precedence order.
const IGNORE_FILE_NAMES: &[&str] = &[".pdfsignore", ".protonignore"];
/// Whether `line` is a rule [`IgnoreRules::load`] accepts: a pattern, a
/// comment or a blank line. The error says what is wrong with it.
pub fn check_pattern(line: &str) -> Result<(), String> {
GitignoreBuilder::new("/")
.add_line(None, line)
.map(|_| ())
.map_err(|e| e.to_string())
}
/// The lines of an ignore file that [`IgnoreRules::load`] would skip, by line
/// number (from 1), with what is wrong with each.
pub fn check_rules(text: &str) -> Vec<(usize, String)> {
text.lines()
.enumerate()
.filter_map(|(i, line)| check_pattern(line).err().map(|e| (i + 1, e)))
.collect()
}
/// A synced folder's own ignore file, read so it can be edited and written
/// back. See [`FolderRules::read`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FolderRules {
/// The file the rules are in: the one in use, or `.pdfsignore` when there
/// is none yet.
pub path: std::path::PathBuf,
/// The rules as read; empty when there is no file. `None` means there was
/// no file, which [`write`](Self::write) checks is still so.
pub text: Option<String>,
}
/// Why [`FolderRules::write`] did not write.
#[derive(Debug)]
pub enum WriteRulesError {
/// The file changed after it was read, for example by an edit on another
/// computer that sync brought in. The rules on disk are the new ones.
Changed,
/// Reading or writing failed.
Io(std::io::Error),
}
impl std::fmt::Display for WriteRulesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Changed => f.write_str("the file changed since it was opened"),
Self::Io(e) => e.fmt(f),
}
}
}
impl std::error::Error for WriteRulesError {}
impl From<std::io::Error> for WriteRulesError {
fn from(e: std::io::Error) -> Self {
Self::Io(e)
}
}
impl FolderRules {
/// Read the ignore file of the folder at `root`, the same one
/// [`IgnoreRules::load`] uses.
pub fn read(root: &Path) -> std::io::Result<Self> {
for name in IGNORE_FILE_NAMES {
let path = root.join(name);
match std::fs::read_to_string(&path) {
Ok(text) => {
return Ok(Self {
path,
text: Some(text),
});
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
Err(e) => return Err(e),
}
}
// Like `load`, a missing folder reads as one without rules; the write
// is what fails then.
Ok(Self {
path: root.join(IGNORE_FILE_NAMES[0]),
text: None,
})
}
/// Replace the rules with `text`, unless the file changed since it was
/// read. Rules that are all blank remove the file, so a folder never keeps
/// an empty one around.
///
/// Written to a temporary file and renamed over the old one, so the sync
/// pass reading the rules at the same moment sees the old ones or the new
/// ones, never half of them.
pub fn write(&self, text: &str) -> Result<(), WriteRulesError> {
let now = match std::fs::read_to_string(&self.path) {
Ok(now) => Some(now),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => return Err(e.into()),
};
if now != self.text {
return Err(WriteRulesError::Changed);
}
if text.trim().is_empty() {
return match std::fs::remove_file(&self.path) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e.into()),
_ => Ok(()),
};
}
let Some(name) = self.path.file_name() else {
return Err(std::io::Error::other("the rules path has no file name").into());
};
let mut tmp_name = std::ffi::OsString::from(".");
tmp_name.push(name);
tmp_name.push(format!(".tmp-{}", std::process::id()));
let tmp = self.path.with_file_name(tmp_name);
let mut body = text.to_string();
if !body.ends_with('\n') {
body.push('\n');
}
let written = std::fs::write(&tmp, body).and_then(|()| std::fs::rename(&tmp, &self.path));
if written.is_err() {
let _ = std::fs::remove_file(&tmp);
}
Ok(written?)
}
/// The patterns in the rules: every line that is not blank or a comment,
/// trimmed of surrounding white space.
pub fn patterns(&self) -> Vec<&str> {
self.text
.as_deref()
.unwrap_or_default()
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && !line.starts_with('#'))
.collect()
}
}
/// How often [`add_folder_pattern`] and [`remove_folder_pattern`] read the
/// rules again when they changed between the read and the write.
const RULES_RETRIES: usize = 3;
/// Add `pattern` at the end of the own rules of the folder at `root`, keeping
/// every other line and comment. Says whether it added it: a pattern already
/// there is left alone.
pub fn add_folder_pattern(root: &Path, pattern: &str) -> std::io::Result<bool> {
let pattern = pattern.trim();
edit_folder_rules(root, |rules| {
if rules.patterns().contains(&pattern) {
return None;
}
let mut text = rules.text.clone().unwrap_or_default();
if !text.is_empty() && !text.ends_with('\n') {
text.push('\n');
}
text.push_str(pattern);
text.push('\n');
Some(text)
})
}
/// Remove every line that is `pattern` from the own rules of the folder at
/// `root`. Says whether there was one.
pub fn remove_folder_pattern(root: &Path, pattern: &str) -> std::io::Result<bool> {
let pattern = pattern.trim();
edit_folder_rules(root, |rules| {
if !rules.patterns().contains(&pattern) {
return None;
}
let text = rules.text.as_deref().unwrap_or_default();
Some(
text.lines()
.filter(|line| line.trim() != pattern)
.map(|line| format!("{line}\n"))
.collect(),
)
})
}
/// Read the folder's rules, let `edit` return their new text (or `None` to
/// leave them), and write it. Rules that changed in between, such as by sync
/// bringing in an edit from another computer, are read again and edited anew.
fn edit_folder_rules(
root: &Path,
edit: impl Fn(&FolderRules) -> Option<String>,
) -> std::io::Result<bool> {
for _ in 0..RULES_RETRIES {
let rules = FolderRules::read(root)?;
let Some(text) = edit(&rules) else {
return Ok(false);
};
match rules.write(&text) {
Ok(()) => return Ok(true),
Err(WriteRulesError::Changed) => continue,
Err(WriteRulesError::Io(e)) => return Err(e),
}
}
Err(std::io::Error::other(
"the rules kept changing while they were being saved",
))
}
/// Where a rule that decided about a path came from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RuleSource {
/// The rules for every synced folder (`ignore_patterns`).
AllFolders,
/// The folder's own ignore file.
ThisFolder,
}
/// What the rules say about one path, and which rule says it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verdict {
/// No rule matches: the path is synced.
Synced,
/// Left out by `pattern`. `pattern` may name a folder the path is in.
Excluded { pattern: String, source: RuleSource },
/// A rule excluded it, and a later `!pattern` brought it back.
Included { pattern: String, source: RuleSource },
}
/// Compiled ignore rules for one synced folder.
pub struct IgnoreRules {
matcher: Option<Gitignore>,
@@ -161,6 +402,27 @@ impl IgnoreRules {
}
}
/// [`load`](Self::load) with `text` standing in for the folder's ignore
/// file, for showing what rules being edited would do before they are
/// saved.
pub fn with_folder_text(root: &Path, globals: &[String], text: &str) -> Self {
let mut builder = GitignoreBuilder::new(root);
let mut any = false;
for pattern in globals {
any |= builder.add_line(None, pattern).is_ok();
}
let file = root.join(IGNORE_FILE_NAMES[0]);
for line in text.lines() {
any |= builder.add_line(Some(file.clone()), line).is_ok();
}
if !any {
return Self { matcher: None };
}
Self {
matcher: builder.build().ok(),
}
}
/// Rules matching nothing, for callers with no folder context.
pub fn empty() -> Self {
Self { matcher: None }
@@ -207,6 +469,50 @@ impl IgnoreRules {
}
}
impl IgnoreRules {
/// What the rules say about `rel`, and which rule decides, the way
/// [`is_ignored`](Self::is_ignored) decides it.
pub fn explain(&self, rel: &str, is_dir: bool) -> Verdict {
let Some(matcher) = &self.matcher else {
return Verdict::Synced;
};
let rel = rel.trim_matches('/');
if rel.is_empty() {
return Verdict::Synced;
}
let source = |glob: &ignore::gitignore::Glob| match glob.from() {
Some(_) => RuleSource::ThisFolder,
None => RuleSource::AllFolders,
};
let mut prefix = String::new();
let mut parts = rel.split('/').peekable();
while let Some(part) = parts.next() {
if !prefix.is_empty() {
prefix.push('/');
}
prefix.push_str(part);
let last = parts.peek().is_none();
let as_dir = if last { is_dir } else { true };
match matcher.matched(&prefix, as_dir) {
ignore::Match::Ignore(glob) => {
return Verdict::Excluded {
pattern: glob.original().to_string(),
source: source(glob),
};
}
ignore::Match::Whitelist(glob) if last => {
return Verdict::Included {
pattern: glob.original().to_string(),
source: source(glob),
};
}
_ => {}
}
}
Verdict::Synced
}
}
impl std::fmt::Debug for IgnoreRules {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("IgnoreRules")
@@ -220,7 +526,7 @@ mod tests {
use super::*;
/// A unique temp directory removed on drop; avoids a dev-dependency, as in
/// [`crate::cache`]'s tests.
/// `pdfs_store::cache`'s tests.
struct TempDir(std::path::PathBuf);
impl TempDir {
fn new() -> Self {
@@ -255,6 +561,198 @@ mod tests {
std::fs::write(root.join(name), body).unwrap();
}
#[test]
fn the_added_defaults_leave_out_clutter_but_not_look_alikes() {
let dir = TempDir::new();
let rules = IgnoreRules::load(dir.path(), &globals());
for (clutter, is_dir) in [
("desktop.ini", false),
("Photos/.directory", false),
(".Trash-1000", true),
(".Trashes", true),
(".Spotlight-V100", true),
(".fuse_hidden0000001a00000002", false),
(".nfs000000000123abcd", false),
("movie.mkv.part", false),
("setup.exe.crdownload", false),
("notes.txt.kate-swp", false),
(".~lock.report.odt#", false),
("~$budget.xlsx", false),
] {
assert!(rules.is_ignored(clutter, is_dir), "{clutter}");
}
for kept in [
"Desktop/notes.txt",
"directory.txt",
"Trash-talk.md",
"nfs-setup.md",
"parts.csv",
"part.txt",
"report.odt",
"budget.xlsx",
] {
assert!(!rules.is_ignored(kept, false), "{kept}");
}
}
#[test]
fn a_bad_pattern_is_reported_with_its_line() {
assert!(check_pattern("*.db").is_ok());
assert!(check_pattern("# a comment").is_ok());
assert!(check_pattern("").is_ok());
assert!(check_pattern("*.{jpg,png").is_err());
assert!(check_pattern("[z-a]").is_err());
let bad = check_rules("*.log\n{oops\nbuild/\n");
assert_eq!(bad.len(), 1);
assert_eq!(bad[0].0, 2);
}
#[test]
fn explain_names_the_rule_and_where_it_came_from() {
let dir = TempDir::new();
write(dir.path(), ".pdfsignore", "*.db\n!keep.tmp\n");
let rules = IgnoreRules::load(dir.path(), &globals());
assert_eq!(
rules.explain("data/cache.db", false),
Verdict::Excluded {
pattern: "*.db".into(),
source: RuleSource::ThisFolder
}
);
assert_eq!(
rules.explain("app/node_modules/x/index.js", false),
Verdict::Excluded {
pattern: "node_modules/".into(),
source: RuleSource::AllFolders
}
);
assert_eq!(
rules.explain("keep.tmp", false),
Verdict::Included {
pattern: "!keep.tmp".into(),
source: RuleSource::ThisFolder
}
);
assert_eq!(rules.explain("src/main.rs", false), Verdict::Synced);
// `explain` and `is_ignored` never disagree.
for (path, is_dir) in [
("data/cache.db", false),
("keep.tmp", false),
("x.tmp", false),
] {
assert_eq!(
rules.is_ignored(path, is_dir),
matches!(rules.explain(path, is_dir), Verdict::Excluded { .. }),
"{path}"
);
}
}
#[test]
fn rules_being_edited_explain_like_the_saved_ones() {
let dir = TempDir::new();
let text = "*.db\n!keep.db\n";
write(dir.path(), ".pdfsignore", text);
let saved = IgnoreRules::load(dir.path(), &globals());
let edited = IgnoreRules::with_folder_text(dir.path(), &globals(), text);
for path in ["a.db", "keep.db", "node_modules/x", "src/x.rs"] {
assert_eq!(
saved.explain(path, false),
edited.explain(path, false),
"{path}"
);
}
}
#[test]
fn folder_rules_are_written_back_and_removed_when_blank() {
let dir = TempDir::new();
let rules = FolderRules::read(dir.path()).unwrap();
assert_eq!(rules.text, None);
assert_eq!(rules.path, dir.path().join(".pdfsignore"));
rules.write("*.db").unwrap();
assert_eq!(
std::fs::read_to_string(dir.path().join(".pdfsignore")).unwrap(),
"*.db\n"
);
assert!(IgnoreRules::load(dir.path(), &[]).is_ignored("x.db", false));
let rules = FolderRules::read(dir.path()).unwrap();
rules.write(" \n").unwrap();
assert!(!dir.path().join(".pdfsignore").exists());
}
#[test]
fn folder_rules_keep_the_file_name_in_use() {
let dir = TempDir::new();
write(dir.path(), ".protonignore", "old/\n");
let rules = FolderRules::read(dir.path()).unwrap();
assert_eq!(rules.path, dir.path().join(".protonignore"));
rules.write("new/\n").unwrap();
assert!(!dir.path().join(".pdfsignore").exists());
assert_eq!(
std::fs::read_to_string(dir.path().join(".protonignore")).unwrap(),
"new/\n"
);
}
#[test]
fn folder_rules_changed_elsewhere_are_not_written_over() {
let dir = TempDir::new();
write(dir.path(), ".pdfsignore", "a/\n");
let rules = FolderRules::read(dir.path()).unwrap();
write(dir.path(), ".pdfsignore", "b/\n");
assert!(matches!(rules.write("c/"), Err(WriteRulesError::Changed)));
assert_eq!(
std::fs::read_to_string(dir.path().join(".pdfsignore")).unwrap(),
"b/\n"
);
// A file that appeared after an empty read counts as a change too.
let dir = TempDir::new();
let rules = FolderRules::read(dir.path()).unwrap();
write(dir.path(), ".pdfsignore", "b/\n");
assert!(matches!(rules.write("c/"), Err(WriteRulesError::Changed)));
}
#[test]
fn a_pattern_added_to_a_folder_keeps_its_other_lines() {
let dir = TempDir::new();
assert!(add_folder_pattern(dir.path(), " *.db ").unwrap());
assert_eq!(
std::fs::read_to_string(dir.path().join(".pdfsignore")).unwrap(),
"*.db\n"
);
write(dir.path(), ".pdfsignore", "# my notes\nbuild/");
assert!(add_folder_pattern(dir.path(), "*.db").unwrap());
assert!(!add_folder_pattern(dir.path(), "build/").unwrap());
assert_eq!(
std::fs::read_to_string(dir.path().join(".pdfsignore")).unwrap(),
"# my notes\nbuild/\n*.db\n"
);
assert_eq!(
FolderRules::read(dir.path()).unwrap().patterns(),
["build/", "*.db"]
);
}
#[test]
fn removing_a_folder_pattern_keeps_comments_and_drops_an_empty_file() {
let dir = TempDir::new();
write(dir.path(), ".pdfsignore", "# keep\nbuild/\n*.db\n");
assert!(remove_folder_pattern(dir.path(), "build/").unwrap());
assert!(!remove_folder_pattern(dir.path(), "build/").unwrap());
assert_eq!(
std::fs::read_to_string(dir.path().join(".pdfsignore")).unwrap(),
"# keep\n*.db\n"
);
write(dir.path(), ".pdfsignore", "*.db\n");
assert!(remove_folder_pattern(dir.path(), "*.db").unwrap());
assert!(!dir.path().join(".pdfsignore").exists());
}
#[test]
fn no_rules_at_all_ignores_nothing() {
let dir = TempDir::new();
File diff suppressed because it is too large. Load diff
+43
View File
@@ -0,0 +1,43 @@
//! Epoch seconds: the clock, and the conversion at the SDK boundary.
use std::time::{SystemTime, UNIX_EPOCH};
use proton_drive_rs::ModificationTime;
/// Current wall-clock time as epoch seconds (0 if the clock is before the epoch).
pub fn now_secs() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
/// A UTC modification time, or `None` when outside the SDK's supported range.
pub fn modification_time(seconds: i64) -> Option<ModificationTime> {
chrono::DateTime::from_timestamp(seconds, 0).map(|time| time.fixed_offset())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn epoch_seconds_preserve_the_instant_including_before_1970() {
for seconds in [-1, 0, 1_709_208_000, 1_782_482_460] {
let time = modification_time(seconds).unwrap();
assert_eq!(time.timestamp(), seconds);
assert_eq!(time.offset().local_minus_utc(), 0);
assert_eq!(time.timestamp_subsec_nanos(), 0);
}
assert_eq!(
modification_time(-1).unwrap().to_rfc3339(),
"1969-12-31T23:59:59+00:00"
);
}
#[test]
fn out_of_range_seconds_omit_the_timestamp() {
assert!(modification_time(i64::MIN).is_none());
assert!(modification_time(i64::MAX).is_none());
}
}
@@ -17,7 +17,7 @@
//! transfer moves is charged to its direction's [`RateLimit`], and the thread
//! moving it sleeps off whatever the charge puts it over the cap.
//!
//! [`Request::GetQueueStatus`]: pdfs_core::control::Request::GetQueueStatus
//! [`Request::GetQueueStatus`]: crate::control::Request::GetQueueStatus
use parking_lot::Mutex;
use std::collections::HashMap;
@@ -26,7 +26,7 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{Duration, Instant};
use pdfs_core::control::{JobItem, TransferDirection, TransferItem};
use crate::control::{JobItem, TransferDirection, TransferItem};
/// One registered transfer. `done` is bumped from the I/O wrapper without the
/// registry lock; the rest is immutable for the transfer's lifetime.
@@ -198,7 +198,7 @@ impl TransferRegistry {
/// Snapshot every in-flight job for [`Response::Transfers`], oldest first, so
/// a front-end's rows keep their order across polls.
///
/// [`Response::Transfers`]: pdfs_core::control::Response::Transfers
/// [`Response::Transfers`]: crate::control::Response::Transfers
pub fn jobs_snapshot(&self) -> Vec<JobItem> {
let map = self.jobs.lock();
let mut ids: Vec<_> = map.keys().copied().collect();
@@ -222,7 +222,7 @@ impl TransferRegistry {
/// running average since the transfer began — simple, and stable enough for a
/// progress widget without per-tick sampling state.
///
/// [`Response::Transfers`]: pdfs_core::control::Response::Transfers
/// [`Response::Transfers`]: crate::control::Response::Transfers
pub fn snapshot(&self) -> Vec<TransferItem> {
let map = self.inner.lock();
let mut ids: Vec<_> = map.keys().copied().collect();
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "pdfs-daemon"
version.workspace = true
edition.workspace = true
license.workspace = true
authors.workspace = true
rust-version.workspace = true
repository.workspace = true
homepage.workspace = true
description = "The Proton Drive Linux daemon's composition root: session, mount and restart loop"
[dependencies]
pdfs-core.workspace = true
pdfs-store.workspace = true
pdfs-fuse.workspace = true
tokio.workspace = true
anyhow.workspace = true
tracing.workspace = true
+469
View File
@@ -0,0 +1,469 @@
//! The daemon's composition root.
//!
//! `pdfs daemon` runs [`run`]: it waits for a stored session, opens the
//! database and the content cache, resumes the session on a runtime of its
//! own, and mounts. It keeps the mount alive: a clean stop exits, an
//! external unmount remounts, and a failure is recorded and retried with a
//! backoff. The mount itself, and the services it starts, are `pdfs-fuse`.
//!
//! Step 3 of `docs/ARCHITECTURE.md` moves the building of those services
//! here, one at a time.
use std::path::PathBuf;
use std::sync::Arc;
use anyhow::{Context, Result};
use pdfs_core::auth;
use pdfs_core::config::AppDirs;
use pdfs_store::cache::ContentCache;
use pdfs_store::db::Db;
/// How long to wait before the next login check, after `attempts` checks have
/// already come back [`pdfs_core::Error::NotLoggedIn`].
///
/// Doubles from 3s to a 15s ceiling. The interval is not just a sleep:
/// [`auth::load`] builds a fresh `keyring::Entry` on every call, so each check
/// opens a new D-Bus connection to the Secret Service and negotiates an
/// encrypted session over it. A flat 3s poll meant 28,800 of those a day from a
/// daemon that had nothing to do; the ceiling cuts that by 80%.
///
/// The ceiling stays low because the sleep is also the worst-case login →
/// mount latency for anything that does *not* poke systemd: front-ends restart
/// the unit on login (`service::enable_start`), which interrupts the sleep
/// immediately, but a hand-run `pdfs daemon` has no such wake-up path.
fn login_poll_delay(attempts: u32) -> std::time::Duration {
const BASE_SECS: u64 = 3;
const MAX_SECS: u64 = 15;
// `checked_shl` rather than `<<`: the daemon can sit unauthenticated for
// weeks, and a shift past the width of the type is a panic, not a big number.
let factor = 1u64.checked_shl(attempts).unwrap_or(u64::MAX);
std::time::Duration::from_secs(BASE_SECS.saturating_mul(factor).min(MAX_SECS))
}
/// Block until a session is stored and unlocked, backing off between checks.
///
/// `load` and `sleep` are parameters rather than direct calls so the backoff
/// schedule can be tested without a keyring and without real time passing.
fn wait_for_session<L, S>(mut load: L, mut sleep: S) -> Result<()>
where
L: FnMut() -> std::result::Result<(), pdfs_core::Error>,
S: FnMut(std::time::Duration),
{
let mut attempts: u32 = 0;
loop {
match load() {
Ok(()) => return Ok(()),
Err(pdfs_core::Error::NotLoggedIn) => {
let delay = login_poll_delay(attempts);
// Say it once at INFO. Repeating it every interval buried the
// journal in tens of thousands of identical lines a day.
if attempts == 0 {
tracing::info!("not logged in; waiting for a session…");
} else {
tracing::debug!(delay_secs = delay.as_secs(), "still not logged in");
}
sleep(delay);
attempts = attempts.saturating_add(1);
}
Err(pdfs_core::Error::Locked) => {
let delay = login_poll_delay(attempts);
if attempts == 0 {
tracing::info!("account is locked; waiting for `pdfs unlock`…");
} else {
tracing::debug!(delay_secs = delay.as_secs(), "account still locked");
}
sleep(delay);
attempts = attempts.saturating_add(1);
}
Err(e) => return Err(e.into()),
}
}
}
/// Run the daemon: the auto-mount loop. Waits for a stored login, mounts, and keeps
/// the mount alive: a clean stop (SIGTERM via `systemctl --user stop`) exits 0;
/// an external unmount triggers a remount; errors back off and retry. This is
/// the entry point for the systemd user service.
pub fn run(mountpoint: Option<PathBuf>) -> Result<()> {
let state_dir = AppDirs::new()?.state_dir();
// A failure an earlier daemon recorded is not this one's.
pdfs_core::mountfail::clear(&state_dir);
let mut failure: Option<pdfs_core::mountfail::MountFailure> = None;
loop {
// Wait until a session is stored. The GUI enables this service on login,
// but the service may also start at boot before the user has logged in.
wait_for_session(auth::ready, pdfs_fuse::idle_sleep)?;
let outcome = mount_once(mountpoint.clone());
if outcome.is_ok() {
// The mount came up, so the next failure starts a new run of them.
failure = None;
}
match outcome {
Ok(pdfs_fuse::MountOutcome::Shutdown) => {
tracing::info!("daemon stopping");
return Ok(());
}
Ok(pdfs_fuse::MountOutcome::ResumeStored) => {
tracing::info!("resuming the session stored in the keyring");
}
Ok(pdfs_fuse::MountOutcome::Unmounted) => {
tracing::warn!("mount ended externally; remounting in 2s");
pdfs_fuse::idle_sleep(std::time::Duration::from_secs(2));
}
Err(e) => {
// `{:#}` so the whole anyhow chain lands in the log — the top
// context alone ("mount failed") never says *why*.
let error = format!("{e:#}");
let now = unix_now();
let attempts = failure.as_ref().map_or(1, |f| f.attempts.saturating_add(1));
let delay = mount_retry_schedule(&e, attempts);
match delay {
Some(delay) => tracing::error!(
error,
attempts,
retry_secs = delay.as_secs(),
"mount failed; retrying"
),
None => tracing::error!(
error,
attempts,
"account keys could not open My Files; waiting for service restart"
),
}
let record = pdfs_core::mountfail::MountFailure {
error: error.clone(),
since: failure.as_ref().map_or(now, |f| f.since),
attempts,
next_attempt: now + delay.map_or(0, |delay| delay.as_secs() as i64),
awaiting_keys: delay.is_none(),
not_empty: not_empty_cause(&e),
};
if let Err(e) = pdfs_core::mountfail::record(&state_dir, &record) {
tracing::warn!(error = %e, "could not record the mount failure");
}
pdfs_fuse::notify_status(&format!("Mount failing: {error}"));
failure = Some(record);
// Retry and a successful login restart the service. Keep the
// watchdog alive while parked without contacting Proton.
match delay {
Some(delay) => pdfs_fuse::idle_sleep(delay),
None => return pdfs_fuse::wait_for_restart().context("wait for key recovery"),
}
}
}
}
}
/// The folder in the way, when `error` is a mount refused over a folder that
/// already has files in it. The refusal travels inside an `io::Error`, whose
/// `source` skips the error it wraps, so each link is unwrapped by hand.
fn not_empty_cause(error: &anyhow::Error) -> Option<pdfs_core::mountpoint::NotEmpty> {
error.chain().find_map(|cause| {
cause
.downcast_ref::<pdfs_core::mountpoint::NotEmpty>()
.or_else(|| {
cause
.downcast_ref::<std::io::Error>()?
.get_ref()?
.downcast_ref::<pdfs_core::mountpoint::NotEmpty>()
})
.cloned()
})
}
fn mount_retry_schedule(error: &anyhow::Error, attempts: u32) -> Option<std::time::Duration> {
let root = error.chain().find_map(|cause| {
cause
.downcast_ref::<std::io::Error>()?
.get_ref()?
.downcast_ref::<pdfs_core::mountfail::RootLookup>()
});
if root.is_some_and(|root| root.needs_account_keys()) {
None
} else {
Some(mount_retry_delay(attempts))
}
}
/// How long to wait before mount attempt `attempts + 1`, after `attempts`
/// failures in a row.
///
/// Doubles from 5 s to a 2-minute ceiling. A flat 5 s retry sent about four
/// requests to Proton per attempt, tens of thousands a day from an account
/// whose mount fails on a key, which no retry fixes (`docs/BUGS.md` B263). The
/// ceiling stays at minutes because a cold start without a network fails the
/// same way, and must mount soon after the network returns.
fn mount_retry_delay(attempts: u32) -> std::time::Duration {
const BASE_SECS: u64 = 5;
const MAX_SECS: u64 = 120;
let factor = 1u64
.checked_shl(attempts.saturating_sub(1))
.unwrap_or(u64::MAX);
std::time::Duration::from_secs(BASE_SECS.saturating_mul(factor).min(MAX_SECS))
}
/// One mount run: resume the session, mount, and block until the mount ends
/// (clean shutdown or external unmount). Returns the [`MountOutcome`] so the
/// daemon loop can decide whether to exit or remount.
pub fn mount_once(mountpoint: Option<PathBuf>) -> Result<pdfs_fuse::MountOutcome> {
let dirs = AppDirs::new()?;
dirs.ensure()?;
let config = dirs.load_config();
// An explicit `--mountpoint` wins; otherwise honor the Settings-page choice
// (config), falling back to the default location.
let mountpoint = mountpoint.unwrap_or_else(|| dirs.resolved_mountpoint(&config));
// Hydrating a large account and remounting its folders can outlast the
// unit's watchdog before the supervisor sends its first ping (B279).
pdfs_fuse::stretch_watchdog_for_startup();
pdfs_fuse::prepare_mountpoint(&mountpoint)
.with_context(|| format!("create mountpoint {}", mountpoint.display()))?;
let username = auth::load().map(|s| s.username).unwrap_or_default();
// The daemon owns the unified DB (single writer). Open it here so the content
// cache and the mount share one handle: the cache uses its `cache_entries`
// table as the LRU index, the mount uses it for nodes/search/event cursor.
let db = Arc::new(Db::open(&dirs.db_path()).context("open cache db")?);
let cache = ContentCache::open(
dirs.content_cache_dir(),
dirs.pins_path(),
config.resolved_cache_budget(),
db.clone(),
)
.context("open content cache")?;
let control_socket = dirs.control_socket();
// Multi-threaded runtime: its worker threads keep servicing async SDK calls
// while the main thread is parked inside the blocking FUSE session loop.
let rt = tokio::runtime::Runtime::new()?;
let (client, session) = rt
.block_on(auth::resume_client())
.context("resume session (run `pdfs login` first)")?;
// Token updates are persisted automatically in real-time. The SDK session has
// a token refresh callback registered during `resume_client` that writes updated
// credentials back to the OS keyring immediately upon rotation. This prevents
// the system keyring from holding stale refresh tokens even if the daemon crashes,
// the system is suspended, or the network changes.
let handle = rt.handle().clone();
let result = pdfs_fuse::mount(
client,
handle,
&mountpoint,
cache,
&control_socket,
db,
pdfs_fuse::MountOptions {
username,
gallery_session: Some(session.clone()),
sweep_mode: config.resolved_conflict_sweep(),
upload_limit: config.upload_limit.unwrap_or(0),
download_limit: config.download_limit.unwrap_or(0),
local_first: config.local_first.unwrap_or(true),
},
);
// Last chance for a rotation the keyring refused when it happened. Only
// that: by now the keyring may hold a newer login, the one this stop was
// restarted for, and the tokens of this session would overwrite it.
if let Err(e) = auth::persist(&session) {
tracing::error!(
error = %e,
"could not save the refreshed session tokens; the next start may need `pdfs login`"
);
}
release_runtime(rt, matches!(result, Ok(pdfs_fuse::MountOutcome::Shutdown)));
let outcome = result.context("mount failed")?;
Ok(outcome)
}
/// Let go of a mount's runtime once the mount has ended.
///
/// On a stop the process exits right after, so the runtime is left running
/// for it to end with. Shutting it down first broke every thread the mount
/// does not join, such as a size lookup or a profile backup a request started
/// during the stop: its next call to Drive panicked with "A Tokio 1.x context
/// was found, but it is being shutdown" (`docs/BUGS.md` B276). A mount that
/// is about to be tried again does shut it down, because a new runtime
/// replaces it. Dropping it would wait for every blocking task, however long;
/// a call still stuck on Drive would hold the retry (B165).
fn release_runtime(rt: tokio::runtime::Runtime, exiting: bool) {
if exiting {
std::mem::forget(rt);
} else {
rt.shutdown_timeout(std::time::Duration::from_secs(2));
}
}
fn unix_now() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
#[cfg(test)]
mod release_runtime_tests {
use super::*;
use std::time::Duration;
/// A thread the mount never joined still reaches Drive after a stop. It
/// used to panic on its first timer once the runtime was shut down.
#[test]
fn a_thread_left_running_at_a_stop_can_still_use_the_runtime() {
let rt = tokio::runtime::Runtime::new().unwrap();
let handle = rt.handle().clone();
let (released_tx, released_rx) = std::sync::mpsc::channel();
let straggler = std::thread::spawn(move || {
released_rx.recv().unwrap();
handle.block_on(async {
tokio::time::sleep(Duration::from_millis(1)).await;
7
})
});
release_runtime(rt, true);
released_tx.send(()).unwrap();
assert_eq!(straggler.join().expect("the thread must not panic"), 7);
}
#[test]
fn a_mount_tried_again_shuts_its_runtime_down() {
let rt = tokio::runtime::Runtime::new().unwrap();
let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
rt.spawn(async move {
let _done = done_tx;
std::future::pending::<()>().await;
});
release_runtime(rt, false);
// The task is dropped with the runtime, and its sender with it.
assert_eq!(
done_rx.recv_timeout(Duration::from_secs(5)),
Err(std::sync::mpsc::RecvTimeoutError::Disconnected)
);
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::*;
/// The mount retry backs off from 5 s to a ceiling of minutes, rather than
/// asking Proton every 5 s forever (`docs/BUGS.md` B263).
#[test]
fn a_failing_mount_backs_off_to_a_ceiling() {
let secs: Vec<u64> = (1..=8).map(|n| mount_retry_delay(n).as_secs()).collect();
assert_eq!(secs, [5, 10, 20, 40, 80, 120, 120, 120]);
assert_eq!(mount_retry_delay(u32::MAX).as_secs(), 120);
}
#[test]
fn cold_root_key_failures_wait_for_a_restart() {
use pdfs_core::proton_sdk::{ProtonError, crypto::CryptoError};
for (cause, parked) in [
(ProtonError::KeysLocked, true),
(CryptoError::Decrypt("missing key".into()).into(), true),
(CryptoError::Decrypt("malformed data".into()).into(), false),
(ProtonError::invalid_operation("missing key"), false),
] {
let io = std::io::Error::other(pdfs_core::mountfail::RootLookup(cause));
let error = anyhow::Error::new(io).context("mount failed");
assert_eq!(mount_retry_schedule(&error, 1).is_none(), parked);
}
let io = std::io::Error::from(std::io::ErrorKind::NetworkUnreachable);
assert_eq!(
mount_retry_schedule(&io.into(), 1),
Some(mount_retry_delay(1))
);
}
/// A refusal over a folder with files in it reaches the failure record
/// through the `io::Error` and the context around it (`docs/BUGS.md` B277).
#[test]
fn a_mount_refused_over_files_is_recorded_as_such() {
let found = pdfs_core::mountpoint::NotEmpty {
path: PathBuf::from("/home/you/ProtonDrive"),
entries: vec!["Work".into()],
count: 1,
};
let error =
anyhow::Error::new(std::io::Error::other(found.clone())).context("mount failed");
assert_eq!(not_empty_cause(&error), Some(found));
let other =
anyhow::Error::new(std::io::Error::other("missing key")).context("mount failed");
assert_eq!(not_empty_cause(&other), None);
}
#[test]
fn poll_delay_doubles_then_holds_at_the_ceiling() {
assert_eq!(login_poll_delay(0), Duration::from_secs(3));
assert_eq!(login_poll_delay(1), Duration::from_secs(6));
assert_eq!(login_poll_delay(2), Duration::from_secs(12));
assert_eq!(login_poll_delay(3), Duration::from_secs(15));
assert_eq!(login_poll_delay(4), Duration::from_secs(15));
// A daemon left unauthenticated for weeks reaches attempt counts well
// past the width of the shift; that must cap, not panic.
assert_eq!(login_poll_delay(64), Duration::from_secs(15));
assert_eq!(login_poll_delay(u32::MAX), Duration::from_secs(15));
}
#[test]
fn waiting_for_a_session_stops_hammering_the_keyring() {
let mut checks_left = 20;
let mut slept: Vec<Duration> = Vec::new();
wait_for_session(
|| {
if checks_left == 0 {
Ok(())
} else {
checks_left -= 1;
Err(pdfs_core::Error::NotLoggedIn)
}
},
|delay| slept.push(delay),
)
.unwrap();
assert_eq!(slept.len(), 20, "one wait per failed check");
assert!(
slept.windows(2).all(|w| w[1] >= w[0]),
"the interval must never shrink: {slept:?}"
);
// The point of the change. Every check is a fresh D-Bus session against
// the Secret Service, so 20 of them must not fit inside a single minute
// the way a flat 3s poll did.
let total: Duration = slept.iter().sum();
assert!(
total >= Duration::from_secs(4 * 60),
"20 checks should span at least 4 minutes, spanned {total:?}"
);
}
#[test]
fn a_locked_account_is_waited_on_until_it_is_unlocked() {
let mut checks = vec![
Ok(()),
Err(pdfs_core::Error::Locked),
Err(pdfs_core::Error::NotLoggedIn),
Err(pdfs_core::Error::Locked),
];
let mut slept = 0;
wait_for_session(|| checks.pop().unwrap(), |_| slept += 1).unwrap();
assert_eq!(slept, 3, "locked and signed-out are both waited out");
}
#[test]
fn a_stored_session_is_not_waited_for_at_all() {
let mut slept = 0;
wait_for_session(|| Ok(()), |_| slept += 1).unwrap();
assert_eq!(slept, 0);
}
}
+28
View File
@@ -0,0 +1,28 @@
[package]
name = "pdfs-drive"
version.workspace = true
edition.workspace = true
license.workspace = true
authors.workspace = true
rust-version.workspace = true
repository.workspace = true
homepage.workspace = true
description = "The Proton Drive calls the Linux client makes, behind a trait"
[features]
# FakeDrive and the simulation RNG, for tests in this and other crates.
sim = ["dep:parking_lot", "dep:tokio", "dep:pdfs-store"]
[dependencies]
pdfs-core.workspace = true
proton-drive-rs.workspace = true
tracing.workspace = true
pdfs-store = { workspace = true, optional = true }
async-trait.workspace = true
futures.workspace = true
parking_lot = { workspace = true, optional = true }
sha1.workspace = true
tokio = { workspace = true, optional = true }
[dev-dependencies]
tokio.workspace = true
+597
View File
@@ -0,0 +1,597 @@
//! A [`DriveApi`] that counts and times every call it forwards.
//!
//! Wrapping the client in [`Counted`] answers "what is the daemon asking Drive,
//! and how long does Drive take" without a debugger or a log at debug level:
//! [`CallStats::snapshot`] gives, per kind of call, how many were made, how
//! many failed, and their total and longest time. The diagnostics report shows
//! it.
//!
//! A streaming call (a batch move, restore or delete) is counted once when it
//! starts. Its time is not measured, because the stream outlives the call.
use std::io::{Read, Write};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use async_trait::async_trait;
use proton_drive_rs::proton_sdk::account::Quota;
use proton_drive_rs::proton_sdk::error::Result;
use proton_drive_rs::proton_sdk::ids::{DriveEventId, NodeUid, ShareId};
use proton_drive_rs::{
AvailableNameTarget, Device, DeviceType, DriveEvent, DriveEventScopeId, Node, NodeMoveItem,
Thumbnail, ThumbnailType, TrashedNode,
};
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
/// Every kind of call [`DriveApi`] makes, one per method.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DriveCall {
GetMyFilesFolder,
ContextShareId,
GetNode,
EnumerateNodes,
EnumerateNodesLight,
EnumerateChildren,
EnumerateEvents,
InvalidateCaches,
CreateFolder,
UploadFile,
UploadFileFrom,
UploadFileReplacingDraft,
UploadNewRevision,
OpenRevision,
DownloadThumbnail,
DownloadFile,
DownloadRevision,
RenameNode,
MoveNode,
CopyNode,
GetAvailableName,
MoveNodes,
TrashNodes,
RestoreNodes,
RestoreNodesStreaming,
DeleteNodes,
EnumerateTrash,
EmptyTrash,
EnumerateTrashedNodes,
Quota,
EnumerateDevices,
CreateDevice,
}
impl DriveCall {
pub const ALL: [DriveCall; 32] = [
DriveCall::GetMyFilesFolder,
DriveCall::ContextShareId,
DriveCall::GetNode,
DriveCall::EnumerateNodes,
DriveCall::EnumerateNodesLight,
DriveCall::EnumerateChildren,
DriveCall::EnumerateEvents,
DriveCall::InvalidateCaches,
DriveCall::CreateFolder,
DriveCall::UploadFile,
DriveCall::UploadFileFrom,
DriveCall::UploadFileReplacingDraft,
DriveCall::UploadNewRevision,
DriveCall::OpenRevision,
DriveCall::DownloadThumbnail,
DriveCall::DownloadFile,
DriveCall::DownloadRevision,
DriveCall::RenameNode,
DriveCall::MoveNode,
DriveCall::CopyNode,
DriveCall::GetAvailableName,
DriveCall::MoveNodes,
DriveCall::TrashNodes,
DriveCall::RestoreNodes,
DriveCall::RestoreNodesStreaming,
DriveCall::DeleteNodes,
DriveCall::EnumerateTrash,
DriveCall::EmptyTrash,
DriveCall::EnumerateTrashedNodes,
DriveCall::Quota,
DriveCall::EnumerateDevices,
DriveCall::CreateDevice,
];
/// The name the diagnostics report shows: the client method's own.
pub fn name(self) -> &'static str {
match self {
DriveCall::GetMyFilesFolder => "get_my_files_folder",
DriveCall::ContextShareId => "context_share_id",
DriveCall::GetNode => "get_node",
DriveCall::EnumerateNodes => "enumerate_nodes",
DriveCall::EnumerateNodesLight => "enumerate_nodes_light",
DriveCall::EnumerateChildren => "enumerate_folder_children_node_uids",
DriveCall::EnumerateEvents => "enumerate_events",
DriveCall::InvalidateCaches => "invalidate_caches_for_event",
DriveCall::CreateFolder => "create_folder",
DriveCall::UploadFile => "upload_file",
DriveCall::UploadFileFrom => "upload_file_from",
DriveCall::UploadFileReplacingDraft => "upload_file_replacing_draft_from",
DriveCall::UploadNewRevision => "upload_new_revision_from",
DriveCall::OpenRevision => "open_revision",
DriveCall::DownloadThumbnail => "download_thumbnail",
DriveCall::DownloadFile => "download_file_to",
DriveCall::DownloadRevision => "download_revision_to",
DriveCall::RenameNode => "rename_node",
DriveCall::MoveNode => "move_node",
DriveCall::CopyNode => "copy_node",
DriveCall::GetAvailableName => "get_available_name",
DriveCall::MoveNodes => "move_nodes_streaming",
DriveCall::TrashNodes => "trash_nodes",
DriveCall::RestoreNodes => "restore_nodes",
DriveCall::RestoreNodesStreaming => "restore_nodes_streaming",
DriveCall::DeleteNodes => "delete_nodes_streaming",
DriveCall::EnumerateTrash => "enumerate_trash_node_uids",
DriveCall::EmptyTrash => "empty_trash",
DriveCall::EnumerateTrashedNodes => "enumerate_trashed_nodes_light",
DriveCall::Quota => "quota",
DriveCall::EnumerateDevices => "enumerate_devices",
DriveCall::CreateDevice => "create_device",
}
}
}
/// One kind of call, as [`CallStats::snapshot`] reports it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CallStat {
pub call: DriveCall,
pub count: u64,
pub errors: u64,
pub total: Duration,
pub longest: Duration,
}
#[derive(Default)]
struct Counter {
count: AtomicU64,
errors: AtomicU64,
total_us: AtomicU64,
longest_us: AtomicU64,
}
/// The counts behind a [`Counted`] drive, shared with whoever reports them.
pub struct CallStats {
counters: [Counter; DriveCall::ALL.len()],
}
impl Default for CallStats {
fn default() -> Self {
Self {
counters: std::array::from_fn(|_| Counter::default()),
}
}
}
impl CallStats {
fn record(&self, call: DriveCall, failed: bool, took: Option<Duration>) {
let counter = &self.counters[call as usize];
counter.count.fetch_add(1, Ordering::Relaxed);
if failed {
counter.errors.fetch_add(1, Ordering::Relaxed);
}
if let Some(took) = took {
let us = u64::try_from(took.as_micros()).unwrap_or(u64::MAX);
counter.total_us.fetch_add(us, Ordering::Relaxed);
counter.longest_us.fetch_max(us, Ordering::Relaxed);
}
}
/// Every kind of call made at least once, in [`DriveCall::ALL`] order.
pub fn snapshot(&self) -> Vec<CallStat> {
DriveCall::ALL
.iter()
.filter_map(|&call| {
let counter = &self.counters[call as usize];
let count = counter.count.load(Ordering::Relaxed);
(count > 0).then(|| CallStat {
call,
count,
errors: counter.errors.load(Ordering::Relaxed),
total: Duration::from_micros(counter.total_us.load(Ordering::Relaxed)),
longest: Duration::from_micros(counter.longest_us.load(Ordering::Relaxed)),
})
})
.collect()
}
}
/// A [`DriveApi`] that forwards to `inner` and records every call in `stats`.
pub struct Counted {
inner: Arc<dyn DriveApi>,
stats: Arc<CallStats>,
}
impl Counted {
pub fn new(inner: Arc<dyn DriveApi>, stats: Arc<CallStats>) -> Self {
Self { inner, stats }
}
async fn timed<T>(
&self,
call: DriveCall,
future: impl std::future::Future<Output = Result<T>>,
) -> Result<T> {
let started = Instant::now();
let result = future.await;
self.stats
.record(call, result.is_err(), Some(started.elapsed()));
result
}
}
#[async_trait]
impl DriveApi for Counted {
async fn get_my_files_folder(&self) -> Result<Node> {
self.timed(
DriveCall::GetMyFilesFolder,
self.inner.get_my_files_folder(),
)
.await
}
async fn context_share_id(&self, uid: &NodeUid) -> Result<ShareId> {
self.timed(DriveCall::ContextShareId, self.inner.context_share_id(uid))
.await
}
async fn get_node(&self, uid: &NodeUid) -> Result<Option<Node>> {
self.timed(DriveCall::GetNode, self.inner.get_node(uid))
.await
}
async fn enumerate_nodes(&self, uids: &[NodeUid]) -> Result<Vec<Node>> {
self.timed(DriveCall::EnumerateNodes, self.inner.enumerate_nodes(uids))
.await
}
async fn enumerate_nodes_light(&self, uids: &[NodeUid]) -> Result<Vec<Node>> {
self.timed(
DriveCall::EnumerateNodesLight,
self.inner.enumerate_nodes_light(uids),
)
.await
}
async fn enumerate_folder_children_node_uids(
&self,
folder_uid: &NodeUid,
) -> Result<Vec<NodeUid>> {
self.timed(
DriveCall::EnumerateChildren,
self.inner.enumerate_folder_children_node_uids(folder_uid),
)
.await
}
async fn enumerate_events(
&self,
scope: &DriveEventScopeId,
cursor: Option<&DriveEventId>,
) -> Result<Vec<DriveEvent>> {
self.timed(
DriveCall::EnumerateEvents,
self.inner.enumerate_events(scope, cursor),
)
.await
}
async fn invalidate_caches_for_event(&self, event: &DriveEvent) -> Result<()> {
self.timed(
DriveCall::InvalidateCaches,
self.inner.invalidate_caches_for_event(event),
)
.await
}
async fn create_folder(
&self,
parent_uid: &NodeUid,
name: &str,
last_modification_time: Option<i64>,
) -> Result<NodeUid> {
self.timed(
DriveCall::CreateFolder,
self.inner
.create_folder(parent_uid, name, last_modification_time),
)
.await
}
async fn upload_file(
&self,
parent_uid: &NodeUid,
name: &str,
media_type: &str,
contents: &[u8],
) -> Result<NodeUid> {
self.timed(
DriveCall::UploadFile,
self.inner
.upload_file(parent_uid, name, media_type, contents),
)
.await
}
async fn upload_file_from_dyn(
&self,
parent_uid: &NodeUid,
name: &str,
media_type: &str,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
aead: bool,
) -> Result<NodeUid> {
self.timed(
DriveCall::UploadFileFrom,
self.inner.upload_file_from_dyn(
parent_uid,
name,
media_type,
reader,
intended_size,
thumbnails,
last_modification_time,
aead,
),
)
.await
}
async fn upload_file_replacing_draft_from_dyn(
&self,
parent_uid: &NodeUid,
name: &str,
media_type: &str,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
aead: bool,
) -> Result<NodeUid> {
self.timed(
DriveCall::UploadFileReplacingDraft,
self.inner.upload_file_replacing_draft_from_dyn(
parent_uid,
name,
media_type,
reader,
intended_size,
thumbnails,
last_modification_time,
aead,
),
)
.await
}
async fn upload_new_revision_from_dyn(
&self,
file_uid: &NodeUid,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
) -> Result<()> {
self.timed(
DriveCall::UploadNewRevision,
self.inner.upload_new_revision_from_dyn(
file_uid,
reader,
intended_size,
thumbnails,
last_modification_time,
),
)
.await
}
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
self.timed(DriveCall::OpenRevision, self.inner.open_revision(uid))
.await
}
async fn download_thumbnail(
&self,
uid: &NodeUid,
thumbnail_type: ThumbnailType,
) -> Result<Option<Vec<u8>>> {
self.timed(
DriveCall::DownloadThumbnail,
self.inner.download_thumbnail(uid, thumbnail_type),
)
.await
}
async fn download_file_to_dyn(
&self,
uid: &NodeUid,
output: &mut (dyn Write + Send),
) -> Result<()> {
self.timed(
DriveCall::DownloadFile,
self.inner.download_file_to_dyn(uid, output),
)
.await
}
async fn download_revision_to_dyn(
&self,
file_uid: &NodeUid,
revision_id: &str,
writer: &mut (dyn Write + Send),
) -> Result<()> {
self.timed(
DriveCall::DownloadRevision,
self.inner
.download_revision_to_dyn(file_uid, revision_id, writer),
)
.await
}
async fn rename_node(
&self,
uid: &NodeUid,
new_name: &str,
new_media_type: Option<&str>,
) -> Result<()> {
self.timed(
DriveCall::RenameNode,
self.inner.rename_node(uid, new_name, new_media_type),
)
.await
}
async fn move_node(&self, uid: &NodeUid, new_parent: &NodeUid) -> Result<()> {
self.timed(DriveCall::MoveNode, self.inner.move_node(uid, new_parent))
.await
}
async fn copy_node(
&self,
uid: &NodeUid,
new_parent: &NodeUid,
name: Option<&str>,
) -> Result<NodeUid> {
self.timed(
DriveCall::CopyNode,
self.inner.copy_node(uid, new_parent, name),
)
.await
}
async fn get_available_name(
&self,
parent_uid: &NodeUid,
name: &str,
target: AvailableNameTarget,
) -> Result<String> {
self.timed(
DriveCall::GetAvailableName,
self.inner.get_available_name(parent_uid, name, target),
)
.await
}
fn move_nodes_streaming<'a>(
&'a self,
items: Vec<NodeMoveItem>,
new_parent: NodeUid,
) -> OutcomeStream<'a> {
self.stats.record(DriveCall::MoveNodes, false, None);
self.inner.move_nodes_streaming(items, new_parent)
}
async fn trash_nodes(&self, uids: &[NodeUid]) -> Result<NodeOutcomes> {
self.timed(DriveCall::TrashNodes, self.inner.trash_nodes(uids))
.await
}
async fn restore_nodes(&self, uids: &[NodeUid]) -> Result<NodeOutcomes> {
self.timed(DriveCall::RestoreNodes, self.inner.restore_nodes(uids))
.await
}
fn restore_nodes_streaming<'a>(&'a self, uids: &[NodeUid]) -> OutcomeStream<'a> {
self.stats
.record(DriveCall::RestoreNodesStreaming, false, None);
self.inner.restore_nodes_streaming(uids)
}
fn delete_nodes_streaming<'a>(&'a self, uids: &[NodeUid]) -> OutcomeStream<'a> {
self.stats.record(DriveCall::DeleteNodes, false, None);
self.inner.delete_nodes_streaming(uids)
}
async fn enumerate_trash_node_uids(&self) -> Result<Vec<NodeUid>> {
self.timed(
DriveCall::EnumerateTrash,
self.inner.enumerate_trash_node_uids(),
)
.await
}
async fn empty_trash(&self) -> Result<()> {
self.timed(DriveCall::EmptyTrash, self.inner.empty_trash())
.await
}
async fn enumerate_trashed_nodes_light(&self, uids: &[NodeUid]) -> Result<Vec<TrashedNode>> {
self.timed(
DriveCall::EnumerateTrashedNodes,
self.inner.enumerate_trashed_nodes_light(uids),
)
.await
}
async fn quota(&self) -> Result<Quota> {
self.timed(DriveCall::Quota, self.inner.quota()).await
}
async fn enumerate_devices(&self) -> Result<Vec<Device>> {
self.timed(DriveCall::EnumerateDevices, self.inner.enumerate_devices())
.await
}
async fn create_device(&self, name: &str, device_type: DeviceType) -> Result<Device> {
self.timed(
DriveCall::CreateDevice,
self.inner.create_device(name, device_type),
)
.await
}
fn landing(&self, uid: &NodeUid) {
self.inner.landing(uid);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_call_has_its_own_counter() {
for (index, call) in DriveCall::ALL.iter().enumerate() {
assert_eq!(*call as usize, index, "{} is out of order", call.name());
}
let names: std::collections::HashSet<_> =
DriveCall::ALL.iter().map(|call| call.name()).collect();
assert_eq!(names.len(), DriveCall::ALL.len());
}
#[test]
fn a_call_is_counted_with_its_failures_and_time() {
let stats = CallStats::default();
stats.record(DriveCall::GetNode, false, Some(Duration::from_millis(30)));
stats.record(DriveCall::GetNode, true, Some(Duration::from_millis(10)));
stats.record(DriveCall::DeleteNodes, false, None);
assert_eq!(
stats.snapshot(),
vec![
CallStat {
call: DriveCall::GetNode,
count: 2,
errors: 1,
total: Duration::from_millis(40),
longest: Duration::from_millis(30),
},
CallStat {
call: DriveCall::DeleteNodes,
count: 1,
errors: 0,
total: Duration::ZERO,
longest: Duration::ZERO,
},
]
);
}
}
+46
View File
@@ -0,0 +1,46 @@
//! The SHA-1 digests Drive keys content on.
use std::io::Read;
use pdfs_core::{CoreError, CoreResult};
use sha1::{Digest, Sha1};
/// The lowercase-hex SHA-1 of everything `reader` yields — the digest Proton's
/// photo duplicate detection is keyed on.
pub fn sha1_of(reader: &mut (dyn Read + Send)) -> CoreResult<String> {
let mut hasher = Sha1::new();
let mut buffer = vec![0u8; 256 * 1024];
loop {
let read = reader
.read(&mut buffer)
.map_err(|e| CoreError::invalid(format!("read failed: {e}")))?;
if read == 0 {
break;
}
hasher.update(&buffer[..read]);
}
Ok(hex_lower(&hasher.finalize()))
}
/// `bytes` as lowercase hex.
pub fn hex_lower(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
out.push_str(&format!("{byte:02x}"));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sha1_of_an_empty_reader_is_the_well_known_digest() {
let mut empty: &[u8] = &[];
assert_eq!(
sha1_of(&mut empty).unwrap(),
"da39a3ee5e6b4b0d3255bfef95601890afd80709"
);
}
}
@@ -25,24 +25,30 @@ use async_trait::async_trait;
use futures::StreamExt as _;
use futures::stream::BoxStream;
use proton_drive_rs::proton_sdk::account::Quota;
use proton_drive_rs::proton_sdk::error::Result;
use proton_drive_rs::proton_sdk::ids::{DriveEventId, NodeUid};
use proton_drive_rs::proton_sdk::api::ResponseCode;
use proton_drive_rs::proton_sdk::error::{ProtonError, Result};
use proton_drive_rs::proton_sdk::ids::{DriveEventId, LinkId, NodeUid, ShareId, VolumeId};
use proton_drive_rs::{
AvailableNameTarget, Device, DeviceType, DriveEvent, DriveEventScopeId, Node, NodeMoveItem,
ProtonDriveClient, RevisionReader, Thumbnail,
AvailableNameTarget, Device, DeviceType, DriveEvent, DriveEventScopeId, Node, NodeKind,
NodeMoveItem, ProtonDriveClient, RevisionReader, Thumbnail, ThumbnailType, TrashedNode,
};
pub mod counted;
pub mod digest;
/// One outcome per node of a batch request; see [`ProtonDriveClient::trash_nodes`].
pub(crate) type NodeOutcomes = Vec<(NodeUid, Result<()>)>;
pub type NodeOutcomes = Vec<(NodeUid, Result<()>)>;
/// The outcomes of a streaming batch request, one item per node as it lands.
pub(crate) type OutcomeStream<'a> = BoxStream<'a, Result<(NodeUid, Result<()>)>>;
pub type OutcomeStream<'a> = BoxStream<'a, Result<(NodeUid, Result<()>)>>;
/// Drive as the sync core sees it. See the module documentation.
#[async_trait]
pub(crate) trait DriveApi: Send + Sync {
pub trait DriveApi: Send + Sync {
async fn get_my_files_folder(&self) -> Result<Node>;
async fn context_share_id(&self, uid: &NodeUid) -> Result<ShareId>;
async fn get_node(&self, uid: &NodeUid) -> Result<Option<Node>>;
async fn enumerate_nodes(&self, uids: &[NodeUid]) -> Result<Vec<Node>>;
@@ -116,6 +122,14 @@ pub(crate) trait DriveApi: Send + Sync {
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>>;
/// The file's thumbnail of `thumbnail_type`, or `None` when its revision
/// carries none.
async fn download_thumbnail(
&self,
uid: &NodeUid,
thumbnail_type: ThumbnailType,
) -> Result<Option<Vec<u8>>>;
async fn download_file_to_dyn(
&self,
uid: &NodeUid,
@@ -170,6 +184,23 @@ pub(crate) trait DriveApi: Send + Sync {
async fn enumerate_trash_node_uids(&self) -> Result<Vec<NodeUid>>;
/// Permanently delete everything in the trash.
async fn empty_trash(&self) -> Result<()>;
/// As [`DriveApi::enumerate_nodes_light`], for nodes in the trash, each
/// with the time it was trashed when the server reports one.
async fn enumerate_trashed_nodes_light(&self, uids: &[NodeUid]) -> Result<Vec<TrashedNode>> {
Ok(self
.enumerate_nodes_light(uids)
.await?
.into_iter()
.map(|node| TrashedNode {
node,
trash_time: None,
})
.collect())
}
/// The account's storage, across every Proton product.
async fn quota(&self) -> Result<Quota>;
@@ -183,14 +214,13 @@ pub(crate) trait DriveApi: Send + Sync {
/// `uid` that landed, or retired the create that made `uid`, before the
/// tree has the node, so a simulation can hold it there. Blocks the drain
/// worker it is called on.
#[cfg(test)]
fn landing(&self, _uid: &NodeUid) {}
}
/// The generic signatures of the client, over the object-safe ones above.
impl dyn DriveApi {
#[allow(clippy::too_many_arguments)]
pub(crate) async fn upload_file_from<R: Read + Send>(
pub async fn upload_file_from<R: Read + Send>(
&self,
parent_uid: &NodeUid,
name: &str,
@@ -215,7 +245,7 @@ impl dyn DriveApi {
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn upload_file_replacing_draft_from<R: Read + Send>(
pub async fn upload_file_replacing_draft_from<R: Read + Send>(
&self,
parent_uid: &NodeUid,
name: &str,
@@ -239,7 +269,7 @@ impl dyn DriveApi {
.await
}
pub(crate) async fn upload_new_revision_from<R: Read + Send>(
pub async fn upload_new_revision_from<R: Read + Send>(
&self,
file_uid: &NodeUid,
mut reader: R,
@@ -257,7 +287,7 @@ impl dyn DriveApi {
.await
}
pub(crate) async fn download_file_to<W: Write + Send>(
pub async fn download_file_to<W: Write + Send>(
&self,
uid: &NodeUid,
output: &mut W,
@@ -265,7 +295,7 @@ impl dyn DriveApi {
self.download_file_to_dyn(uid, output).await
}
pub(crate) async fn download_revision_to<W: Write + Send>(
pub async fn download_revision_to<W: Write + Send>(
&self,
file_uid: &NodeUid,
revision_id: &str,
@@ -278,7 +308,7 @@ impl dyn DriveApi {
/// An open revision that block reads are served from; see [`RevisionReader`].
#[async_trait]
pub(crate) trait RevisionRead: Send + Sync {
pub trait RevisionRead: Send + Sync {
/// Plaintext size of the revision.
fn size(&self) -> u64;
@@ -305,6 +335,10 @@ impl RevisionRead for RevisionReader {
#[async_trait]
impl DriveApi for ProtonDriveClient {
async fn context_share_id(&self, uid: &NodeUid) -> Result<ShareId> {
ProtonDriveClient::context_share_id(self, uid).await
}
async fn get_my_files_folder(&self) -> Result<Node> {
ProtonDriveClient::get_my_files_folder(self).await
}
@@ -346,7 +380,13 @@ impl DriveApi for ProtonDriveClient {
name: &str,
last_modification_time: Option<i64>,
) -> Result<NodeUid> {
ProtonDriveClient::create_folder(self, parent_uid, name, last_modification_time).await
ProtonDriveClient::create_folder(
self,
parent_uid,
name,
last_modification_time.and_then(pdfs_core::timestamp::modification_time),
)
.await
}
async fn upload_file(
@@ -378,7 +418,7 @@ impl DriveApi for ProtonDriveClient {
reader,
intended_size,
thumbnails,
last_modification_time,
last_modification_time.and_then(pdfs_core::timestamp::modification_time),
aead,
)
.await
@@ -403,7 +443,7 @@ impl DriveApi for ProtonDriveClient {
reader,
intended_size,
thumbnails,
last_modification_time,
last_modification_time.and_then(pdfs_core::timestamp::modification_time),
aead,
)
.await
@@ -423,7 +463,7 @@ impl DriveApi for ProtonDriveClient {
reader,
intended_size,
thumbnails,
last_modification_time,
last_modification_time.and_then(pdfs_core::timestamp::modification_time),
)
.await
}
@@ -433,6 +473,14 @@ impl DriveApi for ProtonDriveClient {
Ok(Arc::new(reader))
}
async fn download_thumbnail(
&self,
uid: &NodeUid,
thumbnail_type: ThumbnailType,
) -> Result<Option<Vec<u8>>> {
ProtonDriveClient::download_thumbnail(self, uid, thumbnail_type).await
}
async fn download_file_to_dyn(
&self,
uid: &NodeUid,
@@ -510,6 +558,14 @@ impl DriveApi for ProtonDriveClient {
ProtonDriveClient::enumerate_trash_node_uids(self).await
}
async fn enumerate_trashed_nodes_light(&self, uids: &[NodeUid]) -> Result<Vec<TrashedNode>> {
ProtonDriveClient::enumerate_trashed_nodes_light(self, uids).await
}
async fn empty_trash(&self) -> Result<()> {
ProtonDriveClient::empty_trash(self).await
}
async fn quota(&self) -> Result<Quota> {
ProtonDriveClient::quota(self).await
}
@@ -522,3 +578,90 @@ impl DriveApi for ProtonDriveClient {
ProtonDriveClient::create_device(self, name, device_type).await
}
}
/// Whether a failed call failed because Proton could not be reached, rather
/// than because it answered and refused.
///
/// A transport error is the network. So is a request timeout: the SDK reports
/// Proton's own "try again" codes that way, and the daemon's `no_answer` reports its
/// deadline that way. Anything else Proton actually said, and says again on a
/// retry, so it must reach the caller rather than be queued.
pub fn is_network_error(e: &ProtonError) -> bool {
match e {
ProtonError::Transport(_) => true,
ProtonError::Api(api) => {
matches!(
api.code,
ResponseCode::RequestTimeout | ResponseCode::Timeout
)
}
_ => false,
}
}
/// The server revision id of a node's active revision, if it is a file that has
/// one. The stable identity the drain conflict-checks against (see `Baseline` in pdfs-store).
pub fn node_revision_id(node: &Node) -> Option<String> {
match &node.kind {
NodeKind::Folder => None,
NodeKind::File {
active_revision_id, ..
} => active_revision_id.clone(),
}
}
/// The plaintext content SHA-1 of a file node, if its active revision carried one.
/// A download-free content fingerprint the conflict sweep uses to prove two files
/// hold identical bytes before it removes one.
pub fn node_content_sha1(node: &Node) -> Option<String> {
match &node.kind {
NodeKind::Folder => None,
NodeKind::File { content_sha1, .. } => content_sha1.clone(),
}
}
/// Parse a `volume~link` uid display string back into a [`NodeUid`]. Front-ends
/// receive uids as strings over the control socket and pass them back verbatim.
pub fn parse_uid(s: &str) -> Option<NodeUid> {
let (vol, link) = s.split_once('~')?;
if vol.is_empty() || link.is_empty() || link.contains('~') {
return None;
}
Some(NodeUid::new(VolumeId::from(vol), LinkId::from(link)))
}
/// Whether a decrypted remote name can stand as one local path component.
///
/// Drive checks names only when a client creates or renames a node, and only
/// for length, so a name made by another client, or by a server that should
/// not be trusted, can hold anything. Joined onto a local path, a `/` or a `..`
/// in it walks out of the folder it belongs to, and the mirror engine would
/// then write or delete outside the sync root. In the mount, the kernel fails
/// the whole listing with EIO on a single such name (`docs/BUGS.md` B215).
pub fn remote_name_is_safe(name: &str) -> bool {
!name.is_empty()
&& name != "."
&& name != ".."
&& name.len() <= 255
&& !name.contains(['/', '\0'])
}
/// A coarse MIME type guessed from a file name's extension; Proton stores this
/// on the node but an exact value is not required for correctness.
pub fn media_type_for(name: &str) -> &'static str {
let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase());
match ext.as_deref() {
Some("txt" | "md" | "log") => "text/plain",
Some("png") => "image/png",
Some("jpg" | "jpeg") => "image/jpeg",
Some("gif") => "image/gif",
Some("pdf") => "application/pdf",
Some("json") => "application/json",
Some("html" | "htm") => "text/html",
_ => "application/octet-stream",
}
}
/// An in-memory Drive and the seeded randomness the simulations share.
#[cfg(feature = "sim")]
pub mod sim;
@@ -62,15 +62,15 @@ use proton_drive_rs::proton_sdk::ids::{
};
use proton_drive_rs::{
AvailableNameTarget, Device as Computer, DeviceType, DriveEvent, DriveEventScopeId, Node,
NodeKind, NodeMoveItem, RevisionState, Thumbnail,
NodeKind, NodeMoveItem, RevisionState, Thumbnail, ThumbnailType,
};
use sha1::{Digest as _, Sha1};
use super::rng::Rng;
use crate::drive::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
/// The volume every fake node lives on.
pub(crate) const VOLUME: &str = "simvol";
pub const VOLUME: &str = "simvol";
/// How long superseded versions of a node are kept for lagging reads. Longer
/// than any lag a test sets.
@@ -160,6 +160,17 @@ impl Server {
.is_some_and(|remote| remote.file.is_none() && !remote.trashed)
}
fn in_trash(&self, uid: &NodeUid) -> bool {
let mut node = self.current(uid);
while let Some(remote) = node {
if remote.trashed {
return true;
}
node = remote.parent.as_ref().and_then(|uid| self.current(uid));
}
false
}
fn is_below(&self, uid: &NodeUid, ancestor: &NodeUid) -> bool {
let mut cursor = Some(uid.clone());
while let Some(at) = cursor {
@@ -339,19 +350,19 @@ impl Server {
/// An in-memory Drive shared by every simulated client. See the module
/// documentation.
pub(crate) struct FakeDrive {
pub struct FakeDrive {
server: Mutex<Server>,
}
/// A node of [`FakeDrive::tree`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Entry {
pub enum Entry {
Folder,
File(Arc<Vec<u8>>),
}
impl FakeDrive {
pub(crate) fn new() -> Arc<Self> {
pub fn new() -> Arc<Self> {
let root = uid("root");
let mut server = Server {
root: root.clone(),
@@ -359,7 +370,7 @@ impl FakeDrive {
next_link: 0,
next_revision: 0,
events: Vec::new(),
block_pattern: vec![pdfs_core::cache::BLOCK_SIZE],
block_pattern: vec![pdfs_store::cache::BLOCK_SIZE],
max_space: 1 << 40,
devices: Vec::new(),
};
@@ -384,7 +395,7 @@ impl FakeDrive {
}
/// A connection to this Drive for one simulated daemon.
pub(crate) fn client(self: &Arc<Self>, seed: u64, faults: Faults) -> FakeClient {
pub fn client(self: &Arc<Self>, seed: u64, faults: Faults) -> FakeClient {
FakeClient(Arc::new(ClientInner {
drive: self.clone(),
faults: Mutex::new(faults),
@@ -396,6 +407,8 @@ impl FakeDrive {
hold_answer: Mutex::new(None),
hold_trash: Mutex::new(None),
hold_download: Mutex::new(None),
thumbnails: Mutex::new(HashMap::new()),
content_read: AtomicU64::new(0),
hold_any_landing: AtomicBool::new(false),
hold_landing: Mutex::new(None),
drop_after_create: AtomicBool::new(false),
@@ -407,29 +420,30 @@ impl FakeDrive {
lose_read: Mutex::new(None),
unrevised_reads: Mutex::new(None),
hold_listing: Mutex::new(None),
hold_children: Mutex::new(None),
}))
}
/// Plaintext block sizes for content uploaded from now on, cycled with the
/// last one repeating: `[1 MiB, 4 MiB]` makes a short first block.
pub(crate) fn set_block_pattern(&self, pattern: Vec<u64>) {
pub fn set_block_pattern(&self, pattern: Vec<u64>) {
assert!(!pattern.is_empty() && pattern.iter().all(|&size| size > 0));
self.server.lock().block_pattern = pattern;
}
/// The account's storage limit; a limit below what is stored refuses every
/// upload until something is deleted.
pub(crate) fn set_quota(&self, max_space: i64) {
pub fn set_quota(&self, max_space: i64) {
self.server.lock().max_space = max_space;
}
pub(crate) fn root(&self) -> NodeUid {
pub fn root(&self) -> NodeUid {
self.server.lock().root.clone()
}
/// The live tree as Drive has it now, by path below the root: every node
/// that is neither trashed nor below a trashed folder.
pub(crate) fn tree(&self) -> BTreeMap<String, Entry> {
pub fn tree(&self) -> BTreeMap<String, Entry> {
let server = self.server.lock();
let mut tree = BTreeMap::new();
for uid in server.nodes.keys() {
@@ -469,7 +483,7 @@ impl FakeDrive {
/// Every name a node has had in the root, trashed or not, as far back as
/// Drive keeps its versions.
pub(crate) fn names_ever_in_root(&self) -> Vec<String> {
pub fn names_ever_in_root(&self) -> Vec<String> {
let server = self.server.lock();
let mut names: Vec<String> = server
.nodes
@@ -485,7 +499,7 @@ impl FakeDrive {
}
/// The uid at `path` below the root, as Drive has it now.
pub(crate) fn lookup(&self, path: &str) -> Option<NodeUid> {
pub fn lookup(&self, path: &str) -> Option<NodeUid> {
let server = self.server.lock();
let mut at = server.root.clone();
for name in path.split('/').filter(|name| !name.is_empty()) {
@@ -495,23 +509,23 @@ impl FakeDrive {
}
/// Every change Drive has logged, oldest first.
pub(crate) fn event_count(&self) -> usize {
pub fn event_count(&self) -> usize {
self.server.lock().events.len()
}
/// Changes made by another device, straight on the server: what a second
/// client would do, without the daemon that client would need.
pub(crate) fn device(&self) -> Device<'_> {
pub fn device(&self) -> Device<'_> {
Device(self)
}
}
/// See [`FakeDrive::device`].
pub(crate) struct Device<'a>(&'a FakeDrive);
pub struct Device<'a>(&'a FakeDrive);
impl Device<'_> {
/// Write `content` at `path`, as a new file or a new revision of one.
pub(crate) fn write(&self, path: &str, content: &[u8]) -> NodeUid {
pub fn write(&self, path: &str, content: &[u8]) -> NodeUid {
let (parent, name) = split_path(path);
let parent = self
.0
@@ -545,8 +559,33 @@ impl Device<'_> {
}
}
/// Make a folder at `path`.
pub fn mkdir(&self, path: &str) -> NodeUid {
let (parent, name) = split_path(path);
let parent = self
.0
.lookup(parent)
.expect("device mkdir into a missing folder");
let mut server = self.0.server.lock();
assert!(server.live_child_named(&parent, name).is_none());
let uid = server.mint_uid();
let now = now_secs();
server.put(
&uid,
Some(Remote {
parent: Some(parent),
name: name.to_owned(),
trashed: false,
created: now,
modified: now,
file: None,
}),
);
uid
}
/// Move the node at `path` to the trash.
pub(crate) fn trash(&self, path: &str) {
pub fn trash(&self, path: &str) {
let uid = self.0.lookup(path).expect("device trash of a missing node");
let mut server = self.0.server.lock();
let mut remote = server.current(&uid).cloned().expect("live node");
@@ -555,7 +594,7 @@ impl Device<'_> {
}
/// Rename the node at `path` in place.
pub(crate) fn rename(&self, path: &str, new_name: &str) {
pub fn rename(&self, path: &str, new_name: &str) {
let uid = self
.0
.lookup(path)
@@ -577,35 +616,35 @@ struct Lag {
/// The faults and timing of one connection. See the module documentation.
#[derive(Clone, Debug)]
pub(crate) struct Faults {
pub struct Faults {
/// Each request takes a time drawn from this range, in milliseconds.
pub(crate) latency_ms: (u64, u64),
pub latency_ms: (u64, u64),
/// How far behind the present reads are about a node appearing or going
/// to the trash.
pub(crate) listing_lag: Duration,
pub listing_lag: Duration,
/// How far behind the present reads are about a live node's name, folder
/// or revision.
pub(crate) update_lag: Duration,
pub update_lag: Duration,
/// How long a change takes to reach the event feed.
pub(crate) event_delay: Duration,
pub event_delay: Duration,
/// Chance that an event is delivered twice.
pub(crate) duplicate_events: f64,
pub duplicate_events: f64,
/// Chance that two neighbouring events of a page swap places.
pub(crate) reorder_events: f64,
pub reorder_events: f64,
/// Chance that a request never reaches Drive.
pub(crate) fail: f64,
pub fail: f64,
/// Chance that a change Drive made loses its reply.
pub(crate) drop_reply: f64,
pub drop_reply: f64,
/// Chance that a request stalls for [`Faults::stall_for`] and then fails.
pub(crate) stall: f64,
pub(crate) stall_for: Duration,
pub stall: f64,
pub stall_for: Duration,
/// Whether renames and moves send the entity cache's name, as the SDK does.
pub(crate) stale_name_cache: bool,
pub stale_name_cache: bool,
}
impl Faults {
/// No latency and no faults beyond the SDK's own stale name cache.
pub(crate) fn none() -> Self {
pub fn none() -> Self {
Self {
latency_ms: (0, 0),
listing_lag: Duration::ZERO,
@@ -622,7 +661,7 @@ impl Faults {
}
/// A good link: a few milliseconds a request, listings barely behind.
pub(crate) fn lan() -> Self {
pub fn lan() -> Self {
Self {
latency_ms: (2, 15),
listing_lag: Duration::from_millis(50),
@@ -633,7 +672,7 @@ impl Faults {
/// A good link whose event feed is slow and untidy: every echo of our own
/// changes comes late, often twice, often out of order.
pub(crate) fn echoes() -> Self {
pub fn echoes() -> Self {
Self {
event_delay: Duration::from_secs(1),
duplicate_events: 0.3,
@@ -644,7 +683,7 @@ impl Faults {
/// The Wi-Fi of the 2026-10 account runs: slow and lossy, with listings
/// and events well behind.
pub(crate) fn wifi() -> Self {
pub fn wifi() -> Self {
Self {
latency_ms: (60, 400),
listing_lag: Duration::from_millis(800),
@@ -677,6 +716,10 @@ struct ClientInner {
hold_trash: Mutex<Option<Arc<HoldState>>>,
/// The download [`FakeClient::hold_next_download`] is waiting for.
hold_download: Mutex<Option<Arc<HoldState>>>,
/// Thumbnails set by [`FakeClient::set_thumbnail`].
thumbnails: Mutex<HashMap<NodeUid, Vec<u8>>>,
/// File content bytes served, by downloads and ranged reads alike.
content_read: AtomicU64,
/// The landing [`FakeClient::hold_next_landing`] is waiting for.
hold_landing: Mutex<Option<Arc<HoldState>>>,
/// Set by [`FakeClient::hold_next_landing_of_any`]: hold whichever node
@@ -702,6 +745,9 @@ struct ClientInner {
/// The listing [`FakeClient::hold_answer_to_next_listing`] is waiting
/// for, and the file it lists without an active revision.
hold_listing: Mutex<Option<(Arc<HoldState>, NodeUid)>>,
/// The folder whose next listing [`FakeClient::hold_next_children_of`]
/// is waiting for.
hold_children: Mutex<Option<Arc<HoldState>>>,
}
struct HoldState {
@@ -741,11 +787,11 @@ async fn wait_until_released(state: &HoldState) {
/// A call held on its way to or from Drive, from [`FakeClient::hold_next_read`]
/// or [`FakeClient::hold_reply_to_next_create`]. It goes on when this is
/// dropped.
pub(crate) struct Held(Arc<HoldState>);
pub struct Held(Arc<HoldState>);
impl Held {
/// Whether the read has come and is being held.
pub(crate) fn reached(&self) -> bool {
pub fn reached(&self) -> bool {
self.0.reached.load(Ordering::SeqCst)
}
}
@@ -759,32 +805,32 @@ impl Drop for Held {
/// One daemon's connection to a [`FakeDrive`]. Cheap to clone; clones share
/// the link, the faults and the entity cache.
#[derive(Clone)]
pub(crate) struct FakeClient(Arc<ClientInner>);
pub struct FakeClient(Arc<ClientInner>);
impl FakeClient {
pub(crate) fn set_online(&self, online: bool) {
pub fn set_online(&self, online: bool) {
self.0.online.store(online, Ordering::SeqCst);
}
pub(crate) fn set_faults(&self, faults: Faults) {
pub fn set_faults(&self, faults: Faults) {
*self.0.faults.lock() = faults;
}
/// Take the link down as soon as the next file create has been answered,
/// so whatever the daemon asks next goes unanswered.
pub(crate) fn drop_link_after_next_create(&self) {
pub fn drop_link_after_next_create(&self) {
self.0.drop_after_create.store(true, Ordering::SeqCst);
}
/// Make the next file create on Drive and lose its answer, as a link that
/// drops it on the way back does.
pub(crate) fn lose_reply_to_next_create(&self) {
pub fn lose_reply_to_next_create(&self) {
self.0.lose_create_reply.store(true, Ordering::SeqCst);
}
/// Hold the next read of `uid` alone, before it reaches Drive, until the
/// answer is dropped. Only one read is held at a time.
pub(crate) fn hold_next_read(&self, uid: &NodeUid) -> Held {
pub fn hold_next_read(&self, uid: &NodeUid) -> Held {
let state = Arc::new(HoldState {
uid: uid.clone(),
reached: AtomicBool::new(false),
@@ -797,7 +843,7 @@ impl FakeClient {
/// Answer the next read of `uid` alone with what Drive holds now, then
/// hold the answer until it is dropped, as a slow link does. Only one
/// answer is held at a time.
pub(crate) fn hold_answer_to_next_read(&self, uid: &NodeUid) -> Held {
pub fn hold_answer_to_next_read(&self, uid: &NodeUid) -> Held {
let state = Arc::new(HoldState {
uid: uid.clone(),
reached: AtomicBool::new(false),
@@ -807,9 +853,21 @@ impl FakeClient {
Held(state)
}
/// Hold the next listing of the children of `folder`, before it reaches
/// Drive, until the answer is dropped.
pub fn hold_next_children_of(&self, folder: &NodeUid) -> Held {
let state = Arc::new(HoldState {
uid: folder.clone(),
reached: AtomicBool::new(false),
released: AtomicBool::new(false),
});
*self.0.hold_children.lock() = Some(state.clone());
Held(state)
}
/// Hold the next trash of `uid` alone, before it reaches Drive, until the
/// answer is dropped.
pub(crate) fn hold_next_trash(&self, uid: &NodeUid) -> Held {
pub fn hold_next_trash(&self, uid: &NodeUid) -> Held {
let state = Arc::new(HoldState {
uid: uid.clone(),
reached: AtomicBool::new(false),
@@ -821,7 +879,17 @@ impl FakeClient {
/// Hold the next download of `uid`'s content once Drive has answered it,
/// before the bytes reach the daemon, until the answer is dropped.
pub(crate) fn hold_next_download(&self, uid: &NodeUid) -> Held {
/// Give `uid` a server thumbnail, as an upload that carried one would.
pub fn set_thumbnail(&self, uid: &NodeUid, bytes: Vec<u8>) {
self.0.thumbnails.lock().insert(uid.clone(), bytes);
}
/// File content bytes served so far, by whole downloads and ranged reads.
pub fn content_read(&self) -> u64 {
self.0.content_read.load(Ordering::SeqCst)
}
pub fn hold_next_download(&self, uid: &NodeUid) -> Held {
let state = Arc::new(HoldState {
uid: uid.clone(),
reached: AtomicBool::new(false),
@@ -834,7 +902,7 @@ impl FakeClient {
/// Hold the drain once the next upload to `uid` has landed and its blob
/// is let go of, before the tree has the node (`DriveApi::landing`), until
/// the answer is dropped.
pub(crate) fn hold_next_landing(&self, uid: &NodeUid) -> Held {
pub fn hold_next_landing(&self, uid: &NodeUid) -> Held {
let state = Arc::new(HoldState {
uid: uid.clone(),
reached: AtomicBool::new(false),
@@ -846,7 +914,7 @@ impl FakeClient {
/// [`FakeClient::hold_next_landing`] for whichever node lands next, such
/// as a new file, whose uid Drive has not minted yet.
pub(crate) fn hold_next_landing_of_any(&self) -> Held {
pub fn hold_next_landing_of_any(&self) -> Held {
let held = self.hold_next_landing(&uid("*"));
self.0.hold_any_landing.store(true, Ordering::SeqCst);
held
@@ -854,7 +922,7 @@ impl FakeClient {
/// Make the next file create on Drive, then hold its answer until the
/// answer is dropped, as a slow link does.
pub(crate) fn hold_reply_to_next_create(&self) -> Held {
pub fn hold_reply_to_next_create(&self) -> Held {
let state = Arc::new(HoldState {
uid: self.0.drive.root(),
reached: AtomicBool::new(false),
@@ -866,7 +934,7 @@ impl FakeClient {
/// Hold the next file create before it reaches Drive, until the answer
/// is dropped.
pub(crate) fn hold_next_create(&self) -> Held {
pub fn hold_next_create(&self) -> Held {
let state = Arc::new(HoldState {
uid: self.0.drive.root(),
reached: AtomicBool::new(false),
@@ -877,32 +945,28 @@ impl FakeClient {
}
/// Make the next revision of a file on Drive and lose its answer.
pub(crate) fn lose_reply_to_next_revision(&self) {
pub fn lose_reply_to_next_revision(&self) {
self.0.lose_revision_reply.store(true, Ordering::SeqCst);
}
/// Make the next revision of a file on Drive and answer it, then lose the
/// answer to the next read of that file alone, as the read-back after an
/// upload meets on a link that drops it.
pub(crate) fn lose_read_back_of_next_revision(&self) {
pub fn lose_read_back_of_next_revision(&self) {
self.0.lose_revision_read_back.store(true, Ordering::SeqCst);
}
/// Answer the next `reads` reads of file `uid` alone that find it as Drive
/// lists a file whose create it has not committed yet: no active revision,
/// no size.
pub(crate) fn answer_reads_unrevised(&self, uid: &NodeUid, reads: usize) {
pub fn answer_reads_unrevised(&self, uid: &NodeUid, reads: usize) {
*self.0.unrevised_reads.lock() = Some((uid.clone(), reads));
}
/// Answer the next listing of `folder`'s nodes with what Drive holds now,
/// `unrevised` in it as Drive lists a file whose create it has not
/// committed yet, then hold the answer until it is dropped.
pub(crate) fn hold_answer_to_next_listing(
&self,
folder: &NodeUid,
unrevised: &NodeUid,
) -> Held {
pub fn hold_answer_to_next_listing(&self, folder: &NodeUid, unrevised: &NodeUid) -> Held {
let state = Arc::new(HoldState {
uid: folder.clone(),
reached: AtomicBool::new(false),
@@ -926,7 +990,7 @@ impl FakeClient {
}
/// Requests made through this client so far.
pub(crate) fn requests(&self) -> u64 {
pub fn requests(&self) -> u64 {
self.0.requests.load(Ordering::SeqCst)
}
@@ -1021,6 +1085,12 @@ impl FakeClient {
}
let parent = new_parent.cloned().or(remote.parent.clone());
let name = new_name.unwrap_or(&remote.name).to_owned();
if server.in_trash(uid) || parent.as_ref().is_some_and(|uid| server.in_trash(uid)) {
return Err(api(
ResponseCode::NotEnoughPermissions,
"an item involved in the move is in Trash",
));
}
if let Some(parent) = &parent {
if !server.is_folder(parent) {
return Err(api(
@@ -1123,6 +1193,14 @@ fn delete_one(server: &mut Server, uid: &NodeUid) -> Result<()> {
#[async_trait]
impl DriveApi for FakeClient {
async fn context_share_id(&self, uid: &NodeUid) -> Result<ShareId> {
self.request(false, |server| {
assert_eq!(uid, &server.root);
Ok(ShareId::new("my-files-share"))
})
.await
}
async fn get_my_files_folder(&self) -> Result<Node> {
self.request(false, |server| {
let root = server.root.clone();
@@ -1219,6 +1297,8 @@ impl DriveApi for FakeClient {
&self,
folder_uid: &NodeUid,
) -> Result<Vec<NodeUid>> {
self.wait_if_held(&self.0.hold_children, std::slice::from_ref(folder_uid))
.await;
let lag = self.lag();
self.request(false, |server| {
let now = Instant::now();
@@ -1467,6 +1547,21 @@ impl DriveApi for FakeClient {
}))
}
async fn download_thumbnail(
&self,
uid: &NodeUid,
_thumbnail_type: ThumbnailType,
) -> Result<Option<Vec<u8>>> {
self.request(false, |server| {
server
.current(uid)
.map(|_| ())
.ok_or_else(|| api(ResponseCode::DoesNotExist, "file not found"))
})
.await?;
Ok(self.0.thumbnails.lock().get(uid).cloned())
}
async fn download_file_to_dyn(
&self,
uid: &NodeUid,
@@ -1482,6 +1577,9 @@ impl DriveApi for FakeClient {
.await?;
self.wait_if_held(&self.0.hold_download, std::slice::from_ref(uid))
.await;
self.0
.content_read
.fetch_add(content.len() as u64, Ordering::SeqCst);
output.write_all(&content).map_err(io_error)
}
@@ -1687,6 +1785,11 @@ impl DriveApi for FakeClient {
.await
}
async fn empty_trash(&self) -> Result<()> {
let trashed = self.enumerate_trash_node_uids().await?;
self.batch(&trashed, delete_one).await.map(|_| ())
}
async fn enumerate_trash_node_uids(&self) -> Result<Vec<NodeUid>> {
self.request(false, |server| {
Ok(server
@@ -1725,18 +1828,24 @@ impl RevisionRead for FakeRevision {
async fn read_at(&self, offset: u64, length: u64) -> Result<Vec<u8>> {
let content = self.content.clone();
self.client
let read = self
.client
.request(false, move |_| {
let start = (offset as usize).min(content.len());
let end = (offset.saturating_add(length) as usize).min(content.len());
Ok(content[start..end].to_vec())
})
.await
.await?;
self.client
.0
.content_read
.fetch_add(read.len() as u64, Ordering::SeqCst);
Ok(read)
}
}
/// A uid on the fake volume.
pub(crate) fn uid(link: &str) -> NodeUid {
pub fn uid(link: &str) -> NodeUid {
NodeUid::new(VolumeId::from(VOLUME), LinkId::from(link))
}
@@ -1816,7 +1925,7 @@ fn api(code: ResponseCode, message: &str) -> ProtonError {
}
/// What a request that never got an answer reports; the daemon reads it as
/// the network (see `link::is_network_error`).
/// the network (see [`crate::is_network_error`]).
fn no_answer() -> ProtonError {
ProtonError::Api(ProtonApiError {
code: ResponseCode::RequestTimeout,
@@ -1836,7 +1945,7 @@ fn now_secs() -> i64 {
#[cfg(test)]
mod tests {
use super::*;
use crate::link::is_network_error;
use crate::is_network_error;
fn code(error: &ProtonError) -> Option<ResponseCode> {
match error {
+6
View File
@@ -0,0 +1,6 @@
//! What the simulation tests need from Drive: [`fake_drive::FakeDrive`], an
//! in-memory Drive that injects Drive's known faults, and the seeded
//! [`rng::Rng`] that makes a run replayable.
pub mod fake_drive;
pub mod rng;
@@ -3,14 +3,14 @@
//! and faults, and no dependency.
#[derive(Clone, Debug)]
pub(crate) struct Rng(u64);
pub struct Rng(u64);
impl Rng {
pub(crate) fn new(seed: u64) -> Self {
pub fn new(seed: u64) -> Self {
Self(seed)
}
pub(crate) fn next_u64(&mut self) -> u64 {
pub fn next_u64(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
@@ -19,26 +19,26 @@ impl Rng {
}
/// A value in `0..n`; `0` when `n` is `0`.
pub(crate) fn below(&mut self, n: u64) -> u64 {
pub fn below(&mut self, n: u64) -> u64 {
if n == 0 { 0 } else { self.next_u64() % n }
}
/// A value in `lo..=hi`.
pub(crate) fn between(&mut self, lo: u64, hi: u64) -> u64 {
pub fn between(&mut self, lo: u64, hi: u64) -> u64 {
lo + self.below(hi.saturating_sub(lo) + 1)
}
/// True with probability `p`.
pub(crate) fn chance(&mut self, p: f64) -> bool {
pub fn chance(&mut self, p: f64) -> bool {
p > 0.0 && (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64 <= p
}
pub(crate) fn pick<'a, T>(&mut self, items: &'a [T]) -> Option<&'a T> {
pub fn pick<'a, T>(&mut self, items: &'a [T]) -> Option<&'a T> {
items.get(self.below(items.len() as u64) as usize)
}
/// A child generator, so one consumer's draws do not shift another's.
pub(crate) fn fork(&mut self) -> Self {
pub fn fork(&mut self) -> Self {
Self::new(self.next_u64())
}
}
+16
View File
@@ -11,20 +11,36 @@ description = "FUSE on-demand filesystem for Proton Drive"
[dependencies]
pdfs-core.workspace = true
pdfs-drive.workspace = true
pdfs-sync.workspace = true
pdfs-store.workspace = true
zip.workspace = true
sha1.workspace = true
proton-drive-rs.workspace = true
proton-gallery-app-rs.workspace = true
proton-gallery-rs.workspace = true
proton-media-rs.workspace = true
hyper = { version = "1", features = ["http1", "server"] }
hyper-util = { version = "0.1", features = ["tokio"] }
http-body-util = "0.1"
getrandom = "0.4"
zeroize.workspace = true
futures.workspace = true
async-trait.workspace = true
tokio.workspace = true
tracing.workspace = true
fuser.workspace = true
libc.workspace = true
rustix = { version = "1", features = ["net", "process"] }
serde.workspace = true
serde_json.workspace = true
base64.workspace = true
image.workspace = true
lofty.workspace = true
notify = "8"
parking_lot.workspace = true
[dev-dependencies]
pdfs-drive = { workspace = true, features = ["sim"] }
tracing-subscriber.workspace = true
tokio = { workspace = true, features = ["test-util"] }
+49
View File
@@ -0,0 +1,49 @@
//! The activity log the front-ends show.
use super::*;
impl Core {
/// Append one entry to the activity log. Callable from any thread (the sync
/// engine and the bulk uploader both log from background tasks). A failed
/// write is logged and dropped: the feed is a record of work, never a reason
/// to fail the work itself.
pub(crate) fn log_activity(
&self,
kind: ActivityKind,
target: impl Into<String>,
// `Display` rather than `Into<String>` so a classified `CoreError` can be
// logged as-is, without the caller flattening it first.
detail: impl std::fmt::Display,
ok: bool,
) {
let entry = ActivityEntry {
time: now_secs(),
kind,
target: target.into(),
detail: detail.to_string(),
ok,
};
if let Err(e) = self.db.activity_add(&entry) {
warn!(error = ?e, "could not record activity");
return;
}
// A sync pass is how a conflict copy reaches the listing, and the sweep
// reports the ones it finds as conflicts.
if matches!(entry.kind, ActivityKind::Conflict | ActivityKind::Sync) {
self.events.publish(&[Topic::Activity, Topic::Conflicts]);
} else {
self.events.publish(&[Topic::Activity]);
}
}
/// The recent activity, newest first, capped at `limit` entries.
pub(super) fn list_activity(&self, limit: usize) -> Vec<ActivityEntry> {
match self.db.activity_list(limit) {
Ok(items) => items,
Err(e) => {
warn!(error = ?e, "could not read activity");
Vec::new()
}
}
}
}
+120 -95
View File
@@ -12,20 +12,20 @@
//! than looked up in our own timeline, where a shared album's photos never
//! appear.
use std::collections::{HashMap, HashSet};
use std::collections::HashSet;
use std::sync::atomic::Ordering;
use pdfs_core::control::{AlbumInfo, PhotoItem, Topic};
use pdfs_core::db::StoredAlbum;
use pdfs_core::{CoreError, CoreResult};
use pdfs_store::db::StoredAlbum;
use proton_drive_rs::NodeKind;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use tracing::warn;
use super::{
ALBUM_SYNCED_PREFIX, ALBUMS_SYNCED_MS, Core, PHOTOS_AVAILABLE, PHOTOS_SYNCED_MS,
TIMELINE_ENRICH_CHUNK, TIMELINE_TTL, now_ms, parse_uid,
ALBUM_SYNCED_PREFIX, ALBUMS_SYNCED_MS, Core, PHOTOS_AVAILABLE, TIMELINE_ENRICH_CHUNK,
TIMELINE_TTL, link, now_ms, parse_uid,
};
impl Core {
@@ -34,7 +34,13 @@ impl Core {
/// [`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 {
if count == 0
&& self
.db
.state_i64(ALBUMS_SYNCED_MS)
.map_err(CoreError::from)?
.is_none()
{
// 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);
@@ -56,89 +62,89 @@ impl Core {
/// the persisted listing. Returns false when the account has no photos
/// volume.
pub(crate) async fn refresh_albums(&self) -> CoreResult<bool> {
let generation = self
.db
.photo_projection_generation()
.map_err(CoreError::from)?;
let photos = self.photos();
if photos
.get_photos_root()
if link::bounded(photos.get_photos_root())
.await
.map_err(|e| CoreError::from_api(&e, "photos root"))?
.is_none()
{
let _ = self.db.set_state_i64(PHOTOS_AVAILABLE, 0);
let _ = self.db.set_state_i64(PHOTOS_SYNCED_MS, now_ms());
let _ = self.db.set_state_i64(ALBUMS_SYNCED_MS, now_ms());
self.db
.albums_replace_at(&[], generation, now_ms())
.map_err(CoreError::from)?;
return Ok(false);
}
let mut uids = photos
.enumerate_album_node_uids()
let mut uids = link::bounded(photos.enumerate_album_node_uids())
.await
.map_err(|e| CoreError::from_api(&e, "albums"))?;
let shared = link::bounded(photos.enumerate_shared_with_me_album_uids())
.await
.map_err(|e| CoreError::from_api(&e, "shared albums"))?;
let shared_keys: HashSet<_> = shared.iter().map(ToString::to_string).collect();
uids.extend(shared);
let mut unique = HashSet::new();
uids.retain(|uid| unique.insert(uid.clone()));
// Shared-with-me albums are a separate listing on the sharer's volume.
// Best-effort: an account whose sharing listing fails still gets its own
// albums rather than an error page.
let shared: HashSet<String> = match photos.enumerate_shared_with_me_album_uids().await {
Ok(shared) => {
let keys = shared.iter().map(|u| u.to_string()).collect();
uids.extend(shared);
keys
}
Err(e) => {
warn!(error = %e, "enumerating shared-with-me albums failed");
HashSet::new()
}
};
// The listings carry uids only; the name, photo count and cover come from
// the album nodes themselves. A chunk that fails to resolve drops those
// albums from this refresh rather than failing the whole listing.
let mut albums: Vec<StoredAlbum> = Vec::with_capacity(uids.len());
let mut albums = Vec::with_capacity(uids.len());
for chunk in uids.chunks(TIMELINE_ENRICH_CHUNK) {
match photos.enumerate_nodes(chunk).await {
Ok(nodes) => {
for node in nodes {
let key = node.uid.to_string();
let props = node.album.as_ref();
albums.push(StoredAlbum {
shared: shared.contains(&key),
uid: key,
name: node.name,
photo_count: props.map_or(0, |a| a.photo_count.max(0) as usize),
cover_uid: props
.and_then(|a| a.cover_photo_uid.as_ref())
.map(|u| u.to_string()),
last_activity: props.and_then(|a| a.last_activity_time),
});
}
}
Err(e) => warn!(error = %e, "resolving an album chunk failed"),
let nodes = link::bounded(photos.enumerate_nodes(chunk))
.await
.map_err(|e| CoreError::from_api(&e, "album metadata"))?;
if nodes.len() != chunk.len() {
return Err(CoreError::remote(
"Some album details are still unavailable.",
));
}
for node in nodes.into_iter().filter(|node| !node.trashed) {
let uid = node.uid.to_string();
let props = node.album.as_ref();
albums.push(StoredAlbum {
shared: shared_keys.contains(&uid),
uid,
name: node.name,
photo_count: props.map_or(0, |a| a.photo_count.max(0) as usize),
cover_uid: props
.and_then(|a| a.cover_photo_uid.as_ref())
.map(ToString::to_string),
last_activity: props.and_then(|a| a.last_activity_time),
});
}
}
// Newest activity first, and albums the server gave no activity time for
// last — an album nobody has touched belongs below the ones in use. Ties
// fall back to the name so the order is stable between refreshes.
albums.sort_by(|a, b| {
b.last_activity
.cmp(&a.last_activity)
.then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
});
self.db.albums_replace(&albums).map_err(CoreError::from)?;
let _ = self.db.set_state_i64(PHOTOS_AVAILABLE, 1);
let _ = self.db.set_state_i64(ALBUMS_SYNCED_MS, now_ms());
if !self
.db
.albums_replace_at(&albums, generation, now_ms())
.map_err(CoreError::from)?
{
return Err(CoreError::remote(
"Photos changed during the album refresh. Try again shortly.",
));
}
Ok(true)
}
/// Refresh the album listing off the request path. At most one runs at a time.
pub(crate) fn spawn_albums_refresh(&self) {
if self.albums_refreshing.swap(true, Ordering::SeqCst) {
if self
.photo_jobs
.albums_refreshing
.swap(true, Ordering::SeqCst)
{
return;
}
let core = self.clone();
self.rt.spawn(async move {
let refreshed = core.refresh_albums().await;
core.albums_refreshing.store(false, Ordering::SeqCst);
core.photo_jobs
.albums_refreshing
.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => core.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background album refresh failed"),
@@ -154,11 +160,21 @@ impl Core {
album: &NodeUid,
offset: usize,
limit: usize,
excluded: &str,
) -> CoreResult<Vec<PhotoItem>> {
let key = album.to_string();
if self.db.photo_removed(&key).map_err(CoreError::from)? {
return Ok(Vec::new());
}
let stamp = format!("{ALBUM_SYNCED_PREFIX}{key}");
let count = self.db.album_photos_count(&key).map_err(CoreError::from)?;
if count == 0 {
if count == 0
&& self
.db
.state_i64(&stamp)
.map_err(CoreError::from)?
.is_none()
{
self.rt.block_on(self.refresh_album(album))?;
} else if self.listing_stale(&stamp, TIMELINE_TTL) {
let core = self.clone();
@@ -172,7 +188,7 @@ impl Core {
let page = self
.db
.album_photos_page(&key, offset, limit)
.album_photos_page_visible(&key, offset, limit, excluded)
.map_err(CoreError::from)?;
Ok(page.into_iter().map(|p| self.photo_item(p)).collect())
}
@@ -213,47 +229,56 @@ impl Core {
/// Re-enumerate one album's photos and replace its persisted contents.
pub(crate) async fn refresh_album(&self, album: &NodeUid) -> CoreResult<()> {
let generation = self
.db
.photo_projection_generation()
.map_err(CoreError::from)?;
let photos = self.photos();
let items = photos
.enumerate_album(album)
let items = link::bounded(photos.enumerate_album(album))
.await
.map_err(|e| CoreError::from_api(&e, "album"))?;
// Same enrichment as the timeline: the listing carries a uid and a
// capture time, and the gallery needs a name and media type to classify
// each entry. Best-effort per chunk.
let uids: Vec<NodeUid> = items.iter().map(|it| it.uid.clone()).collect();
let mut meta: HashMap<String, (Option<String>, Option<String>)> = HashMap::new();
let key = album.to_string();
let mut meta = self
.db
.album_photo_metadata(&key)
.map_err(CoreError::from)?;
let uids: Vec<NodeUid> = items
.iter()
.filter(|item| !meta.contains_key(&item.uid.to_string()))
.map(|item| item.uid.clone())
.collect();
for chunk in uids.chunks(TIMELINE_ENRICH_CHUNK) {
match photos.enumerate_nodes(chunk).await {
Ok(nodes) => {
for node in nodes {
let media_type = match &node.kind {
NodeKind::File { media_type, .. } => Some(media_type.clone()),
NodeKind::Folder => None,
};
meta.insert(node.uid.to_string(), (Some(node.name), media_type));
}
}
Err(e) => warn!(error = %e, "resolving album photo metadata failed"),
let nodes = link::bounded(photos.enumerate_nodes(chunk))
.await
.map_err(|e| CoreError::from_api(&e, "album photo metadata"))?;
for node in nodes.into_iter().filter(|node| !node.trashed) {
let media_type = match node.kind {
NodeKind::File { media_type, .. } => Some(media_type),
NodeKind::Folder => None,
};
meta.insert(node.uid.to_string(), (node.name, media_type));
}
}
let rows: Vec<(String, i64, Option<String>, Option<String>)> = items
.iter()
.map(|it| {
let key = it.uid.to_string();
let (name, media_type) = meta.get(&key).cloned().unwrap_or((None, None));
(key, it.capture_time, name, media_type)
let rows: Vec<_> = items
.into_iter()
.map(|item| {
let uid = item.uid.to_string();
let (name, media_type) = meta
.get(&uid)
.map(|(name, mime)| (Some(name.clone()), mime.clone()))
.unwrap_or_default();
(uid, item.capture_time, name, media_type)
})
.collect();
let key = album.to_string();
self.db
.album_photos_replace(&key, &rows)
.map_err(CoreError::from)?;
let _ = self
if !self
.db
.set_state_i64(&format!("{ALBUM_SYNCED_PREFIX}{key}"), now_ms());
.album_photos_replace_at(&key, &rows, generation, now_ms())
.map_err(CoreError::from)?
{
return Err(CoreError::remote(
"Photos changed during the album refresh. Try again shortly.",
));
}
Ok(())
}
@@ -283,7 +308,7 @@ impl Core {
.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.album_photos_replace(&key, &[]) {
if let Err(error) = self.db.photos_delete(&[key]) {
warn!(%album, %error, "a deleted album's photos could not be dropped");
}
self.after_album_change(None);
+150
View File
@@ -0,0 +1,150 @@
//! Explicitly bind an existing My files folder to a real local mirror.
//!
//! Unlike a FUSE mount, this never covers or evicts the local directory.
//! The existing three-way engine performs the initial, non-destructive union.
use super::{Core, parse_uid, sync};
use pdfs_core::{CoreError, CoreResult};
use pdfs_store::db::StoredSyncFolder;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use std::collections::HashSet;
use std::path::{Component, Path, PathBuf};
impl Core {
/// A bounded, server-verified ancestry walk. Do not decide ownership or
/// remote-root overlap from a possibly incomplete cached folder listing.
pub(crate) fn attach_ancestors(&self, start: &NodeUid) -> CoreResult<Vec<NodeUid>> {
self.remote_ancestry(start, false)
}
/// The ancestry walk behind [`attach_ancestors`](Self::attach_ancestors).
/// With `through_trash`, a folder in the trash is walked like any other
/// instead of failing the walk.
fn remote_ancestry(&self, start: &NodeUid, through_trash: bool) -> CoreResult<Vec<NodeUid>> {
let mut ancestors = Vec::new();
let mut seen = HashSet::new();
let mut next = Some(start.clone());
while let Some(uid) = next {
if !seen.insert(uid.clone()) || ancestors.len() >= 256 {
return Err(CoreError::invalid(
"invalid or excessively deep remote folder ancestry",
));
}
ancestors.push(uid.clone());
if uid == self.primary_root_uid {
break;
}
let nodes = self
.rt
.block_on(self.drive.enumerate_nodes(std::slice::from_ref(&uid)))
.map_err(|e| CoreError::from_api(&e, "verify sync folder ancestry"))?;
let node = nodes
.into_iter()
.next()
.ok_or_else(|| CoreError::not_found("remote sync folder is missing"))?;
if node.trashed && !through_trash {
return Err(CoreError::invalid("remote sync folder is in the trash"));
}
next = node.parent_uid;
}
Ok(ancestors)
}
pub(crate) fn attach_sync_folder(
&self,
local: &Path,
remote: &Path,
mountpoint: &Path,
) -> CoreResult<StoredSyncFolder> {
let _registration = super::devices::SYNC_ROOT_REGISTRATION.lock();
if !self.primary {
return Err(CoreError::invalid("attach must use My files"));
}
if remote.is_absolute()
|| remote
.components()
.any(|c| !matches!(c, Component::Normal(_) | Component::CurDir))
{
return Err(CoreError::invalid(
"remote folder must stay inside My files",
));
}
let local = local
.canonicalize()
.map_err(|e| CoreError::invalid(format!("resolve {}: {e}", local.display())))?;
if !local.is_dir() {
return Err(CoreError::invalid("local sync path is not a directory"));
}
let existing = self
.db
.sync_folder_list()
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
let others = existing
.iter()
.map(|f| PathBuf::from(&f.local_path))
.collect::<Vec<_>>();
let mut reserved = crate::devices::sync_root_reserved();
reserved.mountpoint = Some(
mountpoint
.canonicalize()
.map_err(|e| CoreError::internal(format!("resolve mountpoint: {e}")))?,
);
if let Some(problem) = pdfs_core::syncroot::problem(&local, &others, &reserved) {
return Err(CoreError::invalid(problem));
}
let (ino, remote_uid) = self.resolve(remote)?;
let is_folder = self
.state()
.entries
.get(&ino)
.is_some_and(|e| e.node.is_folder() && !e.node.trashed);
if !is_folder {
return Err(CoreError::invalid("remote sync path is not a folder"));
}
let ancestors = self.attach_ancestors(&remote_uid)?;
if remote_uid == self.primary_root_uid || !ancestors.contains(&self.primary_root_uid) {
return Err(CoreError::invalid(
"choose an owned folder below My files, not its root or a shared folder",
));
}
for other in existing.iter().filter(|f| f.kind == "attached") {
let uid = parse_uid(&other.remote_uid)
.ok_or_else(|| CoreError::internal("invalid existing remote sync root"))?;
// Another synced folder whose Drive folder is in the trash, or gone
// for good, must not block every attach: its own walk fails, but
// the question is only whether it lies below the new one. A
// trashed folder keeps its parent, so the walk goes through the
// trash; one that no longer exists lies below nothing.
let theirs = match self.remote_ancestry(&uid, true) {
Ok(theirs) => theirs,
Err(e) if e.kind == pdfs_core::control::ErrorKind::NotFound => Vec::new(),
Err(e) => return Err(e),
};
if uid == remote_uid || ancestors.contains(&uid) || theirs.contains(&remote_uid) {
return Err(CoreError::invalid(
"remote folder overlaps an existing synced folder",
));
}
}
let share_id = self
.rt
.block_on(self.drive.context_share_id(&self.primary_root_uid))
.map_err(|e| CoreError::from_api(&e, "resolve My files share"))?
.to_string();
if share_id.is_empty() {
return Err(CoreError::invalid("My files share is unavailable"));
}
let id = self
.db
.sync_folder_attach(&local.to_string_lossy(), &remote_uid.to_string(), &share_id)
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
// An empty baseline makes one-sided files new, never deletions. The
// engine hashes matching-size files and preserves divergent versions.
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
let _ = self.sync.tx.send(sync::SyncMsg::Reconcile(id));
self.db
.sync_folder_get(id)
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?
.ok_or_else(|| CoreError::not_found("new sync folder disappeared"))
}
}
+153 -83
View File
@@ -109,7 +109,7 @@ fn apply_event(core: &Core, event: &DriveEvent, dirty: &mut DirtyParents) -> pdf
let foreign_delete = is_foreign_node_delete(event, &core.primary_root_uid.volume_id);
let serializes_shared_publication =
event_serializes_shared_publication(event, &core.primary_root_uid.volume_id);
let _publication = serializes_shared_publication.then(|| core.shared_publication.lock());
let _publication = serializes_shared_publication.then(|| core.shared.shared_publication.lock());
if serializes_shared_publication {
core.invalidate_shared_refreshes();
}
@@ -132,6 +132,29 @@ fn apply_event(core: &Core, event: &DriveEvent, dirty: &mut DirtyParents) -> pdf
});
})
};
// A mirror pass starts from its last walk of Drive and lists again only
// the folders marked here, so a mark that cannot be made keeps the
// event to be applied again.
let marked = match event {
DriveEvent::NodeUpdated {
node_uid,
parent_node_uid,
..
} => core.db.sync_remote_changed(
&node_uid.to_string(),
parent_node_uid.as_ref().map(ToString::to_string).as_deref(),
),
DriveEvent::NodeDeleted { node_uid, .. } => {
core.db.sync_remote_changed(&node_uid.to_string(), None)
}
// What changed went by unseen: every pass walks Drive whole again.
DriveEvent::ContinuityLost { .. } => core.db.sync_walks_clear_all().map(|()| Vec::new()),
_ => Ok(Vec::new()),
};
match marked {
Ok(folders) => dirty.synced.extend(folders),
Err(e) => apply_result = apply_result.and(Err(e)),
}
match event {
DriveEvent::NodeUpdated {
node_uid,
@@ -157,6 +180,17 @@ fn apply_event(core: &Core, event: &DriveEvent, dirty: &mut DirtyParents) -> pdf
if ours {
debug!(uid = %node_uid, "ignoring remote event for a node with a queued write");
}
// A file kept offline keeps its copy through a change, and the
// keeper replaces it once this batch's listings are read again.
// The copy is checked against the revision's `(mtime, size)`, so
// no read takes it for a newer revision. Evicted, it was gone until
// something read the file, which then downloaded it (B282). A
// node new in, or moved into, a kept folder is fetched by checking
// that folder.
let kept = match !*is_trashed && !ours {
true => kept_by_pin(core, node_uid, parent_node_uid.as_ref()),
false => None,
};
let mut had_node = false;
core.for_each_mount(|st, notify| {
if *is_trashed {
@@ -172,9 +206,12 @@ fn apply_event(core: &Core, event: &DriveEvent, dirty: &mut DirtyParents) -> pdf
}
});
// Once, not once per mount: the content cache is per-daemon.
if had_node {
if had_node && kept.is_none() {
core.cache.evict(node_uid);
}
if let Some(kept) = kept {
dirty.kept.insert(kept);
}
// A create, rename or move-in shows up as a change to the parent
// listing too, which is recorded for the end of the batch rather
// than acted on here — see [`DirtyParents`].
@@ -205,6 +242,8 @@ fn apply_event(core: &Core, event: &DriveEvent, dirty: &mut DirtyParents) -> pdf
| DriveEvent::ScopeAccessLost { .. }
| DriveEvent::SharedWithMeUpdated { .. } => {
warn!("event access continuity lost; downgrading shared trees and resyncing lazily");
// Changes went by unseen, kept files among them (B282).
core.recheck_all_pins();
apply_result = apply_result.and(core.db.clear_state(SHARED_WITH_ME_SYNCED_MS));
core.for_each_mount(|st, notify| {
let dirs: Vec<u64> = st.children.keys().copied().collect();
@@ -296,6 +335,25 @@ struct DirtyParents {
/// Checked per mount — a mount that already lists every one of those
/// children under that parent keeps its listing.
ours: HashMap<NodeUid, HashSet<NodeUid>>,
/// Pinned files and folders the batch changed, for the pin keeper to
/// check once the listings above are dropped (`keeper`).
kept: HashSet<NodeUid>,
/// Mirror folders the batch changed on Drive. The batch marked the
/// folders it touched dirty in their saved walk of Drive, and each gets a
/// pass, which lists those folders again (`docs/SYNC_ENGINE.md`).
synced: HashSet<i64>,
}
/// What the pin keeper has to check after a remote change to `node_uid`,
/// whose parent is now `parent_uid`: the node itself when a pin keeps it, or
/// else the parent, when a pinned folder holds it and the node is new there.
fn kept_by_pin(core: &Core, node_uid: &NodeUid, parent_uid: Option<&NodeUid>) -> Option<NodeUid> {
if core.cache.is_pinned(node_uid) {
return Some(node_uid.clone());
}
parent_uid
.filter(|parent| core.cache.is_pinned(parent))
.cloned()
}
/// Whether this mount's cached listing of `parent_uid` already accounts for
@@ -392,6 +450,14 @@ pub(super) async fn run_event_sync(
match client.enumerate_events(&scope, None).await {
Ok(events) => {
let head = events.last().map(|e| e.id().clone());
// No walk of Drive saved before can say what
// changed before this cursor either.
if let Err(e) = db.sync_walks_clear_all() {
warn!(error = %e, ?delay, "dropping the saved walks of Drive failed; retrying");
tokio::time::sleep(delay).await;
delay = (delay * 2).min(ONLINE_PROBE_MAX);
continue;
}
let Some(c) = &head else {
break None;
};
@@ -436,6 +502,9 @@ pub(super) async fn run_event_sync(
}
};
if events.is_empty() {
core.sync
.events_read_at
.store(now_secs(), Ordering::Relaxed);
continue;
}
debug!(count = events.len(), "applying remote events");
@@ -444,6 +513,7 @@ pub(super) async fn run_event_sync(
// through to that flush, so an interrupted batch still publishes what it
// did apply.
let mut dirty = DirtyParents::default();
let mut whole = true;
for event in &events {
if recent.repeat(event) {
debug!(id = %event.id().as_str(), "skipping an event already applied");
@@ -457,6 +527,7 @@ pub(super) async fn run_event_sync(
// our FUSE state, so nothing else does this.
if let Err(e) = client.invalidate_caches_for_event(event).await {
warn!(error = %e, "sdk cache invalidation for event failed; retaining cursor for retry");
whole = false;
break;
}
let applied = match acknowledge_applied_event(
@@ -467,6 +538,7 @@ pub(super) async fn run_event_sync(
Ok(applied) => applied,
Err(e) => {
warn!(error = %e, "event application or acknowledgment failed; retaining prior cursor for retry");
whole = false;
break;
}
};
@@ -476,6 +548,17 @@ pub(super) async fn run_event_sync(
cursor = Some(applied);
}
flush_dirty_parents(&core, &dirty);
for uid in &dirty.kept {
core.recheck_pinned(uid);
}
for &id in &dirty.synced {
let _ = core.sync.tx.send(crate::sync::SyncMsg::Reconcile(id));
}
if whole {
core.sync
.events_read_at
.store(now_secs(), Ordering::Relaxed);
}
// Another device changed the tree: whatever a front-end lists may have
// moved, including what is shared and what is in the trash.
core.events
@@ -483,32 +566,15 @@ pub(super) async fn run_event_sync(
}
}
/// The state key holding the photos volume's event cursor. Separate from the
/// Drive cursor because the two volumes have their own event streams, and one
/// cursor cannot address both.
const PHOTOS_EVENT_CURSOR: &str = "photos_event_cursor";
/// Poll the photos volume's event stream, so a photo deleted or added on another
/// device shows up in the gallery within one poll instead of on the timeline's
/// freshness window.
///
/// Deliberately much smaller than [`run_event_sync`]: the photos volume is not
/// part of the FUSE mount, so there is no inode space to converge and nothing to
/// invalidate in the kernel. A trash or a delete removes the rows behind the
/// gallery; anything else only drops the timeline's freshness stamp, and the
/// next read re-enumerates. Getting that wrong costs a stale tile, not a wrong
/// file.
/// 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();
// 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 {
match photos.get_photos_root().await {
match link::bounded(photos.get_photos_root()).await {
Ok(Some(root)) => break root.tree_event_scope_id(),
Ok(None) => {
debug!("no photos volume; photo event sync not started");
return;
}
Ok(None) => core.next_poll(POLL_INTERVAL).await,
Err(error) if session_revoked(&error) => {
core.mark_session_expired("read the photos root", &error);
return;
@@ -520,39 +586,71 @@ pub(super) async fn run_photos_event_sync(core: Core) {
}
};
let mut cursor: Option<DriveEventId> = core
.db
.state_str(PHOTOS_EVENT_CURSOR)
.ok()
.flatten()
.map(DriveEventId::from);
info!(?cursor, "photo event sync started");
let key = format!("photos_event_cursor:{}", scope.volume_id());
let mut cursor = loop {
match core.db.state_str(&key) {
Ok(cursor) => break cursor.map(DriveEventId::from),
Err(error) => {
warn!(%error, "reading the photo event checkpoint failed");
core.next_poll(POLL_INTERVAL).await;
}
}
};
info!("photo event sync started");
loop {
core.next_poll(POLL_INTERVAL).await;
let events = match link::bounded(photos.enumerate_events(&scope, cursor.as_ref())).await {
Ok(events) => events,
Err(error) if core.lost_link(&error, "poll photo events") => continue,
Err(error) => {
warn!(%error, "photo event poll failed; retrying after interval");
if !core.lost_link(&error, "poll photo events") {
warn!(%error, "photo event poll failed; retrying after interval");
}
core.next_poll(POLL_INTERVAL).await;
continue;
}
};
let Some(head) = events.last().map(|event| event.id().clone()) else {
continue;
};
apply_photo_events(&core, &events);
core.events.publish(&[Topic::Photos]);
// One cursor write per batch, after the batch is applied: a crash in
// between replays events whose effects are idempotent.
if let Err(error) = core.db.set_state_str(PHOTOS_EVENT_CURSOR, head.as_str()) {
warn!(%error, "persisting the photo event cursor failed");
continue;
if let Some(head) = events.last().map(|event| event.id().clone()) {
if let Err(error) = invalidate_photo_events(&core, &events).await {
warn!(%error, "invalidating photo event metadata failed");
core.next_poll(POLL_INTERVAL).await;
continue;
}
// A failed database write must replay all changes, including echoes.
let plan = classify_photo_events(&events, |_| false);
if let Err(error) = core.db.photos_apply_events(
&key,
head.as_str(),
&plan.gone,
&plan.touched,
plan.full,
cursor.is_none(),
) {
warn!(%error, "committing the photo event checkpoint failed");
core.next_poll(POLL_INTERVAL).await;
continue;
}
cursor = Some(head);
if !plan.is_empty() {
core.events.publish(&[Topic::Photos]);
}
}
cursor = Some(head);
if core.db.photos_need_work().unwrap_or(true) {
core.spawn_timeline_refresh();
}
core.next_poll(POLL_INTERVAL).await;
}
}
async fn invalidate_photo_events(
core: &Core,
events: &[DriveEvent],
) -> proton_drive_rs::proton_sdk::error::Result<()> {
for event in events {
core.client.invalidate_caches_for_event(event).await?;
}
Ok(())
}
/// What one batch of photos-volume events asks the gallery's tables to do.
#[derive(Debug, Default, PartialEq)]
pub(super) struct PhotoEventPlan {
@@ -582,14 +680,22 @@ fn classify_photo_events(
mut is_echo: impl FnMut(&NodeUid) -> bool,
) -> PhotoEventPlan {
let mut plan = PhotoEventPlan::default();
for event in events {
let mut seen = HashSet::new();
for event in events.iter().rev() {
match event {
DriveEvent::NodeDeleted { node_uid, .. } => plan.gone.push(node_uid.to_string()),
DriveEvent::NodeDeleted { node_uid, .. } => {
if seen.insert(node_uid) {
plan.gone.push(node_uid.to_string());
}
}
DriveEvent::NodeUpdated {
node_uid,
is_trashed,
..
} => {
if !seen.insert(node_uid) {
continue;
}
if *is_trashed {
plan.gone.push(node_uid.to_string());
} else if !is_echo(node_uid) {
@@ -607,47 +713,11 @@ fn classify_photo_events(
DriveEvent::CursorAdvanced { .. } | DriveEvent::SharedWithMeUpdated { .. } => {}
}
}
plan.gone.reverse();
plan.touched.reverse();
plan
}
/// Apply one batch of photos-volume events to the gallery's tables.
fn apply_photo_events(core: &Core, events: &[DriveEvent]) {
let plan = classify_photo_events(events, |uid| core.take_self_change(uid));
let PhotoEventPlan {
gone,
touched,
full,
} = &plan;
if !gone.is_empty() {
match core.db.photos_delete(gone) {
Ok(removed) if removed > 0 => {
debug!(removed, "photos removed by a remote event");
}
Ok(_) => {}
Err(error) => warn!(%error, "removing remotely deleted photos failed"),
}
}
// A stale mark is what makes the next refresh cheap: it reads these photos'
// nodes and carries every other photo's metadata as it stands.
if !touched.is_empty() {
match core.db.photos_mark_unresolved(touched) {
Ok(marked) if marked > 0 => debug!(marked, "photos changed by a remote event"),
Ok(_) => {}
Err(error) => warn!(%error, "marking remotely changed photos failed"),
}
}
if *full {
match core.db.photos_mark_all_unresolved() {
Ok(marked) => debug!(marked, "the photo event stream lost continuity"),
Err(error) => warn!(%error, "marking the whole timeline unresolved failed"),
}
}
if !plan.is_empty() {
core.invalidate_photos();
core.invalidate_albums();
}
}
/// Keep the local-file index fresh for the launcher prompt's "This computer"
/// results. Rebuilds the index whenever it is older than [`LOCAL_INDEX_TTL`],
/// then sleeps; runs on its own thread for the life of the daemon.
+1 -1
View File
@@ -151,7 +151,7 @@ impl Core {
rel.display()
)));
}
self.conflict_notified.lock().remove(&uid);
self.sweep.conflict_notified.lock().remove(&uid);
Ok(())
}
}
+280 -62
View File
@@ -110,7 +110,7 @@ struct ControlHandlerPermit;
impl ControlHandlerPermit {
fn acquire() -> Option<Self> {
ACTIVE_CONTROL_HANDLERS
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |active| {
.try_update(Ordering::AcqRel, Ordering::Acquire, |active| {
(active < MAX_CONTROL_HANDLERS).then_some(active + 1)
})
.ok()
@@ -204,18 +204,42 @@ fn route_to_mount(core: &Core, mountpoint: &Path, path: &str) -> CoreResult<(Cor
/// B99), so resolving one needs this too. A mirror folder has no mount to run
/// against: a file there is an ordinary local file.
fn route_change(core: &Core, mountpoint: &Path, path: &str) -> CoreResult<(Core, PathBuf)> {
route_within(core, mountpoint, path, |path| {
format!("{path} is in a mirrored folder; change the local file there instead")
})
}
/// [`route_to_mount`] for keeping a node offline or releasing it. A file in an
/// on-demand synced folder is a different Drive node from any file of the
/// same name under the primary mount, and keeping one offline did nothing for
/// the other: a program reading the synced folder's copy downloaded it
/// (`docs/BUGS.md` B281). A mirror folder already holds every file on disk.
fn route_keep(core: &Core, mountpoint: &Path, path: &str) -> CoreResult<(Core, PathBuf)> {
route_within(core, mountpoint, path, |path| {
format!(
"{path} is in a mirrored folder, which keeps all its files on this computer already"
)
})
}
/// [`route_to_mount`], refusing a path that leaves the mount it routed to and
/// answering a path in a mirror folder, which has no mount, with `mirrored`.
fn route_within(
core: &Core,
mountpoint: &Path,
path: &str,
mirrored: impl FnOnce(&str) -> String,
) -> CoreResult<(Core, PathBuf)> {
let routed = route_to_mount(core, mountpoint, path).map_err(|e| {
let p = Path::new(path);
let mirrored = core
let in_mirror = core
.db
.sync_folder_list()
.unwrap_or_default()
.iter()
.any(|folder| folder.mode == "mirror" && p.starts_with(&folder.local_path));
if mirrored {
CoreError::invalid(format!(
"{path} is in a mirrored folder; change the local file there instead"
))
if in_mirror {
CoreError::invalid(mirrored(path))
} else {
e
}
@@ -231,6 +255,18 @@ fn route_change(core: &Core, mountpoint: &Path, path: &str) -> CoreResult<(Core,
}
}
/// The path the pin registry keeps for a pin made through `routed`: the
/// mount-relative path on the primary mount, as it always was, and the
/// absolute path the request named on an on-demand folder's mount, since
/// that node is not under the primary mountpoint (`docs/BUGS.md` B281).
fn pin_record(routed: &Core, rel: &Path, path: &str) -> PathBuf {
if routed.primary {
rel.to_path_buf()
} else {
Path::new(path).components().collect()
}
}
/// [`route_change`] for a request that trashes or renames the node it names.
/// A mount's root is My files or a whole synced folder. An on-demand folder's
/// root has a parent on Drive, so nothing further down would stop `pdfs rm
@@ -328,7 +364,7 @@ pub(crate) fn status_response(core: &Core, username: &str, mountpoint: &Path) ->
let queued = core.db.pending_op_counts().unwrap_or_default();
// Read after the queue: the drain counts an upload as landing before it
// retires the op, so one of the two always has it (B119).
let landing = core.landing_uploads.load(Ordering::SeqCst);
let landing = core.drain.landing_uploads.load(Ordering::SeqCst);
let staging = core.cache.staging_usage();
CtlResponse::Status {
parked_uploads: queued.parked.max(0) as u64,
@@ -360,6 +396,11 @@ fn touched_topics(request: &CtlRequest) -> &'static [Topic] {
use CtlRequest as R;
match request {
R::Pin { .. } | R::Unpin { .. } => &[Topic::Files],
// Only locking invalidates a hidden view. Authentication does not
// change the public catalog and must not emit this notification.
R::DriveGallery {
action: pdfs_core::control::GalleryAction::Lock,
} => &[Topic::GalleryVisibility],
R::CreateAlbum { .. }
| R::RenameAlbum { .. }
| R::DeleteAlbum { .. }
@@ -385,6 +426,7 @@ fn touched_topics(request: &CtlRequest) -> &'static [Topic] {
R::RenameDevice { .. } | R::DeleteDevice { .. } => &[Topic::Devices],
R::AdoptDevice { .. } | R::MigrateDevice { .. } => &[Topic::Devices, Topic::Locations],
R::AddSyncFolder { .. }
| R::AttachSyncFolder { .. }
| R::RemoveSyncFolder { .. }
| R::SetSyncFolderMode { .. }
| R::SetSyncFolderPaused { .. }
@@ -515,13 +557,75 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
// Registered before the request is even parsed, so a handler that wedges
// inside the daemon shows up by name in `pdfs diagnostics`.
let _inflight = super::diagnostics::InflightGuard::new(super::diagnostics::request_kind(&line));
if let Ok(CtlRequest::PhotoMonths { kind }) = &request {
let started = std::time::Instant::now();
let visibility = core.cached_gallery_visibility();
let visibility_ms = started.elapsed().as_millis() as u64;
let mut database_ms = None;
let mut response_started = std::time::Instant::now();
let response = match visibility {
Ok(visibility) => {
let excluded = serde_json::to_string(&visibility.media)
.expect("a set of file identifiers serializes");
let query = std::time::Instant::now();
let months = core.db.photos_months_visible(*kind, &excluded);
response_started = std::time::Instant::now();
database_ms = Some(response_started.duration_since(query).as_millis() as u64);
match months {
Ok(months) => CtlResponse::PhotoMonths {
months: months
.into_iter()
.map(|(year, month, count)| PhotoMonth { year, month, count })
.collect(),
},
Err(error) => CtlResponse::error(error.into()),
}
}
Err(error) => CtlResponse::error(error),
};
write_response(stream, response);
tracing::info!(
visibility_ms,
database_ms,
response_ms = response_started.elapsed().as_millis() as u64,
total_ms = started.elapsed().as_millis() as u64,
"PhotoMonths timings"
);
return;
}
let visibility = if matches!(
&request,
Ok(CtlRequest::PhotosTimeline { .. }
| CtlRequest::PhotoDuplicates
| CtlRequest::PhotoSimilar
| CtlRequest::PhotoPlaces
| CtlRequest::PlacePhotos { .. }
| CtlRequest::PlaceLocations { .. }
| CtlRequest::PhotosOnThisDay { .. }
| CtlRequest::PhotoGroup { .. }
| CtlRequest::PhotoAlbums
| CtlRequest::AlbumPhotos { .. }
| CtlRequest::PhotoThumbs { .. }
| CtlRequest::OpenGalleryImage { private: false, .. }
| CtlRequest::OpenPhoto { .. })
) {
core.gallery_visibility()
} else {
Ok(std::sync::Arc::default())
};
let visibility = match visibility {
Ok(visibility) => visibility,
Err(error) => return write_response(stream, CtlResponse::error(error)),
};
let excluded =
serde_json::to_string(&visibility.media).expect("a set of file identifiers serializes");
let response = match request {
Ok(CtlRequest::Status) => status_response(core, username, mountpoint),
Ok(CtlRequest::Subscribe) => {
CtlResponse::error(CoreError::invalid("a subscription is served on its own"))
}
Ok(CtlRequest::Pin { path }) => match rel_to_mount(mountpoint, &path) {
Ok(rel) => match core.pin(&rel) {
Ok(CtlRequest::Pin { path }) => match route_keep(core, mountpoint, &path) {
Ok((routed, rel)) => match routed.pin(&rel, &pin_record(&routed, &rel, &path)) {
Ok(name) => {
core.touch_profile();
CtlResponse::Ok {
@@ -532,8 +636,8 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
},
Err(e) => CtlResponse::error(e),
},
Ok(CtlRequest::Unpin { path }) => match rel_to_mount(mountpoint, &path) {
Ok(rel) => match core.unpin(&rel) {
Ok(CtlRequest::Unpin { path }) => match route_keep(core, mountpoint, &path) {
Ok((routed, rel)) => match routed.unpin(&rel) {
Ok(name) => {
core.touch_profile();
CtlResponse::Ok {
@@ -590,7 +694,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
// A full refresh is "forget what you know", not a second code
// path: the ordinary refresh then finds every photo stale.
if let Some(Err(e)) = full.then(|| core.db.photos_mark_all_unresolved()) {
warn!(error = %e, "marking the whole timeline unresolved failed");
return write_response(stream, CtlResponse::error(e.into()));
}
// Whatever changed the timeline can just as easily have
// changed an album; one scope covers the whole photos view.
@@ -631,11 +735,12 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
range,
favorites,
not_in_album,
&excluded,
) {
Ok(Some(items)) => CtlResponse::Photos {
available: true,
items,
counts: core.db.photos_counts().ok(),
counts: core.db.photos_counts_visible(&excluded).ok(),
},
Ok(None) => CtlResponse::Photos {
available: false,
@@ -656,7 +761,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
},
Err(e) => CtlResponse::error(e),
},
Ok(CtlRequest::PhotoPlaces) => match core.photo_places() {
Ok(CtlRequest::PhotoPlaces) => match core.photo_places(&excluded) {
Ok(items) => CtlResponse::Places {
items,
mapping: core.timeline_progress(),
@@ -664,7 +769,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
Err(e) => CtlResponse::error(e),
},
Ok(CtlRequest::PlacePhotos { id, offset, limit }) => {
match core.place_photos(id, offset, clamp_limit(limit)) {
match core.place_photos(id, offset, clamp_limit(limit), &excluded) {
Ok(items) => CtlResponse::Photos {
available: true,
items,
@@ -678,7 +783,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
Err(e) => CtlResponse::error(e),
},
Ok(CtlRequest::PhotosOnThisDay { limit }) => {
match core.photos_on_this_day(clamp_limit(limit)) {
match core.photos_on_this_day(clamp_limit(limit), &excluded) {
Ok(items) => CtlResponse::Photos {
available: true,
items,
@@ -723,7 +828,10 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
// 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 core.album_photos(&album, offset, clamp_limit(limit)) {
Some(album) => match visibility
.permits(&uid)
.and_then(|()| core.album_photos(&album, offset, clamp_limit(limit), &excluded))
{
Ok(items) => CtlResponse::Photos {
available: true,
items,
@@ -765,17 +873,28 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
core.remove_from_album(album, photos)
})
}
Ok(CtlRequest::PhotoMonths { kind }) => match core.db.photos_months(kind) {
Ok(months) => CtlResponse::PhotoMonths {
months: months
.into_iter()
.map(|(year, month, count)| PhotoMonth { year, month, count })
.collect(),
Ok(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(e) => CtlResponse::error(e.into()),
Err(error) => CtlResponse::error(error),
},
Ok(CtlRequest::PhotoMonths { .. }) => unreachable!("handled before visibility requests"),
Ok(CtlRequest::PhotoThumbs { uids }) => {
let parsed: Vec<NodeUid> = uids.iter().filter_map(|u| parse_uid(u)).collect();
let parsed: Vec<NodeUid> = uids
.iter()
.filter(|uid| !visibility.media.contains(*uid))
.filter_map(|u| parse_uid(u))
.collect();
CtlResponse::Thumbs {
items: core.photo_thumbs(&parsed),
}
@@ -825,7 +944,7 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
running: core.timeline_refreshing(),
},
Ok(CtlRequest::OpenPhoto { uid }) => match parse_uid(&uid) {
Some(u) => match core.open_photo(&u) {
Some(u) => match visibility.permits(&uid).and_then(|()| core.open_photo(&u)) {
Ok(p) => CtlResponse::FilePath {
path: p.display().to_string(),
},
@@ -833,6 +952,38 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
},
None => CtlResponse::error(CoreError::invalid(format!("bad uid: {uid}"))),
},
Ok(CtlRequest::DriveGallery {
action: pdfs_core::control::GalleryAction::AuthenticateHidden,
}) => core
.authenticate_hidden_gallery(&stream)
.unwrap_or_else(CtlResponse::error),
Ok(CtlRequest::DriveGallery { action }) => core
.drive_gallery(action)
.unwrap_or_else(CtlResponse::error),
Ok(CtlRequest::OpenGalleryVideo { uid, private }) => core
.open_gallery_video(&uid, private)
.unwrap_or_else(CtlResponse::error),
Ok(CtlRequest::OpenGalleryImage { uid, private: true }) => {
core.gallery_image(&uid).unwrap_or_else(CtlResponse::error)
}
Ok(CtlRequest::OpenGalleryImage {
uid,
private: false,
}) => match visibility
.permits(&uid)
.and_then(|()| core.open_shared_file(&uid))
{
Ok(path) => CtlResponse::FilePath {
path: path.display().to_string(),
},
Err(error) => CtlResponse::error(error),
},
Ok(CtlRequest::CloseGalleryVideo { token }) => core
.close_gallery_video(&token)
.unwrap_or_else(CtlResponse::error),
Ok(CtlRequest::GalleryThumbnail { uid, private }) => core
.gallery_thumbnail(&uid, private)
.unwrap_or_else(CtlResponse::error),
// The scan alone walks every archive's central directory, so even the
// dry run goes to a background thread and is read back through
// `ImportStatus` rather than answered inline.
@@ -840,35 +991,23 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
if archives.is_empty() {
CtlResponse::error(CoreError::invalid("no Takeout archives given"))
} else {
let paths: Vec<PathBuf> = archives.into_iter().map(PathBuf::from).collect();
let missing: Vec<String> = paths
.iter()
.filter(|path| !path.is_file())
.map(|path| path.display().to_string())
.collect();
if !missing.is_empty() {
CtlResponse::error(CoreError::not_found(format!(
"cannot read: {}",
missing.join(", ")
)))
} else {
let count = paths.len();
match core.spawn_takeout_import(paths, dry_run) {
Ok(()) => CtlResponse::Ok {
message: format!(
"{} {count} archive(s)",
if dry_run { "scanning" } else { "importing" }
),
},
Err(e) => CtlResponse::error(e),
}
}
let paths = archives.into_iter().map(PathBuf::from).collect();
start_takeout_import(core, paths, dry_run)
}
}
Ok(CtlRequest::ImportStatus) => {
let (running, summary) = crate::takeout::import_status();
CtlResponse::ImportStatus { running, summary }
let report = crate::takeout::import_status();
CtlResponse::ImportStatus {
running: report.running,
summary: report.summary,
progress: report.progress,
resumable: report.resumable,
}
}
Ok(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),
},
Ok(CtlRequest::CancelImport) => {
if crate::takeout::cancel_import() {
CtlResponse::Ok {
@@ -938,6 +1077,8 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
});
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.upload_thumbnails(Path::new(&source_path), &name);
@@ -959,7 +1100,8 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
// 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.
if let Err(e) = core.rt.block_on(core.refresh_timeline()) {
core.invalidate_photos();
if let Err(e) = core.refresh_timeline_joined() {
warn!(error = %e, "timeline refresh after upload failed");
}
CtlResponse::Ok {
@@ -1200,6 +1342,10 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
Ok(entries) => CtlResponse::Entries { entries },
Err(e) => CtlResponse::error(e),
},
Ok(CtlRequest::ListTrashedFolder { uid }) => match core.list_trashed_folder(&uid) {
Ok(entries) => CtlResponse::Entries { entries },
Err(e) => CtlResponse::error(e),
},
Ok(CtlRequest::Restore { uids }) => match core.restore(&uids) {
Ok(n) => {
core.log_activity(ActivityKind::Restore, format!("{n} item(s)"), "", true);
@@ -1293,11 +1439,9 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
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| {
let mut cfg = dirs.load_config();
cfg.cache_budget = Some(bytes);
dirs.save_config(&cfg)
}) {
match AppDirs::new()
.map(|dirs| dirs.update_config(|cfg| cfg.cache_budget = Some(bytes)))
{
Ok(Ok(())) => {
core.touch_profile();
CtlResponse::Ok {
@@ -1317,10 +1461,10 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
// Persisted like the cache budget: best-effort, the live caps are
// already applied.
match AppDirs::new().map(|dirs| {
let mut cfg = dirs.load_config();
cfg.upload_limit = Some(upload);
cfg.download_limit = Some(download);
dirs.save_config(&cfg)
dirs.update_config(|cfg| {
cfg.upload_limit = Some(upload);
cfg.download_limit = Some(download);
})
}) {
Ok(Ok(())) => CtlResponse::Ok {
message: format!(
@@ -1397,6 +1541,20 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
message: format!("adding {local_path}"),
}
}
Ok(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),
}
}
Ok(CtlRequest::ListSyncFolders) => match core.list_sync_folders() {
Ok(items) => CtlResponse::SyncFolders { items },
Err(e) => CtlResponse::error(e),
@@ -1890,9 +2048,14 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
// The request did not parse: the caller sent something malformed.
Err(e) => CtlResponse::error(CoreError::invalid(format!("bad request: {e}"))),
};
let response = filter_gallery_response(response, &visibility);
if !touched.is_empty() && !matches!(response, CtlResponse::Error { .. }) {
core.events.publish(touched);
}
write_response(stream, response);
}
fn write_response(mut stream: UnixStream, response: CtlResponse) {
let mut out = match serde_json::to_vec(&response) {
Ok(v) => v,
Err(e) => {
@@ -1901,10 +2064,40 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
}
};
out.push(b'\n');
let mut stream = stream;
let _ = stream.write_all(&out);
}
fn filter_gallery_response(
mut response: CtlResponse,
visibility: &super::gallery::Visibility,
) -> CtlResponse {
let visible = |item: &pdfs_core::control::PhotoItem| !visibility.media.contains(&item.uid);
match &mut response {
CtlResponse::Photos { items, .. } => items.retain(visible),
CtlResponse::Albums { items, .. } => {
items.retain(|item| !visibility.albums.contains(&item.uid));
for album in items {
if album
.cover_uid
.as_ref()
.is_some_and(|uid| visibility.media.contains(uid))
{
album.cover_uid = None;
}
}
}
CtlResponse::PhotoDuplicates { sets } | CtlResponse::PhotoSimilar { sets, .. } => {
for set in sets.iter_mut() {
set.retain(visible);
}
sets.retain(|set| set.len() > 1);
}
CtlResponse::PhotoLocations { items } => items.retain(|located| visible(&located.photo)),
_ => {}
}
response
}
/// Listen on the control socket, serving one command per connection, each on its
/// own thread. Runs on its own thread; returns only if the listener itself fails.
///
@@ -1956,6 +2149,31 @@ pub(crate) fn run_control_socket(
}
}
/// Check that every archive is there, then start the import in the background.
fn start_takeout_import(core: &Core, paths: Vec<PathBuf>, dry_run: bool) -> CtlResponse {
let missing: Vec<String> = paths
.iter()
.filter(|path| !path.is_file())
.map(|path| path.display().to_string())
.collect();
if !missing.is_empty() {
return CtlResponse::error(CoreError::not_found(format!(
"cannot read: {}",
missing.join(", ")
)));
}
let count = paths.len();
match core.spawn_takeout_import(paths, dry_run) {
Ok(()) => CtlResponse::Ok {
message: format!(
"{} {count} archive(s)",
if dry_run { "scanning" } else { "importing" }
),
},
Err(e) => CtlResponse::error(e),
}
}
#[cfg(test)]
mod request_limit_tests {
use super::*;
+71 -36
View File
@@ -17,10 +17,10 @@ use pdfs_core::control::{
ActivityKind, DeviceInfo, JobItem, MountKind, MountSpec, SyncFolderInfo, SyncPhase,
SyncProgress,
};
use pdfs_core::db::{StoredDevice, StoredSyncFolder};
use pdfs_core::mounts::MountMode;
use pdfs_core::profile::PROFILE_DIR_NAME;
use pdfs_core::{CoreError, CoreResult};
use pdfs_store::db::{StoredDevice, StoredSyncFolder};
use proton_drive_rs::proton_sdk::ids::{DeviceUid, NodeUid};
use proton_drive_rs::{DeviceType, Node};
use std::sync::OnceLock;
@@ -33,6 +33,16 @@ use super::{
now_secs, parse_uid, spawn_session, sync_folder_info, this_hostname,
};
/// How long a removal waits for a running pass to reach a checkpoint and let
/// go of the folder. A checkpoint comes after each remote folder listing and
/// each batch of transfers, so a minute covers all but a very large upload.
const REMOVE_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(60);
/// Registration validates local and remote root overlap before inserting a
/// mapping. Serialize all registration paths so concurrent control requests
/// cannot both validate against the same old set of roots.
pub(super) static SYNC_ROOT_REGISTRATION: Mutex<()> = Mutex::new(());
/// A mode that this daemon is allowed to apply.
///
/// Persisted and control-protocol values first pass through [`MountMode`] so
@@ -118,9 +128,7 @@ pub(crate) fn sync_root_reserved() -> pdfs_core::syncroot::Reserved {
pub(crate) fn set_adopted_device_uid(uid: Option<&str>) -> CoreResult<()> {
let dirs = pdfs_core::config::AppDirs::new()
.map_err(|e| CoreError::internal(format!("config dirs: {e}")))?;
let mut cfg = dirs.load_config();
cfg.device_uid = uid.map(|u| u.to_string());
dirs.save_config(&cfg)
dirs.update_config(|cfg| cfg.device_uid = uid.map(|u| u.to_string()))
.map_err(|e| CoreError::internal(format!("write config: {e}")))
}
@@ -145,14 +153,16 @@ impl Core {
/// Unified local-location listing for the control protocol.
pub(crate) fn list_locations(&self) -> CoreResult<Vec<MountSpec>> {
let progress = self.sync_progress.lock();
let progress = self.sync.progress.lock();
let mut locations = self
.db
.mount_list()
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
for location in &mut locations {
location.mounted = self.states.is_mounted_at(Path::new(&location.local_path));
if let MountKind::Device { sync_folder_id } = &location.kind {
if let MountKind::Device { sync_folder_id } | MountKind::Attached { sync_folder_id } =
&location.kind
{
location.progress = progress.get(sync_folder_id).cloned();
location.paused = self.sync_folder_paused(*sync_folder_id);
}
@@ -495,7 +505,7 @@ impl Core {
}
/// Everything directly under a device root, trashed nodes included.
fn device_root_nodes(&self, root_uid: &NodeUid) -> CoreResult<Vec<Node>> {
pub(super) fn device_root_nodes(&self, root_uid: &NodeUid) -> CoreResult<Vec<Node>> {
let uids = self
.rt
.block_on(self.drive.enumerate_folder_children_node_uids(root_uid))
@@ -513,6 +523,7 @@ impl Core {
/// tree into it once, and record the mapping. Phase 1 is a one-shot upload —
/// the two-way engine (Phase 2) reconciles later changes.
pub(crate) fn add_sync_folder(&self, local: &Path) -> CoreResult<StoredSyncFolder> {
let _registration = SYNC_ROOT_REGISTRATION.lock();
let meta = std::fs::metadata(local)
.map_err(|e| CoreError::internal(format!("stat {}: {e}", local.display())))?;
if !meta.is_dir() {
@@ -590,8 +601,8 @@ impl Core {
// Hand the initial upload to the sync engine: an empty baseline against a
// full local tree reconciles as "upload everything", and the folder is
// added to the filesystem watch set in the same pass.
let _ = self.sync_tx.send(sync::SyncMsg::Rewatch);
let _ = self.sync_tx.send(sync::SyncMsg::Reconcile(id));
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
let _ = self.sync.tx.send(sync::SyncMsg::Reconcile(id));
info!(local = %local.display(), id, "added sync folder");
self.db
@@ -603,7 +614,9 @@ impl Core {
/// List this device's synced folders for the front-ends, each carrying the
/// live progress of its pass when one is running.
pub(crate) fn list_sync_folders(&self) -> CoreResult<Vec<SyncFolderInfo>> {
let progress = self.sync_progress.lock();
// Copied out rather than held: the pass takes this lock for every
// entry it scans, and the queries below need not stall it.
let progress = self.sync.progress.lock().clone();
Ok(self
.db
.sync_folder_list()
@@ -629,7 +642,8 @@ impl Core {
pub(crate) fn jobs_snapshot(&self) -> Vec<JobItem> {
let mut jobs = self.transfers.jobs_snapshot();
let mut passes: Vec<(i64, SyncProgress)> = self
.sync_progress
.sync
.progress
.lock()
.iter()
.map(|(id, p)| (*id, p.clone()))
@@ -684,21 +698,31 @@ impl Core {
jobs
}
/// The lock guarding sync-folder `id` against concurrent reconcile/mode-switch.
pub(crate) fn sync_lock(&self, id: i64) -> Arc<Mutex<()>> {
self.sync_locks.lock().entry(id).or_default().clone()
}
/// Remove a synced folder from the sync set. `delete_remote` also deletes its
/// folder under the device root; otherwise the cloud copy is left in place.
pub(crate) fn remove_sync_folder(&self, id: i64, delete_remote: bool) -> CoreResult<()> {
let lock = self.sync_lock(id);
let _guard = lock.lock();
let lock = self.sync.lock(id);
// A pass holds the lock for as long as it runs, hours on a large
// folder. Ask it to stop at its next checkpoint rather than wait it
// out on a control handler (B294).
self.sync.abandon.lock().insert(id);
let guard = lock.try_lock_for(REMOVE_LOCK_WAIT);
let Some(_guard) = guard else {
return Err(CoreError::conflict(
"the folder is in the middle of a sync step; try again in a minute",
));
};
self.sync.abandon.lock().remove(&id);
let folder = self
.db
.sync_folder_get(id)
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?
.ok_or_else(|| CoreError::not_found(format!("no synced folder with id {id}")))?;
if folder.kind == "attached" && delete_remote {
return Err(CoreError::invalid(
"attached My files folders cannot be deleted by stopping sync; omit --delete-remote",
));
}
// An `ondemand` folder *is* a FUSE mount over its local path, so dropping
// only the row would strand the mount: the path would keep serving a
// folder the daemon no longer tracks, and nothing would ever unmount it.
@@ -731,7 +755,7 @@ impl Core {
drop(_guard);
self.clear_sync_folder_paused(id);
// Stop watching the folder we just dropped.
let _ = self.sync_tx.send(sync::SyncMsg::Rewatch);
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
if delete_remote
&& let Some(uid) = parse_uid(&folder.remote_uid)
&& let Err(e) = self
@@ -747,8 +771,8 @@ impl Core {
/// Trigger a reconcile: one folder by id, or every folder when `id` is `None`.
pub(crate) fn sync_now(&self, id: Option<i64>) {
let _ = match id {
Some(id) => self.sync_tx.send(sync::SyncMsg::Reconcile(id)),
None => self.sync_tx.send(sync::SyncMsg::ReconcileAll),
Some(id) => self.sync.tx.send(sync::SyncMsg::Reconcile(id)),
None => self.sync.tx.send(sync::SyncMsg::ReconcileAll),
};
}
@@ -785,6 +809,11 @@ impl Core {
.sync_folder_get(id)
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?
.ok_or_else(|| CoreError::not_found(format!("no synced folder with id {id}")))?;
if folder.kind == "attached" && target_mode != ApplicableMountMode::Mirror {
return Err(CoreError::invalid(
"attached My files folders only support mirror mode; use the My files mount for online-only access",
));
}
let current_mode = ApplicableMountMode::parse(&folder.mode)
.map_err(|error| CoreError::invalid(format!("unsupported current mode: {error}")))?;
// A switch waits on the folder's reconcile, which a pause skips; refuse
@@ -796,7 +825,7 @@ impl Core {
}
if current_mode == target_mode {
let mode_str = target_mode.as_str();
let lock = self.sync_lock(id);
let lock = self.sync.lock(id);
match lock.try_lock() {
Some(_guard) => {
let current = self
@@ -814,7 +843,7 @@ impl Core {
self.db
.sync_folder_set_pending_mode(id, None)
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
let _ = self.sync_tx.send(sync::SyncMsg::Rewatch);
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
return Ok(if current.pending_mode.is_some() {
format!("staying {mode_str}")
} else {
@@ -831,7 +860,7 @@ impl Core {
self.db
.sync_folder_set_pending_mode(id, Some(mode_str))
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
let _ = self.sync_tx.send(sync::SyncMsg::Reconcile(id));
let _ = self.sync.tx.send(sync::SyncMsg::Reconcile(id));
return Ok(format!("staying {mode_str}"));
}
}
@@ -847,7 +876,7 @@ impl Core {
self.db
.sync_folder_set_pending_mode(id, Some(mode_str))
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
let _ = self.sync_tx.send(sync::SyncMsg::Reconcile(id));
let _ = self.sync.tx.send(sync::SyncMsg::Reconcile(id));
Ok(match mode {
ApplicableMountMode::OnDemand => format!(
"{} will go on-demand once its local changes are uploaded",
@@ -949,7 +978,7 @@ impl Core {
// failing is exactly "still syncing" — and it is the only reliable signal:
// the `state` column is still `idle` in the window between `add_sync_folder`
// inserting the row and the engine picking it up.
let lock = self.sync_lock(id);
let lock = self.sync.lock(id);
let Some(_guard) = lock.try_lock() else {
return Err(SwitchBlocked::NotNow);
};
@@ -960,6 +989,11 @@ impl Core {
.sync_folder_get(id)
.map_err(|e| SwitchBlocked::Failed(format!("db: {e:?}")))?
.ok_or_else(|| SwitchBlocked::Failed(format!("no synced folder with id {id}")))?;
if folder.kind == "attached" && mode != ApplicableMountMode::Mirror {
return Err(SwitchBlocked::Failed(
"attached My files folders only support mirror mode".into(),
));
}
if !pending_intent_matches(folder.pending_mode.as_deref(), expected_pending) {
return Err(SwitchBlocked::Superseded);
}
@@ -989,7 +1023,7 @@ impl Core {
.db
.sync_entries(id)
.map_err(|e| SwitchBlocked::Failed(format!("db: {e:?}")))?;
let rules = self.ignore_rules(&local);
let rules = self.syncer().ignore_rules(&local);
// Emptied before any pass saw it, the folder is still `idle`, and
// the check below would refuse the switch for good. The push pass
// of a queued switch forgets those paths instead (`docs/BUGS.md`
@@ -1048,7 +1082,7 @@ impl Core {
})?;
self.publish_secondary_mount(id, mount)
.map_err(SwitchBlocked::Failed)?;
let _ = self.sync_tx.send(sync::SyncMsg::Rewatch);
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
self.db.sync_folder_set_state(id, "idle", now_secs()).ok();
info!(id, path = %local.display(), "mounted sync folder on-demand");
Ok(format!("{} is now on-demand", local.display()))
@@ -1075,8 +1109,8 @@ impl Core {
self.db
.sync_folder_set_mode(id, "mirror")
.map_err(|e| SwitchBlocked::Failed(format!("db: {e:?}")))?;
let _ = self.sync_tx.send(sync::SyncMsg::Rewatch);
let _ = self.sync_tx.send(sync::SyncMsg::Reconcile(id));
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
let _ = self.sync.tx.send(sync::SyncMsg::Reconcile(id));
info!(id, path = %local.display(), "restored sync folder to mirror");
Ok(format!(
"{} is mirroring again; downloading",
@@ -1098,7 +1132,7 @@ impl Core {
/// that switch runs reads an unrecorded local file as new and would upload
/// a second copy of every file Drive already has.
pub(crate) fn reset_sync_folder(&self, id: i64) -> CoreResult<String> {
let lock = self.sync_lock(id);
let lock = self.sync.lock(id);
let Some(_guard) = lock.try_lock() else {
return Err(CoreError::conflict(
"this folder is syncing; try again when the pass ends",
@@ -1122,7 +1156,7 @@ impl Core {
.sync_folder_set_pending_mode(id, None)
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
}
let _ = self.sync_tx.send(sync::SyncMsg::Reconcile(id));
let _ = self.sync.tx.send(sync::SyncMsg::Reconcile(id));
info!(id, path = %folder.local_path, "sync folder reset");
Ok(format!(
"{} will sync from scratch",
@@ -1170,7 +1204,7 @@ impl Core {
}
fn mark_restore_error_if_current(&self, snapshot: &StoredSyncFolder) {
let lock = self.sync_lock(snapshot.id);
let lock = self.sync.lock(snapshot.id);
let _guard = lock.lock();
if self
.db
@@ -1199,7 +1233,7 @@ impl Core {
}
};
for folder in folders {
if folder.mode != "ondemand" {
if folder.kind != "device" || folder.mode != "ondemand" {
continue;
}
let Some(root_uid) = parse_uid(&folder.remote_uid) else {
@@ -1225,7 +1259,7 @@ impl Core {
continue;
}
};
let lock = self.sync_lock(folder.id);
let lock = self.sync.lock(folder.id);
let _guard = lock.lock();
let current = match self.db.sync_folder_get(folder.id) {
Ok(Some(current)) if restore_snapshot_matches(&folder, &current) => current,
@@ -1308,7 +1342,7 @@ impl Core {
#[cfg(test)]
mod tests {
use pdfs_core::db::StoredSyncFolder;
use pdfs_store::db::StoredSyncFolder;
use super::{
ApplicableMountMode, commit_after_teardown, migrated_name, pending_intent_matches,
@@ -1395,6 +1429,7 @@ mod tests {
fn folder(local_path: &str, remote_uid: &str, mode: &str) -> StoredSyncFolder {
StoredSyncFolder {
kind: "device".into(),
id: 7,
local_path: local_path.to_string(),
remote_uid: remote_uid.to_string(),
+103 -22
View File
@@ -13,12 +13,12 @@
//! diagnostic that blocks on the hang it is diagnosing reports nothing at
//! exactly the moment it matters.
use std::sync::LazyLock;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Instant;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, LazyLock};
use std::time::{Duration, Instant};
use parking_lot::Mutex;
use pdfs_core::control::{Diagnostics, InflightRequest, WorkerState};
use pdfs_core::control::{Diagnostics, DriveCallStat, InflightRequest, ServiceState, WorkerState};
use super::Core;
@@ -163,32 +163,77 @@ impl Core {
control_handlers: super::control::active_handlers(),
control_handler_limit: super::control::handler_limit(),
pending_ops: self.pending_ops_quickly(),
sync: Some(self.sync_engine.report()),
sync: Some(self.sync.engine.report()),
services: self
.services
.health()
.into_iter()
.map(|service| ServiceState {
name: service.name,
running: service.running,
age_secs: service.age.as_secs(),
})
.collect(),
drive_calls: self
.drive_calls
.snapshot()
.into_iter()
.map(|stat| DriveCallStat {
call: stat.call.name().to_owned(),
count: stat.count,
errors: stat.errors,
total_ms: u64::try_from(stat.total.as_millis()).unwrap_or(u64::MAX),
longest_ms: u64::try_from(stat.longest.as_millis()).unwrap_or(u64::MAX),
})
.collect(),
}
}
/// Queued mutations, or `0` if the database did not answer within
/// [`PENDING_COUNT_DEADLINE`].
fn pending_ops_quickly(&self) -> u64 {
/// Queued mutations, or `None` when the database did not answer within
/// [`PENDING_COUNT_DEADLINE`] or an earlier probe is still waiting on it.
///
/// The supervisor asks for a report every tick. One thread per report
/// would pile up behind a database that never answers, so a second probe
/// is not started until the first one has returned.
fn pending_ops_quickly(&self) -> Option<u64> {
let db = self.db.clone();
let (tx, rx) = std::sync::mpsc::channel();
if std::thread::Builder::new()
.name("pdfs-diagnostics".into())
.spawn(move || {
let counts = db.pending_op_counts().unwrap_or_default();
let total = counts.uploads.max(0) as u64 + counts.changes.max(0) as u64;
let _ = tx.send(total);
})
.is_err()
{
return 0;
}
rx.recv_timeout(PENDING_COUNT_DEADLINE).unwrap_or(0)
probe_once(&self.pending_probe, PENDING_COUNT_DEADLINE, move || {
let counts = db.pending_op_counts().ok()?;
Some(counts.uploads.max(0) as u64 + counts.changes.max(0) as u64)
})
}
}
/// Run `probe` on a thread of its own and wait up to `deadline` for it.
///
/// `None` when it did not answer in time, or when the previous probe sharing
/// `busy` has not returned yet: then no new thread is started at all.
fn probe_once<T: Send + 'static>(
busy: &Arc<AtomicBool>,
deadline: Duration,
probe: impl FnOnce() -> Option<T> + Send + 'static,
) -> Option<T> {
if busy.swap(true, Ordering::AcqRel) {
return None;
}
let done = Arc::clone(busy);
let (tx, rx) = std::sync::mpsc::channel();
let spawned = std::thread::Builder::new()
.name("pdfs-diagnostics".into())
.spawn(move || {
let answer = probe();
done.store(false, Ordering::Release);
let _ = tx.send(answer);
});
if spawned.is_err() {
busy.store(false, Ordering::Release);
return None;
}
rx.recv_timeout(deadline).ok().flatten()
}
/// How long the report waits for the database before reporting without it.
const PENDING_COUNT_DEADLINE: std::time::Duration = std::time::Duration::from_millis(500);
const PENDING_COUNT_DEADLINE: Duration = Duration::from_millis(500);
#[cfg(test)]
mod tests {
@@ -252,4 +297,40 @@ mod tests {
);
assert_eq!(parse_vm_rss("VmPeak:\t 100 kB\n"), 0);
}
#[test]
fn a_stuck_probe_is_not_started_again() {
let busy = Arc::new(AtomicBool::new(false));
let (release, wait) = std::sync::mpsc::channel::<()>();
let short = Duration::from_millis(50);
let stuck = probe_once(&busy, short, move || {
let _ = wait.recv();
Some(1)
});
assert_eq!(stuck, None, "a probe that does not answer reports nothing");
let started = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&started);
let second = probe_once(&busy, short, move || {
flag.store(true, Ordering::SeqCst);
Some(2)
});
assert_eq!(second, None);
assert!(
!started.load(Ordering::SeqCst),
"no second thread while the first is out"
);
release.send(()).unwrap();
let deadline = Instant::now() + Duration::from_secs(10);
while busy.load(Ordering::Acquire) {
assert!(Instant::now() < deadline, "the first probe never returned");
std::thread::yield_now();
}
assert_eq!(
probe_once(&busy, Duration::from_secs(10), || Some(3)),
Some(3)
);
}
}
File diff suppressed because it is too large. Load diff
+813
View File
@@ -0,0 +1,813 @@
//! Draining a create or a mkdir: sending it, adopting a twin an unanswered
//! attempt left on Drive, and swapping the placeholder for the real node.
use super::*;
impl Core {
/// Finish adopting the node `op` is for, if its create landed but could
/// not be read back.
///
/// Until it is, the tree has the node as it was made locally, and a write
/// queued over it is based on that rather than on what Drive holds. Sent
/// so, the write found our own create's revision in its way and landed as
/// a conflict copy (`docs/BUGS.md` B143).
pub(crate) fn finish_adoption(&self, op: &PendingOp) -> Result<(), Box<dyn std::error::Error>> {
let Some(real) = parse_node_uid(&op.uid) else {
return Ok(());
};
let local = match self.drain.unadopted.lock().get(&real).cloned() {
Some(local) => local,
// The map does not outlive a restart, which also forgets the
// stand-in: the row is under the real uid by then. A file as it was
// made here has no revision of Drive's (`docs/BUGS.md` B182).
None if op.kind == OP_REVISION && self.never_read_back(&real) => real.clone(),
None => return Ok(()),
};
// A node gone since is the op's to deal with.
if self.fetch_node_remote(&real)?.is_some() {
self.adopt_real_uid(&local, &real, |_| {})?;
}
self.drain.unadopted.lock().remove(&real);
debug!(%local, %real, "adopted a landed create");
Ok(())
}
/// Whether the tree has the file `real` as it was made here: its create
/// landed, but Drive's answer was never read back.
pub(crate) fn never_read_back(&self, real: &NodeUid) -> bool {
let st = self.state();
st.by_uid
.get(real)
.and_then(|ino| st.entries.get(ino))
.is_some_and(|entry| !entry.node.is_folder() && node_revision_id(&entry.node).is_none())
}
/// Make a node that so far exists only on this machine real, and adopt the
/// uid the server gives it.
pub(crate) fn drain_local_node(
&self,
op: &PendingOp,
) -> Result<(), Box<dyn std::error::Error>> {
// Drive holds the name the create is sent with once it lands, whatever
// became of the file meanwhile, until the rename or trash queued
// behind it frees it (`Core::name_is_held`).
if let (Some(parent), Some(name)) = (op.parent_uid.as_deref(), op.name.as_deref())
&& let Some(parent) = parse_node_uid(parent)
{
self.drain
.creating
.lock()
.insert(op.id, (parent, name.to_string()));
}
let created = self.create_local_node(op);
self.drain.creating.lock().remove(&op.id);
created
}
pub(crate) fn create_local_node(
&self,
op: &PendingOp,
) -> Result<(), Box<dyn std::error::Error>> {
let local = parse_node_uid(&op.uid).ok_or("pending op has an unparseable uid")?;
let parent_str = op.parent_uid.as_deref().ok_or("create op has no parent")?;
// `run_pending_drain` will not offer an op whose parent is still a
// placeholder, so reaching here with one is a bug, not a wait.
if is_local_uid_str(parent_str) {
return Err(format!("parent {parent_str} has not been created yet").into());
}
let parent = parse_node_uid(parent_str).ok_or("create op has an unparseable parent")?;
let wanted = op.name.clone().ok_or("create op has no name")?;
if self.db.has_withdrawn_create(parent_str, &wanted)? {
return Err(held_by_queued_change(&wanted));
}
// Someone else may have taken the name while this sat in the queue —
// reachable only because the op waited, which is the whole point of the
// queue. Never overwrite theirs and never drop ours: land under a
// conflict name, exactly as the sync engine does.
//
// Two things can hold the name that are not someone else's file. The
// node a create made before the network dropped its answer is ours: the
// create was queued because nobody heard back, so adopt it. And a node
// whose trash is still queued is about to let go of it.
let mut name = wanted.clone();
let mut home = parent.clone();
let mut sent = (parent_str.to_string(), wanted.clone());
let mut blob_landed = true;
// An earlier attempt, sent before the file was renamed or moved, may
// have made it and lost the answer. That node is ours where it was
// sent, and the rename follows it (`docs/BUGS.md` B184).
let mut real = match self.earlier_twin(op, parent_str, &wanted)? {
Some(EarlierTwin {
parent: was_in,
name: was_named,
twin,
holds_blob,
}) => {
info!(%local, %twin, was_named, wanted, "an earlier attempt landed unanswered under another name; adopting it");
sent = (was_in.to_string(), was_named.clone());
home = was_in;
name = was_named;
blob_landed = holds_blob;
Ok(twin)
}
None => self.create_drained_node(op, &parent, &name),
};
if real.as_ref().is_err_and(|e| is_already_exists(e.as_ref()))
&& let Some((twin, holds_blob)) = self.adoptable_twin(op, &parent, &wanted)?
{
info!(%local, %twin, wanted, "the name is held by our own unanswered create; adopting it");
real = Ok(twin);
blob_landed = holds_blob;
}
if real.as_ref().is_err_and(|e| is_already_exists(e.as_ref()))
&& self.name_is_held(op, Some(&parent), &wanted)?
{
return Err(held_by_queued_change(&wanted));
}
// What held it may have let go since Drive answered (docs/BUGS.md
// B144).
if real.as_ref().is_err_and(|e| is_already_exists(e.as_ref())) {
real = self.create_drained_node(op, &parent, &wanted);
}
if real.as_ref().is_err_and(|e| is_already_exists(e.as_ref())) {
name = conflict_name(&wanted, now_secs());
warn!(%local, wanted, name, "name is taken remotely; creating under a conflict name");
real = self.create_drained_node(op, &parent, &name);
if real.is_ok() {
self.log_activity(
ActivityKind::Upload,
&wanted,
format!("name was taken remotely; created as {name}"),
false,
);
}
}
// The folder this node was created in may have been trashed remotely
// while the op waited, in which case nothing will ever make the op
// succeed as written and retrying it forever wedges the queue behind a
// file that has bytes to save. Re-home it to the root: not where the
// user put it, but it exists, it is visible, and the bytes are intact.
//
// Not for a create a delete withdrew while it was on the wire: the
// folder is most often gone because the user removed it, with this
// file, and the file would come back in the root (`docs/BUGS.md` B168).
if let Some(root) = self.root_uid()
&& real.is_err()
&& !self.db.has_pending_op(&op.uid, OP_TRASH)?
&& self.parent_is_gone(&parent)
{
warn!(%local, name, "parent folder is gone remotely; creating in the root instead");
real = self.create_drained_node(op, &root, &name);
if real.as_ref().is_err_and(|e| is_already_exists(e.as_ref())) {
name = conflict_name(&wanted, now_secs());
real = self.create_drained_node(op, &root, &name);
}
home = root;
if real.is_ok() {
self.log_activity(
ActivityKind::Upload,
&wanted,
format!("its folder was trashed remotely; created in the root as {name}"),
false,
);
}
}
let real = real?;
// Retiring the op makes the ops behind it due: a child created in a new
// folder, a rename made while the create was on the wire. Drive answers
// a create before it lists the node, and those ops sent before then
// found no folder or dropped the rename as gone. Best effort:
// `adopt_real_uid` reads it back again and reports the failure.
let _ = self.read_back(&real);
// Retire the op before touching anything else: if we crash here the node
// exists remotely and the local placeholder is reconciled by the event
// sync, whereas a surviving op would create the file a second time.
// An adopted node made empty has not had a blob this op carries
// uploaded: it goes on as a revision of the node instead.
let uploaded = blob_landed.then_some(op.blob_path.as_deref()).flatten();
let landing = CreateLanding {
local: &local.to_string(),
real: &real.to_string(),
sent: (&sent.0, &sent.1),
landed: (&home.to_string(), &name),
};
// Counted from the op's retirement until the bytes are cached and the
// tree has the real uid, as an upload is. Uncounted, the queue read
// empty while that still ran: a delete in between took an open file
// for closed and dropped what its handle reads, and a script that
// waited for an empty queue read the file before it was cached
// (`docs/BUGS.md` B257).
let _landing = LandingUpload::begin(&self.drain.landing_uploads);
let newer = match self.retire_create(op, uploaded, &landing, &local, &real)? {
CreateRetired::Withdrawn { trash } => {
return self.trash_withdrawn_create(op, trash, &local, &real, &name);
}
retired => matches!(retired, CreateRetired::Newer { .. }),
};
// The uploaded blob is the new file's content, so it becomes the cached
// content, as for a revision. A partial write fills its gaps from it;
// without it the next write open was refused (`docs/BUGS.md` B123).
let landed: Option<StagedWrite> = uploaded
.filter(|_| !newer)
.and(op.meta_json.as_deref())
.and_then(|json| serde_json::from_str(json).ok());
// The op is gone, so the create has landed whatever the read-back
// says. One that fails is finished before anything else is sent for
// the node (`docs/BUGS.md` B143).
if let Err(e) = self.adopt_real_uid(&local, &real, |node| {
if let (Some(blob), Some(meta)) = (uploaded, &landed)
&& node_size(node) == meta.len
&& keeps_landed_upload(self.cache.is_pinned(&real), meta.len, self.cache.budget())
{
let _ =
self.cache
.store_file(&real, node.modification_time, meta.len, Path::new(blob));
}
}) {
warn!(%local, %real, error = %e, "reading back a landed create failed; adopting it later");
self.drain
.unadopted
.lock()
.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`).
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.
if let Some(blob) = uploaded {
self.cache.discard_staged(Path::new(blob));
}
if newer {
info!(%local, %real, name, "a write landed during the create; queued it as a revision");
self.wake_drain();
}
self.log_activity(ActivityKind::Upload, &name, "created", true);
info!(%local, %real, name, kind = %op.kind, "pending create landed");
Ok(())
}
/// Whether `name` is held on Drive by a change of ours that is to free it:
/// a queued trash, a queued rename away from it, or another create on the
/// wire that was sent with it in `parent`, which a rename or trash follows
/// (`Db::finish_create`). The op that wants the name waits for it rather
/// than land under a conflict name.
///
/// A trash is waited for as long as it takes. The rest only for
/// [`NAME_HOLD_ATTEMPTS`]: two files swapping names each hold the name the
/// other wants.
pub(crate) fn name_is_held(
&self,
op: &PendingOp,
parent: Option<&NodeUid>,
name: &str,
) -> Result<bool, Box<dyn std::error::Error>> {
let parent_uid = parent.map(NodeUid::to_string);
if self
.db
.has_pending_trash_named(name, parent_uid.as_deref())?
{
return Ok(true);
}
if op.attempts >= NAME_HOLD_ATTEMPTS {
return Ok(false);
}
let creating = self
.drain
.creating
.lock()
.iter()
.any(|(id, (p, n))| *id != op.id && Some(p) == parent && n == name);
Ok(creating || self.db.has_pending_move_from(name)?)
}
/// Whether a create other than `op` is on the wire under `name`, in any
/// folder.
pub(crate) fn creating_named(&self, op: &PendingOp, name: &str) -> bool {
self.drain
.creating
.lock()
.iter()
.any(|(id, (_, n))| *id != op.id && n == name)
}
/// The node an earlier attempt at create `op` made under a parent or name
/// the op has been moved from since ([`Core::adoptable_twin`]).
pub(super) fn earlier_twin(
&self,
op: &PendingOp,
parent: &str,
name: &str,
) -> Result<Option<EarlierTwin>, Box<dyn std::error::Error>> {
for (was_in, was_named) in self.db.create_targets(op.id)? {
if (was_in.as_str(), was_named.as_str()) == (parent, name) {
continue;
}
let Some(was_in) = parse_node_uid(&was_in) else {
continue;
};
match self.adoptable_twin(op, &was_in, &was_named) {
Ok(Some((twin, holds_blob))) => {
return Ok(Some(EarlierTwin {
parent: was_in,
name: was_named,
twin,
holds_blob,
}));
}
Ok(None) => {}
Err(e) if is_gone(e.as_ref()) => {}
Err(e) => return Err(e),
}
}
Ok(None)
}
/// The node already holding `name` under `parent`, if it is the one an
/// earlier attempt at this op made before its answer was lost, and whether
/// it holds the op's blob already.
///
/// A create that timed out may still have landed; the op was queued because
/// the caller never heard back. Without this, its replay forked a
/// `(sync-conflict)` copy of a file nobody else had touched.
pub(crate) fn adoptable_twin(
&self,
op: &PendingOp,
parent: &NodeUid,
name: &str,
) -> Result<Option<(NodeUid, bool)>, Box<dyn std::error::Error>> {
// A second file queued under the same name, after the first was
// renamed away, finds the first one's node fresh and empty while its
// create is on the wire. Taking it put both files on one node, and the
// first one's rename took the second one's bytes along
// (docs/BUGS.md B147).
let racing = self
.drain
.creating
.lock()
.iter()
.any(|(id, (p, n))| *id != op.id && p == parent && n == name);
if racing {
return Ok(None);
}
let uids = self.block_on_bounded(self.drive.enumerate_folder_children_node_uids(parent))?;
let children = self.block_on_bounded(self.drive.enumerate_nodes_light(&uids))?;
// A node this mount trashed is not one an unanswered create made, even
// 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 Some(twin) = children
.into_iter()
.find(|node| node.name == name && !node.trashed && !hidden.contains(&node.uid))
else {
return Ok(None);
};
// A node in the tree was answered for, by this mount or by a listing:
// the same race after the first create landed. Without the adoption,
// an unanswered twin forks a conflict copy, which loses nothing.
if self.state().by_uid.contains_key(&twin.uid) {
return Ok(None);
}
// The light listing carries no file size or digest.
let twin = match twin.kind {
NodeKind::Folder => twin,
NodeKind::File { .. } => match self.fetch_node_remote(&twin.uid)? {
Some(node) => node,
None => return Ok(None),
},
};
// A create uploads its bytes in the same call, so the node a lost
// answer leaves holds them (docs/BUGS.md B127): the ones the op holds
// now, or ones a write has replaced since (B156), which still go up.
let current = match op.blob_path.as_deref() {
Some(blob) if node_size(&twin) > 0 => Some(staged_sha1(Path::new(blob))?),
_ => None,
};
let holds_blob = current
.as_deref()
.is_some_and(|sha| holds_bytes(&twin, sha));
let sent = self.create_sent_digests(op.id, current);
Ok(
adoptable(op.kind == OP_MKDIR, &twin, self.first_sent(op), &sent)
.then_some((twin.uid, holds_blob)),
)
}
/// The SHA-1s of the bytes queued create `id` may have made its file with:
/// `current`, those of the blob it holds now, and those each earlier
/// attempt uploaded.
pub(crate) fn create_sent_digests(&self, id: i64, current: Option<String>) -> Vec<String> {
let mut sent = self.db.create_sent(id).unwrap_or_else(|e| {
warn!(id, error = %e, "reading what a queued create sent failed");
Vec::new()
});
sent.extend(current);
sent
}
/// When create `op` first went out, which is the earliest a node its lost
/// answer left can have been made. An op queued offline may wait for days
/// before that; measured from when it was queued, the adoption window let
/// it take a node another device made in the meantime. Ops sent before the
/// time was recorded fall back to when they were queued.
pub(crate) fn first_sent(&self, op: &PendingOp) -> i64 {
match self.db.create_first_sent(op.id) {
Ok(Some(at)) => at.max(op.created_at),
Ok(None) => op.created_at,
Err(e) => {
warn!(id = op.id, error = %e, "reading when a queued create was sent failed");
op.created_at
}
}
}
/// Make one queued `create`/`mkdir` real under a given name, and hand back
/// the API's own error so the caller can tell a name clash from a failure.
///
/// Split out because the conflict path has to run it twice: the second time
/// under a different name.
pub(crate) fn create_drained_node(
&self,
op: &PendingOp,
parent: &NodeUid,
name: &str,
) -> Result<NodeUid, Box<dyn std::error::Error>> {
self.db
.note_create_target(op.id, &parent.to_string(), name, now_millis())?;
match op.kind == OP_MKDIR {
true => Ok(self.block_on_bounded(self.drive.create_folder(
parent,
name,
Some(now_secs()),
))?),
false => self.upload_created_file(op, parent, name),
}
}
/// Upload the bytes a queued create accumulated, if any. A file that was
/// created but never written (`touch`) has no blob and uploads as empty.
pub(crate) fn upload_created_file(
&self,
op: &PendingOp,
parent: &NodeUid,
name: &str,
) -> Result<NodeUid, Box<dyn std::error::Error>> {
let Some(blob) = op.blob_path.as_deref() else {
return Ok(self.block_on_bounded(self.drive.upload_file(
parent,
name,
media_type_for(name),
b"",
))?);
};
let meta: StagedWrite = serde_json::from_str(op.meta_json.as_deref().unwrap_or(""))?;
// An incomplete blob would be authored bytes over zeros, and there is no
// base to repair it from — the file has never existed remotely. Refusing
// to queue that is `queue_revision`'s job, so reaching here means the blob
// is whole.
if !meta.complete {
return Err("queued create holds an incomplete blob".into());
}
// The call may make the file and lose its answer, and the op may hold
// 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 guard = self
.transfers
.begin(name, op.uid.clone(), TransferDirection::Upload, meta.len);
let reader = CountingReader::new(File::open(blob)?, &guard);
let uid = self.block_on_within(
link::upload_deadline(meta.len, self.transfers.upload_cap()),
self.drive.upload_file_from(
parent,
name,
media_type_for(name),
reader,
meta.len as i64,
thumbnails,
None,
false,
),
)?;
Ok(uid)
}
/// Retire a landed create's op and move its queued state to the real uid,
/// unless the create was withdrawn while it was on the wire.
///
/// Runs under the `pending` lock, which `Core::enqueue_staged_write` also
/// holds from attaching a blob to a create until it records the pending
/// entry. So a write either attached before this ran and is carried over,
/// or finds the create gone and queues against the real uid itself. The
/// open write handles are repointed right after, for the same reason:
/// a handle released later must not queue against the placeholder.
pub(crate) fn retire_create(
&self,
op: &PendingOp,
uploaded: Option<&str>,
landing: &CreateLanding<'_>,
local: &NodeUid,
real: &NodeUid,
) -> Result<CreateRetired, Box<dyn std::error::Error>> {
let retired = {
let mut pending = self.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();
serde_json::to_string(&meta).ok()
})?;
// A withdrawn create's placeholder is the delete's to clean up, and
// an open handle may still read its pending entry.
if let CreateRetired::Withdrawn { .. } = retired {
return Ok(retired);
}
pending.remove(local);
if let CreateRetired::Newer { blob, meta } = &retired {
let meta: StagedWrite = serde_json::from_str(meta)?;
pending.insert(
real.clone(),
PendingRevision {
path: PathBuf::from(blob),
meta,
},
);
}
retired
};
#[cfg(test)]
self.drive.landing(real);
if retired == CreateRetired::Landed
&& let Some(blob) = uploaded
{
self.cache_created(op, local, real, blob);
}
self.for_each_state(|st| {
if let Some(ino) = st.by_uid.remove(local) {
st.by_uid.insert(real.clone(), ino);
// The node too: the next write of it upserts the row by the
// node's uid, and would bring the placeholder row back.
if let Some(e) = st.entries.get_mut(&ino) {
e.uid = real.clone();
e.node.uid = real.clone();
}
// Its children still name the placeholder as their parent, and
// the next write of one would put it back on the row.
for kid in st.children.get(&ino).cloned().unwrap_or_default() {
if let Some(e) = st.entries.get_mut(&kid)
&& e.node.parent_uid.as_ref() == Some(local)
{
e.node.parent_uid = Some(real.clone());
}
}
}
for aw in st.active_writes.values_mut() {
if aw.uid == *local {
aw.uid = real.clone();
}
}
});
Ok(retired)
}
/// Cache a landed create's uploaded `blob` under `real`, keyed as the tree
/// has the file.
///
/// A write handle open on the file is repointed at `real` right after this,
/// and a release fills its gaps from the cache by the size and mtime it
/// opened over. Drive lists the new node a moment after the create, so
/// `adopt_real_uid` caches the bytes only once it can read the node back.
/// A release in between found nothing to fill from, and the next write open
/// was refused (docs/BUGS.md B131).
pub(crate) fn cache_created(
&self,
op: &PendingOp,
local: &NodeUid,
real: &NodeUid,
blob: &str,
) {
let Some(meta) = op
.meta_json
.as_deref()
.and_then(|json| serde_json::from_str::<StagedWrite>(json).ok())
else {
return;
};
let mut mtime = None;
self.for_each_state(|st| {
if let Some(entry) = st.by_uid.get(local).and_then(|ino| st.entries.get(ino)) {
mtime = Some(entry.node.modification_time);
}
});
if let Some(mtime) = mtime
&& keeps_landed_upload(self.cache.is_pinned(real), meta.len, self.cache.budget())
{
let _ = self
.cache
.store_file(real, mtime, meta.len, Path::new(blob));
}
}
/// Swap a placeholder uid for the real one across everything that keyed off
/// it: queued children, the DB, the in-memory tree, and the caches.
///
/// The inode is deliberately kept, so anything already holding the file open
/// keeps working across the drain.
///
/// Applied to the tree every mount shares. A node created inside an
/// on-demand sync folder once lived in that fork's own state, where the
/// primary mount's drain never looked, and stayed on its `local~` uid —
/// an empty file for as long as the daemon ran (`docs/BUGS.md` B74).
///
/// `adopt` sees the node as Drive made it, before anything is rebased onto
/// it.
pub(crate) fn adopt_real_uid(
&self,
local: &NodeUid,
real: &NodeUid,
adopt: impl FnOnce(&Node),
) -> Result<(), Box<dyn std::error::Error>> {
// A rename made while the create was on the wire is queued against the
// real uid (`Db::finish_create`). Until it lands, the tree keeps the
// name and folder the user gave it. Asked before the read-back: a
// rename that lands while Drive answers leaves no op behind, and the
// answer may still have the old name (`docs/BUGS.md` B161).
let real_key = real.to_string();
let renaming = self.db.has_pending_op(&real_key, OP_RENAME)?;
// Drive answers a create before it lists the new node.
let mut node = self
.read_back(real)
.map_err(|e| self.errno_error(e, "fetch node"))?;
// Before open handles are rebased onto the node, so one released in
// between finds what `adopt` keeps (`docs/BUGS.md` B123).
adopt(&node);
// What Drive holds is the base open handles and queued writes are
// rebased onto below. The tree shows a write queued over it, as a
// listing does: a write open sized from the landed node over a shorter
// queued blob left a gap that refused the next open (`docs/BUGS.md`
// B123).
let remote = node.clone();
self.stamp_pending_sizes(std::slice::from_mut(&mut node));
// The rows and queued ops already follow the node: `retire_create`
// moved its row to the real uid, and ops find it by local id.
self.for_each_state(|st| {
if let Some(ino) = st.by_uid.remove(local) {
st.by_uid.insert(real.clone(), ino);
}
let Some(&ino) = st.by_uid.get(real) else {
st.write_through(node.clone());
return;
};
// Asked again under the lock: `Core::queue_rename` queues its op
// before it renames the entry under this lock. Asked only before,
// a rename made since was overwritten with the name the create was
// sent with, here and in the node row (`docs/BUGS.md` B152).
let renaming =
renaming || matches!(self.db.has_pending_op(&real_key, OP_RENAME), Ok(true));
if renaming && let Some(e) = st.entries.get(&ino) {
node.name = e.node.name.clone();
node.parent_uid = e.node.parent_uid.clone();
}
st.write_through(node.clone());
let mut landed = node.clone();
st.keep_open_write_size(ino, &mut landed);
if let Some(e) = st.entries.get_mut(&ino) {
e.uid = real.clone();
e.node = landed;
}
// Where the op said the node goes and where it actually landed can
// differ — a conflict re-homes it — so the tree follows the parent
// the server reports rather than the one we asked for.
if let Some(parent) = node.parent_uid.clone()
&& let Some(&pino) = st.by_uid.get(&parent)
&& st.entries.get(&ino).is_some_and(|e| e.parent != pino)
{
let old = st.entries.get(&ino).map(|e| e.parent);
if let Some(old) = old
&& let Some(kids) = st.children.get_mut(&old)
{
kids.retain(|&k| k != ino);
}
if let Some(e) = st.entries.get_mut(&ino) {
e.parent = pino;
}
if let Some(kids) = st.children.get_mut(&pino)
&& !kids.contains(&ino)
{
kids.push(ino);
}
}
});
// A handle still open on the placeholder was based on no revision at
// all: a local-clock mtime and no revision id. Released as it is, its
// write would land as a conflict copy of the empty file this create just
// made (`docs/BUGS.md` B113). Rebased before the restamp below, so a
// release that races this is caught there.
//
// A release that took its base before the rebase and queues after the
// restamp is caught by neither. The revision this create sealed is
// ours, as one a revision upload sealed is, so the drain chains that
// write onto it instead of forking a conflict copy (B70 layer B).
if let Some(rev) = node_revision_id(&remote)
&& let Err(e) = self
.db
.set_own_sealed_rev(&real.to_string(), &rev, now_millis())
{
warn!(%real, error = %e, "persisting our sealed revision failed");
}
self.rebase_open_writes(real, &remote);
// A write carried over from the create was made against no revision at
// all; the one just created is what it now replaces.
self.rebaseline_pending(real, &remote);
if node.is_folder() {
// It was recorded as listed while local (it was empty and had nothing
// to enumerate). That still holds: its queued children re-intern under
// the real uid as they drain.
if let Err(e) = self.db.set_listed(real, true) {
warn!(%real, error = %e, "db set_listed(true) failed after remap");
}
}
Ok(())
}
/// Retire parks that are never going to end (docs/BUGS.md B70).
///
/// A parked create waits for one event: the rename from the transient name
/// to the finished one. Nothing else ever un-parks it, and plenty of writers
/// never perform it — an editor unlinks its swap file, a download is
/// abandoned, or the file was always going to be called `index.tmp`. Such a
/// row stayed at [`PARK_UNTIL`] for the life of the database, pinning the
/// only copy of its bytes in `staging/` and counting against the queue.
///
/// Two outcomes, and neither deletes bytes a user can still see:
///
/// * The node is gone from the tree — the file was deleted while its create
/// was parked, so the create is no longer wanted. The op and its blob go,
/// which is what [`Core::discard_queued_ops`] would have done had the
/// delete path reached it.
/// * The node is still there and has been parked past
/// [`PARK_EXPIRY_MS`] with nothing holding it open — the park has outlived
/// the writer it was protecting. Un-park it, and the ordinary drain
/// uploads it like any other create.
///
/// An open node is left alone whatever its age: it is still being written.
pub(crate) fn sweep_parked_creates(&self) {
let parked = match self.db.parked_create_ops() {
Ok(parked) if !parked.is_empty() => parked,
Ok(_) => return,
Err(error) => {
warn!(%error, "reading parked creates failed; skipping the park sweep");
return;
}
};
let now = now_millis();
let (mut released, mut dropped) = (0usize, 0usize);
for op in &parked {
let Some(uid) = parse_node_uid(&op.uid) else {
continue;
};
let name = op.name.as_deref().unwrap_or("?");
let listed = match self.db.node_by_uid(&op.uid) {
Ok(known) => known.is_some(),
// Never infer "deleted" from a failed read: that would discard
// the bytes over a transient database error.
Err(error) => {
debug!(%uid, %error, "cannot tell whether a parked node still exists");
continue;
}
};
match park_verdict(op.created_at, now, self.uid_is_open(&uid), listed) {
ParkVerdict::Keep => continue,
ParkVerdict::Drop => {
if let Err(error) = self.discard_queued_ops(&uid) {
warn!(%uid, name, ?error, "dropping a deleted transient's parked create failed");
continue;
}
dropped += 1;
debug!(%uid, name, "dropped a parked create whose file was deleted");
continue;
}
ParkVerdict::Release => {}
}
match self.db.set_create_hold(&op.uid, false) {
Ok(true) => {
released += 1;
info!(%uid, name, parked_ms = now - op.created_at,
"un-parked a transient create that was never renamed; uploading it");
}
Ok(false) => {}
Err(error) => warn!(%uid, name, %error, "un-parking an expired park failed"),
}
}
if released > 0 || dropped > 0 {
info!(released, dropped, "swept parked creates");
}
if released > 0 {
self.wake_drain();
}
}
}
+203
View File
@@ -0,0 +1,203 @@
//! Draining a rename or a move.
use super::*;
impl Core {
/// Apply a queued rename/move to the remote.
///
/// The op is the desired end state, so the remote's current state decides
/// what actually has to be called: either half may already match (the event
/// sync saw someone else do it, or an earlier attempt got half way through
/// before failing). That also makes the whole thing idempotent, which a
/// retrying queue needs.
pub(crate) fn drain_rename(&self, op: &PendingOp) -> Result<(), Box<dyn std::error::Error>> {
let uid = parse_node_uid(&op.uid).ok_or("rename op has an unparseable uid")?;
let parent_str = op.parent_uid.as_deref().ok_or("rename op has no parent")?;
if is_local_uid_str(parent_str) {
return Err(format!("destination {parent_str} has not been created yet").into());
}
let parent = parse_node_uid(parent_str).ok_or("rename op has an unparseable parent")?;
let name = op.name.clone().ok_or("rename op has no name")?;
// A trashed node can be restored. Only retire the operation if the node
// is gone entirely.
let node = match self.fetch_node_remote(&uid)? {
Some(n) if n.trashed => return Err(TrashedMove(n.name).into()),
Some(n) => n,
None => {
warn!(%uid, name, "renamed node is gone remotely; dropping the rename");
self.db.delete_op(op.id)?;
return Ok(());
}
};
let meta: Option<RenameMeta> = op
.meta_json
.as_deref()
.map(serde_json::from_str)
.transpose()?;
if let Some(meta) = &meta
&& moved_elsewhere(meta, &node, &parent, &name)
{
// Someone moved or renamed it while ours was queued. Ours still
// wins, as the last change does on Drive.
info!(%uid, from = %node.name, to = %name,
"node moved remotely while its rename was queued");
}
let landed = if node.parent_uid.as_ref() == Some(&parent) {
self.drain_rename_in_place(op, &uid, Some(&parent), &node.name, &name)?
} else {
// Move and rename land as one request (`move-multiple` takes a
// target name), so there is no half-applied state between them and
// no window for the requirements to go stale between two calls —
// the race B46 queued this op to get away from.
let target = (node.name != name).then_some(name.as_str());
let try_move = |target| {
self.move_rename_remote(&uid, &parent, target).map_err(
|error| -> Box<dyn std::error::Error> {
if (is_gone(&error) || refusal(&error) == Some(Some(SyncIssue::Access)))
&& let Some(name) = trashed_move_folder(
node.parent_uid.iter().chain(std::iter::once(&parent)),
|uid| self.fetch_node_remote(uid).ok().flatten(),
)
{
return TrashedMove(name).into();
}
error.into()
},
)
};
match try_move(target) {
Ok(()) => name.clone(),
// The destination holds that name already. Landing under a
// *different* name is the non-destructive resolution: it neither
// clobbers their file nor drops ours, and it is visible.
Err(e) if is_already_exists(e.as_ref()) => {
if self.name_is_held(op, Some(&parent), &name)? {
return Err(held_by_queued_change(&name));
}
// What held it may have let go since Drive answered
// (docs/BUGS.md B144).
match try_move(target) {
Ok(()) => name.clone(),
Err(e) if is_already_exists(e.as_ref()) => {
let alt = conflict_name(&name, now_secs());
warn!(%uid, name, alt, "destination already holds that name; using a conflict name");
try_move(Some(&alt))?;
self.adopt_drained_name(&uid, &alt);
self.log_activity(
ActivityKind::Rename,
&name,
format!("destination already had that name; moved as {alt}"),
false,
);
alt
}
Err(e) => return Err(e),
}
}
// The destination folder is gone. Leaving the node in its current
// parent is the honest outcome: it is not where the user asked for
// it, but it exists and it is where it has always been. The name
// the user chose still applies there. Retrying the move could
// only fail again — the folder is not coming back — and would
// wedge the queue.
Err(e) if is_gone(e.as_ref()) => {
warn!(%uid, name, %parent, "move destination is gone; leaving the node where it is");
let landed = match self.drain_rename_in_place(
op,
&uid,
node.parent_uid.as_ref(),
&node.name,
&name,
) {
Ok(landed) => landed,
// The node went with it; nothing is left to rename.
Err(e) if is_gone(e.as_ref()) => node.name.clone(),
Err(e) => return Err(e),
};
self.log_activity(
ActivityKind::Rename,
&landed,
"destination folder no longer exists; the file was left in place"
.to_string(),
false,
);
landed
}
Err(e) => return Err(e),
}
};
self.db.delete_op(op.id)?;
// An op that wanted the name this node let go of waits no longer.
if let Some(from) = meta.and_then(|m| m.original_name)
&& from != landed
{
self.db.wake_ops_waiting_for(&from)?;
self.wake_drain();
}
info!(%uid, name = %landed, "pending rename landed");
Ok(())
}
/// Rename `uid` without moving it, from `current` to `name`, and return the
/// name it landed under. Someone may have taken the name while we were
/// offline; the node then lands under a conflict name instead.
pub(crate) fn drain_rename_in_place(
&self,
op: &PendingOp,
uid: &NodeUid,
parent: Option<&NodeUid>,
current: &str,
name: &str,
) -> Result<String, Box<dyn std::error::Error>> {
if current == name {
return Ok(current.to_string());
}
match self.rename_remote(uid, name) {
Ok(()) => Ok(name.to_string()),
Err(e) if is_already_exists(&e) => {
if self.name_is_held(op, parent, name)? {
return Err(held_by_queued_change(name));
}
// What held it may have let go since Drive answered
// (docs/BUGS.md B144).
match self.rename_remote(uid, name) {
Ok(()) => return Ok(name.to_string()),
Err(e) if is_already_exists(&e) => {}
Err(e) => return Err(e.into()),
}
let alt = conflict_name(name, now_secs());
warn!(%uid, name, alt, "rename target name is taken; using a conflict name");
self.rename_remote(uid, &alt)?;
self.adopt_drained_name(uid, &alt);
self.log_activity(
ActivityKind::Rename,
name,
format!("name was taken remotely; renamed to {alt}"),
false,
);
Ok(alt)
}
Err(e) => Err(e.into()),
}
}
/// Record the name the remote actually gave a node, after a conflict forced
/// it away from the one the user asked for. Best effort: the event sync
/// would correct the tree anyway, but not before the user has looked at it.
pub(crate) fn adopt_drained_name(&self, uid: &NodeUid, name: &str) {
self.for_each_state(|st| {
let Some(&ino) = st.by_uid.get(uid) else {
return;
};
let Some(entry) = st.entries.get_mut(&ino) else {
return;
};
entry.node.name = name.to_string();
let node = entry.node.clone();
if let Err(e) = st.db.upsert_node(&node) {
warn!(%uid, error = %e, "db upsert_node failed after a conflict rename");
}
});
}
}
+702
View File
@@ -0,0 +1,702 @@
//! Draining a revision: the upload, the conflict check before it, and
//! placing what landed in the tree and the cache.
use super::*;
impl Core {
/// How long a freshly queued revision of `uid` should wait before a worker
/// may pick it up.
///
/// [`DRAIN_REVISION_DEBOUNCE`] exists for a tool that preallocates a file
/// and then writes it, where two seconds is the right scale. It is the wrong
/// scale for a large file on a slow link: an editor saving a 200 MB project
/// every ten seconds queues a write, the drain starts sending it, the next
/// save supersedes it mid-flight, and the file never finishes uploading
/// while the user keeps working. Waiting roughly as long as the last upload
/// of *this* node took moves that supersede into the queue, where replacing
/// a row costs nothing.
///
/// Never shorter than the fixed debounce and never longer than
/// [`DRAIN_REVISION_DEBOUNCE_MAX`]: a node whose upload is genuinely slow
/// still has to reach Drive, and a single pathological stall must not park
/// it.
///
/// [`DRAIN_REVISION_DEBOUNCE`]: crate::DRAIN_REVISION_DEBOUNCE
/// [`DRAIN_REVISION_DEBOUNCE_MAX`]: crate::DRAIN_REVISION_DEBOUNCE_MAX
pub(crate) fn revision_debounce(&self, uid: &NodeUid) -> Duration {
let measured = self
.drain
.upload_times
.lock()
.get(&uid.to_string())
.map(|&(ms, _)| Duration::from_millis(ms));
adaptive_debounce(measured)
}
/// Remember how long an upload of `uid` took, for the next write's
/// debounce.
///
/// Only a *completed* upload is a measurement. A cancelled or failed one
/// says how long it ran before it stopped, which is not how long the file
/// takes to send, and feeding that back would let one network fault widen
/// the debounce for good.
pub(crate) fn record_upload_time(&self, uid: &NodeUid, took: Duration) {
let mut times = self.drain.upload_times.lock();
let now = now_millis();
if times.len() >= UPLOAD_TIME_MEMORY
&& !times.contains_key(&uid.to_string())
&& let Some(oldest) = times
.iter()
.min_by_key(|(_, (_, at))| *at)
.map(|(k, _)| k.clone())
{
times.remove(&oldest);
}
times.insert(uid.to_string(), (took.as_millis() as u64, now));
}
/// Register a cancellation flag for an upload of `uid` that is about to
/// start, returning a guard that deregisters it.
///
/// Deregistration is by identity rather than by key: a supersede that
/// arrives just as this upload finishes may already have registered the
/// *next* upload's flag under the same uid, and removing that one would
/// leave the newer upload uncancellable.
pub(super) fn begin_cancellable_upload(&self, uid: &NodeUid) -> UploadCancel {
let flag = Arc::new(AtomicBool::new(false));
self.drain
.upload_cancel
.lock()
.insert(uid.clone(), flag.clone());
UploadCancel {
registry: self.drain.upload_cancel.clone(),
uid: uid.clone(),
flag,
}
}
/// Tell an upload of `uid` that is on the wire to stop, if there is one.
///
/// Called when a newer revision of the file is queued. The upload does not
/// stop instantly — it stops when the SDK next asks its reader for bytes,
/// which for a 4 MiB block is soon enough to matter and late enough to be
/// safe: the staged blob it is reading stays open until it lets go.
pub(crate) fn cancel_upload(&self, uid: &NodeUid) {
if let Some(flag) = self.drain.upload_cancel.lock().get(uid) {
flag.store(true, Ordering::Relaxed);
debug!(%uid, "cancelling a superseded upload");
}
}
/// Why a queued write must not be applied to its node, or `None` when it
/// still can be.
///
/// A queued write is an edit of a specific revision. Time passes before it
/// drains — indefinitely, if that is how long the network is gone — and in
/// that window the node can be rewritten by another device, trashed, or
/// deleted outright. Sending the blob anyway would silently drop whatever
/// happened in between, which is exactly the thing the sync engine refuses
/// to do.
///
/// Only checkable against a recorded baseline: a write staged before
/// [`StagedWrite::based_on`] existed, or one against a node that has never
/// existed remotely, has nothing to compare and is applied as before.
pub(crate) fn revision_conflict(
&self,
uid: &NodeUid,
meta: &StagedWrite,
blob: &Path,
) -> Result<Option<String>, Box<dyn std::error::Error>> {
let Some(ref base) = meta.based_on else {
return Ok(None);
};
let Some(node) = self.fetch_node_remote(uid)? else {
return Ok(Some("the file no longer exists remotely".into()));
};
if node.trashed {
return Ok(Some("the file was trashed remotely".into()));
}
let Some(reason) = revision_changed(base, &node) else {
return Ok(None);
};
// The remote moved on from the baseline — normally a conflict. But if it
// sits at a revision *this daemon* sealed, no other device changed the
// file: it is a single-writer stall→resume (a browser that closed and
// reopened its download fd; B70 layer B). Chain onto it — supersede
// instead of forking — so the finished bytes win the name rather than
// being exiled to a `(sync-conflict)` copy.
let remote_rev = node_revision_id(&node);
// The table, so the answer survives a restart (`own_sealed_rev`).
let own_rev = self
.db
.own_sealed_rev(&uid.to_string(), now_millis())
.unwrap_or_default();
if is_own_self_supersede(meta.complete, remote_rev.as_deref(), own_rev.as_deref()) {
debug!(%uid, ?remote_rev,
"queued write chains onto our own sealed revision; not a conflict");
return Ok(None);
}
// An earlier attempt at this write may have landed with its answer
// lost: the remote then holds these very bytes in a revision we never
// heard of. Forked, the write was a conflict copy of itself
// (docs/BUGS.md B155); sent again, it is a revision of the same bytes.
if meta.complete
&& node_size(&node) == meta.len
&& let NodeKind::File {
content_sha1: Some(remote),
..
} = &node.kind
&& remote.eq_ignore_ascii_case(&staged_sha1(blob)?)
{
debug!(%uid, ?remote_rev, "the remote already holds the queued write; not a conflict");
return Ok(None);
}
// An upload of ours landed and its read-back went unanswered, so its
// revision id was never recorded as ours. The bytes it sent say the
// same: the remote holds them, so no other device wrote since
// (docs/BUGS.md B157).
let sealed = self.drain.sealed_unread.lock().get(uid).cloned();
if meta.complete
&& let Some(sealed) = sealed
&& let NodeKind::File {
content_sha1: Some(remote),
..
} = &node.kind
&& remote.eq_ignore_ascii_case(&sealed)
{
debug!(%uid, ?remote_rev, "queued write chains onto our own unread revision; not a conflict");
return Ok(None);
}
Ok(Some(reason))
}
/// Land a queued write that can no longer be applied to its own node as a
/// *new* file beside it, and retire the op.
///
/// The non-destructive resolution, and the same one the sync engine reaches
/// for: the remote keeps whatever it has, the user keeps their bytes, and
/// the name says which is which.
///
/// An incomplete blob is gap-filled from whatever the node holds *now* —
/// mixing revisions, which is only defensible because the result is
/// explicitly a conflict copy rather than anyone's file. When even that is
/// impossible the op is dropped but the staged bytes are deliberately left
/// on disk: unreachable through the mount, but not destroyed, and the
/// activity log says where they are.
pub(crate) fn keep_as_conflict_copy(
&self,
op: &PendingOp,
blob: &Path,
meta: &StagedWrite,
uid: &NodeUid,
reason: &str,
) -> Result<(), Box<dyn std::error::Error>> {
let place = self.node_place(uid);
let name = place
.as_ref()
.map(|(_, n)| n.clone())
.unwrap_or_else(|| self.node_name(uid));
// A node the tree has forgotten still has bytes worth keeping, so the
// copy falls back to the root rather than being abandoned. So does one
// whose folder went with it: an upload into a folder Drive no longer
// has fails on every retry (B150).
let folder = match place.map(|(p, _)| p) {
Some(p) if self.fetch_node_remote(&p)?.is_some_and(|n| !n.trashed) => Some(p),
_ => None,
};
let Some(parent) = folder.or_else(|| self.root_uid()) else {
return self.abandon_to_staging(op, blob, uid, &name, reason);
};
warn!(%uid, name, reason, "queued write conflicts; keeping a conflict copy");
if !meta.complete {
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(blob)?;
let mut written = Intervals::default();
for &(s, e) in &meta.authored {
written.add(s, e);
}
if let Err(e) = self.fill_gaps(
uid,
&file,
meta.len,
meta.base_mtime,
meta.base_size,
&written,
) {
error!(%uid, name, error = ?e, "cannot complete a conflicted partial write");
return self.abandon_to_staging(op, blob, uid, &name, reason);
}
}
let alt = conflict_name(&name, now_secs());
let thumbnails = self.upload_thumbnails(blob, &alt);
let guard =
self.transfers
.begin(&alt, meta.uid.clone(), TransferDirection::Upload, meta.len);
let reader = CountingReader::new(File::open(blob)?, &guard);
self.block_on_within(
link::upload_deadline(meta.len, self.transfers.upload_cap()),
self.drive.upload_file_from(
&parent,
&alt,
media_type_for(&alt),
reader,
meta.len as i64,
thumbnails,
None,
false,
),
)?;
drop(guard);
self.db.delete_op(op.id)?;
// Dropping the pending entry hands the node back to the remote's truth:
// reads stop coming from the staged blob, and the event sync stops
// skipping it as "ahead of the server". Only if it
// is still *this* write's entry — see [`Core::release_pending`].
self.release_pending(uid, blob);
self.cache.discard_staged(blob);
self.cache.evict(uid);
self.evict_reader(uid);
// The conflict copy is a node the tree has never seen.
self.for_each_state(|st| {
if let Some(&ino) = st.by_uid.get(&parent) {
st.invalidate_listing(ino);
}
});
self.log_activity(
ActivityKind::Upload,
&name,
format!("{reason}; local changes uploaded as {alt}"),
false,
);
self.events.publish(&[
pdfs_core::control::Topic::Files,
pdfs_core::control::Topic::Conflicts,
]);
info!(%uid, name, alt, "queued write landed as a conflict copy");
Ok(())
}
/// Give up on placing a queued write anywhere the mount can see, without
/// destroying it: the op goes (it could only fail forever) but the staged
/// blob deliberately stays on disk, and the activity log says where.
///
/// The last resort of the conflict path, and the same bargain
/// [`Core::stage_orphaned_write`] strikes at the other end: bytes we cannot
/// place are still bytes we do not get to delete.
pub(crate) fn abandon_to_staging(
&self,
op: &PendingOp,
blob: &Path,
uid: &NodeUid,
name: &str,
reason: &str,
) -> Result<(), Box<dyn std::error::Error>> {
error!(%uid, name, reason, staged = %blob.display(),
"cannot place a conflicted write; bytes kept in staging");
self.db.delete_op(op.id)?;
self.release_pending(uid, blob);
self.cache.evict(uid);
self.evict_reader(uid);
self.log_activity(
ActivityKind::Upload,
name,
format!("{reason}; local changes kept at {}", blob.display()),
false,
);
Ok(())
}
/// Upload a staged revision of a file the server already knows about.
pub(crate) fn drain_revision(&self, op: &PendingOp) -> Result<(), Box<dyn std::error::Error>> {
let op_started = Instant::now();
let blob = op
.blob_path
.clone()
.ok_or("pending op has no staged blob")?;
let blob = PathBuf::from(blob);
let mut meta: StagedWrite = serde_json::from_str(op.meta_json.as_deref().unwrap_or(""))?;
let uid = parse_node_uid(&meta.uid).ok_or("staged write has an unparseable uid")?;
if let Some(reason) = self.revision_conflict(&uid, &meta, &blob)? {
// Trashing the file from the mount drops its queued write, but not
// from under a worker already holding it. That worker then finds the
// node trashed — by us — and would upload the withdrawn bytes as a
// conflict copy (a `recovered-…` file in the root when the tree has
// already forgotten the node). A write nobody queues any more is
// not a conflict.
if !self.db.op_exists(op.id)? {
debug!(%uid, reason, "queued write withdrawn while it drained; dropping it");
return Ok(());
}
return self.keep_as_conflict_copy(op, &blob, &meta, &uid, &reason);
}
// An incomplete blob is authored bytes over zeros; the untouched ranges
// have to be filled from the base before it can be sent. This is the case
// the write could not resolve at release time (it was offline), and the
// reason it is safe to do now is that we are not.
if !meta.complete {
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(&blob)?;
let mut written = Intervals::default();
for &(s, e) in &meta.authored {
written.add(s, e);
}
self.fill_gaps(
&uid,
&file,
meta.len,
meta.base_mtime,
meta.base_size,
&written,
)
.map_err(|e| self.errno_error(e, "gap-fill from base failed"))?;
// The blob is whole now. Recorded, so that a retry after a lost
// answer can match these bytes against the server's revision
// (`revision_conflict`) instead of forking a conflict copy of the
// user's own write.
meta.complete = true;
match serde_json::to_string(&meta) {
Ok(json) => {
let path = op.blob_path.as_deref().unwrap_or_default();
if let Err(e) = self.db.update_op_meta_for_blob(op.id, path, &json) {
warn!(%uid, error = %e,
"recording a gap-filled blob as whole failed; \
a lost answer may land it as a conflict copy");
}
}
Err(e) => warn!(%uid, error = %e, "serializing a gap-filled sidecar failed"),
}
}
let name = self.node_name(&uid);
let thumbnails = self.upload_thumbnails(&blob, &name);
let guard =
self.transfers
.begin(&name, meta.uid.clone(), TransferDirection::Upload, meta.len);
// Registered before the first byte moves, so a write that lands while
// this is on the wire can stop it rather than paying for a revision the
// op it queued will immediately replace.
let cancel = self.begin_cancellable_upload(&uid);
// An unlink that withdrew this op before the flag above existed had no
// upload to cancel; the row is the record that it happened.
if !self.db.op_exists(op.id)? {
debug!(%uid, "queued write withdrawn before it went out; dropping it");
return Ok(());
}
let reader = CountingReader::new(File::open(&blob)?, &guard).with_cancel(cancel.flag());
let started = Instant::now();
let sent = self.block_on_within(
link::upload_deadline(meta.len, self.transfers.upload_cap()),
self.drive
.upload_new_revision_from(&uid, reader, meta.len as i64, thumbnails, None),
);
let took = started.elapsed();
if let Err(e) = sent {
if cancel.cancelled() {
// Not a failure, and not this op's row to retire: the write that
// cancelled us deleted it and took ownership of the staged blob
// when it superseded this revision. Leaving the blob alone here
// is the whole point — it is either already unlinked or it
// belongs to the newer op.
info!(%uid, "upload abandoned; a newer write superseded it");
return Ok(());
}
return Err(e.into());
}
drop(cancel);
drop(guard);
// Only a completed upload times how long this file takes to send, which
// is what the next write's debounce is scaled from.
self.record_upload_time(&uid, took);
// Still pending to whoever asks until the bytes are cached below, and
// counted before the op goes so the status never reads empty in between.
// An empty queue is how a script or the app knows a written file reads
// without the network; retiring the op alone left the read-back's round
// trip in which it did not (B119). The op itself has to go first: one
// restored after a crash would re-send a revision this daemon has not
// yet recorded as its own, and come back as a conflict copy.
let _landing = LandingUpload::begin(&self.drain.landing_uploads);
// Retire the op before dropping the blob: a crash between the two leaves
// an orphaned file (harmless), whereas the reverse would leave a queued
// op pointing at nothing.
self.db.delete_op(op.id)?;
self.evict_reader(&uid);
// The staged blob now matches the sealed revision, so it becomes the
// file's cached content, stamped like the revision just read back.
// Reading the file again then needs no network, which an editor or a
// build does at once and a flaky link cannot always give (`docs/BUGS.md`
// B119). Adopted by link, not by value: the blob is the whole file, and
// a video read into a `Vec` here is an OOM. `discard_staged` below drops
// the staging name only — the cache keeps the inode.
self.refresh_after_upload(&uid, &blob, |mtime, size| {
if size == meta.len
&& keeps_landed_upload(self.cache.is_pinned(&uid), meta.len, self.cache.budget())
{
let _ = self.cache.store_file(&uid, mtime, meta.len, &blob);
}
});
self.cache.discard_staged(&blob);
self.log_activity(ActivityKind::Upload, &name, "uploaded", true);
// Both times, so a slow drain shows whether the upload itself or the
// checks and gap-fill around it are where the time goes.
info!(
%uid,
len = meta.len,
upload_ms = took.as_millis() as u64,
total_ms = op_started.elapsed().as_millis() as u64,
"pending upload landed"
);
Ok(())
}
/// Adopt the server's metadata for a node we have just uploaded a revision
/// for.
///
/// [`State::record_pending_write`] deliberately stamps the node with the
/// moment we *accepted* the write, so `ls` reflects it before the upload
/// lands. The server stamps the sealed revision with its own time, and the
/// two differ by however long the upload took. That difference is not
/// cosmetic: [`Core::remote_baseline`] reads this node to build
/// [`StagedWrite::based_on`], and [`Core::revision_conflict`] compares that
/// baseline against the remote — so leaving our optimistic time in place
/// makes the *next* write to this file look like another device changed it
/// underneath us, and diverts it into a conflict copy over nothing.
///
/// A write queued while this upload was on the wire is handled instead by
/// [`Core::rebaseline_pending`]: its optimistic size/mtime must stay on the
/// node (the same reason `apply_event` refuses to overwrite a node with a
/// queued write), but its *baseline* still has to learn about the revision
/// we just sealed. Skipping both, as this used to, is what produced a file
/// that conflicted with itself and left a full-size duplicate behind.
///
/// `blob` is the revision that landed, which stays the pending one until
/// open write handles are rebased off it, and `adopt` gets the mtime and
/// size of the node read back before that, so the uploaded bytes can be
/// cached under its revision first. A handle released in between fills its
/// gaps from one or the other; with the blob let go first and the cache
/// filled last, it found neither, and the next write open was refused
/// (docs/BUGS.md B123). When the node cannot be read back, `adopt` gets
/// the stamp the tree still has, which is the base a write opened next
/// takes: without it the blob went and nothing replaced it (B157). The
/// blob's digest then stands in for the revision id the read-back did
/// not bring, so the next write knows the revision as its own.
///
/// Best effort: a failure here costs a spurious conflict copy on the next
/// write, not this upload, which has already landed. Returns the node as
/// the server now has it, or `None` when it could not be read back.
pub(crate) fn refresh_after_upload(
&self,
uid: &NodeUid,
blob: &Path,
adopt: impl FnOnce(i64, u64),
) -> Option<Node> {
// Asked before the read-back: the op went before it, so a rename queued
// behind the upload can land while Drive answers, and the answer may
// still have the old name (`docs/BUGS.md` B172).
let placed = self.placement(uid);
let renaming = self
.db
.has_pending_op(&uid.to_string(), OP_RENAME)
.unwrap_or(false);
let fetched = self.fetch_node_remote(uid);
if fetched.is_ok() {
self.drain.sealed_unread.lock().remove(uid);
}
let node = match fetched {
Ok(Some(node)) => node,
// Trashed or deleted under us: the tree will hear it from the event
// sync, which is better placed to unhook the inode than we are.
Ok(None) => {
self.release_pending(uid, blob);
return None;
}
Err(e) => {
warn!(%uid, error = %e,
"refreshing metadata after an upload failed; \
the next write to this file may conflict with itself");
match staged_sha1(blob) {
Ok(sha) => {
self.drain.sealed_unread.lock().insert(uid.clone(), sha);
}
Err(_) => {
self.drain.sealed_unread.lock().remove(uid);
}
}
// No newer write took over, so the tree's stamp is this upload's.
if self.pending_blob(uid).as_deref() == Some(blob) {
let mut stamp = None;
self.for_each_state(|st| {
if let Some(entry) = st.by_uid.get(uid).and_then(|ino| st.entries.get(ino))
{
stamp = Some((entry.node.modification_time, node_size(&entry.node)));
}
});
if let Some((mtime, size)) = stamp {
adopt(mtime, size);
}
}
self.release_pending(uid, blob);
return None;
}
};
adopt(node.modification_time, node_size(&node));
// 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`).
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`
// name the revision we just replaced. Without this update,
// `remote_baseline` will build a `based_on` from those stale values, the
// drain will compare them against the revision we sealed, and the write
// will be diverted into a conflict copy of itself.
//
// This is the open-handle counterpart of `rebaseline_pending`, which
// covers the same gap for *queued* ops.
{
// Remember it as ours, so a queued write that opened over an earlier
// revision recognises this as a self-supersede rather than a foreign
// change and does not fork (B70 layer B; consulted in
// `revision_conflict`).
if let Some(rev) = node_revision_id(&node) {
// In the table, not in memory: losing it at shutdown reopened
// the fork window B70 layer B closed, for the first drain
// after a restart.
if let Err(e) = self
.db
.set_own_sealed_rev(&uid.to_string(), &rev, now_millis())
{
warn!(%uid, error = %e, "persisting our sealed revision failed");
}
}
// A write open from here until the tree has the node takes it as
// its base: the blob it would have copied is let go of below, and
// the tree's stamp names the revision this one replaced
// (docs/BUGS.md B170).
self.drain.landed.lock().insert(uid.clone(), node.clone());
self.rebase_open_writes(uid, &node);
}
self.release_pending(uid, blob);
#[cfg(test)]
self.drive.landing(uid);
self.place_landed(uid, &node, placed, renaming);
self.drain.landed.lock().remove(uid);
Some(node)
}
/// Put a node whose upload just landed into the tree, unless a newer write
/// is queued for it. `before` is where the tree had the node and
/// `renaming` whether a rename of it was queued, both from before the
/// read-back.
pub(crate) fn place_landed(
&self,
uid: &NodeUid,
node: &Node,
before: Option<(String, Option<NodeUid>)>,
renaming: bool,
) {
// Ordered so that a write queued *during* the fetch above is still
// caught: it took its baseline from the node's optimistic stamp, and
// this overwrites it with the revision the server actually holds.
if self.rebaseline_pending(uid, node) {
return;
}
// A rename queued behind the upload has not reached Drive yet, or
// landed after Drive read the node back, and the tree keeps the name
// and folder the user gave the file, as `adopt_real_uid` does. Taking
// Drive's put the file back under its old name. A rename queued since
// the read-back began has already moved the entry when the tree is
// updated, so a name that changed in between is the user's too
// (docs/BUGS.md B146, B172).
let renaming = renaming
|| self
.db
.has_pending_op(&uid.to_string(), OP_RENAME)
.unwrap_or(false);
self.for_each_state(|st| {
let moved = placed_in(st, uid) != before;
let Some(entry) = st.by_uid.get(uid).and_then(|ino| st.entries.get(ino)) else {
return;
};
let parent = entry.parent;
let mut node = node.clone();
if renaming || moved {
node.name = entry.node.name.clone();
node.parent_uid = entry.node.parent_uid.clone();
}
st.intern(parent, node);
});
}
/// Where the tree has `uid`: its name and parent.
pub(crate) fn placement(&self, uid: &NodeUid) -> Option<(String, Option<NodeUid>)> {
placed_in(&self.state(), uid)
}
/// Rebase every write handle open on `uid` onto `node`, a revision this
/// daemon has just put there itself (`WriteHandle::rebase_onto`).
pub(crate) fn rebase_open_writes(&self, uid: &NodeUid, node: &Node) {
self.for_each_state(|st| {
for aw in st.active_writes.values_mut() {
if aw.uid == *uid {
aw.rebase_onto(node);
debug!(%uid, mtime = aw.base_mtime, size = aw.base_size,
"rebased open write handle onto the revision just landed");
}
}
});
}
/// Point a still-queued write at the revision this upload just sealed, and
/// report whether there was one.
///
/// The revision we sent *is* the base the queued write will be applied over,
/// but nothing else says so. [`Core::remote_baseline`] carries a baseline
/// across a supersede because the op it inherits from "is the last one that
/// actually observed the remote" — true only until that op drains. Once it
/// has, the inherited baseline names a revision we replaced ourselves, and
/// [`Core::revision_conflict`] reads that as another device having moved the
/// file. It is a self-conflict, and it is expensive: the whole staged blob
/// is re-uploaded as a second file.
///
/// Both copies of the sidecar are updated — the in-memory one the next
/// `release` inherits from, and the persisted one the drain reloads after a
/// restart. Best effort on the DB half; the in-memory half is what the
/// immediate next write reads.
pub(crate) fn rebaseline_pending(&self, uid: &NodeUid, sealed: &Node) -> bool {
let base = Baseline {
mtime: sealed.modification_time,
size: node_size(sealed),
hash: None,
revision_id: node_revision_id(sealed),
};
let mut pending = self.pending.lock();
let Some(p) = pending.get_mut(uid) else {
return false;
};
p.meta.based_on = Some(base.clone());
match serde_json::to_string(&p.meta) {
Ok(json) => {
if let Err(e) = self.db.update_op_meta(&uid.to_string(), OP_REVISION, &json) {
warn!(%uid, error = %e,
"restamping a queued write's baseline failed; \
it may land as a conflict copy of itself");
}
}
Err(e) => warn!(%uid, error = %e, "serializing a restamped sidecar failed"),
}
debug!(%uid, mtime = base.mtime, size = base.size,
"queued write rebaselined onto the revision just uploaded");
true
}
}
+224
View File
@@ -0,0 +1,224 @@
//! Draining a trash, and withdrawing a create that was removed before it
//! landed.
use super::*;
impl Core {
/// Apply a queued trash to the remote.
///
/// A node that is already gone is a success, not a failure: the outcome the
/// op asked for holds either way, and retrying forever against a node the
/// server has forgotten would wedge the queue.
pub(crate) fn drain_trash(&self, op: &PendingOp) -> Result<(), Box<dyn std::error::Error>> {
let uid = parse_node_uid(&op.uid).ok_or("trash op has an unparseable uid")?;
let name = op.name.clone().unwrap_or_else(|| op.uid.clone());
// The trash a delete left of a create that was sent, on the wire or
// before, and failed (`Db::delete_ops_for_uid`). A create that failed
// may still have made the node and lost only its answer, and the node
// would keep the deleted file's name and bytes (docs/BUGS.md B151).
if is_local_uid_str(&op.uid) {
match self.withdrawn_twin(op)? {
Some(twin) => {
self.hidden.lock().insert(twin.clone());
match self
.block_on_bounded(self.drive.trash_nodes(std::slice::from_ref(&twin)))
.and_then(batch::into_unit)
{
Ok(()) => {}
Err(e) if is_gone(&e) => {}
Err(e) => return Err(e.into()),
}
self.invalidate_trash();
info!(%uid, %twin, name, "a withdrawn create had landed unanswered; trashed it");
}
None => debug!(%uid, name, "withdrawn create never landed; trash op satisfied"),
}
self.retire_trash_op(op, &uid)?;
return Ok(());
}
match self
.block_on_bounded(self.drive.trash_nodes(std::slice::from_ref(&uid)))
.and_then(batch::into_unit)
{
Ok(()) => {}
Err(e) if is_gone(&e) => {
debug!(%uid, name, "node was already gone remotely; trash op satisfied");
}
Err(e) => return Err(e.into()),
}
self.retire_trash_op(op, &uid)?;
// A file trashed while open kept the bytes its handle reads, and a
// final close while the trash was queued left them to this
// (`docs/BUGS.md` B186).
if !self.is_open_anywhere(&uid) {
if let Some(blob) = self.pending_blob(&uid) {
self.release_pending(&uid, &blob);
self.cache.discard_staged(&blob);
}
self.cache.evict(&uid);
self.evict_reader(&uid);
}
if let Err(e) = self.db.clear_own_sealed_rev(&uid.to_string()) {
debug!(%uid, error = %e, "clearing the sealed-revision record failed");
}
self.invalidate_trash();
self.log_activity(ActivityKind::Trash, &name, "trashed", true);
info!(%uid, name, "pending trash landed");
Ok(())
}
/// Remove a trash op that landed, and the blob of a create it withdrew.
pub(crate) fn retire_trash_op(
&self,
op: &PendingOp,
uid: &NodeUid,
) -> Result<(), Box<dyn std::error::Error>> {
if let Some(blob) = self.db.complete_trash_op(op.id, uid)? {
self.cache.discard_staged(Path::new(&blob));
}
Ok(())
}
/// The node a create that a trash withdrew made on Drive although its
/// answer was lost: in the create's folder under its name, or under one
/// an attempt was sent with before a rename (`docs/BUGS.md` B184).
pub(crate) fn withdrawn_twin(
&self,
op: &PendingOp,
) -> Result<Option<NodeUid>, Box<dyn std::error::Error>> {
let mut targets: Vec<(String, String)> = op
.parent_uid
.clone()
.zip(op.name.clone())
.into_iter()
.collect();
for target in self.db.create_targets(op.id)? {
if !targets.contains(&target) {
targets.push(target);
}
}
for (parent, name) in targets {
if is_local_uid_str(&parent) {
continue;
}
let Some(parent) = parse_node_uid(&parent) else {
continue;
};
if let Some(twin) = self.withdrawn_twin_in(op, &parent, &name)? {
return Ok(Some(twin));
}
}
Ok(None)
}
/// The node in `parent` under `name` a withdrawn create made, if it is one
/// the create would have adopted had it been retried ([`adoptable`]). A
/// node with a change of ours queued is one the user is still working on.
pub(crate) fn withdrawn_twin_in(
&self,
op: &PendingOp,
parent: &NodeUid,
name: &str,
) -> Result<Option<NodeUid>, Box<dyn std::error::Error>> {
let uids =
match self.block_on_bounded(self.drive.enumerate_folder_children_node_uids(parent)) {
Ok(uids) => uids,
Err(e) if is_gone(&e) => return Ok(None),
Err(e) => return Err(e.into()),
};
let children = self.block_on_bounded(self.drive.enumerate_nodes_light(&uids))?;
// As for a create's own twin (`Core::adoptable_twin`): a node this
// 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 Some(twin) = children
.into_iter()
.find(|node| node.name == name && !node.trashed && !hidden.contains(&node.uid))
else {
return Ok(None);
};
if self.state().by_uid.contains_key(&twin.uid) {
return Ok(None);
}
let queued = twin.uid.to_string();
for kind in [OP_RENAME, OP_REVISION, OP_TRASH] {
if self.db.has_pending_op(&queued, kind)? {
return Ok(None);
}
}
let is_dir = match twin.kind {
// A folder made by a create that never answered has nothing in
// it: what was queued inside waited for its uid.
NodeKind::Folder => {
let inside = self
.block_on_bounded(self.drive.enumerate_folder_children_node_uids(&twin.uid))?;
if !inside.is_empty() {
return Ok(None);
}
true
}
NodeKind::File { .. } => false,
};
let twin = match is_dir {
true => twin,
false => match self.fetch_node_remote(&twin.uid)? {
Some(node) => node,
None => return Ok(None),
},
};
// A blob gone from staging matches nothing, and leaves the node be.
let current = match op.blob_path.as_deref() {
Some(blob) if node_size(&twin) > 0 => staged_sha1(Path::new(blob)).ok(),
_ => None,
};
let sent = self.create_sent_digests(op.id, current);
Ok(adoptable(is_dir, &twin, self.first_sent(op), &sent).then_some(twin.uid))
}
/// Trash the node a create made after the file was deleted, or replaced by
/// a rename, while its upload was on the wire (`docs/BUGS.md` B129).
///
/// `Db::finish_create` queued the trash, claimed, in the transaction that
/// found the create gone. It goes out now rather than behind the queue:
/// until it lands the node holds its name on Drive, and a file created
/// there again forks a conflict copy. A failure leaves it queued.
pub(crate) fn trash_withdrawn_create(
&self,
op: &PendingOp,
trash: i64,
local: &NodeUid,
real: &NodeUid,
name: &str,
) -> Result<(), Box<dyn std::error::Error>> {
self.hidden.lock().insert(real.clone());
self.note_self_change(real);
let trash = PendingOp {
id: trash,
kind: OP_TRASH.to_string(),
uid: real.to_string(),
parent_uid: None,
name: Some(name.to_string()),
blob_path: None,
meta_json: None,
created_at: op.created_at,
attempts: 0,
last_error: None,
next_attempt_at: 0,
};
info!(%local, %real, name, "a create landed after its file was deleted; trashing it");
if let Err(e) = self.drain_trash(&trash) {
warn!(%real, name, error = %e, "trashing a withdrawn create failed; queued");
if let Err(e) = self.db.record_op_failure(
trash.id,
&e.to_string(),
now_millis() + DRAIN_BACKOFF_MIN.as_millis() as i64,
) {
error!(%real, error = %e, "recording a drain failure failed");
}
self.release_claim(&trash);
self.wake_drain();
}
Ok(())
}
}
+77
View File
@@ -0,0 +1,77 @@
//! Our own changes echoed back by the event feed: which nodes this daemon
//! changed on Drive, so the first event for each is taken as the echo it is.
use super::*;
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`].
pub(crate) fn note_self_change(&self, uid: &NodeUid) {
note_self_change(&mut self.self_changes.lock(), 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())
}
}
/// 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`].
pub(super) const SELF_CHANGE_TTL_MS: i64 = 120_000;
/// A remote change this daemon made, awaiting its echo from the event feed.
pub(super) struct SelfChange {
/// When we made it, in the same epoch millis as [`now_millis`].
at_ms: i64,
/// Echoes not yet seen. More than one because a single file can be created
/// and then have a revision uploaded, and the feed reports both.
echoes: u32,
}
/// Record one remote change this daemon made. Split from [`Core`] so the
/// expiry and echo-counting rules can be tested against a clock the test owns.
pub(super) fn note_self_change(
changes: &mut HashMap<NodeUid, SelfChange>,
uid: &NodeUid,
now_ms: i64,
) {
// Echoes that never arrived — a node trashed before its event came round, a
// feed that skipped it — would otherwise accumulate for the life of the
// daemon. Pruning on write keeps the map the size of the recent queue.
changes.retain(|_, c| now_ms - c.at_ms < SELF_CHANGE_TTL_MS);
let change = changes.entry(uid.clone()).or_insert(SelfChange {
at_ms: now_ms,
echoes: 0,
});
change.at_ms = now_ms;
change.echoes += 1;
}
/// Claim one echo, per [`Core::take_self_change`].
pub(super) fn take_self_change(
changes: &mut HashMap<NodeUid, SelfChange>,
uid: &NodeUid,
now_ms: i64,
) -> bool {
let Some(change) = changes.get_mut(uid) else {
return false;
};
// Too old to attribute: the feed is far enough behind that this is as likely
// to be someone else's change as ours, and guessing wrong here costs the user
// a stale file.
if now_ms - change.at_ms >= SELF_CHANGE_TTL_MS {
changes.remove(uid);
return false;
}
change.echoes -= 1;
if change.echoes == 0 {
changes.remove(uid);
}
true
}
+882
View File
@@ -0,0 +1,882 @@
//! Turning what the mount was asked into queued ops: revisions, truncates,
//! creates, renames and trashes, and taking queued ops back again.
use super::*;
impl Core {
/// Queue what the write handles the kernel never released hold.
///
/// `close(2)` returns before the kernel sends `release`, and the stop
/// aborts the FUSE connection with the releases still queued: a file a
/// program had just saved was never queued, and Drive kept it as it was
/// (`docs/BUGS.md` B190). Runs once every session has ended, so no release
/// can race it. A handle still open in a program goes the same way, with
/// what it wrote so far; one on an unlinked file only leaves its scratch.
pub(crate) fn queue_unreleased_writes(&self) {
let handles: Vec<(WriteHandle, bool)> = {
let mut st = self.state();
st.handles.clear();
let inos: Vec<u64> = st.active_writes.keys().copied().collect();
inos.into_iter()
.filter_map(|ino| {
let unlinked = st.entries.get(&ino).is_some_and(|e| e.unlinked);
st.active_writes.remove(&ino).map(|h| (h, unlinked))
})
.collect()
};
for (mut h, unlinked) in handles {
if unlinked {
self.cache.clear_scratch_durable(&h.path);
let _ = std::fs::remove_file(&h.path);
continue;
}
self.follow_landed_create(&mut h);
match self.queue_revision(&mut h) {
Ok(()) => info!(uid = %h.uid, "queued a write the kernel never released"),
Err(error) => {
warn!(uid = %h.uid, ?error, "cannot queue a write the kernel never released")
}
}
}
}
/// Accept a released write handle's bytes and queue their upload.
///
/// This is what makes a copy into the mount run at disk speed: the caller's
/// `close` returns once the bytes are staged on local disk and the intent is
/// in `pending_op`, instead of waiting out a full upload inside the FUSE
/// handler. It is also what makes an offline write succeed rather than EIO —
/// the queued op simply waits for the network.
///
/// The scratch file is *moved* into staging, never copied: it is the only
/// copy of what the user wrote.
pub(super) fn queue_revision(&self, h: &mut WriteHandle) -> Result<(), Errno> {
// Closing an untouched writable handle is not a mutation. It remains
// valid after a downgrade and only owes cleanup of its empty scratch.
if !h.dirty {
self.cache.clear_scratch_durable(&h.path);
let _ = std::fs::remove_file(&h.path);
// A new file's create waits for this release to wake the drain
// (`Core::queue_local_node`). Closed empty, it attached nothing
// that would, and sat until the idle poll (`docs/BUGS.md` B192).
if is_local_uid(&h.uid) {
self.wake_drain();
}
return Ok(());
}
preserve_on_access_denied(self.require_uid_writable(&h.uid), h.dirty, || {
let meta = self.recovery_meta(h);
self.stage_orphaned_write(
&h.uid,
h.ino,
&h.path,
&meta,
"access changed before the write could be queued",
);
})?;
// The handle is being retired either way, so any durability sidecar an
// `fsync` left has done its job: from here the bytes are tracked as a
// staged write and a queued op, and a sidecar outliving them would offer
// recovery a second, stale copy of the same write.
self.cache.clear_scratch_durable(&h.path);
if is_local_uid(&h.uid) && !self.db.has_create_op(&h.uid.to_string()).unwrap_or(true) {
// A create that landed since the handle last looked left no op
// either. It moved the row to its uid in the same transaction, so
// the row says which it was (`docs/BUGS.md` B176).
self.follow_landed_create(h);
if is_local_uid(&h.uid) {
debug!(uid = %h.uid, "local node was unlinked before creation; dropping revision");
let _ = std::fs::remove_file(&h.path);
return Ok(());
}
}
// Materialize as much of the full content as is free to materialize. A
// complete blob is uploadable without the network and lets a later write
// to the same file supersede this one without any reconstruction at all.
//
// What is deliberately *not* done here is fetching the untouched ranges
// from the remote: that is a download of everything the edit did not
// touch, and this runs on the FUSE dispatch loop, so closing a large
// file after a small edit stopped every other request on the mount for
// the length of it (audit F1). An incomplete blob is first-class —
// `read_pending` resolves its gaps against the base, and `drain_revision`
// fills them on the drain thread — so the network half of the fill
// belongs there, and only there.
//
// A node that exists only locally has no remote base to fill from: its
// untouched ranges live in the blob queued by an earlier write, which
// `merge_over_pending` folds in below.
if let Err(e) = h.file.set_len(h.len) {
error!(uid = %h.uid, error = %e, "resize scratch file failed");
return Err(Errno::EIO);
}
let mut written = h.written.clone();
if !(is_local_uid(&h.uid) && h.base_size > 0) {
// A local node has no remote base, so nothing of it can be fetched
// or cached: passing zero says so, and leaves the fill doing only
// the part that still applies — claiming the zeroed tail.
let base_size = if is_local_uid(&h.uid) { 0 } else { h.base_size };
self.fill_gaps_cached(
&h.uid,
&h.file,
h.len,
h.base_mtime,
base_size,
&mut written,
);
}
let authored: Vec<(u64, u64)> = written
.segments(0, h.len)
.into_iter()
.filter(|&(_, _, authored)| authored)
.map(|(s, e, _)| (s, e))
.collect();
let meta = StagedWrite {
uid: h.uid.to_string(),
len: h.len,
base_size: h.base_size,
base_mtime: h.base_mtime,
complete: StagedWrite::covers(&authored, h.len),
authored,
based_on: self.remote_baseline(
&h.uid,
h.base_mtime,
h.base_size,
h.base_revision_id.clone(),
),
};
let complete = meta.complete;
self.enqueue_staged_write(&h.uid, h.ino, &h.path, meta)?;
debug!(uid = %h.uid, len = h.len, complete, "queued revision upload");
Ok(())
}
/// Describe the locally authored ranges without gap-filling them.
///
/// Used when a write was accepted by the kernel but a queue-time access
/// check now denies it. Building this metadata is side-effect free, so the
/// permission guard still precedes cache, database, and tree mutation.
pub(super) fn recovery_meta(&self, h: &WriteHandle) -> StagedWrite {
let authored: Vec<(u64, u64)> = h
.written
.segments(0, h.len)
.into_iter()
.filter(|&(_, _, authored)| authored)
.map(|(start, end, _)| (start, end))
.collect();
StagedWrite {
uid: h.uid.to_string(),
len: h.len,
base_size: h.base_size,
base_mtime: h.base_mtime,
complete: StagedWrite::covers(&authored, h.len),
authored,
based_on: self.remote_baseline(
&h.uid,
h.base_mtime,
h.base_size,
h.base_revision_id.clone(),
),
}
}
/// The remote revision a change to `uid` is being made against, for
/// [`StagedWrite::based_on`].
///
/// Normally that is simply the base the handle opened over. The exception is
/// a write that supersedes a still-queued one: its "base" is the previous
/// *staged blob*, whose size and mtime are ours, not the server's — so the
/// baseline is inherited from the op being superseded, which is the last one
/// that actually observed the remote. Without that, chaining two writes
/// before the queue drains would leave the drain comparing the remote
/// against a revision it never had, and cutting a conflict copy over
/// nothing.
///
/// `None` for a node that has never existed remotely: there is no revision
/// to conflict with until its create drains.
pub(super) fn remote_baseline(
&self,
uid: &NodeUid,
base_mtime: i64,
base_size: u64,
base_revision_id: Option<String>,
) -> Option<Baseline> {
if is_local_uid(uid) {
return None;
}
match self.pending.lock().get(uid) {
Some(p) => p.meta.based_on.clone(),
None => Some(Baseline {
mtime: base_mtime,
size: base_size,
hash: None,
revision_id: base_revision_id,
}),
}
}
/// Move a file holding a node's intended new content into staging and queue
/// the upload that will make it the remote's content. Shared by the release
/// of a write handle and by a path-based truncate.
///
/// `src` is consumed either way: on success it is *moved* into staging, and
/// on the refusal below it is moved there too, just without an op to upload
/// it. It is the only copy of what the user wrote, so nothing here may
/// simply delete it.
pub(super) fn enqueue_staged_write(
&self,
uid: &NodeUid,
ino: u64,
src: &Path,
mut meta: StagedWrite,
) -> Result<(), Errno> {
preserve_on_access_denied(self.require_uid_writable(uid), true, || {
self.stage_orphaned_write(
uid,
ino,
src,
&meta,
"access changed before the staged write could be queued",
);
})?;
// An incomplete blob's gaps refer to the *remote* base. If an earlier
// write to this file is still queued, the remote no longer holds that
// base — the previous staged blob does — so taking those gaps at face
// value would fill them from the wrong revision. Fold the blob being
// superseded into this one instead: its authored bytes are a local copy
// 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();
if !meta.complete
&& let Some(previous) = previous
&& let Err(error) = merge_over_pending(&mut meta, src, &previous)
{
// Without the earlier bytes the gaps cannot be resolved against
// anything, so this is where the write stops being uploadable.
// Keep it recoverable rather than corrupting the file.
warn!(%uid, %error, "folding in the undrained edit failed");
self.stage_orphaned_write(
uid,
ino,
src,
&meta,
"write overlaps an undrained incomplete edit",
);
return Err(Errno::EIO);
}
let path = self.cache.stage_write(&meta, src).map_err(|e| {
error!(%uid, error = %e, "staging write failed");
// The scratch file is still the only copy of these bytes, and the
// caller is releasing the handle it belongs to — without a
// durability sidecar `discard_unmarked_scratch` deletes it at the
// next mount, the one place the "never delete on a failure path"
// invariant would break. Mark it first, whatever went wrong.
if let Err(mark) = self.cache.mark_scratch_durable(src, &meta) {
error!(%uid, error = %mark,
"could not mark an unstageable write durable; bytes at risk");
}
if e.is_disk_full() {
// Free cached blobs so the retry has somewhere to land, and tell
// the caller what is actually wrong.
self.cache.emergency_evict();
Errno::ENOSPC
} else {
Errno::EIO
}
})?;
// Whatever this write supersedes, it supersedes now — including an
// upload already on the wire, whose bytes describe a revision the row
// written just below replaces. Signalled before the enqueue so the
// in-flight reader stops at its next block rather than after however
// much of the file is left.
self.cancel_upload(uid);
let mut uid = uid.clone();
let len = meta.len;
let superseded = 'queued: {
if is_local_uid(&uid) {
// The node has no server-side identity to hang a revision on, so
// the bytes ride on the create that will mint it. Attached and
// recorded under one hold of `pending`, which is what the drain
// takes to retire a landed create: it either sees this blob and
// 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 attached = self
.db
.attach_blob_to_create(&uid.to_string(), &path.to_string_lossy(), &meta_json)
.map_err(|e| {
error!(%uid, error = %e, "attaching write to queued create failed");
Errno::EIO
})?;
if let Some(attached) = attached {
pending.insert(uid.clone(), PendingRevision { path, meta });
break 'queued attached.superseded;
}
drop(pending);
// The create landed while this handle was open, and its row
// already has the uid Drive gave it.
let Some(real) = self.landed_row_uid(ino) else {
error!(%uid, staged = %path.display(),
"queued create vanished under a write; bytes kept in staging");
return Err(Errno::EIO);
};
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();
meta.based_on = previous.as_ref().and_then(|p| p.meta.based_on.clone());
if !meta.complete
&& let Some(previous) = previous
&& let Err(error) = merge_over_pending(&mut meta, &path, &previous)
{
error!(%uid, %error, staged = %path.display(),
"folding in the write the create carried failed; bytes kept in staging");
return Err(Errno::EIO);
}
}
let op = PendingOp {
id: 0,
kind: OP_REVISION.to_string(),
uid: uid.to_string(),
parent_uid: None,
name: None,
blob_path: Some(path.to_string_lossy().into_owned()),
meta_json: Some(serde_json::to_string(&meta).unwrap_or_default()),
created_at: now_millis(),
attempts: 0,
last_error: None,
next_attempt_at: now_millis() + self.revision_debounce(&uid).as_millis() as i64,
};
let (_id, superseded) = self.db.enqueue_op(&op).map_err(|e| {
error!(%uid, error = %e, "queueing upload failed");
Errno::EIO
})?;
self.pending
.lock()
.insert(uid.clone(), PendingRevision { path, meta });
superseded
};
if let Some(old) = superseded {
self.cache.discard_staged(Path::new(&old));
}
let uid = &uid;
// Reflect the write in the tree straight away: `ls` must show the new
// size and mtime even though the remote still holds the old revision.
let now = now_secs();
let updated = {
let mut st = self.state();
st.record_pending_write(ino, len, now)
};
// The only record that the file is as long as the caller was told. If it
// cannot be written the write did not fully take, and saying so beats
// acknowledging a `close(2)` and then serving the old size — the bytes
// themselves are already staged and queued either way. Written out here
// rather than inside `State` so the commit does not hold the inode lock.
let recorded = match updated {
Some(node) => self.db.upsert_node(&node),
None => Ok(()),
};
// Cached blobs and open readers describe the superseded revision. Reads
// come from the staged blob until the op drains, so just drop them.
// Done even when the row above failed: the staged blob is the file's
// content now either way, and leaving a stale one cached would serve it.
self.cache.evict(uid);
self.evict_reader(uid);
self.wake_drain();
if let Err(e) = recorded {
error!(%uid, error = %e, "recording a queued write's size failed");
return Err(if e.is_disk_full() {
Errno::ENOSPC
} else {
Errno::EIO
});
}
Ok(())
}
/// Queue the new content of a path-based truncate — `> file`, or any
/// `setattr(size=…)` arriving without a write handle.
///
/// No bytes have been authored at truncate time, which is why this path was
/// never staged and instead resized the remote content inline. That is also
/// why a shell redirect failed offline *before* the write that follows it:
/// the truncate itself needed the network. Staging a blob describing the
/// result puts it on the same queue as every other write.
///
/// The blob is a hole of the new length; what is real about it is `authored`:
///
/// - `> file` (size 0) is the whole point and needs nothing at all — an
/// empty file is complete content, so it queues and drains offline.
/// - Extending past the end authors the new tail (zeros, by definition) and
/// leaves the head to be gap-filled from the base.
/// - Shrinking authors nothing: every remaining byte still comes from the
/// base, so it is the drain that has to fetch it.
pub(super) fn queue_truncate(&self, ino: u64, size: u64) -> Result<(), Errno> {
let (uid, base_mtime, base_size, base_revision_id) = {
let st = self.state();
match st.entries.get(&ino) {
Some(e) if e.node.is_file() => (
e.uid.clone(),
e.node.modification_time,
node_size(&e.node),
node_revision_id(&e.node),
),
Some(_) => return Err(Errno::EISDIR),
None => return Err(Errno::ENOENT),
}
};
self.require_uid_writable(&uid)?;
if size == base_size {
return Ok(());
}
// A close immediately followed by truncate is common (`write`, close,
// `truncate(2)`) and usually beats the write-back debounce. In that
// 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();
if pending_base
.as_ref()
.is_some_and(|pending| !pending.meta.complete)
{
// An incomplete pending blob still has holes referring to the
// remote revision. Stacking another incomplete transform on it is
// not representable safely; preserve the existing refusal.
return Err(Errno::EIO);
}
let (authored, complete) = if size == 0 {
// An empty file has no content to be missing.
(Vec::new(), true)
} else if base_size == 0 {
// Nothing to gap-fill from: every byte is a zero this truncate
// defines.
(vec![(0, size)], true)
} else if size > base_size {
(vec![(base_size, size)], false)
} else {
(Vec::new(), false)
};
let (file, path) = self.cache.create_scratch().map_err(|e| {
error!(%uid, error = %e, "create scratch file for truncate failed");
Errno::EIO
})?;
if let Some(pending) = &pending_base
&& let Err(e) = copy_pending_for_truncate(pending, &file)
{
error!(%uid, source = %pending.path.display(), error = %e,
"copy pending revision for truncate failed");
let _ = std::fs::remove_file(&path);
return Err(Errno::EIO);
}
file.set_len(size).map_err(|e| {
error!(%uid, error = %e, "resize scratch file for truncate failed");
let _ = std::fs::remove_file(&path);
Errno::EIO
})?;
let meta = match pending_base {
Some(pending) => StagedWrite {
uid: uid.to_string(),
len: size,
base_size: pending.meta.len,
base_mtime: pending.meta.base_mtime,
authored: if size == 0 {
Vec::new()
} else {
vec![(0, size)]
},
complete: true,
// Both local revisions descend from the same last-observed
// remote revision. Never replace this with the optimistic
// mtime/size currently published by State.
based_on: pending.meta.based_on,
},
None => StagedWrite {
uid: uid.to_string(),
len: size,
base_size,
base_mtime,
authored,
complete,
based_on: self.remote_baseline(&uid, base_mtime, base_size, base_revision_id),
},
};
self.enqueue_staged_write(&uid, ino, &path, meta)?;
debug!(%uid, size, complete, "queued truncate");
Ok(())
}
/// Invent a node under `parent_uid` and queue the op that will make it real.
/// Returns the node to intern, exactly as the online
/// path returns the one the server minted.
///
/// The parent may itself be a placeholder — `mkdir -p` offline, or `cp -r` of
/// a tree. That is fine: the op records the parent it was made under by local
/// id, and is not sent until the parent's row has the uid it landed as.
pub(super) fn queue_local_node(
&self,
parent_uid: &NodeUid,
name: &str,
is_dir: bool,
hold: bool,
) -> Result<Node, Errno> {
self.require_uid_writable(parent_uid)?;
// The row the tree would give it anyway, now: the node goes by its
// local id until it lands.
let lid = self
.db
.add_local_row(&parent_uid.to_string(), name, is_dir, now_secs())
.map_err(|e| {
error!(%parent_uid, name, error = %e, "giving a local node its row failed");
Errno::EIO
})?;
let uid = local_node_uid(lid);
let node = local_node(uid.clone(), parent_uid.clone(), name.to_string(), is_dir);
let op = PendingOp {
id: 0,
kind: if is_dir { OP_MKDIR } else { OP_CREATE }.to_string(),
uid: uid.to_string(),
parent_uid: Some(parent_uid.to_string()),
name: Some(name.to_string()),
blob_path: None,
meta_json: None,
created_at: now_millis(),
attempts: 0,
last_error: None,
// Parked when the name is transient: its bytes ride on this create
// (via `attach_blob_to_create`) and must not upload until a rename to
// the finished name un-parks it (docs/BUGS.md B70).
next_attempt_at: if hold { PARK_UNTIL } else { 0 },
};
self.db.enqueue_op(&op).map_err(|e| {
error!(%parent_uid, name, error = %e, "queueing local node failed");
Errno::EIO
})?;
debug!(%uid, %parent_uid, name, is_dir, "created node offline; queued");
// A folder is due now; without this the workers slept through it to
// the idle poll (B160). A file is not: its bytes ride on the create, and
// its release wakes the drain, with bytes or without (B192).
if is_dir {
self.wake_drain();
}
Ok(node)
}
/// Queue giving a node a new parent and/or name, and apply it to the tree
/// now.
///
/// The op records the desired end state rather than the step, so it both
/// supersedes any earlier queued rename and lets the drain skip whichever
/// half the remote already agrees with.
///
/// `new_parent_uid` may be a placeholder — moving a file into a folder
/// created offline — which is why this cannot simply be the online call with
/// a retry around it: the API would 404 on a `local~` parent. The op waits
/// for that folder's drain to rewrite it, exactly as a queued create does.
pub(super) fn queue_rename(
&self,
ino: u64,
uid: &NodeUid,
old_parent_uid: &NodeUid,
new_parent_ino: u64,
new_parent_uid: &NodeUid,
new_name: &str,
) -> Result<(), Errno> {
self.require_uid_writable(uid)?;
self.require_uid_writable(old_parent_uid)?;
self.require_uid_writable(new_parent_uid)?;
self.queue_rename_authorized(
ino,
uid,
old_parent_uid,
new_parent_ino,
new_parent_uid,
new_name,
)
}
/// Enqueue a rename whose access was linearized immediately before a
/// replacement victim was removed. Rechecking here could reject after that
/// destructive half had already completed.
pub(super) fn queue_rename_authorized(
&self,
ino: u64,
uid: &NodeUid,
old_parent_uid: &NodeUid,
new_parent_ino: u64,
new_parent_uid: &NodeUid,
new_name: &str,
) -> Result<(), Errno> {
self.enqueue_rename(ino, uid, old_parent_uid, new_parent_uid, new_name)?;
self.state
.lock()
.rename_in_place(ino, new_parent_ino, new_parent_uid, new_name);
self.wake_drain();
debug!(%uid, %new_parent_uid, new_name, "renamed offline; queued");
Ok(())
}
/// Record the queued rename op, and nothing else: the caller moves the node
/// in the tree, through the kernel or around it.
pub(super) fn enqueue_rename(
&self,
ino: u64,
uid: &NodeUid,
old_parent_uid: &NodeUid,
new_parent_uid: &NodeUid,
new_name: &str,
) -> Result<(), Errno> {
// A rename that replaces a queued one keeps where the node started.
let meta = match self.db.pending_op_meta(&uid.to_string(), OP_RENAME) {
Ok(Some(json)) => serde_json::from_str::<RenameMeta>(&json).map_err(|error| {
error!(%uid, %error, "queued rename authority metadata is invalid");
Errno::EIO
})?,
Ok(None) => RenameMeta {
original_parent_uid: old_parent_uid.to_string(),
original_name: self
.state
.lock()
.entries
.get(&ino)
.map(|entry| entry.node.name.clone()),
},
Err(error) => {
error!(%uid, %error, "reading queued rename authority failed");
return Err(Errno::EIO);
}
};
let meta_json = serde_json::to_string(&meta).map_err(|error| {
error!(%uid, %error, "serializing queued rename authority failed");
Errno::EIO
})?;
let op = PendingOp {
id: 0,
kind: OP_RENAME.to_string(),
uid: uid.to_string(),
parent_uid: Some(new_parent_uid.to_string()),
name: Some(new_name.to_string()),
blob_path: None,
meta_json: Some(meta_json),
created_at: now_millis(),
attempts: 0,
last_error: None,
next_attempt_at: 0,
};
self.db.enqueue_op(&op).map_err(|e| {
error!(%uid, new_name, error = %e, "queueing rename failed");
Errno::EIO
})?;
Ok(())
}
pub(super) fn has_pending_moves_out_of(&self, uid: &NodeUid) -> Result<bool, Errno> {
self.db
.has_pending_moves_out_of(&uid.to_string())
.map_err(|error| {
error!(%uid, %error, "checking for moves out of a trash target failed");
Errno::EIO
})
}
/// Queue trashing a node the server knows about, and drop it from the tree
/// now.
///
/// Anything else queued for this node is discarded first: the user has said
/// the file should not exist, so uploading bytes to it or renaming it are
/// both work towards an outcome nobody wants any more. That does throw away
/// staged bytes that never landed — which is precisely what deleting an
/// un-uploaded file means, and the alternative (upload it, then trash it) is
/// worse in every way.
///
/// A file still open keeps the bytes its handle reads, the queued ones and
/// the cached ones, as when the trash is sent at once: a partial write
/// fills its gaps from them, offline too (`docs/BUGS.md` B186). The final
/// close or the trash landing, whichever comes last, lets go of them.
///
/// `open` is whether the caller found the file open. A create that landed
/// under a delete is trashed by its real uid before the tree has it, so
/// asking the tree alone took an open file for closed (`docs/BUGS.md`
/// B257).
pub(super) fn queue_trash(&self, uid: &NodeUid, name: &str, open: bool) -> Result<(), Errno> {
self.require_uid_writable(uid)?;
// The bytes below are about to be discarded, and a drain worker may be
// reading them onto the wire right now. Stop it first: with several
// workers the trash op this queues can be claimed while that upload is
// still running, and the two would race to decide whether the file
// exists.
self.cancel_upload(uid);
let (_, blobs) = self
.db
.replace_ops_with_trash(&uid.to_string(), name, now_millis())
.map_err(|e| {
error!(%uid, error = %e, "queueing trash failed");
Errno::EIO
})?;
let open_now = open || self.is_open_anywhere(uid);
if open_now {
let read_from = self.pending_blob(uid);
self.release_dropped_below(
blobs
.into_iter()
.filter(|blob| read_from.as_deref() != Some(Path::new(blob)))
.collect(),
);
} else {
self.release_dropped_ops(uid, blobs);
}
self.hidden.lock().insert(uid.clone());
// 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).
self.for_each_state(|st| {
st.unlink_mem(uid);
});
if !open_now {
self.cache.evict(uid);
self.evict_reader(uid);
}
self.wake_drain();
debug!(%uid, name, "trashed offline; queued");
Ok(())
}
/// Drop every op queued against a node, and the staged bytes they own.
pub(super) fn discard_queued_ops(&self, uid: &NodeUid) -> Result<(), Errno> {
// Same reason as `queue_trash`: an upload may be reading the very blobs
// this is about to unlink.
self.cancel_upload(uid);
let blobs = self.db.delete_ops_for_uid(&uid.to_string()).map_err(|e| {
error!(%uid, error = %e, "dropping queued ops failed");
Errno::EIO
})?;
self.release_dropped_ops(uid, blobs);
Ok(())
}
/// Drop every op queued against a node that just left the namespace while
/// a handle still has it open, but keep the bytes that handle reads.
///
/// The ops cannot wait for the final close: the node is already trashed, and
/// a revision the drain sends in the meantime lands on it after the trash —
/// an editor's save loop then found the name it was renaming onto still
/// taken (`docs/BUGS.md` B106). The pending entry and its staged blob are
/// what the open handle reads, so they stay until the final close drops
/// them.
pub(super) fn withdraw_queued_ops(&self, uid: &NodeUid) -> Result<(), Errno> {
self.cancel_upload(uid);
let blobs = self.db.delete_ops_for_uid(&uid.to_string()).map_err(|e| {
error!(%uid, error = %e, "withdrawing queued ops failed");
Errno::EIO
})?;
let read_from = self.pending_blob(uid);
let blobs = blobs
.into_iter()
.filter(|blob| read_from.as_deref() != Some(Path::new(blob)))
.collect();
self.release_dropped_below(blobs);
Ok(())
}
/// Let go of what the ops just dropped for `uid` held: their pending
/// entries, any upload still reading their bytes, and the bytes.
///
/// Removing a folder also drops the queued revisions of the files below it
/// (`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.release_dropped_below(blobs);
}
/// [`Core::release_dropped_ops`] without touching the node's own pending
/// entry.
pub(super) fn release_dropped_below(&self, blobs: Vec<String>) {
let below: Vec<NodeUid> = {
let mut pending = self.pending.lock();
let below: Vec<NodeUid> = pending
.iter()
.filter(|(_, p)| blobs.iter().any(|b| p.path == Path::new(b)))
.map(|(k, _)| k.clone())
.collect();
for k in &below {
pending.remove(k);
}
below
};
for k in &below {
self.cancel_upload(k);
}
for blob in blobs {
self.cache.discard_staged(Path::new(&blob));
}
}
/// Keep a write we cannot safely queue, so the bytes are recoverable even
/// though the caller is getting an error. See [`Core::queue_revision`].
pub(super) fn stage_orphaned_write(
&self,
uid: &NodeUid,
ino: u64,
src: &Path,
meta: &StagedWrite,
reason: &str,
) {
match self.cache.preserve_write(meta, src) {
Ok(staged) => {
self.cache.clear_scratch_durable(src);
error!(
%uid,
staged = %staged.display(),
%reason,
"cannot queue write; bytes kept in staging"
);
let name = {
let st = self.state();
st.entries
.get(&ino)
.map(|e| e.node.name.clone())
.unwrap_or_default()
};
self.log_activity(
ActivityKind::Upload,
&name,
format!(
"write not queued ({reason}); changes kept at {}",
staged.display()
),
false,
);
}
Err(e) => {
let surviving = e.surviving_path.clone();
let marker = e.marker_path.clone();
error!(
%uid,
error = %e,
surviving = %surviving.display(),
marker = ?marker,
%reason,
"write rescue was only partially published; bytes retained"
);
let name = {
let st = self.state();
st.entries
.get(&ino)
.map(|entry| entry.node.name.clone())
.unwrap_or_default()
};
self.log_activity(
ActivityKind::Upload,
&name,
format!(
"write not queued ({reason}); changes retained at {}",
surviving.display()
),
false,
);
}
}
}
}
+20 -23
View File
@@ -467,21 +467,16 @@ impl Filesystem for ProtonFs {
let handled = {
let mut st = self.core.state();
match st.active_writes.get_mut(&ino.0) {
Some(aw) => {
if size < aw.len {
// Shrink: drop authored ranges past the new end.
aw.written.clip(size);
} else if size > aw.len {
// Grow: the new tail is defined as zeros, so claim
// it as authored rather than base content.
aw.written.add(aw.len, size);
}
let _ = aw.file.set_len(size);
aw.len = size;
aw.dirty = true;
true
}
None => false,
Some(aw) => aw.resize(size).map(|()| true).map_err(Errno::from),
None => Ok(false),
}
};
let handled = match handled {
Ok(handled) => handled,
Err(error) => {
debug!(ino = ino.0, size, ?error, "setattr resize refused");
reply.error(error);
return;
}
};
debug!(ino = ino.0, size, fh = ?fh, handled, "setattr resize");
@@ -1474,7 +1469,7 @@ impl ProtonFs {
// a lock-tight comparison — against the multi-gigabyte copy
// above, which is the window that actually loses data.
let current = self.core.pending_blob(&uid);
let landed = self.core.landed.lock().get(&uid).cloned();
let landed = self.core.drain.landed.lock().get(&uid).cloned();
let mut st = self.core.state();
// Only a handle this open is about to *create* can carry a stale
// base; if one already exists, that handle is authoritative and
@@ -2372,17 +2367,19 @@ impl ProtonFs {
}
}
}
// Offline: queue it. Trashing is the one mutation a user expects to work
// regardless — the file is gone from their point of view the moment the
// command returns. The same when the network goes
// away under the remote call below.
let queue_it = |reply: ReplyEmpty| match self.core.queue_trash(&uid, name) {
// Queue a folder trash while Drive still holds children that were moved
// out locally. The drain waits for those moves before sending it.
let queue_it = |reply: ReplyEmpty| match self.core.queue_trash(&uid, name, open_now) {
Ok(()) => reply.ok(),
Err(e) => reply.error(e),
};
if !self.core.sends_inline() {
queue_it(reply);
return;
return queue_it(reply);
}
match self.core.has_pending_moves_out_of(&uid) {
Ok(false) => {}
Ok(true) => return queue_it(reply),
Err(error) => return reply.error(error),
}
if let Err(e) = self.core.require_uid_writable(&uid) {
reply.error(e);
+653
View File
@@ -0,0 +1,653 @@
//! Host Proton Gallery's account and catalog services in the Drive daemon.
mod video;
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::{
Arc, RwLock,
atomic::{AtomicU64, Ordering},
};
use std::time::{Duration, Instant};
use pdfs_core::control::{
GalleryAction, GalleryAlbum, GalleryFolder, GalleryPlace, PhotoItem, PhotoKind, Response,
};
use pdfs_core::{CoreError, CoreResult};
use proton_drive_rs::proton_sdk::session::ProtonApiSession;
use proton_gallery_app_rs::{App, View};
use proton_gallery_rs::CancellationToken;
use proton_gallery_rs::model::{AssetKey, SourceId};
use tokio::sync::{Mutex, Notify, OnceCell};
use super::{Core, NodeUid, parse_uid};
pub(super) struct Gallery {
root: PathBuf,
session: ProtonApiSession,
cancel: CancellationToken,
app: OnceCell<App>,
checked: Mutex<Option<Instant>>,
visibility: RwLock<Option<Arc<Visibility>>>,
refresh: Notify,
access: AtomicU64,
video: video::Server,
}
#[derive(Default, PartialEq, Eq)]
pub(super) struct Visibility {
pub(super) media: HashSet<String>,
pub(super) albums: HashSet<String>,
}
impl Visibility {
pub(super) fn permits(&self, uid: &str) -> CoreResult<()> {
if self.media.contains(uid) || self.albums.contains(uid) {
return Err(CoreError::invalid("Unlock hidden albums to open this item"));
}
Ok(())
}
}
impl Gallery {
pub(super) fn new(root: PathBuf, session: ProtonApiSession) -> Self {
Self {
root,
session,
cancel: CancellationToken::new(),
app: OnceCell::new(),
checked: Mutex::new(None),
visibility: RwLock::default(),
refresh: Notify::new(),
access: AtomicU64::new(0),
video: video::Server::default(),
}
}
pub(super) fn cancel(&self) {
self.cancel.cancel();
self.video.close_all();
}
async fn app(&self, core: &Core) -> CoreResult<&App> {
self.app
.get_or_try_init(|| async {
App::open_hosted(
self.root.clone(),
self.session.clone(),
core.client.clone(),
self.cancel.child_token(),
)
.await
.map_err(gallery_error)
})
.await
}
async fn ensure_visibility(
&self,
core: &Core,
app: &App,
force: bool,
) -> CoreResult<Arc<Visibility>> {
if self.cancel.is_cancelled() {
return Err(CoreError::remote("The Gallery session expired"));
}
let mut checked = self.checked.lock().await;
if !force
&& let Some(instant) = *checked
&& instant.elapsed()
< if self.snapshot().is_some() {
Duration::from_secs(60)
} else {
Duration::from_secs(5)
}
{
return self.snapshot().ok_or_else(visibility_loading);
}
if self.snapshot().is_none()
&& app
.gallery_visibility_cached()
.await
.map_err(gallery_error)?
{
self.publish_visibility(core, self.read_visibility(core, app).await?);
}
let started = Instant::now();
let result = tokio::select! {
biased;
_ = self.cancel.cancelled() => Err(CoreError::remote("The Gallery session expired")),
result = tokio::time::timeout(Duration::from_secs(20), async {
app.refresh_gallery_configuration(false).await.map_err(gallery_error)?;
self.read_visibility(core, app).await
}) => result.unwrap_or_else(|_| Err(CoreError::remote("Gallery visibility check timed out"))),
};
tracing::debug!(
elapsed_ms = started.elapsed().as_millis() as u64,
success = result.is_ok(),
"Gallery visibility refresh"
);
*checked = Some(Instant::now());
if let Ok(visibility) = result {
self.publish_visibility(core, visibility.clone());
return Ok(visibility);
}
if !force && let Some(visibility) = self.snapshot() {
return Ok(visibility);
}
result
}
fn snapshot(&self) -> Option<Arc<Visibility>> {
self.visibility
.read()
.unwrap_or_else(|e| e.into_inner())
.clone()
}
fn publish_visibility(&self, core: &Core, visibility: Arc<Visibility>) {
let mut snapshot = self.visibility.write().unwrap_or_else(|e| e.into_inner());
if snapshot.as_ref() != Some(&visibility) {
*snapshot = Some(visibility);
drop(snapshot);
self.video.close_all();
core.events
.publish(&[pdfs_core::control::Topic::GalleryVisibilitySynced]);
}
}
async fn read_visibility(&self, core: &Core, app: &App) -> CoreResult<Arc<Visibility>> {
let account = self.account()?;
let mut visibility = Visibility::default();
for (volume, node) in app
.catalog
.hidden_assets(account.clone())
.await
.map_err(gallery_error)?
{
visibility
.media
.insert(NodeUid::new(volume.into(), node.into()).to_string());
}
visibility.media.extend(
core.db
.photo_group_members_for(&visibility.media)
.map_err(CoreError::from)?,
);
for album in app
.catalog
.hidden_configuration_albums(account)
.await
.map_err(gallery_error)?
{
visibility.albums.insert(
NodeUid::new(album.volume.as_str().into(), album.node.as_str().into()).to_string(),
);
}
Ok(Arc::new(visibility))
}
fn account(&self) -> CoreResult<proton_gallery_rs::model::AccountId> {
proton_gallery_rs::model::AccountId::new(self.session.user_id().as_str())
.map_err(gallery_error)
}
async fn page(
&self,
app: &App,
album: Option<GalleryPlace>,
proton: bool,
access: Option<u64>,
offset: usize,
limit: usize,
) -> CoreResult<Response> {
let private = access.is_some();
let parent = album
.as_ref()
.map(|a| (a.gallery.as_str(), a.album.as_str()));
let mut albums = Vec::new();
if offset == 0 && !proton {
if private && parent.is_none() {
albums.extend(
app.photo_albums_with_hidden(true)
.await
.map_err(gallery_error)?
.into_iter()
.filter(|entry| entry.settings.hidden)
.map(|entry| gallery_album(entry, true)),
);
albums.extend(
app.hidden_drive_albums()
.await
.map_err(gallery_error)?
.into_iter()
.map(|entry| gallery_album(entry, false)),
);
} else {
albums.extend(
app.drive_albums(parent, private)
.await
.map_err(gallery_error)?
.into_iter()
.map(|entry| gallery_album(entry, false)),
);
}
}
let (items, total) = if let Some(GalleryPlace { gallery, album }) = album {
let view = if proton && private {
let id = SourceId::new(&album).map_err(gallery_error)?;
if !app
.catalog
.album_settings(id)
.await
.map_err(gallery_error)?
.hidden
{
return Err(CoreError::not_found("Hidden album"));
}
View::PhotoAlbum(album)
} else {
if private
&& !app
.catalog
.drive_album_is_private(
SourceId::new(&gallery).map_err(gallery_error)?,
SourceId::new(&album).map_err(gallery_error)?,
)
.await
.map_err(gallery_error)?
{
return Err(CoreError::not_found("Hidden gallery folder"));
}
View::DriveAlbum { gallery, album }
};
let outline = app
.outline_with_visibility(view, false, private)
.await
.map_err(gallery_error)?;
let total = outline.len();
let items = app
.outline_items(&outline, offset.min(total), limit.clamp(1, 250))
.await
.map_err(gallery_error)?
.into_iter()
.flatten()
.map(|item| PhotoItem {
uid: asset_uid(&item.key),
capture_time: item.sort_time,
thumb_path: None,
name: Some(item.name),
ratio: item.aspect_ratio,
no_thumb: false,
kind: if item.is_video {
PhotoKind::Video
} else {
PhotoKind::Photo
},
favorite: item.favorite,
group_size: 1,
has_raw: false,
place_id: None,
})
.collect();
(items, total)
} else {
(Vec::new(), 0)
};
self.require_access(access)?;
Ok(Response::GalleryPage {
albums,
items,
total,
})
}
fn lock(&self) {
let _ = self
.access
.try_update(Ordering::SeqCst, Ordering::SeqCst, |value| {
Some((value | 1).wrapping_add(1))
});
self.video.close_all();
}
fn private_access(&self) -> CoreResult<u64> {
let access = self.access.load(Ordering::SeqCst);
if access & 1 == 0 {
return Err(CoreError::invalid("Unlock hidden albums to open this item"));
}
Ok(access)
}
fn require_access(&self, access: Option<u64>) -> CoreResult<()> {
if let Some(access) = access
&& self.private_access()? != access
{
return Err(CoreError::invalid("Hidden albums were locked"));
}
Ok(())
}
pub(super) async fn poll(self: Arc<Self>, core: Core) {
loop {
tokio::select! {
biased;
_ = self.cancel.cancelled() => break,
_ = self.refresh.notified() => {},
_ = tokio::time::sleep(Duration::from_secs(60)) => {}
}
if let Ok(Ok(app)) = tokio::time::timeout(Duration::from_secs(5), self.app(&core)).await
{
let _ = self.ensure_visibility(&core, app, false).await;
}
}
}
fn asset(&self, uid: &NodeUid) -> CoreResult<AssetKey> {
Ok(AssetKey {
account: self.account()?,
volume: proton_gallery_rs::model::VolumeId::new(uid.volume_id.as_str())
.map_err(gallery_error)?,
node: proton_gallery_rs::model::NodeId::new(uid.link_id.as_str())
.map_err(gallery_error)?,
})
}
}
fn gallery_album(entry: proton_gallery_rs::library::Album, proton: bool) -> GalleryAlbum {
GalleryAlbum {
place: GalleryPlace {
gallery: entry.gallery.to_string(),
album: entry.source.id.to_string(),
},
proton,
folder: GalleryFolder {
uid: NodeUid::new(
entry.source.volume.as_str().into(),
entry.source.root.as_str().into(),
)
.to_string(),
name: entry.settings.title.unwrap_or(entry.source.label),
},
cover: entry.cover.map(|asset| asset_uid(&asset.key)),
items: entry.direct_items,
folders: entry.child_albums,
hidden: entry.settings.hidden,
}
}
fn gallery_error(error: impl std::fmt::Display) -> CoreError {
CoreError::remote(error.to_string())
}
fn uid(value: &str) -> CoreResult<NodeUid> {
parse_uid(value).ok_or_else(|| CoreError::invalid("Invalid gallery node"))
}
fn done() -> Response {
Response::Ok {
message: "Gallery updated".into(),
}
}
fn asset_uid(asset: &AssetKey) -> String {
NodeUid::new(asset.volume.as_str().into(), asset.node.as_str().into()).to_string()
}
fn visibility_loading() -> CoreError {
CoreError::new(
pdfs_core::control::ErrorKind::Offline,
"Gallery visibility is loading. Try again shortly.",
)
}
impl Core {
pub(super) fn cached_gallery_visibility(&self) -> CoreResult<Arc<Visibility>> {
if self.gallery.is_none() {
return Ok(Arc::default());
}
let gallery = self.gallery_host()?;
match gallery.snapshot() {
Some(snapshot) => Ok(snapshot),
None => {
gallery.refresh.notify_one();
Err(visibility_loading())
}
}
}
pub(super) fn gallery_visibility(&self) -> CoreResult<Arc<Visibility>> {
if self.gallery.is_none() {
return Ok(Arc::default());
}
let gallery = self.gallery_host()?;
self.rt.block_on(async {
let app = gallery.app(self).await?;
gallery.ensure_visibility(self, app, false).await
})
}
fn gallery_host(&self) -> CoreResult<&Gallery> {
self.gallery
.as_deref()
.filter(|gallery| !gallery.cancel.is_cancelled())
.ok_or_else(|| CoreError::remote("The Gallery session is unavailable"))
}
pub(super) fn authenticate_hidden_gallery(
&self,
stream: &std::os::unix::net::UnixStream,
) -> CoreResult<Response> {
let gallery = self.gallery_host()?;
let access = gallery.access.load(Ordering::SeqCst);
let peer = rustix::net::sockopt::socket_peercred(stream)
.map_err(|_| CoreError::invalid("Couldn’t identify the authentication requester."))?;
if peer.uid != rustix::process::geteuid() {
return Err(CoreError::invalid(
"Use your Linux sign-in to unlock Hidden albums.",
));
}
let subject = proton_gallery_app_rs::desktop_auth::Subject::new(
peer.pid.as_raw_nonzero().get() as u32,
peer.uid.as_raw(),
)
.map_err(gallery_error)?;
self.rt
.block_on(subject.authenticate("io.narl.proton-drive-linux.unlock-hidden-albums"))
.map_err(gallery_error)?;
if gallery.cancel.is_cancelled() {
return Err(CoreError::invalid("The Gallery session has ended."));
}
gallery
.access
.compare_exchange(access, access | 1, Ordering::SeqCst, Ordering::SeqCst)
.map_err(|_| CoreError::invalid("Hidden albums were locked"))?;
Ok(done())
}
pub(super) fn drive_gallery(&self, action: GalleryAction) -> CoreResult<Response> {
let gallery = self.gallery_host()?;
let action = match action {
GalleryAction::Lock => {
gallery.lock();
return Ok(done());
}
other => other,
};
self.rt.block_on(async {
let app = gallery.app(self).await?;
gallery
.ensure_visibility(self, app, matches!(action, GalleryAction::Refresh))
.await?;
match action {
GalleryAction::AuthenticateHidden | GalleryAction::Lock => unreachable!(),
GalleryAction::List {
album,
offset,
limit,
} => gallery.page(app, album, false, None, offset, limit).await,
GalleryAction::PrivateList {
album,
proton,
offset,
limit,
} => {
let access = gallery.private_access()?;
gallery
.page(app, album, proton, Some(access), offset, limit)
.await
}
GalleryAction::Folders { parent } => {
let list = app
.browse_drive_folders(parent.as_deref().map(uid).transpose()?)
.await
.map_err(gallery_error)?;
Ok(Response::GalleryFolders {
folders: list
.children
.into_iter()
.map(|folder| GalleryFolder {
uid: folder.uid.to_string(),
name: folder.name,
})
.collect(),
})
}
GalleryAction::Add { uid: node } => {
app.add_drive_folder(uid(&node)?)
.await
.map_err(gallery_error)?;
gallery.ensure_visibility(self, app, true).await?;
Ok(done())
}
GalleryAction::Remove { gallery: id } => {
app.forget_drive_gallery(SourceId::new(id).map_err(gallery_error)?)
.await
.map_err(gallery_error)?;
gallery.ensure_visibility(self, app, true).await?;
Ok(done())
}
GalleryAction::Refresh => {
for album in app.drive_albums(None, true).await.map_err(gallery_error)? {
let root = NodeUid::new(
album.source.volume.as_str().into(),
album.source.root.as_str().into(),
);
app.scan_drive_folder(root).await.map_err(gallery_error)?;
}
gallery.ensure_visibility(self, app, true).await?;
Ok(done())
}
GalleryAction::Cover { album, uid: node } => {
let id = SourceId::new(&album.album).map_err(gallery_error)?;
let root = SourceId::new(&album.gallery).map_err(gallery_error)?;
app.checked_album(album.gallery, album.album)
.await
.map_err(gallery_error)?;
let access = if app
.catalog
.drive_album_is_private(root.clone(), id.clone())
.await
.map_err(gallery_error)?
{
Some(gallery.private_access()?)
} else {
None
};
let mut settings = app
.catalog
.album_settings(id.clone())
.await
.map_err(gallery_error)?;
gallery.require_access(access)?;
settings.cover = Some(gallery.asset(&uid(&node)?)?);
app.catalog
.set_album_settings_at(Some(root), id, settings)
.await
.map_err(gallery_error)?;
gallery.ensure_visibility(self, app, true).await?;
Ok(done())
}
}
})
}
pub(super) fn open_gallery_video(&self, node: &str, private: bool) -> CoreResult<Response> {
let gallery = self.gallery_host()?;
let uid = uid(node)?;
self.rt.block_on(async {
let app = gallery.app(self).await?;
let visibility = gallery.ensure_visibility(self, app, false).await?;
let access = if private {
Some(gallery.private_access()?)
} else {
visibility.permits(node)?;
None
};
let stream = app
.stream_video(&gallery.asset(&uid)?)
.await
.map_err(gallery_error)?;
let response = gallery.video.open(stream, &gallery.cancel).await?;
if let Err(error) = gallery.require_access(access) {
if let Response::GalleryVideo { token, .. } = &response {
gallery.video.close(token);
}
return Err(error);
}
Ok(response)
})
}
pub(super) fn gallery_image(&self, node: &str) -> CoreResult<Response> {
use base64::{Engine, engine::general_purpose::STANDARD};
let gallery = self.gallery_host()?;
let access = gallery.private_access()?;
let asset = gallery.asset(&uid(node)?)?;
self.rt.block_on(async {
let app = gallery.app(self).await?;
let bytes = tokio::time::timeout(Duration::from_secs(30), async {
if let Some(bytes) = app.preview(&asset).await? {
Ok(bytes)
} else {
app.original_in_memory(&asset, 8 * 1024 * 1024).await
}
})
.await
.map_err(|_| CoreError::remote("Proton took too long to open this photo"))?
.map_err(gallery_error)?;
gallery.require_access(Some(access))?;
Ok(Response::GalleryThumbnail {
data: Some(STANDARD.encode(bytes)),
})
})
}
pub(super) fn close_gallery_video(&self, token: &str) -> CoreResult<Response> {
self.gallery_host()?.video.close(token);
Ok(done())
}
pub(super) fn gallery_thumbnail(&self, node: &str, private: bool) -> CoreResult<Response> {
use base64::{Engine, engine::general_purpose::STANDARD};
let gallery = self.gallery_host()?;
let asset = gallery.asset(&uid(node)?)?;
self.rt.block_on(async {
let app = gallery.app(self).await?;
let visibility = gallery.ensure_visibility(self, app, false).await?;
let access = if private {
Some(gallery.private_access()?)
} else {
visibility.permits(node)?;
None
};
let data = app
.thumbnail(&asset)
.await
.map_err(gallery_error)?
.map(|bytes| STANDARD.encode(bytes));
gallery.require_access(access)?;
Ok(Response::GalleryThumbnail { data })
})
}
}
+205
View File
@@ -0,0 +1,205 @@
use std::{collections::VecDeque, io, sync::Arc, time::Duration};
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use http_body_util::{BodyExt, Empty, StreamBody, combinators::UnsyncBoxBody};
use hyper::{
Method, Request, Response, StatusCode,
body::{Bytes, Frame, Incoming},
header,
server::conn::http1,
service::service_fn,
};
use hyper_util::rt::TokioIo;
use pdfs_core::{CoreResult, control::Response as ControlResponse};
use proton_gallery_app_rs::video::VideoStream;
use proton_gallery_rs::CancellationToken;
use tokio::net::TcpListener;
type Body = UnsyncBoxBody<Bytes, io::Error>;
const LEASE: Duration = Duration::from_secs(4 * 60 * 60);
const MAX_STREAMS: usize = 4;
const CHUNK: u32 = 256 * 1024;
#[derive(Default)]
pub(super) struct Server {
active: parking_lot::Mutex<VecDeque<(String, CancellationToken)>>,
}
impl Server {
pub(super) fn close(&self, token: &str) {
let mut active = self.active.lock();
if let Some(index) = active.iter().position(|(id, _)| id == token)
&& let Some((_, cancel)) = active.remove(index)
{
cancel.cancel();
}
}
pub(super) fn close_all(&self) {
for (_, cancel) in self.active.lock().drain(..) {
cancel.cancel();
}
}
pub(super) async fn open(
&self,
stream: Arc<VideoStream>,
account: &CancellationToken,
) -> CoreResult<ControlResponse> {
let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))
.await
.map_err(super::gallery_error)?;
let address = listener.local_addr().map_err(super::gallery_error)?;
let mut nonce = [0; 32];
getrandom::fill(&mut nonce).map_err(super::gallery_error)?;
let token = URL_SAFE_NO_PAD.encode(nonce);
let path: Arc<str> = format!("/{token}").into();
let cancel = account.child_token();
{
let mut active = self.active.lock();
active.retain(|(_, cancel)| !cancel.is_cancelled());
if active.len() >= MAX_STREAMS
&& let Some((_, oldest)) = active.pop_front()
{
oldest.cancel();
}
active.push_back((token.clone(), cancel.clone()));
}
let size = stream.length();
tokio::spawn(async move {
let mut connections = tokio::task::JoinSet::new();
let lifetime = tokio::time::sleep(LEASE);
tokio::pin!(lifetime);
loop {
tokio::select! {
biased;
_ = cancel.cancelled() => break,
_ = &mut lifetime => break,
_ = connections.join_next(), if !connections.is_empty() => {},
incoming = listener.accept(), if connections.len() < 8 => {
let Ok((socket, _)) = incoming else { break };
let stream = stream.clone();
let path = path.clone();
connections.spawn(async move {
let service = service_fn(move |request| reply(request, stream.clone(), path.clone()));
let _ = http1::Builder::new()
.timer(hyper_util::rt::TokioTimer::new())
.header_read_timeout(Duration::from_secs(10))
.keep_alive(false)
.serve_connection(TokioIo::new(socket), service).await;
});
}
}
}
stream.stop();
cancel.cancel();
connections.abort_all();
});
Ok(ControlResponse::GalleryVideo {
url: format!("http://{address}/{token}"),
token,
size,
})
}
}
fn range(value: Option<&str>, size: u64) -> Option<(u64, u64)> {
let Some(value) = value else {
return Some((0, size));
};
let (first, last) = value.strip_prefix("bytes=")?.split_once('-')?;
if first.is_empty() {
let suffix = last.parse::<u64>().ok()?.min(size);
return (suffix > 0).then_some((size - suffix, size));
}
let start = first.parse::<u64>().ok()?;
let end = if last.is_empty() {
size
} else {
last.parse::<u64>().ok()?.saturating_add(1).min(size)
};
(start < end).then_some((start, end))
}
fn empty() -> Body {
Empty::new().map_err(|never| match never {}).boxed_unsync()
}
async fn reply(
request: Request<Incoming>,
stream: Arc<VideoStream>,
path: Arc<str>,
) -> Result<Response<Body>, hyper::http::Error> {
let response = Response::builder().header(header::CACHE_CONTROL, "no-store");
if request
.uri()
.path_and_query()
.is_none_or(|actual| actual.as_str() != path.as_ref())
{
return response.status(StatusCode::NOT_FOUND).body(empty());
}
if !matches!(*request.method(), Method::HEAD | Method::GET) {
return response
.status(StatusCode::METHOD_NOT_ALLOWED)
.body(empty());
}
let size = stream.length();
let requested = request.headers().get(header::RANGE);
let parsed = match requested {
Some(value) => value
.to_str()
.ok()
.and_then(|value| range(Some(value), size)),
None => range(None, size),
};
let Some((start, end)) = parsed else {
return response
.status(StatusCode::RANGE_NOT_SATISFIABLE)
.header(header::CONTENT_RANGE, format!("bytes */{size}"))
.body(empty());
};
let response = response
.header(header::ACCEPT_RANGES, "bytes")
.header(header::CONTENT_LENGTH, end - start)
.header(header::CONTENT_TYPE, "application/octet-stream");
let response = if requested.is_some() {
response.status(StatusCode::PARTIAL_CONTENT).header(
header::CONTENT_RANGE,
format!("bytes {start}-{}/{size}", end - 1),
)
} else {
response
};
if request.method() == Method::HEAD {
return response.body(empty());
}
let body = futures::stream::try_unfold((stream, start), move |(stream, at)| async move {
if at == end {
return Ok(None);
}
let read = (end - at).min(u64::from(CHUNK)) as u32;
let bytes = stream.read(at, read).await.map_err(io::Error::other)?;
if bytes.is_empty() {
return Err(io::Error::from(io::ErrorKind::UnexpectedEof));
}
let next = at + bytes.len() as u64;
Ok(Some((Frame::data(Bytes::from(bytes)), (stream, next))))
});
response.body(BodyExt::boxed_unsync(StreamBody::new(body)))
}
#[cfg(test)]
mod tests {
use super::range;
#[test]
fn resolves_seek_ranges_and_rejects_invalid_ranges() {
assert_eq!(range(None, 10), Some((0, 10)));
assert_eq!(range(Some("bytes=3-5"), 10), Some((3, 6)));
assert_eq!(range(Some("bytes=9-"), 10), Some((9, 10)));
assert_eq!(range(Some("bytes=-3"), 10), Some((7, 10)));
assert_eq!(range(Some("bytes=10-"), 10), None);
assert_eq!(range(Some("bytes=0-1,3-4"), 10), None);
}
}
+129
View File
@@ -0,0 +1,129 @@
//! Hold off a shutdown while queued changes exist only on this computer.
//!
//! A change made through the mount is staged here and sent by the drain. Until
//! it lands, this computer has the only copy, so powering off then risks it
//! more than the user expects (`docs/BUGS.md` B66). While the queue holds work
//! the drain can still send, the daemon takes a logind shutdown inhibitor
//! through `systemd-inhibit`, which desktops show in their power-off dialog
//! with the reason. It is let go as soon as the queue empties.
//!
//! Work that cannot drain on its own — a temporary file waiting for its final
//! name, or a change Drive refused or that keeps failing — never holds the
//! lock, or a shutdown would be held up for something that is not coming.
//! Without `systemd-inhibit` nothing happens.
use std::process::{Child, Command, Stdio};
use std::time::Duration;
use pdfs_store::db::PendingCounts;
use tracing::{debug, warn};
use super::Core;
/// How often the queue is looked at.
const CHECK_EVERY: Duration = Duration::from_secs(5);
/// Changes the drain can still send by itself.
fn sendable(counts: &PendingCounts) -> i64 {
(counts.uploads + counts.changes - counts.parked - counts.failing).max(0)
}
/// Run until the daemon stops, holding the inhibitor while changes wait.
pub(crate) fn run(core: Core) {
let mut held: Option<Child> = None;
loop {
let waiting = core
.db
.pending_op_counts()
.map(|counts| sendable(&counts))
.unwrap_or(0);
// The helper can go away (logind restarted, or it was killed); the
// lock is then taken again on the next round.
if let Some(child) = &mut held
&& !matches!(child.try_wait(), Ok(None))
{
held = None;
}
match (&mut held, waiting > 0) {
(None, true) => held = take(waiting),
(Some(child), false) => {
release(child);
held = None;
}
_ => {}
}
if !core.shutdown.sleep(CHECK_EVERY) {
break;
}
}
if let Some(mut child) = held {
release(&mut child);
}
}
fn take(waiting: i64) -> Option<Child> {
let why = if waiting == 1 {
"Sending 1 change to Proton Drive".to_string()
} else {
format!("Sending {waiting} changes to Proton Drive")
};
match Command::new("systemd-inhibit")
.args([
"--what=shutdown",
"--who=Proton Drive",
&format!("--why={why}"),
"--mode=block",
"sleep",
"infinity",
])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
{
Ok(child) => {
debug!(waiting, "holding off shutdown while changes are queued");
Some(child)
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
Err(error) => {
warn!(%error, "taking the shutdown inhibitor failed");
None
}
}
}
fn release(child: &mut Child) {
let _ = child.kill();
let _ = child.wait();
debug!("queue drained; shutdown no longer held off");
}
#[cfg(test)]
mod tests {
use super::*;
fn counts(uploads: i64, changes: i64, parked: i64, failing: i64) -> PendingCounts {
PendingCounts {
uploads,
changes,
parked,
failing,
last_error: None,
}
}
#[test]
fn only_work_the_drain_can_send_holds_off_a_shutdown() {
assert_eq!(sendable(&counts(0, 0, 0, 0)), 0);
assert_eq!(sendable(&counts(2, 1, 0, 0)), 3);
assert_eq!(sendable(&counts(1, 0, 1, 0)), 0);
assert_eq!(sendable(&counts(2, 0, 0, 2)), 0);
assert_eq!(sendable(&counts(3, 2, 1, 1)), 3);
}
#[test]
fn counts_that_overlap_never_go_negative() {
assert_eq!(sendable(&counts(1, 0, 1, 1)), 0);
}
}
+271
View File
@@ -0,0 +1,271 @@
//! Keeping pinned files on this computer after they were pinned.
//!
//! A pin downloads a file once. Nothing downloaded it again afterwards: a
//! change from another device deleted the cached copy, a file added to a
//! pinned folder elsewhere was never fetched, and a download that failed while
//! the link was down stayed failed. Each of those left a file listed as kept
//! offline that the next read downloaded, and that could not be read at all
//! without a network (`docs/BUGS.md` B282).
//!
//! The keeper is one thread that checks pins again and downloads what is
//! missing or stale: every pin when the daemon starts and when the link comes
//! back, and the pins a batch of remote events touched once the batch is
//! applied. A remote change no longer deletes a pinned file's copy. The copy
//! is stored under the revision's `(mtime, size)`, so a read of a newer
//! revision does not take it, and the keeper replaces it once the new one is
//! downloaded.
use std::collections::HashSet;
use std::time::{Duration, Instant};
use proton_drive_rs::NodeKind;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use tracing::{debug, info, warn};
use super::{Core, is_local_uid, node_size, parse_uid};
/// How often the keeper looks for work.
const KEEPER_TICK: Duration = Duration::from_secs(1);
/// The first wait before a check that could not download everything is tried
/// again. It doubles on every failure, up to [`RETRY_MAX`].
const RETRY_FIRST: Duration = Duration::from_secs(30);
const RETRY_MAX: Duration = Duration::from_secs(30 * 60);
/// What the keeper owes a check.
#[derive(Debug, Default)]
pub(crate) struct PinWork {
/// Every pin.
all: bool,
/// The pinned files and folders named here. A folder is checked whole.
nodes: HashSet<NodeUid>,
}
impl PinWork {
fn is_empty(&self) -> bool {
!self.all && self.nodes.is_empty()
}
fn merge(&mut self, other: PinWork) {
self.all |= other.all;
self.nodes.extend(other.nodes);
}
}
/// A file a pin keeps, as the tree knows it now.
pub(crate) struct KeptFile {
pub(crate) uid: NodeUid,
pub(crate) name: String,
pub(crate) mtime: i64,
pub(crate) size: u64,
}
impl Core {
/// Have the keeper check every pin.
pub(crate) fn recheck_all_pins(&self) {
self.pin_work.lock().all = true;
}
/// Have the keeper check the pinned file or folder `uid`.
pub(crate) fn recheck_pinned(&self, uid: &NodeUid) {
self.pin_work.lock().nodes.insert(uid.clone());
}
/// The keeper's loop, until the daemon stops. Starts with a check of every
/// pin, which catches up on whatever changed while the daemon was down.
///
/// Work that failed waits out a backoff of its own. New work does not wait
/// for it, so a file that keeps failing does not hold up the next change.
pub(crate) fn run_pin_keeper(&self) {
self.recheck_all_pins();
let mut backlog = PinWork::default();
let mut backlog_due = Instant::now();
let mut retry = RETRY_FIRST;
while self.shutdown.sleep(KEEPER_TICK) {
if !self.is_online() {
continue;
}
let mut work = std::mem::take(&mut *self.pin_work.lock());
let retrying = !backlog.is_empty() && Instant::now() >= backlog_due;
if retrying {
work.merge(std::mem::take(&mut backlog));
}
if work.is_empty() {
continue;
}
let failed = self.keep_pins(&work);
if failed.is_empty() {
if retrying {
retry = RETRY_FIRST;
}
continue;
}
backlog.merge(failed);
backlog_due = Instant::now() + retry;
retry = (retry * 2).min(RETRY_MAX);
}
}
/// Download every file `work` covers whose cached copy is missing or
/// stale. Returns what could not be checked or downloaded.
fn keep_pins(&self, work: &PinWork) -> PinWork {
let mut failed = PinWork::default();
let roots: Vec<NodeUid> = if work.all {
self.cache
.list_pins()
.iter()
.filter_map(|pin| parse_uid(&pin.uid))
.chain(work.nodes.iter().cloned())
.collect()
} else {
work.nodes.iter().cloned().collect()
};
let mut seen: HashSet<u64> = HashSet::new();
let mut files: Vec<u64> = Vec::new();
for uid in roots {
if self.shutdown.is_stopping() {
return failed;
}
if !self.cache.is_pinned(&uid) {
continue;
}
let found = {
let st = self.state();
st.by_uid.get(&uid).and_then(|&ino| {
let e = st.entries.get(&ino)?;
Some((ino, e.parent, e.node.is_folder()))
})
};
let Some((ino, parent, is_folder)) = found else {
debug!(%uid, "pin keeper: pinned node is not in the tree");
continue;
};
if is_folder {
match self.pin_subtree_files(ino) {
Ok(inos) => files.extend(inos.into_iter().filter(|i| seen.insert(*i))),
Err(e) => {
warn!(%uid, error = %e, "pin keeper: listing a kept folder failed");
failed.nodes.insert(uid);
}
}
continue;
}
// An event about this file dropped its parent's listing. Listing
// it again brings the file's entry up to the revision Drive has
// now, which is what the cached copy is checked against.
if !work.all
&& parent != ino
&& let Err(e) = self.ensure_children(parent)
{
warn!(%uid, error = ?e, "pin keeper: listing a kept file's folder failed");
failed.nodes.insert(uid);
continue;
}
if seen.insert(ino) {
files.push(ino);
}
}
let stale: Vec<KeptFile> = files
.into_iter()
.filter_map(|ino| self.kept_file(ino))
.filter(|f| !self.cache.is_cached(&f.uid, f.mtime, f.size))
.collect();
if stale.is_empty() {
return failed;
}
let job = self.transfers.begin_job("Updating files kept offline");
job.set_total(stale.len() as u64);
let (mut fetched, mut failures) = (0usize, 0usize);
for file in stale {
if self.shutdown.is_stopping() {
break;
}
// Unpinned while the check ran.
if !self.cache.is_pinned(&file.uid) {
job.step();
continue;
}
job.detail(file.name.clone());
match self.fetch_pinned(&file.uid, &file.name, file.mtime, file.size) {
Ok(()) => fetched += 1,
Err(e) => {
warn!(uid = %file.uid, error = %e, "pin keeper: download failed");
failed.nodes.insert(file.uid);
failures += 1;
}
}
job.step();
}
info!(
fetched,
failed = failures,
"pin keeper: brought files kept offline up to date"
);
failed
}
/// The file at `ino`, as a pin keeps it. `None` for a folder, a file this
/// daemon still owes an upload for, or a file whose real size cannot be
/// read.
///
/// A queued write is ahead of Drive. Downloading Drive's revision would
/// cache what the write replaces, and the drain keeps the uploaded bytes
/// of a pinned file once they land.
///
/// A listing carries the ciphertext size until its size upgrade lands
/// (B12). Stored under that size, the copy never matched the plaintext it
/// holds, so every read downloaded the file again and every check
/// downloaded it once more.
pub(crate) fn kept_file(&self, ino: u64) -> Option<KeptFile> {
let (uid, name, mtime, size, provisional) = {
let st = self.state();
let e = st.entries.get(&ino)?;
let NodeKind::File { claimed_size, .. } = &e.node.kind else {
return None;
};
(
e.uid.clone(),
e.node.name.clone(),
e.node.modification_time,
node_size(&e.node),
claimed_size.is_none(),
)
};
if is_local_uid(&uid) || self.pending.lock().contains_key(&uid) {
return None;
}
let size = match provisional {
true => self.resolve_provisional_size(ino, &uid)?,
false => size,
};
Some(KeptFile {
uid,
name,
mtime,
size,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn work_that_failed_keeps_every_node_and_the_full_check() {
let mut backlog = PinWork::default();
assert!(backlog.is_empty());
let uid = parse_uid("vol~a").unwrap();
backlog.merge(PinWork {
all: false,
nodes: HashSet::from([uid.clone()]),
});
backlog.merge(PinWork {
all: true,
nodes: HashSet::from([uid.clone()]),
});
assert!(backlog.all);
assert_eq!(backlog.nodes.len(), 1);
assert!(!backlog.is_empty());
}
}
+168 -5383
View File
File diff suppressed because it is too large. Load diff
+7 -19
View File
@@ -84,25 +84,7 @@ impl Link {
}
}
/// Whether a failed call failed because Proton could not be reached, rather
/// than because it answered and refused.
///
/// A transport error is the network. So is a request timeout: the SDK reports
/// Proton's own "try again" codes that way, and [`no_answer`] reports our
/// deadline that way. Anything else Proton actually said, and says again on a
/// retry, so it must reach the caller rather than be queued.
pub(crate) fn is_network_error(e: &ProtonError) -> bool {
match e {
ProtonError::Transport(_) => true,
ProtonError::Api(api) => {
matches!(
api.code,
ResponseCode::RequestTimeout | ResponseCode::Timeout
)
}
_ => false,
}
}
pub(crate) use pdfs_drive::is_network_error;
/// The error a call reports when it runs past `after` without an answer.
pub(crate) fn no_answer(after: Duration) -> ProtonError {
@@ -232,6 +214,9 @@ impl Core {
/// Unless the keyring holds a newer session than the refused one: then
/// the mount ends, for the daemon to mount again on that one.
pub(crate) fn mark_session_expired(&self, what: &str, error: &dyn std::fmt::Display) {
if let Some(gallery) = &self.gallery {
gallery.cancel();
}
if self.link.resume_stored.load(Ordering::Relaxed) {
return self.mark_offline(what, error);
}
@@ -286,6 +271,9 @@ impl Core {
warn!(error = %e, "moving backed-off ops up after a reconnect failed");
}
self.wake_drain();
// Downloads for pins failed while the link was down, and the events
// that would have named the files are behind us (`docs/BUGS.md` B282).
self.recheck_all_pins();
}
/// Wait up to `budget` for the link to come back. Returns whether it is up.
+456
View File
@@ -0,0 +1,456 @@
//! Folder listings: when one is listed again, and what a listing from Drive
//! is merged with (queued ops, landed creates, offline copies).
use super::*;
impl Core {
/// Whether [`Core::ensure_children`] would answer for `ino` without
/// touching the network. Lets a handler decide between answering inline
/// and handing off to a worker.
///
/// A resident listing is not enough on its own. A shared folder's, or the
/// Shared with me root's, is fetched again once it is a minute old, and
/// that fetch ran on the dispatch loop, so every request on the mount
/// waited for Drive to answer (`docs/BUGS.md` B219).
pub(super) fn children_cached(&self, ino: u64) -> bool {
let (uid, resident) = {
let st = self.state();
match st.entries.get(&ino) {
Some(e) => (e.uid.clone(), st.children.contains_key(&ino)),
// `list_children` answers ENOENT without the network.
None => return true,
}
};
if !resident {
return false;
}
let freshness = if is_virtual_uid(&uid) {
Some(SHARED_WITH_ME_SYNCED_MS.to_string())
} else if !self.is_own_or_virtual(&uid) && !is_local_uid(&uid) {
Some(Self::shared_folder_freshness_key(&uid))
} else {
None
};
freshness.is_none_or(|key| {
!listing_needs_refresh(
self.online.load(Ordering::Relaxed),
self.shared_listing_stale(&key),
)
})
}
/// Re-apply the optimistic size of any queued write to `nodes`.
///
/// A node that arrives from the remote (or from its DB row) carries the size
/// of the revision the *server* holds, which for a file with a write still
/// queued is the pre-write size — often 0 for a file created moments ago.
/// Interning it as-is silently reverts the optimistic size that
/// `record_pending_write` stamped, and a file that stats as 0 bytes is a file
/// the kernel will not issue a single `read` for: `cat` prints nothing and
/// the staged blob that `read_range` would have served is never asked for.
/// That reads as data loss even though nothing is lost (B11).
///
/// [`Core::hydrate`] does the same thing for the restart case. This covers
/// every *live* re-enumeration — which is what a rename or move triggers,
/// since both invalidate the listings they touch.
///
/// Snapshots the pending map and returns before any caller takes the state
/// 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()
};
apply_pending_sizes(nodes, &sizes);
}
pub(super) fn is_own_or_virtual(&self, uid: &NodeUid) -> bool {
is_own_or_virtual_uid(uid, &self.primary_root_uid.volume_id)
}
/// The nodes of `before`, queued in `folder_uid` when its listing was asked
/// of Drive, that are no longer queued in `after`, as the DB has them now.
///
/// Their create landed while the listing was on the wire, after Drive took
/// it, and so is in neither. One unlinked or moved away meanwhile is not
/// under the folder by that name any more and stays out.
pub(super) fn landed_meanwhile(
&self,
folder_uid: &NodeUid,
before: Vec<Node>,
after: &[Node],
) -> Vec<Node> {
let still: HashSet<&str> = after.iter().map(|node| node.name.as_str()).collect();
let landed: HashSet<String> = before
.into_iter()
.map(|node| node.name)
.filter(|name| !still.contains(name.as_str()))
.collect();
if landed.is_empty() {
return Vec::new();
}
match self.db.known_children(folder_uid) {
Ok(known) => known
.into_iter()
.filter(|node| landed.contains(&node.name))
.collect(),
Err(e) => {
warn!(%folder_uid, error = %e, "db known_children failed");
Vec::new()
}
}
}
/// Serve a listing without the network: the one already in memory if any,
/// else whatever children the DB still knows. The fallback only answers
/// until the link is back, when [`Core::relist_offline_listings`] drops it:
/// a listing dropped as stale may lack a child another device made, and a
/// create over that name lands as a conflict copy rather than an `EIO` now.
pub(super) fn adopt_stale_listing(
&self,
ino: u64,
folder_uid: &NodeUid,
cached: bool,
primary_root: bool,
) -> Result<(), Errno> {
if cached {
return Ok(());
}
let nodes = self.db.known_children(folder_uid).map_err(|e| {
warn!(%folder_uid, error = %e, "db known_children failed");
Errno::EIO
})?;
debug!(%folder_uid, count = nodes.len(), "offline: listing a folder from what the DB knows");
self.link.stale_listings.lock().insert(ino);
self.adopt_db_listing(ino, folder_uid, nodes, primary_root)
}
/// Relist every folder [`Core::adopt_stale_listing`] served while offline.
pub(crate) fn relist_offline_listings(&self) {
let stale = std::mem::take(&mut *self.link.stale_listings.lock());
if stale.is_empty() {
return;
}
let mut st = self.state();
for &ino in &stale {
st.invalidate_listing(ino);
}
drop(st);
for mount in self.states.live() {
if let Some(notifier) = mount.notifier.get() {
for &ino in &stale {
let _ = notifier.inval_inode(ino);
}
}
}
}
/// Install `nodes`, read from the DB, as `ino`'s listing.
pub(super) fn adopt_db_listing(
&self,
ino: u64,
folder_uid: &NodeUid,
mut nodes: Vec<Node>,
primary_root: bool,
) -> Result<(), Errno> {
let folder_uid = folder_uid.clone();
if primary_root {
nodes.retain(|node| !is_virtual_uid(&node.uid));
}
// 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 mut st = self.state();
if st.children.contains_key(&ino) {
return Ok(());
}
let mut child_inos = Vec::with_capacity(nodes.len());
let mut needs_size = Vec::new();
for node in nodes {
if !node_visible(&node, &folder_uid, &hidden) {
continue;
}
if matches!(
&node.kind,
NodeKind::File {
claimed_size: None,
..
}
) {
needs_size.push(node.uid.clone());
}
child_inos.push(st.intern_from_db(ino, node));
}
st.children.insert(ino, child_inos);
let root_snapshot = primary_root.then(|| RootListingSnapshot::capture(&st, ino).unwrap());
drop(st);
self.flush_access_changes();
if let Some(snapshot) = root_snapshot {
self.reconcile_virtual_root_dentry(ino, snapshot)?;
}
// Rows persisted from a cheap enumeration whose upgrade never
// ran (a restart in between, say) still owe their real sizes.
self.spawn_size_upgrade(ino, needs_size);
Ok(())
}
/// Enumerate `ino`'s children from the remote and cache them. No-op if the
/// directory has already been listed. Network I/O happens without the lock
/// held so concurrent metadata reads aren't blocked behind a fetch.
///
/// A listing that changed while it was being published answers EAGAIN: the
/// root listed again after a restart, an event, a newer refresh of a shared
/// folder. The listing is still owed, so it is taken again rather than
/// handed to the lookup or open that asked (B159).
pub(super) fn ensure_children(&self, ino: u64) -> Result<(), Errno> {
for _ in 1..LISTING_ATTEMPTS {
match self.list_children(ino) {
Err(e) if e.code() == Errno::EAGAIN.code() => {
debug!(ino, "listing changed while it was published; listing again");
}
done => return done,
}
}
self.list_children(ino)
}
pub(super) fn list_children(&self, ino: u64) -> Result<(), Errno> {
let (folder_uid, cached) = {
let st = self.state();
match st.entries.get(&ino) {
Some(e) => (e.uid.clone(), st.children.contains_key(&ino)),
None => return Err(Errno::ENOENT),
}
};
if is_virtual_uid(&folder_uid) {
return self.ensure_shared_children(ino);
}
let primary_root =
is_primary_root_listing(self.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),
)
});
if cached && !refresh_foreign {
if primary_root {
self.reconcile_virtual_root_dentry(ino, self.resident_root_listing_snapshot(ino)?)?;
}
return Ok(());
}
// Offline fast path: a folder the DB still records as fully enumerated
// can be rebuilt from disk without hitting the API, even if its listing
// was trimmed from the hot cache mid-run.
let cached_nodes = if refresh_foreign {
Ok(None)
} else {
self.db.children_if_listed(&folder_uid)
};
match cached_nodes {
Ok(Some(nodes)) => return self.adopt_db_listing(ino, &folder_uid, nodes, primary_root),
Ok(None) => {}
Err(e) => warn!(%folder_uid, error = %e, "db children_if_listed failed"),
}
// Drive knows nothing by a stand-in. Until its mkdir lands the folder
// is only here, and once it has, the DB holds what Drive does. A
// listing dropped meanwhile was asked of Drive, and every lookup in
// the folder failed with EIO (`docs/BUGS.md` B125).
if is_local_uid(&folder_uid) {
let nodes = self.db.known_children(&folder_uid).map_err(|e| {
warn!(%folder_uid, error = %e, "db known_children failed");
Errno::EIO
})?;
return self.adopt_db_listing(ino, &folder_uid, nodes, primary_root);
}
if !self.is_online() {
return self.adopt_stale_listing(ino, &folder_uid, cached, primary_root);
}
let refresh_generation =
refresh_foreign.then(|| self.shared.shared_generation.load(Ordering::SeqCst));
// What is queued before Drive is asked: a create that lands while the
// listing is on the wire is in neither Drive's answer nor the queue read
// after it (`docs/BUGS.md` B166).
let queued_before = (!foreign)
.then(|| self.db.queued_children(&folder_uid).ok())
.flatten();
let uids = match self
.rt
.block_on(self.drive.enumerate_folder_children_node_uids(&folder_uid))
{
Ok(uids) => uids,
Err(e) if self.lost_link(&e, "list folder") => {
return self.adopt_stale_listing(ino, &folder_uid, cached, primary_root);
}
Err(e) => {
error!(%folder_uid, error = %e, "enumerate folder children failed");
return Err(Errno::EIO);
}
};
// Cheap enumeration: `Light` skips unlocking each *file's* node key,
// which is an S2K derivation per file and was ~74% of the cost of a cold
// listing (B12 — measured with `perf`, 64% of cycles in SHA-256 alone).
// Folders are unlocked either way; their keys are what the children are
// decrypted with, so the walk cannot proceed without them.
//
// The price is that files come back without a `claimed_size`, so
// `node_size` falls back to the *ciphertext* size until
// `spawn_size_upgrade` below fills the real one in.
let mut nodes = match self.rt.block_on(self.drive.enumerate_nodes_light(&uids)) {
Ok(nodes) => nodes,
Err(e) if self.lost_link(&e, "list folder") => {
return self.adopt_stale_listing(ino, &folder_uid, cached, primary_root);
}
Err(e) => {
error!(%folder_uid, error = %e, "enumerate nodes failed");
return Err(Errno::EIO);
}
};
// Drive shows none of what is still queued for the folder (B132).
// A shared folder's listing is published as Drive has it.
if !foreign {
match self.db.queued_children(&folder_uid) {
Ok((mut queued, gone)) => {
if let Some((before, _)) = queued_before {
queued.extend(self.landed_meanwhile(&folder_uid, before, &queued));
}
overlay_queued(&mut nodes, queued, &gone)
}
Err(e) => warn!(%folder_uid, error = %e, "db queued_children failed"),
}
}
// 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 mut filtered_nodes: Vec<Node> = nodes
.into_iter()
.filter(|node| node_visible(node, &folder_uid, &hidden))
.collect();
if foreign {
for node in &mut filtered_nodes {
node.parent_uid = Some(folder_uid.clone());
}
let _publication = self.shared.shared_publication.lock();
if !refresh_generation_is_current(
refresh_generation.expect("foreign refresh has a generation"),
self.shared.shared_generation.load(Ordering::SeqCst),
) {
return Err(Errno::EAGAIN);
}
let removed = self
.db
.publish_foreign_children(&folder_uid, &uids, &filtered_nodes)
.map_err(|error| {
error!(%folder_uid, %error, "publishing foreign-folder listing failed");
Errno::EIO
})?;
let mut snapshot = self.db.visible_children(&folder_uid).map_err(|error| {
error!(%folder_uid, %error, "loading published foreign-folder listing failed");
Errno::EIO
})?;
self.stamp_pending_sizes(&mut snapshot);
snapshot.retain(|node| node_visible(node, &folder_uid, &hidden));
let needs_size: Vec<NodeUid> = snapshot
.iter()
.filter(|node| {
matches!(
&node.kind,
NodeKind::File {
claimed_size: None,
..
}
)
})
.map(|node| node.uid.clone())
.collect();
let mut st = self.state();
for uid in &removed {
st.hide_foreign_subtree(uid);
}
let children = snapshot
.into_iter()
.map(|node| st.intern_from_db(ino, node))
.collect();
st.children.insert(ino, children);
drop(st);
self.flush_access_changes();
self.mark_shared_refresh_success(
foreign_key
.as_deref()
.expect("foreign refresh has a freshness key"),
);
self.spawn_size_upgrade(ino, needs_size);
return Ok(());
}
let preassigned = state::inos_for(&self.db, &filtered_nodes);
let mut st = self.state();
// Lost the race? Another thread already populated it.
if st.children.contains_key(&ino) {
return Ok(());
}
let mut child_inos = Vec::with_capacity(filtered_nodes.len());
// Files whose real size the cheap enumeration could not read. Collected
// before interning so the upgrade below has the uids without re-walking.
let needs_size: Vec<NodeUid> = filtered_nodes
.iter()
.filter(|n| {
matches!(
&n.kind,
NodeKind::File {
claimed_size: None,
..
}
)
})
.map(|n| n.uid.clone())
.collect();
let inos = st.intern_batch_with_inos(ino, filtered_nodes, preassigned);
child_inos.extend(inos);
st.children.insert(ino, child_inos);
let root_snapshot = primary_root.then(|| RootListingSnapshot::capture(&st, ino).unwrap());
// Record the listing as complete so a later restart (or a trimmed hot
// cache) can rebuild it from the DB without the API. Written with the
// children's rows when the lock goes, not under it.
st.record_listed(folder_uid.clone());
drop(st);
self.flush_access_changes();
if let Some(snapshot) = root_snapshot {
self.reconcile_virtual_root_dentry(ino, snapshot)?;
}
self.spawn_size_upgrade(ino, needs_size);
Ok(())
}
/// A page of the photos timeline (newest first), sliced out of the DB.
/// `Ok(None)` when the account has no photos volume.
///
/// Stale-while-revalidate: a persisted timeline is served *immediately*, and
/// refreshed on the runtime if it is older than [`TIMELINE_TTL`] — so opening
/// the app paints from disk rather than waiting on a full `enumerate_timeline`
/// (which returns the whole timeline, not a page). Only an empty DB blocks on
/// the network, i.e. the very first run.
///
/// 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`].
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,
}
}
}
+99
View File
@@ -0,0 +1,99 @@
//! Database maintenance moved off the request thread: `VACUUM` and the deep
//! integrity check, one at a time, with the last check's result kept.
use super::*;
impl Core {
/// Start a background `VACUUM`, or refuse because maintenance is already
/// running.
///
/// Returns as soon as the thread is spawned; the caller acknowledges the
/// request. The outcome is a log line and a job that disappears from
/// `GetQueueStatus` when it is done — a vacuum has nothing to report that a
/// follow-up `CacheInspect` cannot show.
pub(super) fn start_vacuum(&self) -> CoreResult<()> {
{
let mut m = self.maintenance.lock();
if m.running {
return Err(CoreError::conflict(
"database maintenance is already running",
));
}
m.running = true;
}
let core = self.clone();
std::thread::spawn(move || {
let job = core.transfers.begin_job("Compacting the cache database");
job.detail("Rewriting the database file");
let started = Instant::now();
match core.db.vacuum() {
Ok(outcome) => info!(
freed_bytes = outcome.freed_bytes(),
before_bytes = outcome.before_bytes,
after_bytes = outcome.after_bytes,
wal_frames = outcome.wal_frames_checkpointed,
elapsed_ms = started.elapsed().as_millis() as u64,
"cache database vacuumed"
),
Err(e) => warn!(error = %e, "vacuum failed"),
}
core.maintenance.lock().running = false;
});
Ok(())
}
/// Answer a deep `CacheInspect`: hand back the last completed integrity
/// check, and start one if none is running.
///
/// Returns `(problems, checked, running)`. A first request gets
/// `(_, false, true)` and the answer lands on a later one — the check reads
/// every page of the database under the connection mutex, so the choice is
/// between answering late and freezing the mount until it finishes.
pub(super) fn start_or_read_integrity_check(&self) -> (Vec<String>, bool, bool) {
let mut m = self.maintenance.lock();
if let Some(problems) = m.integrity.clone() {
return (problems, true, m.running);
}
if m.running {
return (Vec::new(), false, true);
}
m.running = true;
drop(m);
let core = self.clone();
std::thread::spawn(move || {
let job = core
.transfers
.begin_background_job("Checking the cache database");
job.detail("Verifying every page");
let problems = match core.db.integrity_check() {
Ok(problems) => problems,
Err(e) => vec![format!("integrity check failed: {e:?}")],
};
if problems.is_empty() {
info!("cache database integrity check found no problems");
} else {
warn!(problems = problems.len(), "cache database integrity check");
}
let mut m = core.maintenance.lock();
m.integrity = Some(problems);
m.running = false;
});
(Vec::new(), false, true)
}
}
/// Background database maintenance: what is running, and what the last deep
/// integrity check found.
///
/// One at a time — both operations are whole-database and there is nothing to
/// gain from overlapping them — and the result of a check outlives the request
/// that asked for it, because the request is answered before the check finishes.
#[derive(Default)]
pub(super) struct Maintenance {
/// A vacuum or integrity check is running right now.
running: bool,
/// Findings of the most recent completed deep check. `None` means none has
/// finished this run, which is *not* the same as "found nothing".
integrity: Option<Vec<String>>,
}
+192 -125
View File
@@ -1,6 +1,7 @@
//! Mount lifecycle and background-service orchestration.
use super::*;
use pdfs_core::lifecycle::{ServiceBoard, Services, Wake};
/// Why a [`mount`] call returned. Lets the daemon decide whether to exit (clean
/// shutdown) or remount (the mount went away under it).
@@ -196,6 +197,43 @@ pub(super) fn clear_stale_mount(mountpoint: &Path) {
}
}
/// Make sure `mountpoint` is a directory a mount can go on, clearing a dead
/// mount a killed daemon left there first.
///
/// A dead mount answers `ENOTCONN`, which `create_dir_all` takes for "absent";
/// it then tries `mkdir` and fails with `EEXIST`. The daemon retried that error
/// forever and never got as far as [`check_mountpoint`], which would have
/// cleared the mount (`docs/BUGS.md` B279).
pub fn prepare_mountpoint(mountpoint: &Path) -> std::io::Result<()> {
if is_stale_mount(mountpoint) {
clear_stale_mount(mountpoint);
}
std::fs::create_dir_all(mountpoint)
}
/// Refuse to mount My files over a folder that already has files in it: FUSE
/// would hide them, unsent and out of sight, until the service stops
/// (`docs/BUGS.md` B277). Runs before the root fetch and before any worker
/// starts, so a refusal costs nothing to retry.
///
/// A dead mount is cleared first, since it cannot be listed. One of this
/// client's own live mounts is left to [`spawn_session`], which clears it as it
/// always has; listing it would show Drive's files, not the folder's.
pub(super) fn check_mountpoint(mountpoint: &Path) -> std::io::Result<()> {
if is_stale_mount(mountpoint) {
clear_stale_mount(mountpoint);
}
if pdfs_core::mountpoint::mounted_fs_type(mountpoint).as_deref()
== Some(pdfs_core::mountpoint::OWN_FS_TYPE)
{
return Ok(());
}
match pdfs_core::mountpoint::not_empty(mountpoint)? {
Some(found) => Err(std::io::Error::other(found)),
None => Ok(()),
}
}
/// `sync_state` key holding the uid of the My Files root, so a later run can
/// recover it from `nodes` without the API.
const ROOT_UID_KEY: &str = "root_uid";
@@ -254,7 +292,7 @@ fn fetch_or_recall_root(
None if start == Start::SessionExpired => Err(std::io::Error::other(format!(
"Proton refused the session ({err}); run `pdfs login`"
))),
None => Err(std::io::Error::other(format!("fetch My Files root: {err}"))),
None => Err(std::io::Error::other(pdfs_core::mountfail::RootLookup(err))),
}
}
@@ -273,6 +311,7 @@ enum Start {
pub struct MountOptions {
/// Proton account the session belongs to, for display and per-user paths.
pub username: String,
pub gallery_session: Option<proton_drive_rs::proton_sdk::session::ProtonApiSession>,
/// What the background conflict sweep may do. See `docs/BUGS.md` B71.
pub sweep_mode: SweepMode,
/// Upload and download caps in bytes per second (`0` = no cap).
@@ -419,6 +458,7 @@ pub(crate) fn mount_with(
) -> std::io::Result<MountOutcome> {
let MountOptions {
username,
gallery_session,
sweep_mode,
upload_limit,
download_limit,
@@ -427,6 +467,13 @@ pub(crate) fn mount_with(
// Start the uptime clock here rather than at the first `pdfs diagnostics`,
// so the age it reports is the daemon's own.
super::diagnostics::start_clock();
// Count every call to Drive from the first, the root lookup included.
let drive_calls = Arc::new(pdfs_drive::counted::CallStats::default());
let drive: Arc<dyn DriveApi> = Arc::new(pdfs_drive::counted::Counted::new(
drive,
drive_calls.clone(),
));
check_mountpoint(mountpoint)?;
let (root, start) = fetch_or_recall_root(drive.as_ref(), &rt, &db)?;
let online = start == Start::Online;
let scope = root.tree_event_scope_id();
@@ -442,76 +489,71 @@ pub(crate) fn mount_with(
let (sync_tx, sync_rx) = std::sync::mpsc::channel::<sync::SyncMsg>();
let paused_until = pause::load_paused_until(&db);
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)));
let cache = Arc::new(cache);
let shutdown = Arc::new(crate::shutdown::Shutdown::default());
let transfers = TransferRegistry::new();
let sync = sync::SyncParts {
store: db.clone(),
drive: drive.clone(),
rt: rt.clone(),
cache: cache.clone(),
transfers: transfers.clone(),
shutdown: shutdown.clone(),
primary_root_uid: root.uid.clone(),
progress: Arc::default(),
engine: Arc::default(),
tx: sync_tx,
locks: Arc::default(),
unscanned: Arc::default(),
abandon: Arc::default(),
events_read_at: Arc::new(AtomicI64::new(0)),
};
let core = Core {
drive,
drive_calls,
client,
gallery,
rt: rt.clone(),
maintenance: Arc::new(Mutex::new(Default::default())),
primary_root_uid: root.uid.clone(),
primary: true,
state: Arc::new(Mutex::new(State::new(db.clone(), share_access))),
state: Arc::new(Ranked::new(
Rank::State,
State::new(db.clone(), share_access),
)),
root: Arc::new(OnceLock::new()),
cache: Arc::new(cache),
readers: Arc::new(Mutex::new(HashMap::new())),
block_ring: Arc::new(Mutex::new(BlockRing::default())),
block_flight: Arc::new(BlockFlight::default()),
content_repairs: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
prefetch: Arc::new(Prefetch::default()),
prefetch_budget: Arc::new(tokio::sync::Semaphore::new(PREFETCH_BUDGET)),
cache,
reads: super::reads::ReadState::new(),
workers: Arc::new(Workers::new(FUSE_WORKERS)?),
db,
shared_publication: Arc::new(Mutex::new(())),
shared_generation: Arc::new(AtomicU64::new(0)),
shared_refresh_deadlines: Arc::new(Mutex::new(SharedRefreshDeadlines::default())),
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())),
creating: Arc::new(Mutex::new(HashMap::new())),
sealed_unread: Arc::new(Mutex::new(HashMap::new())),
landed: Arc::new(Mutex::new(HashMap::new())),
unadopted: Arc::new(Mutex::new(HashMap::new())),
drain_wake: Arc::new((Mutex::new(false), Condvar::new())),
shutdown: Arc::new(crate::shutdown::Shutdown::default()),
upload_times: Arc::new(Mutex::new(HashMap::new())),
upload_cancel: Arc::new(Mutex::new(HashMap::new())),
landing_uploads: Arc::new(AtomicU64::new(0)),
timeline_refreshing: Arc::new(AtomicBool::new(false)),
timeline_progress: Arc::new(Mutex::new(None)),
similar_hashing: Arc::new(AtomicBool::new(false)),
albums_refreshing: Arc::new(AtomicBool::new(false)),
trash_refreshing: Arc::new(AtomicBool::new(false)),
trash_progress: Arc::new(tokio::sync::Notify::new()),
conflict_notified: Arc::new(Mutex::new(HashSet::new())),
sweep_mode,
drain: super::drain::DrainState::new(),
pin_work: Arc::new(Mutex::new(Default::default())),
sizes: super::sizes::SizeState::new(),
trash: super::trash::TrashState::new(),
shared: super::shared::SharedState::new(),
quota_cache: super::sharing::QuotaCache::new(),
sweep: super::sweep::SweepState::new(sweep_mode),
shutdown,
services: ServiceBoard::default(),
photo_jobs: super::photos::PhotoJobs::new(),
local_first,
self_changes: Arc::new(Mutex::new(HashMap::new())),
thumb_gen: Arc::new(Mutex::new(HashSet::new())),
thumb_gen_budget: Arc::new(tokio::sync::Semaphore::new(
super::photos::THUMB_GEN_CONCURRENCY,
)),
file_thumb_generation: Arc::new(AtomicU64::new(0)),
file_thumb_cancel: Arc::new(tokio::sync::Notify::new()),
thumbnail_build: Arc::new(Mutex::new(Default::default())),
thumbnail_build_cancelled: Arc::new(AtomicBool::new(false)),
thumbnail_build_cancel: Arc::new(tokio::sync::Notify::new()),
thumbnail_misses: Arc::new(Mutex::new(Default::default())),
quota: Arc::new(Mutex::new(None)),
quota_refreshing: Arc::new(AtomicBool::new(false)),
size_upgrades: Arc::new(Mutex::new(HashMap::new())),
size_waiters: Arc::new(Default::default()),
notifier: Arc::new(OnceLock::new()),
session_live: Arc::new(AtomicBool::new(false)),
transfers: TransferRegistry::new(),
transfers,
sync,
events: Arc::new(Default::default()),
indexing: Arc::new(AtomicBool::new(false)),
sync_progress: Arc::new(Mutex::new(HashMap::new())),
sync_engine: Arc::default(),
sync_tx,
pending_probe: Arc::default(),
mounts: Arc::new(Mutex::new(SecondaryMountRegistry::default())),
sync_locks: Arc::new(Mutex::new(HashMap::new())),
sync_unscanned: Arc::new(Mutex::new(HashMap::new())),
states: Arc::new(StateRegistry::default()),
};
// Before anything can queue work against it: the drain thread below reaches
@@ -539,18 +581,36 @@ pub(crate) fn mount_with(
// joined at the end of this function. Leaving them running turned an
// in-process remount into a second generation of drain workers, sync engines
// and sweeps all operating on a mount that no longer exists (`docs/BUGS.md` B44).
let mut workers: Vec<std::thread::JoinHandle<()>> = Vec::new();
let mut workers = Services::new(core.services.clone());
for worker in 0..DRAIN_WORKERS {
let drain_core = core.clone();
let spawned = std::thread::Builder::new()
.name(format!("pdfs-drain-{worker}"))
.spawn(move || drain_core.run_pending_drain(worker == 0));
// The drain workers wait on their own condvar, which a stop has to
// notify; one notify wakes them all.
let wake: Option<Wake> = (worker == 0).then(|| {
let core = core.clone();
Box::new(move || core.wake_drain()) as Wake
});
let spawned = workers.spawn(&format!("pdfs-drain-{worker}"), wake, move || {
drain_core.run_pending_drain(worker == 0)
});
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
}
// Start the folder-sync engine. It watches every mirror folder, polls the
// remotes, and reconciles on its own thread — never in front of a FUSE call.
workers.extend(sync::spawn(core.clone(), sync_rx));
// It waits on its channel, so a stop sends it `Stop`.
{
let syncer = core.syncer();
let tx = core.sync.tx.clone();
let wake: Wake = Box::new(move || {
let _ = tx.send(sync::SyncMsg::Stop);
});
if let Err(error) =
workers.spawn("pdfs-sync", Some(wake), move || sync::run(syncer, sync_rx))
{
warn!(%error, "failed to start sync engine");
}
}
// 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);
@@ -566,9 +626,9 @@ pub(crate) fn mount_with(
} else {
info!(mode = ?sweep_mode, "conflict sweep enabled");
let sweep_core = core.clone();
let spawned = std::thread::Builder::new()
.name("pdfs-conflict-sweep".into())
.spawn(move || sweep_core.run_conflict_sweep_loop());
let spawned = workers.spawn("pdfs-conflict-sweep", None, move || {
sweep_core.run_conflict_sweep_loop()
});
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
}
@@ -577,23 +637,37 @@ pub(crate) fn mount_with(
// must notice it coming back just the same.
{
let probe_core = core.clone();
let spawned = std::thread::Builder::new()
.name("pdfs-online-probe".into())
.spawn(move || probe_core.run_online_probe());
let spawned = workers.spawn("pdfs-online-probe", None, move || {
probe_core.run_online_probe()
});
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
}
// Keep pinned files on this computer through changes made elsewhere, and
// fetch the ones a failed or missed download left out (`docs/BUGS.md`
// B282). Its own thread: a check lists folders and downloads files.
{
let keeper_core = core.clone();
let spawned = workers.spawn("pdfs-pin-keeper", None, move || {
keeper_core.run_pin_keeper()
});
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
}
// Keep the launcher prompt's "This computer" index fresh. Its own thread:
// the walk is I/O-heavy and must never sit in front of a FUSE callback.
if matches!(host, Host::Daemon) {
if let Some(gallery) = &core.gallery {
rt.spawn(gallery.clone().poll(core.clone()));
}
let db = core.db.clone();
let indexing = core.indexing.clone();
let transfers = core.transfers.clone();
let mountpoint = mountpoint.to_path_buf();
let shutdown = core.shutdown.clone();
let spawned = std::thread::Builder::new()
.name("pdfs-localindex".into())
.spawn(move || run_local_index(db, indexing, transfers, mountpoint, shutdown));
let spawned = workers.spawn("pdfs-localindex", None, move || {
run_local_index(db, indexing, transfers, mountpoint, shutdown)
});
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
}
@@ -637,11 +711,21 @@ pub(crate) fn mount_with(
let control_core = core.clone();
let username = username.clone();
let mountpoint = mountpoint.to_path_buf();
match std::thread::Builder::new()
.name("pdfs-control".into())
.spawn(move || run_control_socket(control_core, username, mountpoint, listener))
{
Ok(handle) => workers.push(handle),
// The listener blocks in `accept`, which only returns when a connection
// arrives, so a stop connects to it. Connect while the socket still
// exists, which is the point of the poke, then unlink it so nothing else
// can arrive behind it. The listener checks the stop flag after every
// accept, so a connection that races the unlink cannot put it back to
// sleep.
let socket = control_socket.to_path_buf();
let wake: Wake = Box::new(move || {
let _ = std::os::unix::net::UnixStream::connect(&socket);
let _ = std::fs::remove_file(&socket);
});
match workers.spawn("pdfs-control", Some(wake), move || {
run_control_socket(control_core, username, mountpoint, listener)
}) {
Ok(()) => {}
Err(error) => {
// A failure here abandons the mount, so the background threads
// started above have to be told to stop with it.
@@ -668,14 +752,12 @@ pub(crate) fn mount_with(
let sampler_core = core.clone();
let username = username.clone();
let mountpoint = mountpoint.to_path_buf();
match std::thread::Builder::new()
.name("pdfs-events".into())
.spawn(move || events::run_event_sampler(sampler_core, username, mountpoint))
{
Ok(handle) => workers.push(handle),
if let Err(error) = workers.spawn("pdfs-events", None, move || {
events::run_event_sampler(sampler_core, username, mountpoint)
}) {
// Not fatal: front-ends still get every published change, only
// not the sampled ones.
Err(error) => warn!(error = %error, "could not start the event sampler"),
warn!(error = %error, "could not start the event sampler");
}
}
// The supervisor watches the pool and answers the systemd watchdog. Started
@@ -684,14 +766,12 @@ pub(crate) fn mount_with(
{
let supervisor_core = core.clone();
let socket = control_socket.to_path_buf();
match std::thread::Builder::new()
.name("pdfs-supervisor".into())
.spawn(move || supervisor::run(supervisor_core, socket))
{
Ok(handle) => workers.push(handle),
if let Err(error) = workers.spawn("pdfs-supervisor", None, move || {
supervisor::run(supervisor_core, socket)
}) {
// Not fatal: the mount works without a supervisor, it just goes back
// to being undiagnosable if it wedges.
Err(error) => warn!(error = %error, "could not start the daemon supervisor"),
warn!(error = %error, "could not start the daemon supervisor");
}
}
// The mount is live and the control socket answers: this is the moment the
@@ -734,6 +814,16 @@ pub(crate) fn mount_with(
warn!(%error, "start My Files share-id repair failed");
}
}
// Hold off a shutdown while changes exist only here (B66). Only the real
// daemon: a simulation's queue is not the user's data.
if matches!(host, Host::Daemon) {
let inhibit_core = core.clone();
if let Err(error) = workers.spawn("pdfs-inhibit", None, move || {
crate::inhibit::run(inhibit_core)
}) {
warn!(%error, "start the shutdown inhibitor failed");
}
}
// Stop signals (SIGTERM from `systemctl --user stop`, SIGINT from Ctrl-C)
// are delivered onto the async runtime; bridge them onto a sync channel so
@@ -862,7 +952,7 @@ const WORKER_JOIN_DEADLINE: Duration = Duration::from_secs(10);
/// expected and correct: a worker part-way through an upload finishes it rather
/// than abandoning the user's bytes mid-flight. Up to [`WORKER_JOIN_DEADLINE`]:
/// past it, systemd kills the daemon anyway, and a queued op is sent again.
fn stop_workers(core: &Core, control_socket: &Path, workers: Vec<std::thread::JoinHandle<()>>) {
fn stop_workers(core: &Core, control_socket: &Path, workers: Services) {
// Say so before the joins: a teardown that takes a while must not be read as
// a missed watchdog ping and turned into a kill.
systemd::stopping();
@@ -877,7 +967,7 @@ fn stop_workers(core: &Core, control_socket: &Path, workers: Vec<std::thread::Jo
/// (`docs/BUGS.md` B264). Unlike [`stop_workers`] this does not tell systemd
/// the daemon is stopping, because it is about to try again, and a manager
/// told so would wait for the process to exit and then kill it.
fn abandon_workers(core: &Core, control_socket: &Path, workers: Vec<std::thread::JoinHandle<()>>) {
fn abandon_workers(core: &Core, control_socket: &Path, workers: Services) {
halt_workers(core, control_socket, workers);
}
@@ -886,34 +976,30 @@ fn abandon_workers(core: &Core, control_socket: &Path, workers: Vec<std::thread:
fn keep_or_abandon(
core: &Core,
control_socket: &Path,
workers: &mut Vec<std::thread::JoinHandle<()>>,
spawned: std::io::Result<std::thread::JoinHandle<()>>,
workers: &mut Services,
spawned: std::io::Result<()>,
) -> std::io::Result<()> {
match spawned {
Ok(handle) => {
workers.push(handle);
Ok(())
}
Err(error) => {
abandon_workers(core, control_socket, std::mem::take(workers));
Err(error)
}
if let Err(error) = spawned {
let started = std::mem::replace(workers, Services::new(core.services.clone()));
abandon_workers(core, control_socket, started);
return Err(error);
}
Ok(())
}
/// Signal every worker to stop, then join them up to [`WORKER_JOIN_DEADLINE`].
fn halt_workers(core: &Core, control_socket: &Path, workers: Vec<std::thread::JoinHandle<()>>) {
core.shutdown.stop();
core.wake_drain();
let _ = core.sync_tx.send(sync::SyncMsg::Stop);
// Connect while the socket still exists — that is the whole point of the
// poke — then unlink it so nothing else can arrive behind us. The listener
// re-checks the flag after every accept, so even a connection that races the
// unlink cannot put it back to sleep.
let _ = std::os::unix::net::UnixStream::connect(control_socket);
let _ = std::fs::remove_file(control_socket);
///
/// Each worker was started with the call that wakes it, if it blocks where the
/// shutdown signal does not reach; [`Services::stop`] makes those calls.
fn halt_workers(core: &Core, control_socket: &Path, workers: Services) {
if let Some(gallery) = &core.gallery {
gallery.cancel();
}
let deadline = Instant::now() + WORKER_JOIN_DEADLINE;
let running = join_until(workers, deadline);
let running = workers.stop(&core.shutdown, deadline);
// A mount that failed before the control thread started has no wake to
// unlink its socket.
let _ = std::fs::remove_file(control_socket);
if !running.is_empty() {
warn!(
running = running.join(","),
@@ -930,32 +1016,13 @@ fn halt_workers(core: &Core, control_socket: &Path, workers: Vec<std::thread::Jo
debug!("background workers stopped");
}
/// Join `workers` until `deadline`, and name the ones still running then.
///
/// A stop used to wait for each one however long it took. The sync engine's
/// mirror pass waits on Drive with no deadline, and a stop that waited for it
/// was killed by systemd (`docs/BUGS.md` B165).
fn join_until(workers: Vec<std::thread::JoinHandle<()>>, deadline: Instant) -> Vec<String> {
let mut running = Vec::new();
for worker in workers {
while !worker.is_finished() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
if !worker.is_finished() {
running.push(worker.thread().name().unwrap_or("unnamed").to_string());
} else if worker.join().is_err() {
warn!("a background worker panicked before shutdown");
}
}
running
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use super::{SecondaryInsertRejection, SecondaryMountRegistry, join_until, teardown_session};
use super::{SecondaryInsertRejection, SecondaryMountRegistry, teardown_session};
use pdfs_core::lifecycle::join_until;
#[test]
fn a_stop_names_the_workers_still_running_at_its_deadline() {
File diff suppressed because it is too large. Load diff
+986
View File
@@ -0,0 +1,986 @@
//! Thumbnails: the ones the server lacks, generated here and uploaded; the
//! file-manager thumbnails for ordinary files and folder covers; and the
//! recursive build started from the Files toolbar.
use super::*;
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())
}
/// [`Core::upload_thumbnails`] on the blocking pool, for async callers.
pub(crate) async fn upload_thumbnails_async(
&self,
path: PathBuf,
name: String,
) -> Vec<Thumbnail> {
let staging_dir = self.cache.raw_thumbnail_staging_dir().to_path_buf();
tokio::task::spawn_blocking(move || upload_thumbnails(&path, &name, &staging_dir))
.await
.unwrap_or_default()
}
/// 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,
/// so a cold timeline paints immediately and only the photos actually on
/// screen cost a round-trip.
///
/// A photo absent from the persisted timeline is skipped: its capture time is
/// the cache's validity tag, and guessing that would poison the cache.
///
/// A camera raw is served by the JPEG of the same shot when there is one:
/// the two files show one picture, and the JPEG is already decodable in
/// milliseconds where the raw costs a full download and a raw decode. The
/// tile still answers under the uid that was asked for.
pub(crate) fn photo_thumbs(&self, requested: &[NodeUid]) -> Vec<PhotoThumb> {
self.photo_thumbs_with(requested, true)
}
/// [`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(
&self,
requested: &[NodeUid],
generate: bool,
) -> Vec<PhotoThumb> {
let ttype = ThumbnailType::Thumbnail.as_i32();
// Only a raw can be stood in for, and that is one batched read; the
// per-shot group lookup is then paid for raws alone, not for a page of
// ordinary photos.
let asked: Vec<String> = requested.iter().map(|u| u.to_string()).collect();
let raws: HashSet<String> = self
.db
.photos_by_uid(&asked)
.unwrap_or_default()
.into_iter()
.filter(|photo| photo.kind == PhotoKind::Raw)
.map(|photo| photo.uid)
.collect();
let sources: Vec<NodeUid> = requested
.iter()
.map(|uid| {
if raws.contains(&uid.to_string()) {
self.thumb_source(uid)
} else {
uid.clone()
}
})
.collect();
let uids = &sources;
let keys: Vec<String> = uids.iter().map(|u| u.to_string()).collect();
let mut stored = self.db.photos_by_uid(&keys).unwrap_or_default();
// Album covers and the contents of an album shared with us are not in our
// own timeline, so their capture time — the cache's validity tag — only
// exists on the album rows. Fill in whatever the timeline didn't cover.
{
let have: HashSet<String> = stored.iter().map(|p| p.uid.clone()).collect();
let missing: Vec<String> = keys
.iter()
.filter(|k| !have.contains(*k))
.cloned()
.collect();
stored.extend(self.db.album_photos_by_uid(&missing).unwrap_or_default());
}
let stored = stored;
let tags: HashMap<String, i64> = stored
.iter()
.map(|p| (p.uid.clone(), p.capture_time))
.collect();
let names: HashMap<String, String> = stored
.iter()
.filter_map(|photo| photo.name.clone().map(|name| (photo.uid.clone(), name)))
.collect();
// Ask the server only for photos that are missing a cached thumbnail and
// haven't already been written off as un-thumbnailable.
let want: Vec<NodeUid> = uids
.iter()
.filter(|uid| {
let key = uid.to_string();
stored
.iter()
.find(|p| p.uid == key)
.is_some_and(|p| p.thumb_state != db::THUMB_NONE)
&& tags.get(&key).is_some_and(|&tag| {
self.cache.cached_thumbnail_path(uid, ttype, tag).is_none()
})
})
.cloned()
.collect();
if !want.is_empty() {
let mut missing = want.clone();
match self.rt.block_on(
self.photos()
.enumerate_thumbnails(&want, ThumbnailType::Thumbnail),
) {
Ok(thumbs) => {
for ft in thumbs {
let Some(&tag) = tags.get(&ft.file_uid.to_string()) else {
continue;
};
let Ok(bytes) = ft.result else { continue };
if bytes.is_empty() {
continue;
}
if self
.cache
.store_thumbnail(&ft.file_uid, ttype, tag, &bytes)
.is_ok()
{
missing.retain(|uid| uid != &ft.file_uid);
self.record_thumb(&ft.file_uid, db::THUMB_HAVE, ratio_of(&bytes));
}
}
}
// A failed batch is not a verdict: leave every uid in `missing` so
// the local fallback still gives those tiles an image.
Err(e) => warn!(error = %e, "batch photo thumbnails failed"),
}
// Whatever the server had nothing for gets a thumbnail made from its
// own bytes — this is what fills in camera photos uploaded by clients
// that never generated one. Off the request path: a full-size photo
// takes far longer to fetch than the whole rest of the batch, and the
// thumbnails that *are* ready must not wait behind it.
if generate && !missing.is_empty() {
self.spawn_generate_thumbs(missing, &tags, &names, ThumbJob::Photos);
}
}
let pending = self.photo_jobs.thumb_gen.lock();
requested
.iter()
.zip(uids)
.map(|(asked, source)| PhotoThumb {
uid: asked.to_string(),
path: tags.get(&source.to_string()).and_then(|&tag| {
self.cache
.cached_thumbnail_path(source, ttype, tag)
.map(|p| p.display().to_string())
}),
pending: pending.contains(source),
})
.collect()
}
/// Which file's thumbnail stands for `uid` on a tile.
///
/// Itself, for all but a camera raw that was written next to a JPEG of the
/// same shot. For that one, the JPEG: same picture, already compressed,
/// often carrying a server thumbnail the raw does not have — so the Raw tab
/// costs no raw download and no raw decode. A raw that stands alone keeps
/// its own local generation.
pub(crate) fn thumb_source(&self, uid: &NodeUid) -> NodeUid {
let members = match self.db.photos_group(&uid.to_string()) {
Ok(members) if members.len() > 1 => members,
_ => return uid.clone(),
};
let key = uid.to_string();
if !members
.iter()
.any(|photo| photo.uid == key && photo.kind == PhotoKind::Raw)
{
return uid.clone();
}
members
.iter()
.find(|photo| photo.kind != PhotoKind::Raw)
.and_then(|photo| parse_uid(&photo.uid))
.unwrap_or_else(|| uid.clone())
}
/// 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
/// Photos timeline: the request supplies each file's modification time as
/// the cache validity tag.
pub(crate) fn file_thumbs(
&self,
items: &[FileThumbRequest],
generation: u64,
) -> Option<Vec<PhotoThumb>> {
let current = generation != 0
&& self.photo_jobs.file_thumb_generation.load(Ordering::SeqCst) == generation;
if !current {
return None;
}
let ttype = ThumbnailType::Thumbnail.as_i32();
let parsed: Vec<(String, NodeUid, i64)> = items
.iter()
.filter_map(|item| {
parse_uid(&item.uid).map(|uid| (item.uid.clone(), uid, item.modified))
})
.collect();
let tags: HashMap<String, i64> = parsed
.iter()
.map(|(raw, _, modified)| (raw.clone(), *modified))
.collect();
let names: HashMap<String, String> = items
.iter()
.map(|item| (item.uid.clone(), item.name.clone()))
.collect();
// Drive makes no thumbnails itself; a file has one only when its
// uploader attached it, as this client and Proton's apps do. The
// generation step asks for that first, and only makes one from the
// file's content without it.
let mut wanted = Vec::new();
let mut seen = HashSet::new();
for (raw, uid, modified) in &parsed {
if self
.cache
.cached_thumbnail_path(uid, ttype, *modified)
.is_some()
|| self
.photo_jobs
.thumbnail_misses
.lock()
.local_contains(&(uid.clone(), ttype), *modified)
|| !seen.insert(raw.clone())
{
continue;
}
wanted.push(uid.clone());
}
if !wanted.is_empty() {
self.spawn_generate_thumbs(wanted, &tags, &names, ThumbJob::Files(generation));
}
let pending = self.photo_jobs.thumb_gen.lock();
Some(
items
.iter()
.map(|item| {
let uid = parse_uid(&item.uid);
PhotoThumb {
uid: item.uid.clone(),
path: uid.as_ref().and_then(|uid| {
self.cache
.cached_thumbnail_path(uid, ttype, item.modified)
.map(|path| path.display().to_string())
}),
pending: uid.as_ref().is_some_and(|uid| pending.contains(uid)),
}
})
.collect(),
)
}
/// Reserve the next ordinary-file listing generation. This daemon-owned
/// monotonic value replaces GUI wall-clock seeds, which can move backwards
/// across NTP corrections, suspend, or dual boot.
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
.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();
generation
}
/// Advance the ordinary-file thumbnail generation. Every queued/download in
/// an older listing observes the new value and exits; Photos and explicit
/// recursive builds do not use this generation and continue normally.
pub(crate) fn cancel_file_thumbs(&self, generation: u64) {
let previous = self
.photo_jobs
.file_thumb_generation
.fetch_max(generation, Ordering::SeqCst);
if generation > previous {
self.photo_jobs.file_thumb_cancel.notify_waiters();
}
}
/// Generate the missing thumbnails on the runtime, skipping any photo already
/// being generated. The uids are marked in-flight before the task starts, so
/// the reply this call is about to send already reports them as pending.
pub(super) fn spawn_generate_thumbs(
&self,
uids: Vec<NodeUid>,
tags: &HashMap<String, i64>,
names: &HashMap<String, String>,
job: ThumbJob,
) {
let fresh: Vec<NodeUid> = {
let mut inflight = self.photo_jobs.thumb_gen.lock();
uids.into_iter()
.filter(|uid| inflight.insert(uid.clone()))
.collect()
};
if fresh.is_empty() {
return;
}
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(|| {
core.generate_thumbs(&fresh, &tags, &names, job)
}));
let mut inflight = core.photo_jobs.thumb_gen.lock();
for uid in &fresh {
inflight.remove(uid);
}
drop(inflight);
if result.is_err() {
warn!("thumbnail generation worker panicked");
}
});
}
/// Make thumbnails for photos the server has none for: download each full
/// file once, scale it to [`THUMB_EDGE`], and store the result in the thumbnail
/// cache exactly as if the server had served it.
///
/// Bounded by [`THUMB_GEN_CONCURRENCY`] — these are full-size originals, and a
/// screenful of them at once would saturate the link. A photo whose bytes
/// can't be decoded (a codec `image` doesn't speak) is marked
/// [`db::THUMB_NONE`] and never attempted again.
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
}
ThumbJob::Photos => true,
ThumbJob::Build => !self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst),
}
}
pub(super) fn generate_thumbs(
&self,
uids: &[NodeUid],
tags: &HashMap<String, i64>,
names: &HashMap<String, String>,
job: ThumbJob,
) -> ThumbBatchSummary {
info!(count = uids.len(), "generating local thumbnails");
let results: Vec<(NodeUid, ThumbAttempt)> = self.rt.block_on(async {
let mut out = Vec::with_capacity(uids.len());
for chunk in uids.chunks(THUMB_GEN_CONCURRENCY) {
let mut set = tokio::task::JoinSet::new();
for uid in chunk {
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 !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
let video = is_video_name(&name);
let audio = is_audio_file_name(&name);
// Without ffmpeg a video can still have its uploader's
// thumbnail, but Photos has asked the server already.
let can_sample = !video || ffmpeg_available();
if !can_sample && matches!(job, ThumbJob::Photos) {
return (uid, ThumbAttempt::Unavailable);
}
// 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();
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) {
return (uid, ThumbAttempt::Cancelled);
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
}
},
ThumbJob::Build => loop {
tokio::select! {
permit = &mut acquire => break permit.ok(),
_ = core.photo_jobs.thumbnail_build_cancel.notified() => {
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
}
},
ThumbJob::Photos => acquire.await.ok(),
};
let Some(_permit) = _permit else {
return (uid, ThumbAttempt::Unavailable);
};
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
let download_uid = uid.clone();
let drive = core.drive.clone();
let audio_name = name.clone();
let download = async move {
// Photos asked the server in one batch already. A
// file view's or a build's file may carry a
// thumbnail its uploader made, which costs one
// small download instead of its content.
if !matches!(job, ThumbJob::Photos)
&& let Some(bytes) = drive
.download_thumbnail(&download_uid, ThumbnailType::Thumbnail)
.await?
.filter(|bytes| !bytes.is_empty())
{
return Ok(Fetched::Ready(bytes));
}
if !can_sample {
return Ok(Fetched::Nothing);
}
if video {
let reader = drive.open_revision(&download_uid).await?;
sample_video(reader.as_ref()).await.map(Fetched::Video)
} else if audio {
let reader = drive.open_revision(&download_uid).await?;
sample_audio(reader.as_ref(), &audio_name)
.await
.map(Fetched::Audio)
} else {
client
.download_file(&download_uid)
.await
.map(Fetched::Whole)
}
};
tokio::pin!(download);
let downloaded = match job {
ThumbJob::Files(_) => loop {
tokio::select! {
result = &mut download => break Some(result),
_ = core.photo_jobs.file_thumb_cancel.notified() => {
if !core.thumb_job_current(job) {
break None;
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
break None;
}
}
}
},
ThumbJob::Build => loop {
tokio::select! {
result = &mut download => break Some(result),
_ = core.photo_jobs.thumbnail_build_cancel.notified() => {
if !core.thumb_job_current(job) {
break None;
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
break None;
}
}
}
},
ThumbJob::Photos => Some(download.await),
};
let Some(downloaded) = downloaded else {
return (uid, ThumbAttempt::Cancelled);
};
let fetched = match downloaded {
Ok(fetched) => fetched,
Err(e) => {
warn!(%uid, error = %e, "download for a thumbnail failed");
return (uid, ThumbAttempt::Unavailable);
}
};
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 = 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) => {
audio_cover_thumbnail(&sample, &name, &staging_dir)
}
Fetched::Video(sample) => video_sample_thumbnail(
&sample,
&name,
&staging_dir,
OsStr::new("ffmpeg"),
FFMPEG_TIMEOUT,
),
Fetched::Whole(bytes) => scale_thumbnail(&bytes, &name, &staging_dir),
Fetched::Nothing => ScaleAttempt::Unavailable,
Fetched::Ready(bytes) => match ratio_of(&bytes) {
Some(ratio) => ScaleAttempt::Made(GeneratedThumb { bytes, ratio }),
None => ScaleAttempt::Undecodable,
},
})
.await
.unwrap_or(ScaleAttempt::Unavailable);
// 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
}
made => made,
};
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
match made {
ScaleAttempt::Made(thumb) => (uid, ThumbAttempt::Made(thumb)),
ScaleAttempt::Undecodable => (uid, ThumbAttempt::Undecodable),
ScaleAttempt::Unavailable => (uid, ThumbAttempt::Unavailable),
}
});
}
while let Some(joined) = set.join_next().await {
if let Ok(result) = joined {
out.push(result);
}
}
}
out
});
let ttype = ThumbnailType::Thumbnail.as_i32();
let mut summary = ThumbBatchSummary::default();
for (uid, attempt) in results {
match attempt {
ThumbAttempt::Made(thumb) => {
let Some(&tag) = tags.get(&uid.to_string()) else {
summary.unavailable += 1;
continue;
};
match self.cache.store_thumbnail(&uid, ttype, tag, &thumb.bytes) {
Ok(()) => {
summary.made += 1;
self.photo_jobs
.thumbnail_misses
.lock()
.forget_local(&(uid.clone(), ttype));
self.record_thumb(&uid, db::THUMB_HAVE, Some(thumb.ratio));
}
Err(e) => {
summary.unavailable += 1;
warn!(%uid, error = %e, "storing generated thumbnail failed");
}
}
}
// The photo's own bytes aren't an image we can read: no thumbnail
// will ever exist for it, so stop trying.
ThumbAttempt::Undecodable => {
summary.undecodable += 1;
if let Some(&tag) = tags.get(&uid.to_string()) {
self.photo_jobs
.thumbnail_misses
.lock()
.remember_local((uid.clone(), ttype), tag);
}
self.record_thumb(&uid, db::THUMB_NONE, None);
}
// The download failed — a dropped connection, an expired link. That
// is not a verdict on the photo: leave its state alone so the next
// scroll past it tries again.
ThumbAttempt::Unavailable => summary.unavailable += 1,
ThumbAttempt::Cancelled => summary.cancelled += 1,
}
}
// A folder on screen whose tiles were given up on, as a recursive
// build's start does to them, fills in without being opened again.
if summary.made > 0 {
self.events.publish(&[Topic::Thumbnails]);
}
summary
}
/// The cover image in the folder of the song `uid`: the best-named one of
/// [`FOLDER_COVER_STEMS`] among its siblings the database knows.
pub(crate) fn folder_cover(&self, uid: &NodeUid) -> Option<proton_drive_rs::Node> {
let node = self.db.node_by_uid(&uid.to_string()).ok()??;
let parent = node.parent_uid?;
let siblings = match self.db.children_if_listed(&parent) {
Ok(Some(children)) => children,
_ => self.db.known_children(&parent).ok()?,
};
siblings
.into_iter()
.filter(|sibling| !sibling.is_folder() && !sibling.trashed)
.filter_map(|sibling| cover_rank(&sibling.name).map(|rank| (rank, sibling)))
.min_by(|(a, x), (b, y)| a.cmp(b).then_with(|| x.name.cmp(&y.name)))
.map(|(_, cover)| cover)
}
/// A thumbnail of the song `uid` made from its folder's cover image: the
/// cover's own cached thumbnail when it has one, else the thumbnail its
/// uploader attached, else the image itself, up to
/// [`FOLDER_COVER_MAX_BYTES`].
///
/// The result is stored under the song, so a cover added to the folder or
/// replaced later shows only once the song changes or the daemon restarts
/// and forgets the songs it found no cover for.
pub(super) async fn folder_cover_thumbnail(
&self,
uid: &NodeUid,
staging_dir: PathBuf,
) -> ScaleAttempt {
let Some(cover) = self.folder_cover(uid) else {
return ScaleAttempt::Undecodable;
};
let ttype = ThumbnailType::Thumbnail;
let cached = self
.cache
.cached_thumbnail_path(&cover.uid, ttype.as_i32(), cover.modification_time)
.and_then(|path| std::fs::read(path).ok());
let ready = match cached {
Some(bytes) => Some(bytes),
None => match self.drive.download_thumbnail(&cover.uid, ttype).await {
Ok(bytes) => bytes.filter(|bytes| !bytes.is_empty()),
Err(e) => {
warn!(cover = %cover.uid, error = %e, "folder cover thumbnail download failed");
return ScaleAttempt::Unavailable;
}
},
};
if let Some(bytes) = ready {
return match ratio_of(&bytes) {
Some(ratio) => ScaleAttempt::Made(GeneratedThumb { bytes, ratio }),
None => ScaleAttempt::Undecodable,
};
}
let read = async {
let reader = self.drive.open_revision(&cover.uid).await?;
if reader.size() > FOLDER_COVER_MAX_BYTES {
return Ok(None);
}
reader.read_at(0, reader.size()).await.map(Some)
};
let bytes = match read.await {
Ok(Some(bytes)) => bytes,
Ok(None) => return ScaleAttempt::Undecodable,
Err(e) => {
warn!(cover = %cover.uid, error = %e, "folder cover download failed");
return ScaleAttempt::Unavailable;
}
};
let name = cover.name;
tokio::task::spawn_blocking(move || scale_thumbnail(&bytes, &name, &staging_dir))
.await
.unwrap_or(ScaleAttempt::Unavailable)
}
pub(crate) fn thumbnail_build_status(&self) -> ThumbnailBuildStatus {
self.photo_jobs.thumbnail_build.lock().clone()
}
/// Start one recursive local-thumbnail build. A request for the same root
/// may attach to it; a different root is rejected explicitly instead of
/// silently pretending the existing job belongs to the caller.
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();
if !thumbnail_build_may_start(&status, &path)? {
return Ok(status.clone());
}
self.photo_jobs
.thumbnail_build_cancelled
.store(false, Ordering::SeqCst);
*status = ThumbnailBuildStatus {
running: true,
scanning: true,
path: path.clone(),
folders_scanned: 0,
images_found: 0,
completed: 0,
failed: 0,
message: None,
};
status.clone()
};
let core = self.clone();
self.rt.spawn_blocking(move || {
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
core.run_thumbnail_build(root)
}))
.is_err()
{
let mut status = core.photo_jobs.thumbnail_build.lock();
status.running = false;
status.scanning = false;
status.message = Some("Thumbnail generation stopped unexpectedly".to_string());
core.photo_jobs
.thumbnail_build_cancelled
.store(false, Ordering::SeqCst);
warn!(path = %status.path, "recursive thumbnail build panicked");
}
});
Ok(status)
}
pub(crate) fn cancel_thumbnail_build(&self) -> ThumbnailBuildStatus {
let (status, cancelled) = {
let status = self.photo_jobs.thumbnail_build.lock();
let cancelled = status.running;
if cancelled {
self.photo_jobs
.thumbnail_build_cancelled
.store(true, Ordering::SeqCst);
}
(status.clone(), cancelled)
};
if cancelled {
self.photo_jobs.thumbnail_build_cancel.notify_waiters();
}
status
}
pub(crate) fn finish_thumbnail_build(&self) {
let mut status = self.photo_jobs.thumbnail_build.lock();
let cancelled = self
.photo_jobs
.thumbnail_build_cancelled
.swap(false, Ordering::SeqCst);
status.running = false;
status.scanning = false;
if cancelled {
status.message = Some("Thumbnail build cancelled".to_string());
}
info!(
path = %status.path,
images = status.images_found,
failed = status.failed,
cancelled,
"recursive thumbnail build finished"
);
}
pub(crate) fn run_thumbnail_build(&self, root: PathBuf) {
let mut folders = vec![root];
let mut images: Vec<(NodeUid, i64, String)> = Vec::new();
let mut seen_folders = HashSet::new();
let mut seen_images = HashSet::new();
while let Some(folder) = folders.pop() {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
self.finish_thumbnail_build();
return;
}
let listing = self.list_dir(&folder);
{
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.photo_jobs.thumbnail_build.lock();
if status.message.is_none() {
status.message = Some(format!(
"Some folders could not be read ({}: {error})",
folder.display()
));
}
continue;
}
};
let mut found_here = 0_u64;
let mut invalid_here = 0_u64;
for entry in entries {
if entry.is_dir {
if seen_folders.insert(entry.uid) {
folders.push(folder.join(entry.name));
}
} else if is_thumbnail_media_name(&entry.name, Some(entry.size)) {
match parse_uid(&entry.uid) {
Some(uid) if seen_images.insert(uid.clone()) => {
found_here += 1;
images.push((uid, entry.modified, entry.name));
}
Some(_) => {}
None => {
found_here += 1;
invalid_here += 1;
}
}
}
}
let mut status = self.photo_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.finish_thumbnail_build();
return;
}
let ttype = ThumbnailType::Thumbnail.as_i32();
let mut todo = Vec::new();
for (uid, modified, name) in images {
if self
.cache
.cached_thumbnail_path(&uid, ttype, modified)
.is_some()
{
self.photo_jobs.thumbnail_build.lock().completed += 1;
} else if self
.photo_jobs
.thumbnail_misses
.lock()
.local_contains(&(uid.clone(), ttype), modified)
{
let mut status = self.photo_jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
} else {
todo.push((uid, modified, name));
}
}
for chunk in todo.chunks(THUMB_BUILD_CHUNK) {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
self.finish_thumbnail_build();
return;
}
let mut claimed = Vec::with_capacity(chunk.len());
let mut tags = HashMap::with_capacity(chunk.len());
let mut names = HashMap::with_capacity(chunk.len());
for (uid, modified, name) in chunk {
// A visible tile may have started this image just before the
// toolbar action. Wait for that one bounded job to finish rather
// than downloading the full image twice.
let waiting_since = Instant::now();
loop {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
self.finish_thumbnail_build();
return;
}
if self
.cache
.cached_thumbnail_path(uid, ttype, *modified)
.is_some()
{
self.photo_jobs.thumbnail_build.lock().completed += 1;
break;
}
if self
.photo_jobs
.thumbnail_misses
.lock()
.local_contains(&(uid.clone(), ttype), *modified)
{
let mut status = self.photo_jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
break;
}
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.photo_jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
if status.message.is_none() {
status.message = Some(
"Some images stayed busy and were skipped after a timeout".into(),
);
}
break;
}
std::thread::sleep(Duration::from_millis(50));
}
}
if claimed.is_empty() {
continue;
}
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
self.generate_thumbs(&claimed, &tags, &names, ThumbJob::Build)
}));
{
let mut inflight = self.photo_jobs.thumb_gen.lock();
for uid in &claimed {
inflight.remove(uid);
}
}
let mut status = self.photo_jobs.thumbnail_build.lock();
match result {
Ok(summary) => {
status.completed += summary.processed();
status.failed += summary.failed();
}
Err(_) => {
status.completed += claimed.len() as u64;
status.failed += claimed.len() as u64;
status.message = Some("Some thumbnail workers stopped unexpectedly".into());
}
}
}
self.finish_thumbnail_build();
}
/// Persist what a thumbnail attempt learned about a photo, against the
/// timeline and against every album the photo sits in — one attempt, one
/// verdict, wherever the photo is painted.
pub(crate) fn record_thumb(&self, uid: &NodeUid, state: i64, ratio: Option<f64>) {
let key = uid.to_string();
if let Err(e) = self.db.photo_set_thumb(&key, state, ratio) {
warn!(%uid, error = %e, "recording thumbnail state failed");
}
if let Err(e) = self.db.album_photo_set_thumb(&key, state, ratio) {
warn!(%uid, error = %e, "recording album thumbnail state failed");
}
}
}
+637
View File
@@ -0,0 +1,637 @@
//! The photos timeline and what is built on it: favorites, duplicates and
//! similar shots, places, on this day, groups, and trashing photos.
use super::*;
impl Core {
#[allow(clippy::too_many_arguments)]
pub(crate) fn photos_timeline(
&self,
offset: usize,
limit: usize,
kind: Option<PhotoKind>,
range: Option<(i64, i64)>,
favorites: bool,
not_in_album: bool,
excluded: &str,
) -> CoreResult<Option<Vec<PhotoItem>>> {
let count = self.db.photos_count().map_err(CoreError::from)?;
let listed = self
.db
.state_i64(PHOTOS_SYNCED_MS)
.map_err(CoreError::from)?
.is_some();
if !listed {
if count == 0 {
if !self.refresh_timeline_joined()? {
return Ok(None);
}
} else {
self.spawn_timeline_refresh();
}
} else if self
.db
.state_i64(PHOTOS_AVAILABLE)
.map_err(CoreError::from)?
== Some(0)
{
return Ok(None);
}
// The filter is only as good as the album contents on disk, and those
// are fetched lazily, per album opened. Fill in the missing ones before
// the first page; later pages reuse what that fetch stored.
if not_in_album && offset == 0 {
self.ensure_album_contents()?;
}
let page = self
.db
.photos_page_visible(
offset,
limit,
kind,
range,
favorites,
not_in_album,
excluded,
)
.map_err(CoreError::from)?;
Ok(Some(page.into_iter().map(|p| self.photo_item(p)).collect()))
}
/// Project a persisted photo into the wire item the front-end paints: its
/// learned aspect ratio, its thumbnail verdict, and the on-disk path of its
/// thumbnail when one is cached (tagged with the capture time, which is the
/// only revision handle a photo carries).
pub(crate) fn photo_item(&self, photo: StoredPhoto) -> PhotoItem {
let thumb_path = parse_uid(&photo.uid).and_then(|uid| {
self.cache
.cached_thumbnail_path(&uid, ThumbnailType::Thumbnail.as_i32(), photo.capture_time)
.map(|p| p.display().to_string())
});
PhotoItem {
uid: photo.uid,
capture_time: photo.capture_time,
thumb_path,
name: photo.name,
ratio: photo.ratio,
no_thumb: photo.thumb_state == db::THUMB_NONE,
kind: photo.kind,
favorite: photo.favorite,
group_size: photo.group_size as u32,
has_raw: photo.has_raw,
place_id: photo.place_id,
}
}
/// Add or remove Proton's `Favorite` tag on a photo, then record the change
/// locally so the gallery reflects it without waiting for a timeline refresh.
///
/// 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 update = PhotoTagsUpdate {
node_uid: uid.clone(),
tags_to_add: if favorite {
vec![PhotoTag::Favorite]
} else {
Vec::new()
},
tags_to_remove: if favorite {
Vec::new()
} else {
vec![PhotoTag::Favorite]
},
};
let outcomes = self
.rt
.block_on(photos.update_photos(std::slice::from_ref(&update)))
.map_err(|e| CoreError::from_api(&e, "update photo tags"))?;
pdfs_core::batch::into_unit(outcomes)
.map_err(|e| CoreError::from_api(&e, "update photo tags"))?;
// The photo event feed replays this write back at us as a bare
// `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.db
.photos_set_favorite(&uid.to_string(), favorite)
.map_err(CoreError::from)?;
Ok(())
}
/// The timeline's duplicate sets, as wire items (see
/// [`db::Db::photo_duplicates`]).
pub(crate) fn photo_duplicates(&self) -> CoreResult<Vec<Vec<PhotoItem>>> {
let sets = self.db.photo_duplicates().map_err(CoreError::from)?;
Ok(sets
.into_iter()
.map(|set| set.into_iter().map(|p| self.photo_item(p)).collect())
.collect())
}
/// The sets of shots that look alike, as wire items (see
/// [`db::Db::photo_similar`]), how far hashing has got while it runs, and
/// how many shots couldn't be compared once it's done. Starts a hashing
/// pass for the shots not hashed yet unless one is running.
pub(crate) fn photo_similar(
&self,
) -> CoreResult<(Vec<Vec<PhotoItem>>, Option<MappingProgress>, usize)> {
self.spawn_similar_hashing();
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
.similar_hashing
.load(Ordering::SeqCst)
.then_some(MappingProgress { done, total });
let uncompared = if hashing.is_some() { 0 } else { total - done };
let sets = sets
.into_iter()
.map(|set| set.into_iter().map(|p| self.photo_item(p)).collect())
.collect();
Ok((sets, hashing, uncompared))
}
pub(crate) fn spawn_similar_hashing(&self) {
if self.photo_jobs.similar_hashing.swap(true, Ordering::SeqCst) {
return;
}
let core = self.clone();
let spawned = std::thread::Builder::new()
.name("pdfs-similar".into())
.spawn(move || {
if let Err(e) = core.hash_similar() {
warn!(error = %e, "similar-photo hashing failed");
}
core.photo_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);
}
}
/// Hash the look of every shot not hashed yet, a chunk at a time. Only
/// thumbnails the server has are used: a photo without one is skipped
/// rather than downloaded whole, and tried again on the next pass.
pub(crate) fn hash_similar(&self) -> CoreResult<()> {
let mut tried: HashSet<String> = HashSet::new();
loop {
if self.shutdown.is_stopping() {
return Ok(());
}
// Shots tried this pass without a thumbnail are still unhashed and
// come back first, so ask past them.
let chunk: Vec<NodeUid> = self
.db
.photos_unhashed(tried.len() + SIMILAR_CHUNK)
.map_err(CoreError::from)?
.into_iter()
.filter(|photo| tried.insert(photo.uid.clone()))
.take(SIMILAR_CHUNK)
.filter_map(|photo| parse_uid(&photo.uid))
.collect();
if chunk.is_empty() {
return Ok(());
}
let paths: Vec<(String, PathBuf)> = self
.photo_thumbs_with(&chunk, false)
.into_iter()
.filter_map(|thumb| Some((thumb.uid, PathBuf::from(thumb.path?))))
.collect();
for (uid, hash) in similar_hashes(paths) {
self.db
.photo_set_similar_hash(&uid, hash)
.map_err(CoreError::from)?;
}
}
}
/// The towns the photos were taken in, as wire items. A town the bundled
/// table no longer knows (the stored id came from an older table) is left
/// out rather than shown without a name.
pub(crate) fn photo_places(&self, excluded: &str) -> CoreResult<Vec<PlaceInfo>> {
let places = self
.db
.photo_places_visible(excluded)
.map_err(CoreError::from)?;
Ok(places
.into_iter()
.filter_map(|place| {
let city = pdfs_core::places::city(place.id)?;
Some(PlaceInfo {
id: place.id,
name: city.name.to_string(),
country: city.country.to_string(),
latitude: city.latitude,
longitude: city.longitude,
photo_count: place.count,
cover: self.photo_item(place.cover),
})
})
.collect())
}
/// A page of the photos taken in town `id`, as wire items.
pub(crate) fn place_photos(
&self,
id: u32,
offset: usize,
limit: usize,
excluded: &str,
) -> CoreResult<Vec<PhotoItem>> {
let photos = self
.db
.photos_at_place_visible(id, offset, limit, excluded)
.map_err(CoreError::from)?;
Ok(photos.into_iter().map(|p| self.photo_item(p)).collect())
}
/// Every photo taken in town `id` with its own location, as wire items.
pub(crate) fn place_locations(&self, id: u32) -> CoreResult<Vec<PhotoLocation>> {
let photos = self
.db
.photo_locations_at_place(id)
.map_err(CoreError::from)?;
Ok(photos
.into_iter()
.map(|(photo, (latitude, longitude))| PhotoLocation {
photo: self.photo_item(photo),
latitude,
longitude,
})
.collect())
}
/// Photos taken on today's date in earlier years, as wire items. Served
/// from the stored timeline only: the strip is a nicety, not worth a wait
/// on the network, and the timeline's own load keeps that store fresh.
pub(crate) fn photos_on_this_day(
&self,
limit: usize,
excluded: &str,
) -> CoreResult<Vec<PhotoItem>> {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs() as i64);
let photos = self
.db
.photos_on_this_day_visible(now, limit, excluded)
.map_err(CoreError::from)?;
Ok(photos.into_iter().map(|p| self.photo_item(p)).collect())
}
/// Every file of one photo's group, in server order, as wire items. A photo
/// the timeline does not hold comes back empty, which the lightbox reads as
/// "nothing to switch between".
pub(crate) fn photo_group(&self, uid: &str) -> CoreResult<Vec<PhotoItem>> {
let members = self.db.photos_group(uid).map_err(CoreError::from)?;
Ok(members
.into_iter()
.map(|photo| self.photo_item(photo))
.collect())
}
/// Every uid asked for, plus the other files of any group they belong to,
/// each once. A uid the timeline does not hold (an album photo on someone
/// else's volume) is passed through unchanged.
pub(crate) fn expand_photo_groups(&self, uids: &[NodeUid]) -> Vec<NodeUid> {
let mut out: Vec<NodeUid> = Vec::with_capacity(uids.len());
let mut seen: HashSet<String> = HashSet::new();
for uid in uids {
let members = self.db.photos_group(&uid.to_string()).unwrap_or_default();
let mut group: Vec<NodeUid> = members
.iter()
.filter_map(|photo| parse_uid(&photo.uid))
.collect();
if group.is_empty() {
group.push(uid.clone());
}
for member in group {
if seen.insert(member.to_string()) {
out.push(member);
}
}
}
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> {
let started = Instant::now();
let generation = self
.db
.photo_projection_generation()
.map_err(CoreError::from)?;
let photos = self.photos();
if self
.db
.state_i64(PHOTOS_SYNCED_MS)
.map_err(CoreError::from)?
.is_none()
{
let available = link::bounded(photos.get_photos_root())
.await
.map_err(|e| CoreError::from_api(&e, "photos root"))?
.is_some();
let items = if available {
link::bounded_by(crate::BATCH_CALL_TIMEOUT, photos.enumerate_timeline())
.await
.map_err(|e| CoreError::from_api(&e, "timeline"))?
.into_iter()
.map(|item| db::TimelineRow::new(item.uid.to_string(), item.capture_time))
.collect()
} else {
Vec::new()
};
if !self
.db
.photos_replace_at(&items, generation, available, now_ms())
.map_err(CoreError::from)?
{
return Err(CoreError::remote(
"Photos changed during the refresh. Try again shortly.",
));
}
if !available {
return Ok(false);
}
} else if self
.db
.state_i64(PHOTOS_AVAILABLE)
.map_err(CoreError::from)?
== Some(0)
{
return Ok(false);
}
let pending = self.db.photos_pending().map_err(CoreError::from)?;
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);
for (index, chunk) in pending.chunks(TIMELINE_ENRICH_CHUNK).enumerate() {
if self.shutdown.is_stopping() {
break;
}
*progress.0.lock() = Some((skipped + index * TIMELINE_ENRICH_CHUNK, total));
let uids: Vec<_> = chunk.iter().filter_map(|uid| parse_uid(uid)).collect();
let nodes = link::bounded(photos.enumerate_nodes(&uids))
.await
.map_err(|e| CoreError::from_api(&e, "read photo metadata"))?;
let rows: Vec<_> = nodes
.into_iter()
.filter_map(|node| {
let NodeKind::File { media_type, .. } = node.kind else {
return None;
};
if node.trashed {
return None;
}
let photo = node.photo.as_ref();
Some(db::TimelineRow {
name: Some(node.name),
media_type: Some(media_type),
favorite: Some(photo.is_some_and(|p| p.tags.contains(&PhotoTag::Favorite))),
content_hash: photo.and_then(|p| p.content_hash.clone()),
location: photo
.and_then(|p| p.location)
.map(|l| (l.latitude, l.longitude)),
main_uid: photo
.and_then(|p| p.main_photo_uid.as_ref())
.map(ToString::to_string),
resolved_at: Some(now_ms()),
..db::TimelineRow::new(node.uid.to_string(), 0)
})
})
.collect();
if !self
.db
.photos_resolve_at(generation, &rows)
.map_err(CoreError::from)?
{
return Err(CoreError::remote(
"Photos changed during the refresh. Try again shortly.",
));
}
resolved += rows.len();
}
info!(
photos = total,
resolved,
wanted = pending.len(),
skipped,
elapsed_ms = started.elapsed().as_millis() as u64,
"photos timeline refreshed"
);
Ok(true)
}
/// Refresh the timeline off the request path, so a stale page is still served
/// at DB speed. At most one refresh runs at a time.
/// Refresh the timeline and wait for it, sharing a refresh already under
/// way instead of starting a second one beside it.
///
/// The first request after an empty cache has nothing to serve until the
/// fetch lands, so it waits. Two such requests (the gallery and its retry,
/// or a background refresh started by an import) used to each fetch the
/// 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)
&& !self.shutdown.is_stopping()
{
std::thread::sleep(std::time::Duration::from_millis(200));
}
// A refresh that landed stamped the timeline fresh. One that failed
// did not, and the caller gets this refresh's own error instead of
// an empty timeline.
if self
.db
.state_i64(PHOTOS_SYNCED_MS)
.map_err(CoreError::from)?
.is_some()
|| 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.photo_jobs
.timeline_refreshing
.store(false, Ordering::SeqCst);
if refreshed.is_ok() {
self.events.publish(&[Topic::Photos]);
}
refreshed
}
pub(crate) fn spawn_timeline_refresh(&self) {
if self
.photo_jobs
.timeline_refreshing
.swap(true, Ordering::SeqCst)
{
return;
}
let core = self.clone();
self.rt.spawn(async move {
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(_) => core.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background timeline refresh failed"),
}
});
}
/// 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
.timeline_progress
.lock()
.map(|(done, total)| MappingProgress { done, total })
}
/// 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)
}
/// 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 node = self
.rt
.block_on(photos.get_node(uid))
.map_err(|e| CoreError::from_api(&e, "photo node"))?
.ok_or_else(|| CoreError::not_found("photo not found"))?;
let (mtime, size) = (node.modification_time, node_size(&node));
if let Some(p) = self.cache.cached_content_path(uid, mtime, size) {
return Ok(p);
}
let bytes = self
.download_photo_tracked(&photos, uid, &node.name, size)
.map_err(|e| CoreError::from_api(&e, "download photo"))?;
self.cache
.store(uid, mtime, size, &bytes)
.map_err(|e| CoreError::internal(format!("cache store: {e}")))?;
Ok(self.cache.content_path(uid))
}
}
+240
View File
@@ -0,0 +1,240 @@
//! Pinning: keeping a file or a folder's files on this computer, and the
//! requests that list and undo pins. The keeper (`keeper.rs`) keeps them.
use super::*;
impl Core {
/// Pin the node at mountpoint-relative `rel`. A file downloads its full
/// plaintext into the content cache before this returns. A folder records a
/// recursive pin and downloads every descendant file on a background thread,
/// reported as a job: a big folder far outlasts the socket read timeout.
/// Returns a human message.
///
/// `recorded` is the path the pin registry keeps for the front ends to
/// open the pin by: `rel` itself on the primary mount, which they join to
/// the mountpoint, and the absolute local path on an on-demand folder's
/// mount, whose node is not reachable under the primary mountpoint at all.
pub(super) fn pin(&self, rel: &Path, recorded: &Path) -> CoreResult<String> {
let (ino, uid) = self.resolve(rel)?;
let (name, is_folder, mtime, size) = {
let st = self.state();
let e = st
.entries
.get(&ino)
.ok_or_else(|| CoreError::not_found("node vanished"))?;
(
e.node.name.clone(),
e.node.is_folder(),
e.node.modification_time,
node_size(&e.node),
)
};
if is_folder {
// Offline, every download would fail and the folder would only look
// kept. Refuse instead, as a file pin does.
if !self.is_online() {
return Err(CoreError::offline());
}
// Record the recursive pin first so every descendant is eviction-
// exempt before we start filling the cache with the subtree.
self.cache
.add_pin(&uid, recorded, true)
.map_err(|e| CoreError::from_api(&e, "pin"))?;
let core = self.clone();
let folder = name.clone();
std::thread::Builder::new()
.name("pin-folder".into())
.spawn(move || core.pin_subtree(ino, &uid, &folder))
.map_err(|e| CoreError::internal(format!("spawn pin: {e}")))?;
return Ok(format!("{name}: downloading its files in the background"));
}
// Stored under a provisional size, the copy would never match the
// plaintext it holds (`docs/BUGS.md` B282).
let size = match self.kept_file(ino) {
Some(file) if file.uid == uid => file.size,
_ => size,
};
self.fetch_content(&uid, &name, mtime, size)?;
self.cache
.add_pin(&uid, recorded, false)
.map_err(|e| CoreError::from_api(&e, "pin"))?;
Ok(name)
}
/// Download and cache every file in the subtree rooted at the pinned folder
/// `ino` (`folder`, named `name`), as a job the front ends show. Walks the
/// tree depth-first, enumerating each folder so a cold subtree is fully
/// discovered; the lock is dropped before each network download. Stops when
/// the folder is unpinned or the daemon stops.
pub(super) fn pin_subtree(&self, ino: u64, folder: &NodeUid, name: &str) {
let job = self
.transfers
.begin_job(format!("Making {name} available offline"));
match self.pin_subtree_files(ino) {
Ok(files) => {
job.set_total(files.len() as u64);
let mut failed = 0usize;
for ino in files {
if self.shutdown.is_stopping() || !self.cache.is_pinned(folder) {
return;
}
// A file with a queued write, or no readable size, is
// left to the drain and the keeper (`keeper::kept_file`).
if let Some(file) = self.kept_file(ino) {
job.detail(file.name.clone());
if let Err(e) =
self.fetch_pinned(&file.uid, &file.name, file.mtime, file.size)
{
warn!(uid = %file.uid, error = %e, "pin folder: download failed");
failed += 1;
}
}
job.step();
}
info!(folder = %name, failed, "pin folder: done");
}
Err(e) => warn!(folder = %name, error = %e, "pin folder: enumerate failed"),
}
}
/// Cache the file `uid` for a folder pin. Its `mtime` and `size` were read
/// before the download, and a create landing or a remote edit can change
/// them while it runs. The blob is then stored under the old ones and reads
/// as stale, so the file is listed as kept but not available offline. Fetch
/// it again under the new ones, a few times at most.
pub(super) fn fetch_pinned(
&self,
uid: &NodeUid,
name: &str,
mtime: i64,
size: u64,
) -> CoreResult<()> {
let mut fetched = (mtime, size);
for _ in 0..3 {
self.fetch_content(uid, name, fetched.0, fetched.1)?;
let current = {
let st = self.state();
st.by_uid
.get(uid)
.and_then(|ino| st.entries.get(ino))
.map(|e| (e.node.modification_time, node_size(&e.node)))
};
match current {
Some(now) if now != fetched => fetched = now,
_ => break,
}
}
Ok(())
}
/// The inode of every file in the subtree rooted at folder `ino`.
pub(super) fn pin_subtree_files(&self, ino: u64) -> CoreResult<Vec<u64>> {
let mut files: Vec<u64> = Vec::new();
let mut stack = vec![ino];
while let Some(dir) = stack.pop() {
if self.shutdown.is_stopping() {
break;
}
self.ensure_children(dir)
.map_err(|e| self.errno_error(e, "enumerate"))?;
let st = self.state();
if let Some(kids) = st.children.get(&dir) {
for &k in kids {
if let Some(e) = st.entries.get(&k) {
if e.node.is_folder() {
stack.push(k);
} else {
files.push(k);
}
}
}
}
}
Ok(files)
}
/// Unpin the node at `rel`, evicting its cached content. For a folder, also
/// evicts every descendant's cached blob (the subtree is no longer kept).
/// A node kept only because a folder above it is pinned is refused: there
/// is no pin of its own to remove, and it would stay kept all the same.
pub(super) fn unpin(&self, rel: &Path) -> CoreResult<String> {
let (ino, uid) = self.resolve(rel)?;
let (name, is_folder) = {
let st = self.state();
st.entries
.get(&ino)
.map(|e| (e.node.name.clone(), e.node.is_folder()))
.unwrap_or_default()
};
if self.pinned_by_folder(ino) {
return Err(CoreError::conflict(format!(
"{name} is kept offline because a folder above it is; unpin that folder instead"
)));
}
self.cache
.remove_pin(&uid)
.map_err(|e| CoreError::from_api(&e, "unpin"))?;
// A recursively-pinned folder's descendants were eviction-exempt; now
// that the pin is gone, reclaim their blobs eagerly instead of waiting
// for budget pressure. Descendants come from the DB node tree. One
// pinned on its own, or under a pinned subfolder, is still kept.
if is_folder && let Ok(uids) = self.db.descendants(&uid.to_string()) {
let still_pinned = self.pinned_set();
for s in uids {
if still_pinned.contains(&s) {
continue;
}
if let Some(u) = parse_uid(&s) {
self.cache.evict(&u);
self.evict_reader(&u);
}
}
}
Ok(name)
}
/// Whether the node at `ino` is kept offline because a folder above it is
/// pinned, whether or not it is also pinned on its own.
pub(super) fn pinned_by_folder(&self, ino: u64) -> bool {
let parent = {
let st = self.state();
st.entries
.get(&ino)
.filter(|e| e.parent != ino)
.and_then(|e| st.entries.get(&e.parent))
.map(|p| p.uid.clone())
};
parent.is_some_and(|uid| self.cache.is_pinned(&uid))
}
/// Every uid that is pinned right now, as one set.
///
/// `cache.is_pinned` is a direct lookup plus an ancestor walk; asking it per
/// candidate was a thousand walks per keystroke. The recursive expansion is
/// the same query, run once.
pub(super) fn pinned_set(&self) -> HashSet<String> {
self.db
.pinned_uids()
.unwrap_or_default()
.into_iter()
.collect()
}
/// Full-text search node names against the local SQLite index, mapping each
/// DB hit to the wire [`SearchHit`] (resolving live pin state from the cache,
/// which the DB doesn't track). Pure local lookup — never hits the network.
/// Every pin, with `cached` saying whether a pinned file's content is on
/// disk, so a front-end listing pins can badge them without a round-trip
/// per file.
pub(super) fn list_pins(&self) -> Vec<pdfs_core::control::Pin> {
let mut pins = self.cache.list_pins();
for pin in pins.iter_mut().filter(|pin| pin.is_dir == Some(false)) {
if let Ok(Some(node)) = self.db.node_by_uid(&pin.uid) {
pin.cached =
self.cache
.is_cached(&node.uid, node.modification_time, node_size(&node));
}
}
pins
}
}
+54 -16
View File
@@ -141,19 +141,11 @@ impl Core {
/// Snapshot the local arrangement into a [`Profile`].
fn build_profile(&self, device_uid: &str, machine_id: &str) -> CoreResult<Profile> {
let folders = self
.db
.sync_folder_list()
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?
.into_iter()
.map(|f| ProfileFolder {
remote_uid: f.remote_uid,
local_path: f.local_path,
// A queued switch is where the user asked the folder to be, so
// that is what the next machine should set up.
mode: MountMode::from(f.pending_mode.unwrap_or(f.mode).as_str()),
})
.collect();
let folders = profile_folders(
self.db
.sync_folder_list()
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?,
);
let pins = self
.db
.pin_list()
@@ -389,6 +381,7 @@ impl Core {
items: &[pdfs_core::control::RestoreItem],
device: Option<&str>,
) -> CoreResult<RestoreOutcome> {
let _registration = super::devices::SYNC_ROOT_REGISTRATION.lock();
if items.is_empty() {
return Err(CoreError::invalid("nothing to restore"));
}
@@ -398,6 +391,11 @@ impl Core {
.sync_folder_list()
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
// A caller must not smuggle a My files root into a device mapping,
// where destructive device-only operations would otherwise be allowed.
let device_root = super::parse_uid(&device.root_uid)
.ok_or_else(|| CoreError::internal("invalid device root"))?;
let children = self.device_root_nodes(&device_root)?;
let reserved = crate::devices::sync_root_reserved();
let mut roots: Vec<PathBuf> = existing
.iter()
@@ -406,6 +404,18 @@ impl Core {
let mut restored = 0usize;
let mut skipped: Vec<String> = Vec::new();
for item in items {
if !children.iter().any(|node| {
node.uid.to_string() == item.remote_uid
&& node.is_folder()
&& !node.trashed
&& node.name != PROFILE_DIR_NAME
}) {
skipped.push(format!(
"{}: not a folder under this device",
item.local_path
));
continue;
}
// The path is proposed from the profile another machine wrote, and
// may hold a folder name from Drive: checked like any new root.
let local = match pdfs_core::syncroot::resolve(Path::new(&item.local_path)) {
@@ -443,7 +453,7 @@ impl Core {
Err(e) => {
// The folders restored before this one still need their
// watches.
let _ = self.sync_tx.send(sync::SyncMsg::Rewatch);
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
return Err(CoreError::internal(format!("db: {e:?}")));
}
};
@@ -453,11 +463,11 @@ impl Core {
if mode == MountMode::OnDemand {
let _ = self.request_sync_folder_mode(id, "ondemand");
}
let _ = self.sync_tx.send(sync::SyncMsg::Reconcile(id));
let _ = self.sync.tx.send(sync::SyncMsg::Reconcile(id));
roots.push(local);
restored += 1;
}
let _ = self.sync_tx.send(sync::SyncMsg::Rewatch);
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
// The reply is gone once the app has shown it; the log keeps why.
for reason in &skipped {
@@ -468,6 +478,19 @@ impl Core {
}
}
/// Only device backups belong in the device's cross-machine profile.
fn profile_folders(folders: Vec<pdfs_store::db::StoredSyncFolder>) -> Vec<ProfileFolder> {
folders
.into_iter()
.filter(|f| f.kind == "device")
.map(|f| ProfileFolder {
remote_uid: f.remote_uid,
local_path: f.local_path,
mode: MountMode::from(f.pending_mode.unwrap_or(f.mode).as_str()),
})
.collect()
}
/// What a restore did: how many folders it attached, and why it left out the
/// others.
pub(crate) struct RestoreOutcome {
@@ -530,6 +553,21 @@ fn default_local_path(name: &str) -> PathBuf {
mod tests {
use super::*;
#[test]
fn attached_my_files_folders_are_not_in_the_device_profile() {
let dir = crate::sim::daemon::scratch("profile-folder-kinds");
let db = pdfs_store::db::Db::open(&dir.join("cache.db")).unwrap();
db.sync_folder_add("/backup", "vol~backup", "device-share")
.unwrap();
db.sync_folder_attach("/work", "vol~work", "my-files-share")
.unwrap();
let folders = profile_folders(db.sync_folder_list().unwrap());
assert_eq!(folders.len(), 1);
assert_eq!(folders[0].remote_uid, "vol~backup");
drop(db);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn foreign_home_is_not_reused() {
assert!(!path_is_usable_here(Path::new(
+1 -1
View File
@@ -11,7 +11,7 @@ use super::*;
use std::io::Write;
use pdfs_core::control::{PendingOpInfo, SyncIssue};
use pdfs_core::db::{FAILING_ATTEMPTS, PARK_UNTIL};
use pdfs_store::db::{FAILING_ATTEMPTS, PARK_UNTIL};
impl Core {
/// Every queued op, oldest first, with a path a person can read.
+69 -90
View File
@@ -127,6 +127,49 @@ static NEXT_OPEN_ID: AtomicU64 = AtomicU64::new(0);
/// re-planned read misses rather than being served the wrong bytes.
type RingKey = (NodeUid, BlockSpan);
/// What the read path keeps between reads, shared by every mount of the
/// daemon: open revision readers, decrypted blocks, block fetches in flight,
/// whole-file repairs, and the prefetch detector with its permits.
#[derive(Clone)]
pub(crate) struct ReadState {
/// Open [`RevisionReader`]s keyed by node, so the block fetches of a file
/// resolve its keys and block table once instead of once per block.
/// Validated by `(mtime, size)` exactly like the content cache, and bounded
/// by [`MAX_OPEN_READERS`].
pub(crate) readers: Arc<Mutex<HashMap<NodeUid, ReaderSlot>>>,
/// Decrypted blocks held in memory, so the ~32 kernel reads a 4 MiB block is
/// delivered in cost the block once — a download for a streaming file, a
/// disk read for a cached one. See [`BlockRing`].
pub(crate) block_ring: Arc<Mutex<BlockRing>>,
/// Block fetches in flight, so concurrent readers of one block (demand read,
/// kernel read-ahead, our own prefetch) share a single download and decrypt.
/// See [`BlockFlight`].
pub(crate) block_flight: Arc<BlockFlight>,
/// One lock per file being repaired by [`Core::repair_block`], so the
/// concurrent block reads that all discover the same untrustworthy block
/// table share a single whole-file download instead of one each.
pub(crate) content_repairs:
Arc<tokio::sync::Mutex<HashMap<NodeUid, Arc<tokio::sync::Mutex<()>>>>>,
/// Per-file sequential-read detection driving [`Core::prefetch`].
pub(crate) prefetch: Arc<Prefetch>,
/// Permits bounding speculative block fetches, so prefetch cannot queue in
/// front of a read someone is waiting on.
pub(crate) prefetch_budget: Arc<tokio::sync::Semaphore>,
}
impl ReadState {
pub(crate) fn new() -> Self {
Self {
readers: Arc::new(Mutex::new(HashMap::new())),
block_ring: Arc::new(Mutex::new(BlockRing::default())),
block_flight: Arc::new(BlockFlight::default()),
content_repairs: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
prefetch: Arc::new(Prefetch::default()),
prefetch_budget: Arc::new(tokio::sync::Semaphore::new(PREFETCH_BUDGET)),
}
}
}
#[derive(Default)]
pub(super) struct BlockRing {
blocks: HashMap<RingKey, Arc<Vec<u8>>>,
@@ -212,15 +255,12 @@ impl BlockRing {
}
/// The result of fetching one block, shared between everyone who wanted it.
type BlockResult = Result<Arc<Vec<u8>>, Errno>;
pub(super) type BlockResult = Result<Arc<Vec<u8>>, Errno>;
/// Identifies a block *of a revision*: node, validity tag, and the plaintext
/// range the block covers — see [`RingKey`] for why it is the range and not the
/// index.
type BlockKey = (NodeUid, i64, u64, BlockSpan);
/// A claim on a block key: who owns the fetch, and where its result is published.
type Claim = (u64, tokio::sync::watch::Receiver<Option<BlockResult>>);
pub(super) type BlockKey = (NodeUid, i64, u64, BlockSpan);
/// Block fetches in flight, so a block is downloaded and decrypted once however
/// many readers want it at that moment (audit T1).
@@ -231,34 +271,7 @@ type Claim = (u64, tokio::sync::watch::Receiver<Option<BlockResult>>);
/// for. Without this each of them pays the full round-trip and decrypt and all
/// but one result is discarded — roughly double the bandwidth and CPU in steady
/// state. Same shape as [`ReaderSlot::Pending`] one level up.
#[derive(Default)]
pub(super) struct BlockFlight {
inflight: Mutex<HashMap<BlockKey, Claim>>,
}
/// Distinguishes attempts at the same key, so a leader only retires its own.
static NEXT_FLIGHT_ID: AtomicU64 = AtomicU64::new(0);
/// The leader's claim on a key. Retires it on drop — including when the task is
/// cancelled mid-fetch, which is what keeps a dropped `JoinSet` from leaving a
/// key nobody will ever publish.
struct Flight {
flight: Arc<BlockFlight>,
key: BlockKey,
id: u64,
}
impl Drop for Flight {
fn drop(&mut self) {
let mut inflight = self.flight.inflight.lock();
if inflight
.get(&self.key)
.is_some_and(|(id, _)| *id == self.id)
{
inflight.remove(&self.key);
}
}
}
pub(super) type BlockFlight = proton_media_rs::SingleFlight<BlockKey, BlockResult>;
/// Where each file's reader is expected to read next, so sequential reads can be
/// told from random ones and only the former prefetched (audit T2).
@@ -326,7 +339,7 @@ impl Core {
),
}
let act = {
let mut readers = self.readers.lock();
let mut readers = self.reads.readers.lock();
match readers.get_mut(uid) {
Some(ReaderSlot::Ready(entry))
if entry.mtime == mtime && entry.size == fsize =>
@@ -385,7 +398,7 @@ impl Core {
}
};
{
let mut readers = self.readers.lock();
let mut readers = self.reads.readers.lock();
// Publish only into the slot we claimed. If it is gone
// or belongs to a later attempt, an eviction or a newer
// revision overtook us: our reader still answers the
@@ -451,11 +464,11 @@ impl Core {
/// to cache what it opened, which is what we want — the eviction says that
/// revision is no longer the truth.
pub(super) fn evict_reader(&self, uid: &NodeUid) {
self.readers.lock().remove(uid);
self.reads.readers.lock().remove(uid);
// The ring holds decrypted bytes of the same revision, and an eviction is
// exactly the statement that those are no longer the file's content.
self.block_ring.lock().drop_node(uid);
self.prefetch.streams.lock().remove(uid);
self.reads.block_ring.lock().drop_node(uid);
self.reads.prefetch.streams.lock().remove(uid);
}
/// How this revision's plaintext is divided into content blocks.
@@ -581,49 +594,12 @@ impl Core {
cache_blocks: bool,
) -> BlockResult {
let key: BlockKey = (uid.clone(), mtime, fsize, span);
let claim = {
let mut inflight = self.block_flight.inflight.lock();
match inflight.get(&key) {
Some((_, rx)) => Err(rx.clone()),
None => {
let id = NEXT_FLIGHT_ID.fetch_add(1, Ordering::Relaxed);
let (tx, rx) = tokio::sync::watch::channel(None);
inflight.insert(key.clone(), (id, rx));
Ok((
tx,
Flight {
flight: self.block_flight.clone(),
key: key.clone(),
id,
},
))
}
}
};
let (tx, flight) = match claim {
Ok(lead) => lead,
Err(mut rx) => {
loop {
if let Some(result) = rx.borrow_and_update().clone() {
return result;
}
if rx.changed().await.is_err() {
break;
}
}
return self
.read_block(reader, uid, mtime, fsize, span, cache_blocks)
.await;
}
};
let result = self
.read_block(reader, uid, mtime, fsize, span, cache_blocks)
.await;
// Retire the claim before publishing, so a racer that wakes and re-enters
// finds no stale entry to join.
drop(flight);
let _ = tx.send(Some(result.clone()));
result
self.reads
.block_flight
.join(key, || {
self.read_block(reader, uid, mtime, fsize, span, cache_blocks)
})
.await
}
/// Download and decrypt one block, then put it where the next reader will
@@ -693,7 +669,8 @@ impl Core {
let _ = cache.store_block(&uid, mtime, fsize, span, &bytes);
});
}
self.block_ring
self.reads
.block_ring
.lock()
.insert(uid, mtime, fsize, span, bytes.clone());
Ok(bytes)
@@ -733,7 +710,7 @@ impl Core {
// One download per file, not per block: every block of a file with a bad
// block table discovers the same problem at once.
let lock = {
let mut locks = self.content_repairs.lock().await;
let mut locks = self.reads.content_repairs.lock().await;
locks.entry(uid.clone()).or_default().clone()
};
let guard = lock.clone().lock_owned().await;
@@ -814,7 +791,7 @@ impl Core {
/// Drop a repair lock's map entry once nobody else holds it, so a file
/// repaired long ago does not keep a mutex alive forever.
async fn release_repair_lock(&self, uid: &NodeUid, lock: Arc<tokio::sync::Mutex<()>>) {
let mut locks = self.content_repairs.lock().await;
let mut locks = self.reads.content_repairs.lock().await;
// Two: the map's and ours. Anything more means a waiter still needs it.
if Arc::strong_count(&lock) <= 2 {
locks.remove(uid);
@@ -843,7 +820,7 @@ impl Core {
last: u64,
cache_blocks: bool,
) {
let depth = self.prefetch.window(uid, first, last);
let depth = self.reads.prefetch.window(uid, first, last);
if depth == 0 {
return;
}
@@ -855,7 +832,8 @@ impl Core {
// Blocks already in memory need nothing; blocks already on disk
// are cheap enough to serve that spending a round-trip to move
// them into the ring would be the wrong trade.
self.block_ring
self.reads
.block_ring
.lock()
.get(uid, mtime, fsize, span)
.is_none()
@@ -877,7 +855,7 @@ impl Core {
// finishes.
let mut set = tokio::task::JoinSet::new();
for span in wanted {
let Ok(permit) = core.prefetch_budget.clone().try_acquire_owned() else {
let Ok(permit) = core.reads.prefetch_budget.clone().try_acquire_owned() else {
break; // the budget is spent; the demand path can have it
};
let (core, reader, uid) = (core.clone(), reader.clone(), uid.clone());
@@ -938,7 +916,7 @@ impl Core {
// no other cache at all, and a cached one would otherwise pay two
// opens, a JSON parse and a 4 MiB read+alloc for every 128 KiB the
// kernel asks for (audit T3).
let hit = self.block_ring.lock().get(uid, mtime, fsize, span);
let hit = self.reads.block_ring.lock().get(uid, mtime, fsize, span);
let hit = hit.or_else(|| {
if !cache_blocks {
return None;
@@ -946,7 +924,8 @@ impl Core {
let bytes = Arc::new(self.cache.cached_block(uid, mtime, fsize, span)?);
// Promote it, so the other ~31 reads of this block are answered
// from memory.
self.block_ring
self.reads
.block_ring
.lock()
.insert(uid, mtime, fsize, span, bytes.clone());
Some(bytes)
@@ -1220,7 +1199,7 @@ impl Core {
}
let mut out = Vec::with_capacity((end - offset) as usize);
for span in self.block_geometry(uid, mtime, fsize).spans(offset, end) {
let ring = self.block_ring.lock().get(uid, mtime, fsize, span);
let ring = self.reads.block_ring.lock().get(uid, mtime, fsize, span);
let block = match ring {
Some(bytes) => bytes,
None => Arc::new(self.cache.cached_block(uid, mtime, fsize, span)?),
+390
View File
@@ -0,0 +1,390 @@
//! Startup: rebuilding the tree and the queue from the database, and
//! recovering writes that were fsynced but not queued when the daemon stopped.
use super::*;
impl Core {
/// Rehydrate the in-memory `State` maps from the DB on mount, so a cold
/// start serves previously-seen metadata (stable inodes, instant listings)
/// without re-hitting the API. The root inode is already installed by
/// [`ProtonFs::new`]; this fills in every other persisted node and rebuilds
/// the child listings of folders the DB records as fully enumerated.
pub(super) fn hydrate(&self) {
let stored = match self.db.load_all() {
Ok(s) => s,
Err(e) => {
warn!(error = %e, "db load_all failed; mounting cold");
return;
}
};
if stored.is_empty() {
return;
}
// A write queued by a previous run carries the optimistic size the file
// grew to, which the sealed remote revision does not yet reflect. The DB
// node still holds the pre-write `claimed_size` (often 0 for a fresh
// file), so without this a queued 500 MB file `stat`s as 0 bytes until
// the drain lands — reads still serve from the staged blob, but `ls`
// 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()
};
// `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 mut st = self.state();
// Pass 1: give every uid its inode from its local id (the root is
// already mapped).
for sn in &stored {
if hidden.contains(&sn.node.uid) || st.by_uid.contains_key(&sn.node.uid) {
continue;
}
st.by_uid
.insert(sn.node.uid.clone(), state::lid_ino(sn.lid));
}
// Pass 2: materialize entries, resolving each parent's inode by uid.
// Track folders flagged complete so their listings rebuild in pass 3.
let mut listed_dirs: Vec<u64> = Vec::new();
for sn in stored {
let StoredNode {
mut node, listed, ..
} = sn;
if hidden.contains(&node.uid) {
continue;
}
let Some(&ino) = st.by_uid.get(&node.uid) else {
continue;
};
// Re-apply a queued write's optimistic size so `stat` matches what
// reads (served from the staged blob) already return.
if let Some(&len) = pending_sizes.get(&node.uid)
&& let NodeKind::File { claimed_size, .. } = &mut node.kind
{
*claimed_size = Some(len as i64);
}
if listed && node.is_folder() {
listed_dirs.push(ino);
}
// A root entry is owned by `ProtonFs::new`; don't overwrite it.
if st.roots.contains(&ino) {
continue;
}
// A node whose parent row never made it to disk must not be adopted
// by the root: it would surface as a phantom top-level entry.
let parent = node
.parent_uid
.as_ref()
.and_then(|p| st.by_uid.get(p).copied())
.unwrap_or(ORPHAN_INO);
let uid = node.uid.clone();
st.entries.insert(
ino,
Entry {
uid,
parent,
node,
access: pdfs_core::Access::Unknown,
lookup_count: 1,
open_count: 0,
unlinked: false,
},
);
}
st.hydrate_access();
// Pass 3: rebuild child listings for fully-enumerated folders.
let listings = listed_children(&st.entries, listed_dirs);
st.children.extend(listings);
info!(nodes = st.entries.len(), "hydrated metadata cache from db");
}
/// Rebuild the in-memory pending map from the `pending_op` table on mount.
///
/// A queued write survives a restart — that is the point of persisting it —
/// so until the drain worker gets to it, reads of that file must still come
/// from its staged blob rather than the remote's older revision.
///
/// A row whose blob has gone missing is dropped: there is nothing left to
/// upload, and keeping it would fail forever.
pub(super) fn hydrate_pending(&self) {
let ops = match self.db.pending_ops() {
Ok(ops) => ops,
Err(e) => {
error!(error = %e, "loading pending uploads failed");
return;
}
};
let mut map = self.pending.lock();
let mut restored = 0usize;
for op in ops {
let Some(uid) = parse_node_uid(&op.uid) else {
error!(uid = %op.uid, id = op.id, "pending op has an unparseable uid; dropping");
let _ = self.db.delete_op(op.id);
continue;
};
if op.kind == OP_TRASH {
self.hidden.lock().insert(uid.clone());
}
restored += 1;
// Only a revision must have a blob. A create carries none until
// something is written to it (`touch` offline is a legitimate op
// with nothing to serve), and a rename never has one. A trash keeps
// the blob of a create it withdrew only to find the node by, not
// to serve. All still have to be replayed, so only the blob — if
// any — is checked.
if op.kind == OP_TRASH || (op.blob_path.is_none() && op.kind != OP_REVISION) {
continue;
}
let parsed = op
.meta_json
.as_deref()
.and_then(|j| serde_json::from_str::<StagedWrite>(j).ok())
.zip(op.blob_path.as_deref().map(PathBuf::from));
let Some((meta, path)) = parsed else {
error!(uid = %op.uid, id = op.id, "pending op is unreadable; dropping");
self.drop_unrecoverable_op(&op, &uid);
restored -= 1;
continue;
};
if !path.exists() {
error!(%uid, path = %path.display(), "staged blob is gone; dropping pending op");
self.drop_unrecoverable_op(&op, &uid);
restored -= 1;
continue;
}
map.insert(uid, PendingRevision { path, meta });
}
if restored > 0 {
info!(count = restored, "restored pending ops");
}
}
/// Re-attach staged blobs that no queued op refers to.
///
/// `staging/` holds the only copy of writes the kernel has already been
/// told succeeded. Three release-path failures put bytes there and return
/// `EIO` without leaving a `pending_op` row behind — an access change
/// mid-release, a write overlapping an undrained incomplete edit, a create
/// that drained out from under its own handle. Until now nothing ever
/// walked the directory again: `hydrate_pending` reads the op table and
/// [`recover_fsynced_writes`](Self::recover_fsynced_writes) reads
/// `recovery/`, so an orphaned staged blob was invisible to the daemon and
/// to the user alike, and stayed that way until someone found the file.
///
/// Runs once at mount, after `hydrate_pending`, so `pending` already
/// describes what the queue owns. An orphan whose sidecar names a real node
/// is queued as an ordinary revision — the condition that made it fail is
/// gone by definition, since the op it collided with has since drained.
/// Anything that cannot be addressed (no sidecar, an unparseable uid, a
/// `local~` placeholder whose create is gone) is left in place and named in
/// the log: unexplained bytes are never evidence that user data is
/// disposable.
pub(super) fn reconcile_staging(&self) {
let staged = self.cache.staged_writes();
if staged.is_empty() {
return;
}
let claimed = match self.db.op_blob_paths() {
Ok(paths) => paths,
Err(e) => {
error!(error = %e, "cannot read queued blob paths; skipping staging reconcile");
return;
}
};
let mut queued = 0usize;
let mut stranded = 0usize;
let mut retired = 0usize;
let mut retired_bytes = 0u64;
let mut example: Option<PathBuf> = None;
for (blob, meta) in staged {
if claimed.contains(&blob.to_string_lossy().into_owned()) {
continue;
}
let addressable = meta.as_ref().and_then(|m| parse_node_uid(&m.uid));
let Some((meta, uid)) = meta.zip(addressable).filter(|(_, uid)| !is_local_uid(uid))
else {
if let Some(bytes) = orphan_past_retention(&blob) {
retired += 1;
retired_bytes += bytes;
warn!(blob = %blob.display(), bytes,
age_days = STAGING_ORPHAN_RETAIN.as_secs() / 86_400,
"retiring staged bytes that name no node and have outlived retention");
self.cache.discard_staged(&blob);
continue;
}
stranded += 1;
example.get_or_insert_with(|| blob.clone());
continue;
};
if self.pending.lock().contains_key(&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.
stranded += 1;
warn!(%uid, blob = %blob.display(),
"staged bytes are superseded by a queued write; kept for recovery");
continue;
}
if self
.db
.has_pending_op(&uid.to_string(), OP_TRASH)
.unwrap_or(false)
{
// The node was deleted while a handle still read these bytes,
// and the daemon stopped before its trash went out. Queued again,
// they lost their blob when the trash landed and retried on it
// for good (`docs/BUGS.md` B188).
info!(%uid, blob = %blob.display(),
"staged bytes belong to a node whose trash is queued; discarded");
self.cache.discard_staged(&blob);
continue;
}
let op = PendingOp {
id: 0,
kind: OP_REVISION.to_string(),
uid: uid.to_string(),
parent_uid: None,
name: None,
blob_path: Some(blob.to_string_lossy().into_owned()),
meta_json: Some(serde_json::to_string(&meta).unwrap_or_default()),
created_at: now_millis(),
attempts: 0,
last_error: None,
next_attempt_at: now_millis(),
};
match self.db.enqueue_op(&op) {
Ok((_, superseded)) => {
if let Some(old) = superseded {
self.cache.discard_staged(Path::new(&old));
}
self.pending.lock().insert(
uid.clone(),
PendingRevision {
path: blob.clone(),
meta,
},
);
queued += 1;
}
Err(e) => {
stranded += 1;
error!(%uid, blob = %blob.display(), error = %e,
"cannot queue an orphaned staged write; bytes kept");
}
}
}
if stranded > 0 {
// One line, not one per blob. A tree of them says exactly as much as
// a single count and an example does, and said it on every mount:
// 86 identical warnings for the same 86 files, boot after boot.
warn!(
count = stranded,
example = %example.map(|b| b.display().to_string()).unwrap_or_default(),
"staged bytes belong to no queued upload and name no node; kept for recovery"
);
}
if queued > 0 || stranded > 0 || retired > 0 {
info!(
queued,
stranded, retired, retired_bytes, "reconciled orphaned staged writes"
);
}
}
/// Queue the writes that an unclean shutdown caught between `fsync(2)` and
/// `close(2)`.
///
/// `fsync` promises the bytes survive a crash, but the queueing that makes a
/// write outlive the daemon happens at `release`. A crash in between used to
/// lose the data outright, because the scratch directory is cleared at open.
/// Now `fsync` leaves a sidecar, `ContentCache::open` moves those blobs to
/// `recovery/`, and this walks them into the same staging + queued-op path a
/// normal release takes.
///
/// Runs after [`hydrate_pending`](Self::hydrate_pending), which is what makes
/// the incomplete-blob check in [`enqueue_staged_write`](Self::enqueue_staged_write)
/// meaningful: a recovered partial write whose earlier write is still queued
/// must not gap-fill from a remote revision that no longer describes the
/// file. With `pending` already loaded, that case is detected and the bytes
/// are parked rather than mis-filled.
///
/// Failure is per-write and never fatal: a node that no longer exists, or an
/// op that cannot be queued, leaves its blob in `recovery/` for the next run
/// (and for a human) instead of taking the mount down.
pub(super) fn recover_fsynced_writes(&self) {
let recovered = self.cache.recovered_writes();
if recovered.is_empty() {
return;
}
let mut queued = 0usize;
for (blob, meta) in recovered {
let Some(uid) = parse_node_uid(&meta.uid) else {
error!(uid = %meta.uid, "recovered write has an unparseable uid; keeping bytes");
continue;
};
// If the write is incomplete and an earlier edit is still queued, merging it
// 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) {
continue;
}
// The inode is only used to stamp the in-memory tree with the new
// size, and nothing is interned this early — `hydrate` reads the
// size back off `pending` when the node is first looked up, so 0
// (no such inode) is correct rather than merely tolerable.
match self.enqueue_staged_write(&uid, 0, &blob, meta) {
Ok(()) => {
self.cache.discard_recovered(&blob);
queued += 1;
}
Err(e) => {
error!(%uid, blob = %blob.display(), error = ?e,
"cannot queue a recovered write; bytes kept for the next run");
// Some failures (a partial write parked by
// `stage_orphaned_write`) still consume the blob. Its sidecar
// would then describe nothing, so retire it — the bytes are
// in staging, which is where a human looks for them.
if !blob.exists() {
self.cache.discard_recovered(&blob);
}
}
}
}
if queued > 0 {
info!(
count = queued,
"recovered fsynced writes from an unclean shutdown"
);
}
}
/// Discard an op that can never be performed, because the bytes it was to
/// upload are gone from staging (something outside the daemon deleted them).
///
/// For a node that only ever existed locally, the placeholder goes too. Its
/// content is unrecoverable and nothing will ever mint it a real uid, so
/// leaving the row would strand a file in the tree that can be listed but
/// never read and never uploaded.
pub(super) fn drop_unrecoverable_op(&self, op: &PendingOp, uid: &NodeUid) {
let _ = self.db.delete_op(op.id);
if is_local_uid(uid) {
error!(%uid, name = op.name.as_deref().unwrap_or("?"),
"discarding a node whose only copy was lost");
if let Err(e) = self.db.delete_node(uid) {
warn!(%uid, error = %e, "db delete_node failed for lost local node");
}
}
}
}
+1
View File
@@ -200,6 +200,7 @@ impl Core {
let reader = CountingReader::new(std::io::BufReader::new(file), &guard);
let metadata = PhotoUploadMetadata {
capture_time: Some(candidate.wanted),
last_modification_time: pdfs_core::timestamp::modification_time(candidate.wanted),
..Default::default()
};
let uploaded = self.rt.block_on(photos.upload_photo_from(
+4 -3
View File
@@ -18,9 +18,8 @@ use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use parking_lot::Mutex;
use pdfs_core::db::{StoredSyncEntry, StoredSyncFolder};
use pdfs_core::{CoreError, CoreResult};
use pdfs_store::db::{StoredSyncEntry, StoredSyncFolder};
use proton_drive_rs::NodeKind;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use tracing::{info, warn};
@@ -200,7 +199,8 @@ impl Core {
.collect();
ids.sort_unstable();
ids.dedup();
let locks: Vec<Arc<Mutex<()>>> = ids.iter().map(|&id| self.sync_lock(id)).collect();
let locks: Vec<Arc<pdfs_core::lockrank::Ranked<()>>> =
ids.iter().map(|&id| self.sync.lock(id)).collect();
let mut guards = Vec::with_capacity(locks.len());
for lock in &locks {
guards.push(lock.try_lock_for(MIRROR_LOCK_WAIT).ok_or_else(|| {
@@ -555,6 +555,7 @@ mod tests {
fn folder(id: i64, local_path: &str, mode: &str) -> StoredSyncFolder {
StoredSyncFolder {
kind: "device".into(),
id,
local_path: local_path.to_string(),
remote_uid: format!("vol~root{id}"),
+96
View File
@@ -0,0 +1,96 @@
//! Changes sent straight to Drive (renames, moves, content changes) and what
//! each one changes in the tree once Drive has answered.
use super::*;
impl Core {
/// Rename `uid` on Drive, riding out an "out of date" answer from a stale
/// name hash. See [`retry_out_of_date`].
pub(crate) fn rename_remote(&self, uid: &NodeUid, name: &str) -> Result<(), ProtonError> {
self.change_remote(uid, || {
self.block_on_bounded(self.drive.rename_node(uid, name, None))
})
}
/// Move `uid` into the folder `parent` on Drive, like [`Core::rename_remote`].
pub(crate) fn move_remote(&self, uid: &NodeUid, parent: &NodeUid) -> Result<(), ProtonError> {
self.change_remote(uid, || {
self.block_on_bounded(self.drive.move_node(uid, parent))
})
}
/// Move `uid` into the folder `parent` on Drive, renaming it to
/// `target_name` on the way when one is given, in one request.
///
/// Done as a rename and then a move, a sibling in the source folder that
/// held the new name made Drive refuse the first half, although the
/// destination was free (docs/BUGS.md B122). One request also leaves no
/// half-applied state between the two.
pub(crate) fn move_rename_remote(
&self,
uid: &NodeUid,
parent: &NodeUid,
target_name: Option<&str>,
) -> Result<(), ProtonError> {
self.change_remote(uid, || {
let item = NodeMoveItem {
uid: uid.clone(),
target_name: target_name.map(str::to_string),
};
self.block_on_bounded(async {
let mut outcomes =
std::pin::pin!(self.drive.move_nodes_streaming(vec![item], parent.clone()));
match outcomes.next().await {
Some(Ok((_, outcome))) => outcome,
Some(Err(e)) => Err(e),
None => Err(ProtonError::invalid_operation(format!(
"move of {uid} reported no outcome"
))),
}
})
})
}
/// Run a rename or move of `uid`, then drop the SDK's now stale copy of it.
pub(super) fn change_remote(
&self,
uid: &NodeUid,
call: impl FnMut() -> Result<(), ProtonError>,
) -> Result<(), ProtonError> {
retry_out_of_date(call, || {
self.forget_sdk_node(uid);
std::thread::sleep(OUT_OF_DATE_RETRY_DELAY);
})
.inspect(|()| self.changed_remote(uid))
}
/// Bookkeeping after a rename or move of `uid` landed: the SDK's copy of it
/// is stale, and the feed will echo the change back. Without the second,
/// that echo reads as someone else's edit and evicts the cached bytes a
/// partial write is about to gap-fill from (docs/BUGS.md B123).
pub(crate) fn changed_remote(&self, uid: &NodeUid) {
self.forget_sdk_node(uid);
self.note_self_change(uid);
}
/// Drop the SDK's cached copy of `uid` after this daemon renamed or moved it.
///
/// The SDK sends a node's name hash from its entity cache, and nothing but
/// the event feed's echo of the change refreshes that entry. Until the next
/// poll, up to [`POLL_INTERVAL`] later, each rename or move of the node would
/// send the old hash and Drive would refuse it as out of date (docs/BUGS.md
/// B121). Feeding the SDK the echo now makes the next call read the link.
pub(crate) fn forget_sdk_node(&self, uid: &NodeUid) {
let changed = DriveEvent::NodeUpdated {
id: DriveEventId::from("pdfs-local-change"),
node_uid: uid.clone(),
parent_node_uid: None,
is_trashed: false,
is_shared: false,
};
if let Err(error) = self.block_on_bounded(self.drive.invalidate_caches_for_event(&changed))
{
debug!(%uid, %error, "could not drop the SDK's cached node");
}
}
}
+851
View File
@@ -0,0 +1,851 @@
//! Requests by path from the control socket: listing, opening, renaming,
//! moving, copying and deleting, and taking a replaced file back.
use super::*;
impl Core {
/// List the directory at mountpoint-relative `rel` for the in-app browser:
/// the same lazy remote enumeration `readdir` uses, projected into
/// serializable [`DirEntry`]s (with per-file pin state).
pub(super) fn list_dir(&self, rel: &Path) -> CoreResult<Vec<DirEntry>> {
let (ino, uid) = self.resolve(rel)?;
self.ensure_children(ino)
.map_err(|e| self.errno_error(e, "enumerate"))?;
self.settle_listing_sizes(ino);
// Every entry shares this folder as its parent, so one lookup says
// whether they are all kept through it.
let pinned_by_folder = self.cache.is_pinned(&uid);
// Snapshot the listing, then drop the lock before touching the on-disk
// pin registry so a slow disk read doesn't block FUSE metadata ops.
let rows: Vec<(String, bool, u64, i64, NodeUid, u64)> = {
let st = self.state();
st.children
.get(&ino)
.map(|kids| {
kids.iter()
.filter_map(|&k| st.entries.get(&k).map(|e| (k, e)))
.map(|(k, e)| {
(
e.node.name.clone(),
e.node.is_folder(),
node_size(&e.node),
e.node.modification_time,
e.uid.clone(),
k,
)
})
.collect()
})
.unwrap_or_default()
};
let issues = self.db.node_issues().unwrap_or_default();
Ok(rows
.into_iter()
.map(|(name, is_dir, size, modified, uid, ino)| DirEntry {
name,
is_dir,
size,
modified,
pinned: pinned_by_folder || self.cache.is_pinned(&uid),
pinned_by_folder,
cached: !is_dir && self.cache.is_cached(&uid, modified, size),
uid: uid.to_string(),
// Listing entries live in the requested dir; the caller derives
// the path from its name. Left empty.
path: String::new(),
// My own tree: a role only means something under a share, and
// this listing never crosses into one.
role: String::new(),
shared_by: String::new(),
shared_at: 0,
shared_by_unverified: false,
trashed_at: 0,
trashed_from: None,
trashed_parent: None,
issue: state::ino_lid(ino)
.and_then(|lid| issues.get(&lid))
.map(|issue| SyncIssue::parse(issue)),
})
.collect())
}
/// Re-fetch the whole photos timeline and persist it. Returns whether the
/// account has a photos volume at all.
/// Download the full content of the Drive file at mountpoint-relative `rel`
/// into the content cache, returning its on-disk path (served from cache
/// when a fresh blob already exists). Lets a front-end open the file with
/// the user's default application without pinning it.
pub(super) fn open_file(&self, rel: &Path) -> CoreResult<PathBuf> {
let (ino, uid) = self.resolve(rel)?;
let (name, mtime, size) = {
let st = self.state();
let e = st
.entries
.get(&ino)
.ok_or_else(|| CoreError::not_found("node vanished"))?;
if !e.node.is_file() {
return Err(CoreError::invalid("not a regular file"));
}
(
e.node.name.clone(),
e.node.modification_time,
node_size(&e.node),
)
};
self.fetch_content(&uid, &name, mtime, size)
}
/// [`open_file`](Self::open_file) addressed by uid instead of by path.
///
/// A search hit is a metadata-index row, and the index covers every
/// location this daemon knows — including on-demand sync folders and
/// mirrors, whose nodes have no path inside the primary mount's tree.
/// Walking such a hit's path from the mount root answers ENOENT even though
/// the node is perfectly reachable, so front-ends address hits by uid.
///
/// Metadata comes from the live tree, then the index, then the API — the
/// last covers a node the index knows but no location holds. Unlike the
/// mutating by-uid handlers this does not demand a
/// [`resolve_anywhere`](Self::resolve_anywhere) residency proof: reading
/// one's own file is what the API authorizes anyway, and requiring
/// residency is exactly what turned an openable search hit into "no such
/// file or folder". [`open_shared_file`](Self::open_shared_file) already
/// works this way. Reserved (local/virtual) uids name no remote node and
/// are still rejected.
pub(super) fn open_file_uid(&self, raw_uid: &str) -> CoreResult<PathBuf> {
let uid = parse_uid(raw_uid)
.filter(|uid| !is_local_uid(uid) && !is_virtual_uid(uid))
.ok_or_else(|| CoreError::invalid(format!("invalid uid: {raw_uid}")))?;
let live = self
.state
.lock()
.entries
.values()
.find(|e| e.uid == uid)
.map(|e| e.node.clone());
let node = match live {
Some(node) => node,
None => match self
.db
.node_by_uid(&uid.to_string())
.map_err(|e| CoreError::from_api(&e, "load node"))?
{
Some(node) => node,
None => self
.rt
.block_on(self.drive.get_node(&uid))
.map_err(|e| CoreError::from_api(&e, "get node"))?
.ok_or_else(|| CoreError::not_found("node vanished"))?,
},
};
if !node.is_file() {
return Err(CoreError::invalid("not a regular file"));
}
self.fetch_content(&uid, &node.name, node.modification_time, node_size(&node))
}
/// Materialise a file's full content into the content cache, returning its
/// on-disk path. Serves a fresh cached blob without touching the network.
pub(super) fn fetch_content(
&self,
uid: &NodeUid,
name: &str,
mtime: i64,
size: u64,
) -> CoreResult<PathBuf> {
if let Some(p) = self.cache.cached_content_path(uid, mtime, size) {
return Ok(p);
}
// Keep the temporary file beside the final cache blob. `store_file`
// can then adopt it with a hard link and atomic rename, while the SDK
// streams decrypted blocks to disk instead of building a file-sized
// `Vec<u8>`. A unique name also keeps concurrent opens of the same node
// from sharing a partially written staging file.
static OPEN_TEMP_SEQ: AtomicU64 = AtomicU64::new(0);
let seq = OPEN_TEMP_SEQ.fetch_add(1, Ordering::Relaxed);
let tmp = self.cache.content_path(uid).with_extension(format!(
"open-{}-{}-{seq}.tmp",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0)
));
let file = File::options()
.write(true)
.create_new(true)
.open(&tmp)
.map_err(|e| CoreError::internal(format!("create download temp: {e}")))?;
let file = match self.download_file_tracked_to(uid, name, size, file) {
Ok(file) => file,
Err(e) => {
let _ = std::fs::remove_file(&tmp);
return Err(CoreError::from_api(&e, "download"));
}
};
if let Err(e) = file.sync_all() {
let _ = std::fs::remove_file(&tmp);
return Err(CoreError::internal(format!("sync download temp: {e}")));
}
if let Err(e) = self.cache.store_file(uid, mtime, size, &tmp) {
let _ = std::fs::remove_file(&tmp);
return Err(CoreError::internal(format!("cache store: {e}")));
}
let _ = std::fs::remove_file(&tmp);
Ok(self.cache.content_path(uid))
}
/// Rename a file or folder to `new_name`. `rel` is mountpoint-relative.
/// Mirrors the FUSE `rename` write path: queued whenever the mount queues
/// ([`Core::queue_relocation`]), otherwise renamed on the remote, then
/// moved to its new name in every mount with the parent listing dropped
/// so the next `ListDir` re-enumerates.
pub(super) fn rename(&self, rel: &Path, new_name: &str) -> CoreResult<String> {
if new_name.is_empty() || new_name.contains('/') {
return Err(CoreError::invalid(format!("invalid name: {new_name:?}")));
}
let (ino, uid) = self.resolve(rel)?;
let old_parent_uid = self.source_parent_uid(ino, rel)?;
require_rename_access(
|authority| self.require_uid_writable(authority),
&uid,
&old_parent_uid,
&old_parent_uid,
)
.map_err(|error| self.errno_error(error, "rename access"))?;
if self.queues_relocation(&uid, &old_parent_uid) {
self.queue_relocation(
ino,
&uid,
&old_parent_uid,
&old_parent_uid,
&rel.with_file_name(new_name),
new_name,
)?;
return Ok(new_name.to_string());
}
self.rename_remote(&uid, new_name)
.map_err(|e| CoreError::from_api(&e, "rename"))?;
self.relocate_everywhere(&uid, &old_parent_uid, new_name);
self.invalidate_parent_listing(rel);
Ok(new_name.to_string())
}
/// Whether a rename or move asked for over the control socket goes
/// through the queue. It does whenever the same change through the mount
/// would, and whenever the node has anything queued: sent straight to
/// Drive, it would land first, and the queued change landing after it
/// would undo it (`docs/BUGS.md` B149).
pub(super) fn queues_relocation(&self, uid: &NodeUid, new_parent_uid: &NodeUid) -> bool {
!self.sends_inline()
|| is_local_uid(uid)
|| is_local_uid(new_parent_uid)
|| self.db.has_any_op(&uid.to_string()).unwrap_or(true)
}
/// Queue renaming or moving the node at `ino` to `dest`, whose last
/// component is `name`, and apply it to every mount now, as the mount's
/// own queued rename does.
///
/// The listings stay: Drive has not been told yet, so listing either
/// folder again would bring back the old name.
pub(super) fn queue_relocation(
&self,
ino: u64,
uid: &NodeUid,
old_parent_uid: &NodeUid,
new_parent_uid: &NodeUid,
dest: &Path,
name: &str,
) -> CoreResult<()> {
// Drive refuses a taken name, but only once the queue sends the change.
match self.resolve_path(dest) {
Ok((found, _)) if found != ino => {
return Err(CoreError::conflict(format!(
"{} already exists",
dest.display()
)));
}
Ok(_) => {}
Err(e) if e.code() == libc::ENOENT => {}
Err(e) => {
return Err(self.errno_error(e, &format!("could not resolve {}", dest.display())));
}
}
let old_name = self
.state()
.entries
.get(&ino)
.map(|entry| entry.node.name.clone())
.unwrap_or_default();
let mut uid = uid.clone();
// A node whose create is still queued is that op: rewriting its target
// is the whole change, as through the mount.
if is_local_uid(&uid) {
match self
.db
.rewrite_op_target(&uid.to_string(), &new_parent_uid.to_string(), name)
{
Ok(true) => {
self.relocate_queued_everywhere(&uid, new_parent_uid, name);
// A parked transient file given a finished name is meant
// to reach Drive now (`docs/BUGS.md` B70).
if is_transient_name(&old_name)
&& !is_transient_name(name)
&& let Err(e) = self.db.set_create_hold(&uid.to_string(), false)
{
warn!(%uid, error = %e, "un-parking a finalized transient create failed");
}
self.wake_drain();
return Ok(());
}
// The create landed meanwhile: rename what Drive made.
Ok(false) => {
uid = self.landed_row_uid(ino).ok_or_else(|| {
CoreError::conflict(format!(
"{old_name} changed while it was being renamed; try again"
))
})?;
}
Err(e) => return Err(CoreError::internal(format!("db: {e}"))),
}
}
self.enqueue_rename(ino, &uid, old_parent_uid, new_parent_uid, name)
.map_err(|e| self.errno_error(e, "queue the change"))?;
self.relocate_queued_everywhere(&uid, new_parent_uid, name);
self.wake_drain();
debug!(%uid, %new_parent_uid, name, "renamed over the control socket; queued");
Ok(())
}
/// Bring every mount level with a rename or move Drive has made of `uid`,
/// to `name` in `new_parent`, and have each kernel session drop the name it
/// cached for it. Returns the name a mount knew the node by.
///
/// For changes that do not come through the mount. The kernel made a
/// rename through the mount itself, but one made over the control socket
/// leaves the old name cached for [`TTL`] (`docs/BUGS.md` B114).
///
/// The node is moved, not forgotten, and so is its row. Forgetting it, as
/// this used to, deleted the row, and until a listing brought it back
/// nothing local knew the node: `pdfs sync queue` showed its queued upload
/// by raw id, and the drain re-read the node and put the upload off
/// (`docs/BUGS.md` B117).
pub(super) fn relocate_everywhere(
&self,
uid: &NodeUid,
new_parent: &NodeUid,
name: &str,
) -> Option<String> {
self.relocate_with(uid, new_parent, name, false)
}
/// [`Core::relocate_everywhere`] for a change the queue has not sent yet.
/// Each mount keeps its listings, which Drive cannot bring up to date
/// until the change lands.
pub(super) fn relocate_queued_everywhere(
&self,
uid: &NodeUid,
new_parent: &NodeUid,
name: &str,
) {
self.relocate_with(uid, new_parent, name, true);
}
pub(super) fn relocate_with(
&self,
uid: &NodeUid,
new_parent: &NodeUid,
name: &str,
queued: bool,
) -> Option<String> {
let mut old_name = None;
let mut moved_row = false;
self.for_each_mount(|st, notify| {
if let Some((from_name, relocated)) =
relocate_in_mount(st, notify, uid, new_parent, name, queued)
{
old_name = Some(from_name);
moved_row |= relocated;
}
});
if !moved_row {
self.move_row(uid, new_parent, name);
}
old_name
}
/// Point the persisted row of `uid` at `name` in `new_parent`, for a node
/// no mount holds where it now is.
pub(super) fn move_row(&self, uid: &NodeUid, new_parent: &NodeUid, name: &str) {
let moved = self.db.node_by_uid(&uid.to_string()).and_then(|node| {
let Some(mut node) = node else {
return Ok(());
};
node.name = name.to_string();
node.parent_uid = Some(new_parent.clone());
self.db.upsert_node(&node)
});
if let Err(error) = moved {
warn!(%uid, ?error, "could not move the node's row along with it");
}
}
/// Forget `uid` in every mount, and have each kernel session drop the name
/// it cached for it. Returns the name a mount knew the node by.
///
/// For a removal that does not come through the mount. The kernel made an
/// unlink through the mount itself, but one made over the control socket
/// leaves the old name cached for [`TTL`], pointing at an inode the mount no
/// longer has (`docs/BUGS.md` B114). Every mount, not only this one, so a
/// fork showing the same node does not keep serving it (`docs/BUGS.md`
/// B74).
pub(super) fn forget_everywhere(&self, uid: &NodeUid) -> Option<String> {
let mut name = None;
self.for_each_mount(|st, notify| {
if let Some(entry) = st.by_uid.get(uid).and_then(|ino| st.entries.get(ino)) {
name = Some(entry.node.name.clone());
}
forget_and_notify(st, notify, uid);
});
name
}
/// Move a file or folder into the folder at `new_parent_rel`. Both paths are
/// mountpoint-relative. Queued whenever the mount queues
/// ([`Core::queue_relocation`]); otherwise moved on the remote, then in
/// every mount, with both listings invalidated so each re-enumerates on
/// next access.
pub(super) fn move_to(&self, rel: &Path, new_parent_rel: &Path) -> CoreResult<String> {
let (ino, uid) = self.resolve(rel)?;
let old_parent_uid = self.source_parent_uid(ino, rel)?;
let (pino, new_parent_uid) = self
.resolve_path(new_parent_rel)
.map_err(|e| self.errno_error(e, "resolve new parent"))?;
require_rename_access(
|authority| self.require_uid_writable(authority),
&uid,
&old_parent_uid,
&new_parent_uid,
)
.map_err(|error| self.errno_error(error, "move access"))?;
let name = self
.state()
.entries
.get(&ino)
.map(|entry| entry.node.name.clone())
.unwrap_or_default();
if self.queues_relocation(&uid, &new_parent_uid) {
if self.state().is_ancestor_of(ino, pino) {
return Err(CoreError::invalid("cannot move a folder into itself"));
}
self.queue_relocation(
ino,
&uid,
&old_parent_uid,
&new_parent_uid,
&new_parent_rel.join(&name),
&name,
)?;
return Ok(name);
}
self.move_remote(&uid, &new_parent_uid)
.map_err(|e| CoreError::from_api(&e, "move"))?;
self.relocate_everywhere(&uid, &new_parent_uid, &name);
self.invalidate_parent_listing(rel);
self.state().invalidate_listing(pino);
Ok(name)
}
/// Copy a file or folder into `new_parent_rel` on Proton Drive, which copies
/// the content there: nothing is downloaded or uploaded. Both paths are
/// mountpoint-relative. A name already taken in the folder gets the next
/// free ` (n)` suffix. Returns the copy's name.
///
/// Drive copies what it holds, so the copy is refused offline and while the
/// mount still owes Drive part of it: a node or folder only queued locally,
/// a file with a queued upload or unsaved writes, or — for a folder, whose
/// queued changes could sit anywhere below it — any queued op at all.
pub(super) fn copy_to(&self, rel: &Path, new_parent_rel: &Path) -> CoreResult<String> {
let (ino, uid) = self.resolve(rel)?;
let (pino, new_parent_uid) = self
.resolve_path(new_parent_rel)
.map_err(|e| self.errno_error(e, "resolve new parent"))?;
self.ensure_children(pino)
.map_err(|e| self.errno_error(e, "enumerate"))?;
self.require_uid_writable(&new_parent_uid)
.map_err(|error| self.errno_error(error, "copy access"))?;
let (name, is_folder, unsaved) = {
let st = self.state();
let entry = st
.entries
.get(&ino)
.ok_or_else(|| CoreError::not_found(format!("{} is gone", rel.display())))?;
// Unsaved writes, or a release still queueing them, to the file or,
// for a folder, to any file below it.
let unsaved = st
.active_writes
.iter()
.filter(|(_, w)| w.dirty)
.map(|(&open, _)| open)
.chain(st.releasing.iter().copied())
.any(|open| relocate::ino_is_under(&st, open, ino));
(entry.node.name.clone(), entry.node.is_folder(), unsaved)
};
// Unlike a move, a copy cannot wait in the queue: it needs the node as
// Drive has it, so it goes now or not at all, local-first or not.
if !self.is_online() {
return Err(CoreError::offline());
}
let owed = unsaved
|| is_local_uid(&uid)
|| is_local_uid(&new_parent_uid)
|| self.db.has_any_op(&uid.to_string()).unwrap_or(true)
|| (is_folder
&& self
.db
.pending_op_counts()
.map(|counts| counts.uploads + counts.changes > 0)
.unwrap_or(true));
if owed {
return Err(CoreError::conflict(format!(
"{name} has changes that have not reached Proton Drive yet; \
copy it once they have synced"
)));
}
let target = if is_folder {
AvailableNameTarget::Folder
} else {
AvailableNameTarget::File
};
let copy_name = self
.rt
.block_on(
self.drive
.get_available_name(&new_parent_uid, &name, target),
)
.map_err(|e| CoreError::from_api(&e, "copy"))?;
let new_uid = self
.rt
.block_on(
self.drive
.copy_node(&uid, &new_parent_uid, Some(&copy_name)),
)
.map_err(|e| CoreError::from_api(&e, "copy"))?;
let node = self
.fetch_minted_node(&new_uid, &copy_name)
.ok_or_else(|| minted_but_unlisted(&copy_name))?;
let mut st = self.state();
let copy_ino = st.intern(pino, node);
if let Some(kids) = st.children.get_mut(&pino)
&& !kids.contains(&copy_ino)
{
kids.push(copy_ino);
}
drop(st);
self.flush_access_changes();
Ok(copy_name)
}
/// What the folder at `rel` holds on Proton Drive: bytes on storage and the
/// number of items below it. Drive adds it up, so nothing is listed here;
/// trashed items count, and the bytes are encrypted ones.
pub(crate) fn folder_size(&self, rel: &Path) -> CoreResult<proton_drive_rs::FolderSize> {
let (ino, uid) = self.resolve(rel)?;
let is_folder = self
.state()
.entries
.get(&ino)
.is_some_and(|entry| entry.node.is_folder());
if !is_folder {
return Err(CoreError::invalid(format!(
"{} is not a folder",
rel.display()
)));
}
self.folder_size_for_uid(&uid)
}
/// [`Core::folder_size`] for a folder addressed through any daemon location.
pub(crate) fn folder_size_by_uid(&self, uid: &str) -> CoreResult<proton_drive_rs::FolderSize> {
let uid = self.resolve_anywhere(uid)?;
self.folder_size_for_uid(&uid)
}
pub(super) fn folder_size_for_uid(
&self,
uid: &NodeUid,
) -> CoreResult<proton_drive_rs::FolderSize> {
if is_local_uid(uid) {
return Err(CoreError::conflict("the folder is not on Proton Drive yet"));
}
if !self.is_online() {
return Err(CoreError::offline());
}
self.rt
.block_on(self.client.get_folder_size(uid))
.map_err(|e| CoreError::from_api(&e, "folder size"))
}
/// Trash a file or folder. `rel` is mountpoint-relative. Forgets the node,
/// evicts any cached content, and invalidates the parent listing.
pub(super) fn delete(&self, rel: &Path) -> CoreResult<String> {
let (ino, uid) = self.resolve(rel)?;
let parent_uid = self.source_parent_uid(ino, rel)?;
require_node_parent_access(
|authority| self.require_uid_writable(authority),
&uid,
&parent_uid,
)
.map_err(|error| self.errno_error(error, "trash access"))?;
if self.db.has_pending_moves_out_of(&uid.to_string())? {
return Err(CoreError::conflict(
"wait for pending moves out of this folder to sync before trashing it",
));
}
self.rt
.block_on(self.drive.trash_nodes(std::slice::from_ref(&uid)))
.and_then(batch::into_unit)
.map_err(|e| CoreError::from_api(&e, "trash"))?;
// Uploads queued for the node or anything below it would now only fail
// against the trash, forever, holding their bytes (`docs/BUGS.md` B102).
if let Err(error) = self.discard_queued_ops(&uid) {
warn!(%uid, ?error, "remote trash landed but queued-op cleanup failed");
}
let name = self.forget_everywhere(&uid).unwrap_or_default();
self.cache.evict(&uid);
self.evict_reader(&uid);
self.invalidate_parent_listing(rel);
self.invalidate_trash();
Ok(name)
}
/// Remove the node a `rename` is about to replace, so the new name is free
/// for the API call that follows.
///
/// `rename(2)` promises to replace an existing destination atomically. Proton
/// offers no such primitive — `rename_node` refuses a name that is already
/// taken — so this is the first half of an emulation that is *not* atomic:
/// see [`Core::restore_replaced`] for the other half (`docs/BUGS.md` B13).
///
/// A node whose own creation is still queued has never reached the server, so
/// dropping its queued ops is the whole removal; nothing goes to the wire and
/// it works offline. A create that landed before its ops were dropped left
/// none: Drive has the node, so it is trashed there like any other
/// (`docs/BUGS.md` B175).
///
/// A handle still open on the replaced node keeps reading its bytes, as
/// `rename(2)` promises: the inode stays as an unlinked entry and its
/// staged bytes, cache and reader go at the final close, exactly as for an
/// `unlink` under an open handle. Its queued ops go now, or the drain would
/// upload to the node after it was trashed (`docs/BUGS.md` B106).
pub(super) fn remove_replaced(&self, ino: u64, uid: &NodeUid, name: &str) -> Result<(), Errno> {
// Asked under the uid the tree has now: a landed create's real uid is
// not in the tree yet (`docs/BUGS.md` B257).
let open = self.is_open_anywhere(uid);
let landed;
let uid = if is_local_uid(uid) {
if open {
self.withdraw_queued_ops(uid)?;
} else {
self.discard_queued_ops(uid)?;
}
self.for_each_state(|st| {
st.forget_or_unlink(uid);
});
match self.landed_row_uid(ino) {
Some(real) => {
debug!(local = %uid, %real, name, "create landed under a replace");
landed = real;
&landed
}
None => {
debug!(%uid, name, "replaced a node whose create was still queued");
return Ok(());
}
}
} else {
uid
};
// Local-first or offline: queue the trash and the rename that follows.
if !self.sends_inline() {
return self.queue_trash(uid, name, open);
}
if self.has_pending_moves_out_of(uid)? {
return Err(Errno::EBUSY);
}
self.require_uid_writable(uid)?;
if let Err(e) = self
.block_on_bounded(self.drive.trash_nodes(std::slice::from_ref(uid)))
.and_then(batch::into_unit)
{
if self.lost_link(&e, "trash a replaced node") {
return self.queue_trash(uid, name, open);
}
error!(%uid, name, error = %e, "trashing the node a rename replaces failed");
self.log_activity(ActivityKind::Trash, name, e.to_string(), false);
return Err(Errno::EIO);
}
// The node was trashed on the server; withdraw it from every inode
// space that had it, not only the mount the rename came through.
let open_now = self.is_open_anywhere(uid);
self.for_each_state(|st| {
st.forget_or_unlink(uid);
});
self.hidden.lock().insert(uid.clone());
if open_now {
if let Err(error) = self.withdraw_queued_ops(uid) {
error!(%uid, "remote replacement landed but queued-op cleanup failed");
return Err(error);
}
} else {
if let Err(error) = self.discard_queued_ops(uid) {
error!(%uid, "remote replacement landed but queued-op cleanup failed");
return Err(error);
}
self.cache.evict(uid);
self.evict_reader(uid);
}
self.invalidate_trash();
// The node is recoverable from the trash, but only if the user knows it
// went there — a rename is not an operation anyone expects to trash
// something, so this is the only record that it happened.
self.log_activity(
ActivityKind::Trash,
name,
"replaced by a rename from the mount",
true,
);
Ok(())
}
/// Whether any mount holds an open handle on `uid`.
pub(super) fn is_open_anywhere(&self, uid: &NodeUid) -> bool {
let mut open = false;
self.for_each_state(|st| {
open |= st
.by_uid
.get(uid)
.and_then(|ino| st.entries.get(ino))
.is_some_and(|entry| entry.open_count > 0);
});
open
}
/// Put back the node [`Core::remove_replaced`] trashed, after the rename it
/// was clearing the way for failed anyway.
///
/// Best-effort by construction: if the restore also fails there is nothing
/// further to try, and the node is still in the trash where `pdfs restore`
/// can reach it. Says so loudly in that case, because the alternative is a
/// file the user believes was only renamed quietly sitting in the trash.
///
/// A restored node comes back to the mount as the ordinary restore brings
/// it: out of `hidden`, and through a fresh listing of `parent` in every
/// mount that shows it (`docs/BUGS.md` B124).
pub(super) fn restore_replaced(
&self,
victim: Option<&(u64, NodeUid)>,
parent: &NodeUid,
name: &str,
) {
let Some((_, uid)) = victim else { return };
if is_local_uid(uid) {
// Its queued create was discarded and cannot be reconstructed from
// here; the caller's error is what the user acts on.
warn!(%uid, name, "a rename failed after discarding a queued node it replaced");
return;
}
match self
.rt
.block_on(self.drive.restore_nodes(std::slice::from_ref(uid)))
.and_then(batch::into_unit)
{
Ok(()) => {
self.hidden.lock().remove(uid);
self.for_each_mount(|st, notify| {
if let Some(&ino) = st.by_uid.get(parent) {
st.invalidate_listing(ino);
notify.inval_entry(ino, name.to_string());
}
});
self.invalidate_trash();
debug!(%uid, name, "restored the node a failed rename had replaced");
}
Err(e) => {
error!(%uid, name, error = %e, "restoring a replaced node failed; it stays in the trash");
self.log_activity(ActivityKind::Restore, name, e.to_string(), false);
}
}
}
/// Drop one folder's cached child listing (`rel` is mountpoint-relative), so
/// the next `ListDir`/`readdir` re-enumerates it from the server. Backs
/// [`CtlRequest::Refresh`] with a [`RefreshScope::Dir`] scope.
pub(super) fn refresh_dir(&self, rel: &Path) -> CoreResult<()> {
let (ino, _uid) = self.resolve(rel)?;
self.state().invalidate_listing(ino);
Ok(())
}
/// Parse wire uids (`volume~link`) into [`NodeUid`]s, rejecting the whole
/// batch if any is malformed — a partial trash mutation is worse than none.
pub(super) fn parse_uids(uids: &[String]) -> CoreResult<Vec<NodeUid>> {
if uids.is_empty() {
return Err(CoreError::invalid("no nodes given"));
}
uids.iter()
.map(|u| parse_uid(u).ok_or_else(|| CoreError::invalid(format!("invalid uid: {u}"))))
.collect()
}
/// Forget every trace of nodes that no longer exist anywhere: their inode and
/// DB row, and their cached content.
pub(super) fn drop_local(&self, uids: &[NodeUid]) {
// These nodes are gone from the server, and a sync-folder fork showing
// the same uid would otherwise keep serving them (`docs/BUGS.md` B74).
self.for_each_state(|st| {
for uid in uids {
st.forget(uid);
}
});
for uid in uids {
self.cache.evict(uid);
self.evict_reader(uid);
}
}
/// Create a folder named `name` under the mountpoint-relative `parent_rel`.
/// Interns the new node directly so it shows up without a re-enumeration.
pub(super) fn create_folder(&self, parent_rel: &Path, name: &str) -> CoreResult<String> {
if name.is_empty() || name.contains('/') {
return Err(CoreError::invalid(format!("invalid name: {name:?}")));
}
let (pino, parent_uid) = self.resolve(parent_rel)?;
self.ensure_children(pino)
.map_err(|e| self.errno_error(e, "enumerate"))?;
self.require_uid_writable(&parent_uid)
.map_err(|error| self.errno_error(error, "create folder access"))?;
let new_uid = self
.rt
.block_on(
self.drive
.create_folder(&parent_uid, name, Some(now_secs())),
)
.map_err(|e| CoreError::from_api(&e, "create folder"))?;
let node = self
.fetch_minted_node(&new_uid, name)
.ok_or_else(|| minted_but_unlisted(name))?;
let mut st = self.state();
let ino = st.intern(pino, node);
if let Some(kids) = st.children.get_mut(&pino)
&& !kids.contains(&ino)
{
kids.push(ino);
}
drop(st);
self.flush_access_changes();
Ok(name.to_string())
}
}
+254
View File
@@ -0,0 +1,254 @@
//! Finding nodes: by path or uid in the tree, in the database, and on Drive,
//! including a create that landed while its placeholder was still in use.
use super::*;
impl Core {
/// Resolve a child `name` within `parent` to its `(inode, uid)`, ensuring
/// the parent's listing is cached first.
pub(super) fn lookup_child(&self, parent: u64, name: &str) -> Result<(u64, NodeUid), Errno> {
self.ensure_children(parent)?;
let st = self.state();
st.children
.get(&parent)
.and_then(|kids| {
kids.iter().copied().find_map(|ino| {
st.entries
.get(&ino)
.filter(|e| e.node.name == name)
.map(|e| (ino, e.uid.clone()))
})
})
.ok_or(Errno::ENOENT)
}
/// Walk a mountpoint-relative path to its `(inode, uid)`, enumerating each
/// directory on the way as needed. Leading `/` and `.` components are
/// ignored; `..` is rejected.
pub(super) fn resolve_path(&self, rel: &Path) -> Result<(u64, NodeUid), Errno> {
let mut ino = self.root_ino();
let mut uid = {
let st = self.state();
st.entries
.get(&ino)
.map(|e| e.uid.clone())
.ok_or(Errno::ENOENT)?
};
for comp in rel.components() {
match comp {
Component::RootDir | Component::CurDir => continue,
Component::Normal(name) => {
let (child_ino, child_uid) = self.lookup_child(ino, &name.to_string_lossy())?;
ino = child_ino;
uid = child_uid;
}
_ => return Err(Errno::EINVAL),
}
}
Ok((ino, uid))
}
/// [`resolve_path`](Self::resolve_path) for the request-serving side.
///
/// The kernel-facing resolver answers in `Errno` because that is what the
/// FUSE reply needs. A front-end needs the opposite: `{:?}` of a libc
/// constant is not something to show a user, and "does not exist" and "the
/// API is down" want different copy and different buttons. This is the one
/// place that knows enough to tell them apart, so it is the place that does.
pub(super) fn resolve(&self, rel: &Path) -> CoreResult<(u64, NodeUid)> {
self.resolve_path(rel)
.map_err(|e| self.errno_error(e, &format!("could not resolve {}", rel.display())))
}
/// Resolve a wire-format uid only when one of this daemon's locations
/// proves that it owns the node.
///
/// The primary and on-demand mounts prove residency through the tree and
/// the roots in [`StateRegistry`]. Mirror locations have no tree, so their root
/// and last-synced descendants are resolved through `sync_folder` and
/// `sync_entry` instead.
pub(crate) fn resolve_anywhere(&self, uid: &str) -> CoreResult<NodeUid> {
resolve_anywhere_with(
uid,
|uid| self.owns_visible_uid(uid),
|uid| self.db.mirror_contains_uid(&uid.to_string()),
)
}
/// [`Core::resolve_anywhere`], widened to the Photos timeline for sharing.
///
/// A photo lives on the photos volume, which no location shows, so the
/// residency proof above never finds it. The timeline in the `photos` table
/// is this daemon's proof instead: it lists only photos on the user's own
/// volume, which are theirs to share. A photo in an album someone else
/// shared is not in it and stays refused.
pub(crate) fn resolve_shareable(&self, uid: &str) -> CoreResult<NodeUid> {
resolve_anywhere_with(
uid,
|uid| self.owns_visible_uid(uid),
|uid| {
let uid = uid.to_string();
Ok(self.db.mirror_contains_uid(&uid)?
|| !self
.db
.photos_by_uid(std::slice::from_ref(&uid))?
.is_empty())
},
)
}
pub(super) fn source_parent_uid(&self, ino: u64, rel: &Path) -> CoreResult<NodeUid> {
let state = self.state();
let entry = state
.entries
.get(&ino)
.ok_or_else(|| CoreError::not_found(format!("could not resolve {}", rel.display())))?;
entry
.node
.parent_uid
.clone()
.or_else(|| {
state
.entries
.get(&entry.parent)
.map(|parent| parent.uid.clone())
})
.ok_or_else(|| CoreError::invalid("the mount root cannot be mutated"))
}
/// Classify a failure that arrived as an `Errno`.
///
/// The internal paths speak `Errno` because they also serve FUSE, where a
/// number is the whole vocabulary. Everything crossing the control socket
/// has to be turned back into something a person can read, and this is the
/// one place that knows how — a call site holding only an `Errno` has
/// already lost the context needed to say what went wrong.
///
/// `Errno` is neither `PartialEq` nor structural-match, so this compares
/// raw codes rather than the `libc` constants.
pub(super) fn errno_error(&self, e: Errno, what: &str) -> CoreError {
match e.code() {
libc::ENOENT => CoreError::not_found(format!("{what}: no such file or folder")),
libc::EACCES | libc::EPERM => CoreError::denied(format!("{what}: not allowed")),
// 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::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")),
libc::ENOTEMPTY => CoreError::conflict(format!("{what}: folder is not empty")),
_ => CoreError::internal(format!("{what}: {e:?}")),
}
}
/// Fetch a single node's current metadata from the remote.
pub(super) fn fetch_node(&self, uid: &NodeUid) -> Result<Node, Errno> {
match self.fetch_node_remote(uid) {
Ok(Some(node)) => Ok(node),
Ok(None) => Err(Errno::ENOENT),
Err(e) => {
if !self.lost_link(&e, "fetch node") {
error!(%uid, error = %e, "enumerate node failed");
}
Err(Errno::EIO)
}
}
}
/// Read back a node just created on the remote.
///
/// Drive can answer a create before a lookup lists the new node, so an
/// empty answer is asked again for a moment. `None` means the node exists
/// but could not be read back. The mount then queues the create, and the
/// drain finds the node by name and adopts it: the application gets its
/// file or folder either way, never an `ENOENT` for something that exists.
pub(super) fn fetch_minted_node(&self, uid: &NodeUid, name: &str) -> Option<Node> {
// The feed echoes the create. Unclaimed, it would take the echo the
// upload of the file's bytes records, and that one would then evict
// the bytes just uploaded (docs/BUGS.md B123).
self.note_self_change(uid);
let node = self.read_back(uid).ok();
if node.is_none() {
warn!(%uid, name, "Drive made the node but did not hand it back");
}
node
}
/// [`Core::fetch_node`] for a node Drive has just made, asked again for a
/// moment while Drive does not list it yet.
///
/// A file Drive lists without an active revision is not listed yet either:
/// the create commits one before it answers, so this answer is from before
/// the commit, with no size. Taken, it emptied the new file in the tree,
/// and a read of it right after found nothing (`docs/BUGS.md` B163).
pub(crate) fn read_back(&self, uid: &NodeUid) -> Result<Node, Errno> {
let mut delays = MINTED_READ_BACK_DELAYS.iter();
loop {
let fetched = match self.fetch_node(uid) {
Ok(node) if is_unrevised(&node) => Err(Errno::ENOENT),
fetched => fetched,
};
match fetched {
Err(e)
if e == Errno::ENOENT
&& let Some(delay) = delays.next() =>
{
std::thread::sleep(*delay);
}
fetched => return fetched,
}
}
}
/// [`Core::fetch_node`] without the collapse to an `Errno`, for the drain:
/// resolving a conflict turns on *why* a call failed, and "the node is not
/// there" (`Ok(None)`) is a different outcome from "we could not ask".
pub(super) fn fetch_node_remote(&self, uid: &NodeUid) -> Result<Option<Node>, ProtonError> {
match self.block_on_bounded(self.drive.enumerate_nodes(std::slice::from_ref(uid))) {
Ok(nodes) => Ok(nodes.into_iter().next()),
// An unknown uid is reported either as an empty result or as an
// outright refusal, depending on the endpoint.
Err(e) if is_gone(&e) => Ok(None),
Err(e) => Err(e),
}
}
/// Point a handle closed while its file's create landed at the uid Drive
/// gave the node.
///
/// `Core::retire_create` moves the row to that uid before it repoints the
/// open handles. A handle closed in between still named the placeholder,
/// which no row has any more, and its write was refused as if access had
/// changed. The inode is the row's local id, which finds it either way.
pub(crate) fn follow_landed_create(&self, h: &mut WriteHandle) {
if !is_local_uid(&h.uid) {
return;
}
if let Some(real) = self.landed_row_uid(h.ino) {
debug!(local = %h.uid, %real, "write handle closed as its create landed");
h.uid = real;
}
}
/// The uid Drive gave the node at `ino`, once its create has landed, or
/// `None` while it is still queued. Read from the row, which has it before
/// the tree does.
pub(crate) fn landed_row_uid(&self, ino: u64) -> Option<NodeUid> {
state::ino_lid(ino).and_then(|lid| self.landed_lid_uid(lid))
}
/// [`Core::landed_row_uid`] for a node known by its stand-in `uid`.
pub(crate) fn landed_stand_in_uid(&self, uid: &NodeUid) -> Option<NodeUid> {
pdfs_store::db::local_lid(&uid.to_string()).and_then(|lid| self.landed_lid_uid(lid))
}
pub(super) fn landed_lid_uid(&self, lid: i64) -> Option<NodeUid> {
self.db
.uid_of_lid(lid)
.ok()
.flatten()
.and_then(|uid| parse_node_uid(&uid))
.filter(|uid| !is_local_uid(uid))
}
}
+5
View File
@@ -111,6 +111,11 @@ impl Core {
// stale from here on, and the server may not have applied the swap yet.
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,
+184
View File
@@ -0,0 +1,184 @@
//! Search over the tree, the database and the home index.
use super::*;
impl Core {
/// The local locations a search result can be opened through, resolved once
/// per search rather than once per hit.
///
/// An on-demand folder only answers while its mount is live — without the
/// mount its `local_path` is an ordinary empty directory. A mirror folder
/// needs no mount: its files are real local copies the sync loop pushes
/// back, so it is a valid open target whenever it is configured.
///
/// This used to be a per-hit call that re-read the sync-folder list and ran
/// an ancestor walk per folder, against a candidate pool of up to a
/// thousand: the whole cost of a keystroke was in here.
pub(super) fn search_roots(&self) -> SearchRoots {
let live_mounts = self.mounts.lock();
let folders = self.db.sync_folder_list().unwrap_or_default();
SearchRoots {
roots: folders
.into_iter()
.filter(|folder| match folder.mode.as_str() {
"ondemand" => live_mounts.contains_key(&folder.id),
"mirror" => true,
_ => false,
})
.filter_map(|folder| {
let root = self.db.node_path(&folder.remote_uid).ok().flatten()?;
Some((root, PathBuf::from(folder.local_path)))
})
.collect(),
}
}
pub(super) fn search(
&self,
query: &str,
limit: usize,
scope: Option<&str>,
) -> CoreResult<Vec<SearchHit>> {
let hits = self
.db
.search_in(query, limit, scope)
.map_err(|e| CoreError::from_api(&e, "search"))?;
let roots = self.search_roots();
let pinned = self.pinned_set();
Ok(hits
.into_iter()
.map(|h| SearchHit {
name: h.node.name.clone(),
is_dir: h.node.is_folder(),
size: node_size(&h.node),
modified: h.node.modification_time,
pinned: pinned.contains(&h.node.uid.to_string()),
cached: !h.node.is_folder()
&& self.cache.is_cached(
&h.node.uid,
h.node.modification_time,
node_size(&h.node),
),
uid: h.node.uid.to_string(),
mounted_path: roots.resolve(&h.path),
path: h.path,
score: 0,
})
.collect())
}
/// Search the index of files on this machine (outside Drive), built by the
/// background scanner in [`run_local_index`]. Pure local lookup, never hits
/// the network — and never touches the FUSE mount, which the scanner excludes.
pub(super) fn search_local(&self, query: &str, limit: usize) -> CoreResult<Vec<LocalHit>> {
let hits = self
.db
.search_local(query, limit)
.map_err(|e| CoreError::from_api(&e, "local search"))?;
Ok(hits
.into_iter()
.map(|h| LocalHit {
name: h.name,
path: h.path,
is_dir: h.is_dir,
size: h.size.max(0) as u64,
modified: h.mtime,
score: 0,
})
.collect())
}
/// Search both prompt sources with identical query and per-source limits.
/// Keeping the composition in the daemon core gives every control surface
/// the same semantics while preserving the legacy source-specific methods.
pub(super) fn search_v2(
&self,
query: &str,
limit: usize,
filters: &SearchFilters,
) -> CoreResult<(Vec<SearchHit>, Vec<LocalHit>)> {
if query.trim().is_empty() || limit == 0 {
return Ok((Vec::new(), Vec::new()));
}
// Candidate generation is intentionally broader than the final result
// cap: filtering and fuzzy rejection happen below, so limiting at the
// SQLite boundary to `limit` would recreate the old empty-filter bug.
let candidate_limit = limit.saturating_mul(10).clamp(100, 1_000);
let mut drive_hits = if filters.sources.contains(&SearchSource::Drive) {
let roots = self.search_roots();
let pinned = self.pinned_set();
self.db
.search_candidates(query, candidate_limit)
.map_err(|e| CoreError::from_api(&e, "search candidates"))?
.into_iter()
.filter(|hit| filters.kind.accepts(&hit.node.name, hit.node.is_folder()))
.filter_map(|hit| {
let parent = Path::new(&hit.path)
.parent()
.map_or_else(String::new, |path| path.display().to_string());
let uid = hit.node.uid.to_string();
let is_pinned = pinned.contains(&uid);
let score = relevance_score(query, &hit.node.name, &parent)?
+ if is_pinned { 250 } else { 0 };
Some(SearchHit {
name: hit.node.name.clone(),
is_dir: hit.node.is_folder(),
size: node_size(&hit.node),
modified: hit.node.modification_time,
pinned: is_pinned,
cached: !hit.node.is_folder()
&& self.cache.is_cached(
&hit.node.uid,
hit.node.modification_time,
node_size(&hit.node),
),
uid,
mounted_path: roots.resolve(&hit.path),
path: hit.path,
score,
})
})
.collect()
} else {
Vec::new()
};
let mut local_hits = if filters.sources.contains(&SearchSource::Local) {
self.db
.search_local_candidates(query, candidate_limit)
.map_err(|e| CoreError::from_api(&e, "local search candidates"))?
.into_iter()
.filter(|hit| filters.kind.accepts(&hit.name, hit.is_dir))
.filter_map(|hit| {
let parent = Path::new(&hit.path)
.parent()
.map_or_else(String::new, |path| path.display().to_string());
Some(LocalHit {
score: relevance_score(query, &hit.name, &parent)?,
name: hit.name,
path: hit.path,
is_dir: hit.is_dir,
size: hit.size.max(0) as u64,
modified: hit.mtime,
})
})
.collect()
} else {
Vec::new()
};
drive_hits.sort_by(|a, b| {
b.score
.cmp(&a.score)
.then_with(|| a.name.cmp(&b.name))
.then_with(|| a.path.cmp(&b.path))
});
local_hits.sort_by(|a, b| {
b.score
.cmp(&a.score)
.then_with(|| a.name.cmp(&b.name))
.then_with(|| a.path.cmp(&b.path))
});
drive_hits.truncate(limit);
local_hits.truncate(limit);
Ok((drive_hits, local_hits))
}
}
+243
View File
@@ -0,0 +1,243 @@
//! The mounted shared tree's listing: the synthetic root, when its folders
//! are listed again, and what invalidates a listing on the wire.
use super::*;
/// Publication of the shared listing, and what invalidates a listing on the
/// wire or suppresses its next refresh.
#[derive(Clone)]
pub(crate) struct SharedState {
/// Serializes only shared-list publication and access-loss invalidation.
/// Network calls happen before taking it.
pub(crate) shared_publication: Arc<Ranked<()>>,
/// Invalidates in-flight shared responses when access/list events arrive.
pub(crate) shared_generation: Arc<AtomicU64>,
/// Successful refreshes suppress retries even if persisting their timestamp
/// fails. Shared across primary/fork clones and cleared by access events.
pub(crate) shared_refresh_deadlines: Arc<Mutex<SharedRefreshDeadlines>>,
}
impl SharedState {
pub(crate) fn new() -> Self {
Self {
shared_publication: Arc::new(Ranked::new(Rank::SharedPublication, ())),
shared_generation: Arc::new(AtomicU64::new(0)),
shared_refresh_deadlines: Arc::new(Mutex::new(SharedRefreshDeadlines::default())),
}
}
}
impl Core {
/// Read the inputs for virtual-root publication without changing SQLite.
///
/// The caller validates the listing snapshot after these reads. Keeping all
/// writes out of this phase prevents an invalidated/repopulated root listing
/// from changing the synthetic node's persisted visibility or FTS ancestry.
pub(super) fn prepare_virtual_root(
&self,
real_names: &HashSet<String>,
) -> Result<VirtualRootPlan, Errno> {
let pinned = self.db.state_str(SHARED_WITH_ME_NAME).map_err(|error| {
error!(%error, "reading shared-root display name failed");
Errno::EIO
})?;
let (name, visible) = virtual_root_name(real_names, pinned.as_deref());
let uid = shared_with_me_uid();
let previous_node = self.db.node_by_uid(&uid.to_string()).map_err(|error| {
error!(%error, "reading synthetic shared root failed");
Errno::EIO
})?;
let mut node = previous_node.unwrap_or_else(|| {
virtual_node(self.primary_root_uid.clone(), name.clone(), now_secs())
});
node.parent_uid = Some(self.primary_root_uid.clone());
node.name = name;
node.kind = NodeKind::Folder;
// A later real-name collision suppresses both the dentry and its search
// hit. The row and pinned name remain, and clearing the collision
// restores both by writing `trashed = false` again.
node.trashed = !visible;
node.membership = None;
Ok(VirtualRootPlan { node, visible })
}
/// Reconcile the synthetic dentry against an already-known primary-root
/// listing. The node remains persisted and pinned even while a real folder
/// of the same name temporarily suppresses its dentry.
pub(super) fn reconcile_virtual_root_dentry(
&self,
parent_ino: u64,
snapshot: RootListingSnapshot,
) -> Result<(), Errno> {
let _publication = self.shared.shared_publication.lock();
let plan = self.prepare_virtual_root(&snapshot.real_names())?;
let mut st = self.state();
// State methods already establish the state -> DB lock order. No path
// holds the DB connection while acquiring state, including shared event
// publication, so keeping state locked across this one transaction
// closes the crash window without introducing an inverse order.
publish_virtual_root_in_listing(&self.db, &mut st, parent_ino, &snapshot, plan)?;
drop(st);
self.flush_access_changes();
Ok(())
}
pub(super) fn resident_root_listing_snapshot(
&self,
ino: u64,
) -> Result<RootListingSnapshot, Errno> {
RootListingSnapshot::capture(&self.state(), ino).ok_or(Errno::EAGAIN)
}
pub(super) fn shared_folder_freshness_key(uid: &NodeUid) -> String {
format!("{SHARED_FOLDER_SYNCED_PREFIX}{uid}")
}
pub(super) fn shared_listing_stale(&self, key: &str) -> bool {
if self
.shared
.shared_refresh_deadlines
.lock()
.is_fresh(key, Instant::now())
{
return false;
}
self.listing_stale(key, SHARED_LISTING_TTL)
}
pub(super) fn mark_shared_refresh_success(&self, key: &str) {
self.shared
.shared_refresh_deadlines
.lock()
.mark(key, Instant::now(), SHARED_LISTING_TTL);
if let Err(error) = self.db.set_state_i64(key, now_millis()) {
warn!(key, %error, "persisting shared-list freshness failed");
}
}
pub(super) fn invalidate_shared_refreshes(&self) {
self.shared.shared_generation.fetch_add(1, Ordering::SeqCst);
self.shared.shared_refresh_deadlines.lock().clear();
}
pub(super) fn ensure_shared_children(&self, ino: u64) -> Result<(), Errno> {
let online = self.online.load(Ordering::Relaxed);
let resident = self.state().children.contains_key(&ino);
match shared_listing_plan(
resident,
online,
self.shared_listing_stale(SHARED_WITH_ME_SYNCED_MS),
) {
SharedListingPlan::Resident => return Ok(()),
SharedListingPlan::Persisted => {
// A completed snapshot remains useful offline even after an
// event expired its freshness stamp.
let nodes = self
.db
.visible_children(&shared_with_me_uid())
.map_err(|error| {
error!(%error, "loading persisted shared roots failed");
Errno::EIO
})?;
let mut st = self.state();
if st.children.contains_key(&ino) {
return Ok(());
}
let children = nodes
.into_iter()
.map(|node| {
let access = st
.share_access
.get(&node.uid)
.copied()
.unwrap_or(Access::Viewer);
st.intern_published_share_root(ino, node, access)
})
.collect();
st.children.insert(ino, children);
drop(st);
self.flush_access_changes();
return Ok(());
}
SharedListingPlan::Refresh => {}
}
let generation = self.shared.shared_generation.load(Ordering::SeqCst);
let accepted = accepted_share_provenance(
self.block_on_within(BATCH_CALL_TIMEOUT, self.client.enumerate_shared_with_me())
.map_err(|error| {
error!(%error, "enumerating shared roots failed");
Errno::EIO
})?,
);
let nodes = if accepted.uids.is_empty() {
Vec::new()
} else {
self.block_on_within(
BATCH_CALL_TIMEOUT,
self.drive.enumerate_nodes_light(&accepted.uids),
)
.map_err(|error| {
error!(%error, "materializing shared roots failed");
Errno::EIO
})?
};
let virtual_uid = shared_with_me_uid();
let published = prepare_shared_roots(&accepted, nodes, &virtual_uid);
let _publication = self.shared.shared_publication.lock();
if !refresh_generation_is_current(
generation,
self.shared.shared_generation.load(Ordering::SeqCst),
) {
return Err(Errno::EAGAIN);
}
let removed = match self
.db
.publish_shared_roots(&virtual_uid, &accepted.uids, &published)
{
Ok(removed) => removed,
Err(error) => {
error!(%error, "publishing shared-root listing failed");
let mut st = self.state();
for uid in &accepted.uids {
st.downgrade_shared_subtree(uid);
}
drop(st);
self.flush_access_changes();
return Err(Errno::EIO);
}
};
let snapshot = self.db.visible_children(&virtual_uid).map_err(|error| {
error!(%error, "loading published shared-root listing failed");
Errno::EIO
})?;
let published_access: HashMap<NodeUid, Access> = published
.iter()
.map(|root| (root.node.uid.clone(), root.access))
.collect();
let mut st = self.state();
for uid in &removed {
st.hide_shared_root(uid);
}
let mut children = Vec::with_capacity(snapshot.len());
for node in snapshot {
let uid = node.uid.clone();
let access = published_access
.get(&uid)
.copied()
.unwrap_or(Access::Viewer);
let child = st.intern_published_share_root(ino, node, access);
children.push(child);
}
st.children.insert(ino, children);
drop(st);
self.flush_access_changes();
self.mark_shared_refresh_success(SHARED_WITH_ME_SYNCED_MS);
if let Some(notifier) = self.notifier.get() {
let _ = notifier.inval_inode(ino);
}
Ok(())
}
}
+51 -12
View File
@@ -7,6 +7,10 @@
//! 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,
@@ -24,6 +28,32 @@ use proton_drive_rs::Node;
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.
#[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>,
}
impl QuotaCache {
pub(crate) fn new() -> Self {
Self {
quota: Arc::new(Mutex::new(None)),
quota_refreshing: Arc::new(AtomicBool::new(false)),
}
}
}
/// A node from a *shared* listing as a [`DirEntry`].
///
/// Still uid-addressed — that is the only handle a foreign-volume node is
@@ -77,6 +107,7 @@ fn shared_entry_of(core: &Core, n: Node) -> DirEntry {
shared_by_unverified,
trashed_at: 0,
trashed_from: None,
trashed_parent: None,
issue: None,
}
}
@@ -105,7 +136,7 @@ impl Core {
role: &str,
message: Option<&str>,
) -> CoreResult<(usize, usize)> {
let uid = self.resolve_anywhere(uid)?;
let uid = self.resolve_shareable(uid)?;
self.share_node_for_uid(&uid, emails, role, message)
}
@@ -138,7 +169,7 @@ impl Core {
&self,
uid: &str,
) -> CoreResult<(Vec<ShareEntry>, Option<PublicLinkInfo>)> {
let uid = self.resolve_anywhere(uid)?;
let uid = self.resolve_shareable(uid)?;
self.list_share_for_uid(&uid)
}
@@ -215,7 +246,7 @@ impl Core {
kind: ShareEntryKind,
role: &str,
) -> CoreResult<()> {
let uid = self.resolve_anywhere(uid)?;
let uid = self.resolve_shareable(uid)?;
self.update_share_role_for_uid(&uid, id, kind, role)
}
@@ -278,7 +309,7 @@ impl Core {
id: &str,
kind: ShareEntryKind,
) -> CoreResult<()> {
let uid = self.resolve_anywhere(uid)?;
let uid = self.resolve_shareable(uid)?;
self.remove_share_entry_for_uid(&uid, id, kind)
}
@@ -349,7 +380,7 @@ impl Core {
password: Option<&str>,
expires: Option<i64>,
) -> CoreResult<PublicLinkInfo> {
let uid = self.resolve_anywhere(uid)?;
let uid = self.resolve_shareable(uid)?;
self.create_public_link_for_uid(&uid, role, password, expires)
}
@@ -391,7 +422,7 @@ impl Core {
password: LinkChange<String>,
expires: LinkChange<i64>,
) -> CoreResult<PublicLinkInfo> {
let uid = self.resolve_anywhere(uid)?;
let uid = self.resolve_shareable(uid)?;
self.update_public_link_for_uid(&uid, id, role, password, expires)
}
@@ -460,7 +491,7 @@ impl Core {
/// [`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_anywhere(uid)?;
let uid = self.resolve_shareable(uid)?;
self.remove_public_link_for_uid(&uid, id)
}
@@ -486,7 +517,7 @@ impl Core {
/// [`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_anywhere(uid)?;
let uid = self.resolve_shareable(uid)?;
self.stop_sharing_for_uid(&uid)
}
@@ -700,7 +731,8 @@ impl Core {
self.lost_link(&e, "account quota");
CoreError::from_api(&e, "account quota")
})?;
*self.quota.lock() = Some((std::time::Instant::now(), q.max_space, q.used_space));
*self.quota_cache.quota.lock() =
Some((std::time::Instant::now(), q.max_space, q.used_space));
Ok((q.max_space, q.used_space))
}
@@ -713,21 +745,28 @@ impl Core {
/// 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.lock()
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.lock().map(|(_, max, used)| (max, used));
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_refreshing
self.quota_cache
.quota_refreshing
.store(false, std::sync::atomic::Ordering::Release);
match refreshed {
Ok(q) => Some(q),
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -2,8 +2,8 @@
//! the faults the real one has, and the tools to drive daemons against it.
pub(crate) mod daemon;
pub(crate) mod fake_drive;
pub(crate) use pdfs_drive::sim::fake_drive;
pub(crate) mod model;
pub(crate) mod rng;
pub(crate) use pdfs_drive::sim::rng;
pub(crate) mod run;
pub(crate) mod watchdog;
Loaded 100 of 262 files, more files were not shown because too many files have changed in this diff. Show more