Compare commits

...
Author SHA1 Message Date
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 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
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
138 changed files with 18376 additions and 10978 deletions

No files matched your search

+1 -1
View File
@@ -48,7 +48,7 @@ runs are destructive: use a dedicated test account, never one holding data you c
- **Keep shared logic in `pdfs-core`.** The CLI and GUI never touch the database or the network;
they speak the control protocol to the daemon.
- **The SQLite schema is forward-only.** Never edit a shipped migration — add a new one and bump
`SCHEMA_VERSION` in `crates/pdfs-core/src/db/migrations.rs`.
`SCHEMA_VERSION` in `crates/pdfs-store/src/db/migrations.rs`.
- **Typed errors and `?` over panics** on runtime paths. Blocking filesystem, keyring, or
control-socket work stays off GTK's main thread.
- **`staging/` and `recovery/` may hold the only copy of user data.** Nothing may clear or purge
Generated
+50
View File
@@ -3641,6 +3641,7 @@ dependencies = [
"clap_complete",
"pdfs-core",
"pdfs-fuse",
"pdfs-store",
"rpassword",
"serde_json",
"tokio",
@@ -3679,6 +3680,21 @@ dependencies = [
"zeroize",
]
[[package]]
name = "pdfs-drive"
version = "3.10.0"
dependencies = [
"async-trait",
"futures",
"parking_lot 0.13.0",
"pdfs-core",
"pdfs-store",
"proton-drive-rs",
"sha1 0.11.0",
"tokio",
"tracing",
]
[[package]]
name = "pdfs-fuse"
version = "3.10.0"
@@ -3697,6 +3713,9 @@ dependencies = [
"notify",
"parking_lot 0.13.0",
"pdfs-core",
"pdfs-drive",
"pdfs-store",
"pdfs-sync",
"proton-drive-rs",
"proton-gallery-app-rs",
"proton-gallery-rs",
@@ -3737,6 +3756,37 @@ dependencies = [
"webkit6",
]
[[package]]
name = "pdfs-store"
version = "3.10.0"
dependencies = [
"libc",
"parking_lot 0.13.0",
"pdfs-core",
"proton-drive-rs",
"proton-gallery-rs",
"rusqlite",
"serde",
"serde_json",
"sha2 0.11.1",
"tracing",
]
[[package]]
name = "pdfs-sync"
version = "3.10.0"
dependencies = [
"notify",
"parking_lot 0.13.0",
"pdfs-core",
"pdfs-drive",
"pdfs-store",
"proton-drive-rs",
"sha1 0.11.0",
"tokio",
"tracing",
]
[[package]]
name = "pem-rfc7468"
version = "0.7.0"
+4 -1
View File
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["crates/pdfs-core", "crates/pdfs-fuse", "crates/pdfs-cli", "crates/pdfs-gui"]
members = ["crates/pdfs-core", "crates/pdfs-store", "crates/pdfs-drive", "crates/pdfs-sync", "crates/pdfs-fuse", "crates/pdfs-cli", "crates/pdfs-gui"]
[workspace.package]
version = "3.10.0"
@@ -24,6 +24,9 @@ chrono = { version = "0.4", default-features = false, features = ["std"] }
# Internal crates.
pdfs-core = { path = "crates/pdfs-core" }
pdfs-store = { path = "crates/pdfs-store" }
pdfs-drive = { path = "crates/pdfs-drive" }
pdfs-sync = { path = "crates/pdfs-sync" }
pdfs-fuse = { path = "crates/pdfs-fuse" }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "fs", "io-util", "time", "signal"] }
+1
View File
@@ -15,6 +15,7 @@ path = "src/main.rs"
[dependencies]
pdfs-core.workspace = true
pdfs-store.workspace = true
pdfs-fuse.workspace = true
tokio.workspace = true
anyhow.workspace = true
+1 -1
View File
@@ -129,7 +129,7 @@ fn cache_file(key: &str) -> Option<PathBuf> {
let runtime = PathBuf::from(std::env::var_os("XDG_RUNTIME_DIR")?);
Some(
runtime
.join("proton-drive-linux")
.join(pdfs_core::config::app_dir_name())
.join(format!("completion-{key}.json")),
)
}
+140 -30
View File
@@ -11,15 +11,15 @@ use anyhow::{Context, Result, anyhow, bail};
use clap::{Parser, Subcommand, ValueHint};
use clap_complete::engine::{ArgValueCandidates, ArgValueCompleter};
use pdfs_core::auth;
use pdfs_core::cache::ContentCache;
use pdfs_core::config::AppDirs;
use pdfs_core::control::{
ConflictKeep, ErrorKind, LinkChange, MountKind, RefreshScope, Request as CtlRequest,
Response as CtlResponse, RestoreItem as CtlRestoreItem, ShareEntryKind, SyncFolderInfo,
SyncIssue, SyncPhase, daemon_outdated, pending_summary,
};
use pdfs_core::db::Db;
use pdfs_core::service;
use pdfs_store::cache::ContentCache;
use pdfs_store::db::Db;
mod complete;
mod journal;
@@ -1035,7 +1035,11 @@ fn cli_error(kind: ErrorKind, message: &str) -> String {
}
fn main() -> Result<()> {
// First: a completion request answers on stdout and exits, so nothing may
// A bad `PDFS_INSTANCE` is refused before anything reads a path or the
// keyring; falling back to the default instance would touch the user's
// own account.
pdfs_core::config::check_instance()?;
// Next: a completion request answers on stdout and exits, so nothing may
// write there before it.
complete::handle_request();
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
@@ -2273,22 +2277,7 @@ fn cmd_login(username: Option<String>, remember: bool) -> Result<()> {
get_mailbox,
get_hv,
))
.map_err(|e| {
// Proton words this block as "update the app", which the user can't
// act on: the release is current and only waiting helps.
let blocked =
matches!(&e, pdfs_core::Error::Proton(p) if pdfs_core::error::sign_in_blocked(p));
let e = anyhow::Error::new(e).context("login failed");
if blocked {
e.context(
"Proton is temporarily refusing sign-in from this device (code 2028). \
Your version is not the problem. Wait several hours, up to a day, \
without trying again, then sign in.",
)
} else {
e
}
})?;
.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
@@ -2304,6 +2293,18 @@ fn cmd_login(username: Option<String>, remember: bool) -> Result<()> {
Ok(())
}
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.
fn prompt_mailbox(attempt: u32, remember: bool) -> pdfs_core::Result<auth::Mailbox> {
if attempt == 0 {
@@ -2688,18 +2689,26 @@ fn cmd_daemon(mountpoint: Option<PathBuf>) -> Result<()> {
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_delay(attempts);
tracing::error!(
error,
attempts,
retry_secs = delay.as_secs(),
"mount failed; retrying"
);
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.as_secs() as i64,
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) {
@@ -2707,7 +2716,12 @@ fn cmd_daemon(mountpoint: Option<PathBuf>) -> Result<()> {
}
pdfs_fuse::notify_status(&format!("Mount failing: {error}"));
failure = Some(record);
pdfs_fuse::idle_sleep(delay);
// 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"),
}
}
}
}
@@ -2730,6 +2744,20 @@ fn not_empty_cause(error: &anyhow::Error) -> Option<pdfs_core::mountpoint::NotEm
})
}
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.
///
@@ -3582,7 +3610,8 @@ fn cmd_diagnostics() -> Result<()> {
"uptime {} rss {} pending ops {}",
human_secs(d.uptime_secs),
human_bytes(d.rss_bytes),
d.pending_ops,
d.pending_ops
.map_or_else(|| "unknown (database busy)".to_owned(), |n| n.to_string()),
);
println!(
"control handlers {}/{}",
@@ -3606,8 +3635,46 @@ fn cmd_diagnostics() -> Result<()> {
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");
@@ -4631,7 +4698,11 @@ fn cmd_diagnose() -> Result<()> {
"failing for {}, {} attempt(s): {}",
human_secs(unix_now().saturating_sub(failure.since).max(0) as u64),
failure.attempts,
failure.error
if failure.awaiting_keys {
format!("{} — after recovering your account keys, restart proton-drive.service", failure.error)
} else {
failure.error
}
),
),
None => println!(
@@ -4884,6 +4955,25 @@ mod diagnose_tests {
mod login_wait_tests {
use super::*;
#[test]
fn login_failure_preserves_only_actionable_upgrade_advice() {
use pdfs_core::proton_sdk::{ProtonApiError, ProtonError, api::ResponseCode};
for (code, blocked) in [
(ResponseCode::Blocked, true),
(ResponseCode::OutdatedApp, false),
] {
let error = ProtonError::Api(ProtonApiError {
code,
http_status: 422,
message: "Please update the app".into(),
details: None,
});
let rendered = format!("{:#}", login_failure(error.into()));
assert_eq!(rendered.contains("2028"), blocked);
assert_eq!(rendered.contains("Please update"), !blocked);
}
}
/// 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]
@@ -4893,6 +4983,26 @@ mod login_wait_tests {
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]
+3 -3
View File
@@ -26,8 +26,8 @@ use std::sync::Arc;
use std::time::Duration;
use chrono::{Datelike, Local, TimeZone};
use pdfs_core::cache::Pin;
use pdfs_core::config::{AppDirs, KEYRING_SERVICE};
use pdfs_core::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,
@@ -108,7 +108,7 @@ fn seed_keyring() -> Result<(), String> {
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(KEYRING_SERVICE, "session")
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())
}
+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),
+9 -6
View File
@@ -42,7 +42,7 @@ 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;
@@ -141,12 +141,15 @@ fn keyring() -> &'static KeyringStore {
STORE.get_or_init(|| {
#[cfg(not(test))]
{
KeyringStore::new(KEYRING_SERVICE)
KeyringStore::new(crate::config::keyring_service())
}
#[cfg(test)]
{
KeyringStore::with_connector(KEYRING_SERVICE, Arc::new(tests::connect_keyring_store))
.replace_items(|| tests::MOCK_STORE.lock().is_none())
KeyringStore::with_connector(
crate::config::KEYRING_SERVICE,
Arc::new(tests::connect_keyring_store),
)
.replace_items(|| tests::MOCK_STORE.lock().is_none())
}
})
}
@@ -1273,7 +1276,7 @@ mod tests {
/// The session's entry, to make its next call fail.
fn keyring_entry() -> Entry {
Entry::new(KEYRING_SERVICE, KEYRING_USER).unwrap()
Entry::new(crate::config::KEYRING_SERVICE, KEYRING_USER).unwrap()
}
/// Make the session entry's next call fail with `error`.
@@ -1420,7 +1423,7 @@ mod tests {
.unwrap();
let found = ss
.search_items(std::collections::HashMap::from([
("service", KEYRING_SERVICE),
("service", crate::config::KEYRING_SERVICE),
("username", KEYRING_USER),
]))
.unwrap();
+117 -6
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
@@ -526,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 })
}
@@ -659,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
@@ -762,6 +848,31 @@ 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]
+178 -4
View File
@@ -12,10 +12,37 @@ use std::time::Duration;
use serde::{Deserialize, Serialize};
use crate::cache::Pin;
use crate::error::Result;
pub use crate::mounts::{MountAccess, MountKind, MountMode, MountSpec};
/// One pin, as carried over the control socket and listed in `status`.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Pin {
/// Node uid in `volume~link` display form.
pub uid: String,
/// Last path the node was pinned under, for display in `status`. Advisory
/// only — the uid is the identity.
pub path: String,
/// A folder pin whose whole subtree is kept on disk. `false` for a single
/// file. Defaulted so a legacy `pins.json` (file pins only) still parses.
#[serde(default)]
pub recursive: bool,
/// Whether the pinned node is a folder, when the node cache knows.
///
/// `recursive` is pin *policy*, not node kind: a folder pinned
/// non-recursively has `recursive: false`, and a front-end reading it as
/// "this is a file" draws a file icon and sends an invalid `OpenFile`. This
/// is resolved from the `nodes` row at list time, so it is `None` for a pin
/// whose node is not cached — and absent from an older daemon's reply,
/// which is why it is defaulted.
#[serde(default)]
pub is_dir: Option<bool>,
/// A pinned file whose content is on disk right now. The daemon fills it
/// in when it answers `ListPins`; folders and older daemons say `false`.
#[serde(default)]
pub cached: bool,
}
/// Cap on the *write* half of a round-trip. A crashed daemon can leave its
/// listening socket in the kernel (e.g. as a `<defunct>` zombie): `connect`
/// then succeeds but no one ever replies. A short write bound trips fast when
@@ -2335,11 +2362,45 @@ pub struct Diagnostics {
/// from the CLI.
pub control_handlers: usize,
pub control_handler_limit: usize,
/// Queued mutations not yet drained.
pub pending_ops: u64,
/// Queued mutations not yet drained. `None` when the database did not
/// answer in time, which is itself the thing to look at.
#[serde(default)]
pub pending_ops: Option<u64>,
/// The folder-sync engine. `None` from a daemon that predates the field.
#[serde(default)]
pub sync: Option<SyncEngineState>,
/// Every kind of call made to Drive since start: how many, how many
/// failed, and how long they took. Empty from a daemon that predates the
/// field.
#[serde(default)]
pub drive_calls: Vec<DriveCallStat>,
/// The daemon's long-lived threads, in start order, and whether each is
/// still running. Empty from a daemon that predates the field.
#[serde(default)]
pub services: Vec<ServiceState>,
}
/// One long-lived daemon thread, in [`Diagnostics::services`].
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct ServiceState {
/// The thread's name, such as `pdfs-sync`.
pub name: String,
/// `false` once the thread has ended, by return or by panic. Every service
/// runs until the mount stops, so one that ended early is a fault.
pub running: bool,
/// How long ago the thread was started.
pub age_secs: u64,
}
/// One kind of call to Drive, in [`Diagnostics::drive_calls`].
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct DriveCallStat {
/// The client method, such as `enumerate_folder_children_node_uids`.
pub call: String,
pub count: u64,
pub errors: u64,
pub total_ms: u64,
pub longest_ms: u64,
}
/// What the folder-sync engine is doing, for [`Diagnostics`].
@@ -2360,6 +2421,111 @@ pub struct SyncEngineState {
pub pass_idle_secs: u64,
/// Passes that ended in a panic since the daemon started.
pub panics: u64,
/// Where the running pass, and the last pass over each folder, spent their
/// time. Empty from a daemon that predates the field.
#[serde(default)]
pub traces: Vec<SyncPassTrace>,
}
/// Where one sync pass spent its time, in a [`SyncEngineState`].
///
/// A pass over a large folder used to say only that it started and, hours
/// later, that it was cut short. Nothing said whether the hours went into the
/// local walk, listing Drive, unlocking node keys or uploading
/// (`docs/BUGS.md` B294).
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct SyncPassTrace {
pub folder_id: i64,
/// How the pass ended: `finished`, `cut short`, `abandoned`, `failed` or
/// `panicked`. Empty while it is still running.
pub ended: String,
/// How long the pass ran, or has run so far.
pub elapsed_ms: u64,
/// The stages of the pass, in order.
pub phases: Vec<SyncTraceStat>,
/// Calls to Drive, and the work applied per kind.
pub calls: Vec<SyncTraceStat>,
/// How many items each stage handled.
pub counts: Vec<SyncTraceCount>,
/// The folder on Drive whose listing took longest, and how long, in ms.
pub slowest_listing: Option<(String, u64)>,
}
/// One line for the journal and `pdfs diagnostics`: `remote walk 2h10m,
/// local walk 41m05s; read nodes full 480000x/1h50m (max 3.0s); nodes full
/// 480000; slowest listing "a/b" 9.0s`. Stages and calls that never happened
/// are left out.
impl std::fmt::Display for SyncPassTrace {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut parts = Vec::new();
let phases: Vec<String> = self
.phases
.iter()
.map(|s| format!("{} {}", s.name, human_ms(s.total_ms)))
.collect();
if !phases.is_empty() {
parts.push(phases.join(", "));
}
let calls: Vec<String> = self
.calls
.iter()
.map(|s| {
format!(
"{} {}x/{} (max {})",
s.name,
s.count,
human_ms(s.total_ms),
human_ms(s.max_ms)
)
})
.collect();
if !calls.is_empty() {
parts.push(calls.join(", "));
}
let counts: Vec<String> = self
.counts
.iter()
.map(|c| format!("{} {}", c.name, c.value))
.collect();
if !counts.is_empty() {
parts.push(counts.join(", "));
}
if let Some((rel, ms)) = &self.slowest_listing {
let rel = if rel.is_empty() { "/" } else { rel.as_str() };
parts.push(format!("slowest listing {rel:?} {}", human_ms(*ms)));
}
f.write_str(&parts.join("; "))
}
}
/// `950ms`, `12.3s`, `41m05s`, `2h10m`.
fn human_ms(ms: u64) -> String {
let secs = ms / 1000;
if ms < 1000 {
format!("{ms}ms")
} else if secs < 60 {
format!("{:.1}s", ms as f64 / 1000.0)
} else if secs < 3600 {
format!("{}m{:02}s", secs / 60, secs % 60)
} else {
format!("{}h{:02}m", secs / 3600, (secs % 3600) / 60)
}
}
/// How often one thing happened in a pass, and how long it took.
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct SyncTraceStat {
pub name: String,
pub count: u64,
pub total_ms: u64,
pub max_ms: u64,
}
/// One counter of a [`SyncPassTrace`].
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct SyncTraceCount {
pub name: String,
pub value: u64,
}
/// The daemon's reply to a [`Request`].
@@ -2372,7 +2538,7 @@ pub enum Response {
username: String,
mountpoint: String,
pinned: usize,
/// Bytes of cached content blobs (see [`crate::cache::ContentCache::usage`]).
/// Bytes of cached content blobs (see `pdfs_store::cache::ContentCache::usage`).
used: u64,
/// Configured soft byte cap (`0` = unlimited).
budget: u64,
@@ -3003,6 +3169,14 @@ fn poll_legacy(socket: &Path, on: &mut impl FnMut(Feed) -> bool) -> bool {
mod tests {
use super::*;
#[test]
fn durations_in_a_trace_read_at_a_glance() {
assert_eq!(human_ms(950), "950ms");
assert_eq!(human_ms(12_345), "12.3s");
assert_eq!(human_ms(2_465_000), "41m05s");
assert_eq!(human_ms(7_800_000), "2h10m");
}
#[test]
fn polls_wait_briefly_and_real_work_waits_long() {
assert_eq!(Request::Status.read_timeout(), POLL_READ_TIMEOUT);
-403
View File
@@ -1,403 +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,
/// `device` backup or `attached` My files mirror.
pub kind: String,
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> {
self.sync_folder_insert(local_path, remote_uid, remote_share_id, "device")
}
/// Attach an existing My files folder, without creating a device backup.
pub fn sync_folder_attach(
&self,
local_path: &str,
remote_uid: &str,
remote_share_id: &str,
) -> Result<i64> {
self.sync_folder_insert(local_path, remote_uid, remote_share_id, "attached")
}
fn sync_folder_insert(
&self,
local_path: &str,
remote_uid: &str,
remote_share_id: &str,
kind: &str,
) -> Result<i64> {
let conn = self.conn.lock();
conn.execute(
"INSERT INTO sync_folder (local_path, remote_uid, remote_share_id, kind)
VALUES (?1, ?2, ?3, ?4)",
params![local_path, remote_uid, remote_share_id, kind],
)?;
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, kind
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)?,
kind: r.get(8)?,
})
})?;
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, kind
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)?,
kind: r.get(8)?,
})
},
)
.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(())
}
}
+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.
+4 -2
View File
@@ -5,14 +5,14 @@
pub mod access;
pub mod auth;
pub mod batch;
pub mod cache;
pub mod config;
pub mod control;
pub mod db;
pub mod error;
pub mod kernelkey;
pub mod keycheck;
pub mod lifecycle;
pub mod localindex;
pub mod lockrank;
pub mod menu;
pub mod mountfail;
pub mod mountpoint;
@@ -23,9 +23,11 @@ pub mod sdkcache;
pub mod search;
pub mod service;
pub mod shell;
pub mod shutdown;
pub mod syncignore;
pub mod syncroot;
pub mod timestamp;
pub mod transfers;
pub mod tray;
pub mod update;
+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");
}
}
+79 -1
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,14 @@ 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.
@@ -68,6 +93,7 @@ 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();
@@ -81,7 +107,59 @@ mod tests {
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()
);
}
}
+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);
+1 -1
View File
@@ -526,7 +526,7 @@ mod tests {
use super::*;
/// A unique temp directory removed on drop; avoids a dev-dependency, as in
/// [`crate::cache`]'s tests.
/// `pdfs_store::cache`'s tests.
struct TempDir(std::path::PathBuf);
impl TempDir {
fn new() -> Self {
+11 -1
View File
@@ -1,7 +1,17 @@
//! Convert the client's stored epoch seconds at the SDK boundary.
//! 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())
@@ -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();
+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,22 +25,26 @@ 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, ShareId};
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, ThumbnailType, TrashedNode,
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>;
@@ -210,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,
@@ -242,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,
@@ -266,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,
@@ -284,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,
@@ -292,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,
@@ -305,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;
@@ -575,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;
@@ -67,10 +67,10 @@ use proton_drive_rs::{
use sha1::{Digest as _, Sha1};
use super::rng::Rng;
use crate::drive::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
/// The volume every fake node lives on.
pub(crate) const VOLUME: &str = "simvol";
pub const VOLUME: &str = "simvol";
/// How long superseded versions of a node are kept for lagging reads. Longer
/// than any lag a test sets.
@@ -350,19 +350,19 @@ impl Server {
/// An in-memory Drive shared by every simulated client. See the module
/// documentation.
pub(crate) struct FakeDrive {
pub struct FakeDrive {
server: Mutex<Server>,
}
/// A node of [`FakeDrive::tree`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Entry {
pub enum Entry {
Folder,
File(Arc<Vec<u8>>),
}
impl FakeDrive {
pub(crate) fn new() -> Arc<Self> {
pub fn new() -> Arc<Self> {
let root = uid("root");
let mut server = Server {
root: root.clone(),
@@ -370,7 +370,7 @@ impl FakeDrive {
next_link: 0,
next_revision: 0,
events: Vec::new(),
block_pattern: vec![pdfs_core::cache::BLOCK_SIZE],
block_pattern: vec![pdfs_store::cache::BLOCK_SIZE],
max_space: 1 << 40,
devices: Vec::new(),
};
@@ -395,7 +395,7 @@ impl FakeDrive {
}
/// A connection to this Drive for one simulated daemon.
pub(crate) fn client(self: &Arc<Self>, seed: u64, faults: Faults) -> FakeClient {
pub fn client(self: &Arc<Self>, seed: u64, faults: Faults) -> FakeClient {
FakeClient(Arc::new(ClientInner {
drive: self.clone(),
faults: Mutex::new(faults),
@@ -420,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() {
@@ -482,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
@@ -498,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()) {
@@ -508,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
@@ -558,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");
@@ -568,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)
@@ -590,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,
@@ -635,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),
@@ -646,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,
@@ -657,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),
@@ -719,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 {
@@ -758,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)
}
}
@@ -776,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),
@@ -814,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),
@@ -824,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),
@@ -839,16 +880,16 @@ impl FakeClient {
/// Hold the next download of `uid`'s content once Drive has answered it,
/// before the bytes reach the daemon, until the answer is dropped.
/// Give `uid` a server thumbnail, as an upload that carried one would.
pub(crate) fn set_thumbnail(&self, uid: &NodeUid, bytes: Vec<u8>) {
pub fn set_thumbnail(&self, uid: &NodeUid, bytes: Vec<u8>) {
self.0.thumbnails.lock().insert(uid.clone(), bytes);
}
/// File content bytes served so far, by whole downloads and ranged reads.
pub(crate) fn content_read(&self) -> u64 {
pub fn content_read(&self) -> u64 {
self.0.content_read.load(Ordering::SeqCst)
}
pub(crate) fn hold_next_download(&self, uid: &NodeUid) -> Held {
pub fn hold_next_download(&self, uid: &NodeUid) -> Held {
let state = Arc::new(HoldState {
uid: uid.clone(),
reached: AtomicBool::new(false),
@@ -861,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),
@@ -873,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
@@ -881,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),
@@ -893,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),
@@ -904,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),
@@ -953,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)
}
@@ -1260,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();
@@ -1806,7 +1845,7 @@ impl RevisionRead for FakeRevision {
}
/// A uid on the fake volume.
pub(crate) fn uid(link: &str) -> NodeUid {
pub fn uid(link: &str) -> NodeUid {
NodeUid::new(VolumeId::from(VOLUME), LinkId::from(link))
}
@@ -1886,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,
@@ -1906,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())
}
}
+5
View File
@@ -11,6 +11,9 @@ description = "FUSE on-demand filesystem for Proton Drive"
[dependencies]
pdfs-core.workspace = true
pdfs-drive.workspace = true
pdfs-sync.workspace = true
pdfs-store.workspace = true
zip.workspace = true
sha1.workspace = true
proton-drive-rs.workspace = true
@@ -38,4 +41,6 @@ notify = "8"
parking_lot.workspace = true
[dev-dependencies]
pdfs-drive = { workspace = true, features = ["sim"] }
tracing-subscriber.workspace = true
tokio = { workspace = true, features = ["test-util"] }
+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()
}
}
}
}
+9 -3
View File
@@ -16,8 +16,8 @@ use std::collections::HashSet;
use std::sync::atomic::Ordering;
use pdfs_core::control::{AlbumInfo, PhotoItem, Topic};
use pdfs_core::db::StoredAlbum;
use pdfs_core::{CoreError, CoreResult};
use pdfs_store::db::StoredAlbum;
use proton_drive_rs::NodeKind;
use proton_drive_rs::proton_sdk::ids::NodeUid;
@@ -132,13 +132,19 @@ impl Core {
/// Refresh the album listing off the request path. At most one runs at a time.
pub(crate) fn spawn_albums_refresh(&self) {
if self.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"),
+23 -9
View File
@@ -4,8 +4,8 @@
//! The existing three-way engine performs the initial, non-destructive union.
use super::{Core, parse_uid, sync};
use pdfs_core::db::StoredSyncFolder;
use pdfs_core::{CoreError, CoreResult};
use pdfs_store::db::StoredSyncFolder;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use std::collections::HashSet;
use std::path::{Component, Path, PathBuf};
@@ -13,7 +13,14 @@ 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(super) fn attach_ancestors(&self, start: &NodeUid) -> CoreResult<Vec<NodeUid>> {
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());
@@ -35,7 +42,7 @@ impl Core {
.into_iter()
.next()
.ok_or_else(|| CoreError::not_found("remote sync folder is missing"))?;
if node.trashed {
if node.trashed && !through_trash {
return Err(CoreError::invalid("remote sync folder is in the trash"));
}
next = node.parent_uid;
@@ -103,10 +110,17 @@ impl Core {
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"))?;
if uid == remote_uid
|| ancestors.contains(&uid)
|| self.attach_ancestors(&uid)?.contains(&remote_uid)
{
// 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",
));
@@ -126,8 +140,8 @@ impl Core {
.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));
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:?}")))?
+50 -1
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,
@@ -315,6 +338,10 @@ struct DirtyParents {
/// 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`,
@@ -423,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;
};
@@ -467,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");
@@ -475,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");
@@ -488,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(
@@ -498,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;
}
};
@@ -510,6 +551,14 @@ pub(super) async fn run_event_sync(
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
+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(())
}
}
+1 -1
View File
@@ -364,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,
+43 -30
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,11 @@ 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.
@@ -148,7 +153,7 @@ 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()
@@ -596,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
@@ -609,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()
@@ -635,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()))
@@ -690,16 +698,21 @@ 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)
@@ -742,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
@@ -758,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),
};
}
@@ -812,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
@@ -830,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 {
@@ -847,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}"));
}
}
@@ -863,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",
@@ -965,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);
};
@@ -1010,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`
@@ -1069,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()))
@@ -1096,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",
@@ -1119,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",
@@ -1143,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",
@@ -1191,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
@@ -1246,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,
@@ -1329,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,
+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)
);
}
}
+103 -29
View File
@@ -27,12 +27,12 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{Duration, Instant};
use parking_lot::Mutex;
use parking_lot::{Condvar, Mutex};
use pdfs_core::batch;
use pdfs_core::cache::{Baseline, StagedWrite};
use pdfs_core::control::{ActivityKind, SyncIssue, TransferDirection};
use pdfs_core::db::{
use pdfs_store::cache::{Baseline, StagedWrite};
use pdfs_store::db::{
CreateLanding, CreateRetired, OP_CREATE, OP_MKDIR, OP_RENAME, OP_REVISION, OP_TRASH,
PARK_EXPIRY_MS, PendingOp, RenameMeta,
};
@@ -53,6 +53,65 @@ use super::{
use proton_drive_rs::proton_sdk::api::ResponseCode;
use proton_drive_rs::proton_sdk::error::ProtonError;
/// The drain's own bookkeeping, shared by its workers and by every mount of
/// the daemon: the wake-up for idle workers, the creates and uploads on the
/// wire, and what a landed one left behind until the tree catches up.
#[derive(Clone)]
pub(crate) struct DrainState {
/// Nudges the drain workers: set true and notify to have them re-examine
/// the queue instead of waiting out their backoff.
pub(crate) drain_wake: Arc<(Mutex<bool>, Condvar)>,
/// The folder and name each create on the wire was sent with, by op id.
/// Drive holds that name until the create lands and a rename or trash
/// queued behind it frees it again.
pub(crate) creating: Arc<Mutex<HashMap<i64, (NodeUid, String)>>>,
/// Creates that landed but could not be read back, by the uid Drive gave
/// them, with the placeholder's. The drain adopts one before it sends
/// anything else for it.
pub(crate) unadopted: Arc<Mutex<HashMap<NodeUid, NodeUid>>>,
/// The SHA-1 of the last revision this daemon uploaded to a file and could
/// not read back, so its revision id is not known (`docs/BUGS.md` B157).
pub(crate) sealed_unread: Arc<Mutex<HashMap<NodeUid, String>>>,
/// The node an upload has just put on Drive, from when the drain lets go
/// of its blob until the tree has the node (`docs/BUGS.md` B170).
pub(crate) landed: Arc<Mutex<HashMap<NodeUid, Node>>>,
/// How long this node's last upload actually took, in milliseconds, with
/// the time it was measured for eviction. Feeds
/// [`Core::revision_debounce`]: a file that takes 30 seconds to send needs
/// a grace period on that scale, or every save supersedes an upload that
/// was already on the wire. Bounded by [`UPLOAD_TIME_MEMORY`].
pub(crate) upload_times: Arc<Mutex<HashMap<String, (u64, i64)>>>,
/// Cancellation flags for uploads currently on the wire, keyed by node.
///
/// Set when a newer revision of the same file is queued: the bytes in
/// flight have just been superseded, and the only thing finishing them
/// achieves is spending the user's uplink on a revision the next op
/// replaces. Read by the upload's own reader ([`CountingReader`]), which is
/// the one thing the SDK calls often enough to notice.
pub(crate) upload_cancel: Arc<Mutex<HashMap<NodeUid, Arc<AtomicBool>>>>,
/// Uploads whose op is retired but whose bytes the content cache has not
/// adopted yet, because the revision just sealed is still being read back.
/// The status counts them as pending, so an empty queue means every file
/// written through the mount reads without the network (`docs/BUGS.md`
/// B119).
pub(crate) landing_uploads: Arc<AtomicU64>,
}
impl DrainState {
pub(crate) fn new() -> Self {
Self {
drain_wake: Arc::new((Mutex::new(false), Condvar::new())),
creating: Arc::new(Mutex::new(HashMap::new())),
unadopted: Arc::new(Mutex::new(HashMap::new())),
sealed_unread: Arc::new(Mutex::new(HashMap::new())),
landed: Arc::new(Mutex::new(HashMap::new())),
upload_times: Arc::new(Mutex::new(HashMap::new())),
upload_cancel: Arc::new(Mutex::new(HashMap::new())),
landing_uploads: Arc::new(AtomicU64::new(0)),
}
}
}
#[derive(Debug)]
struct TrashedMove(String);
@@ -93,8 +152,8 @@ const DRAIN_ACCESS_RECHECK: Duration = Duration::from_secs(5);
/// recheck records a failure, so the op enters the ordinary backoff and, at
/// [`FAILING_ATTEMPTS`], is counted and named by `Response::Status`.
///
/// [`Db::effective_node_access`]: pdfs_core::db::Db::effective_node_access
/// [`FAILING_ATTEMPTS`]: pdfs_core::db::FAILING_ATTEMPTS
/// [`Db::effective_node_access`]: pdfs_store::db::Db::effective_node_access
/// [`FAILING_ATTEMPTS`]: pdfs_store::db::FAILING_ATTEMPTS
const DRAIN_ACCESS_DEFER_LIMIT: Duration = Duration::from_secs(300);
/// A registered cancellation flag for one in-flight upload, deregistered when
@@ -315,7 +374,7 @@ impl Core {
/// worker would just multiply them.
///
/// [`DRAIN_WORKERS`]: super::DRAIN_WORKERS
/// [`Db::claim_next_due_op`]: pdfs_core::db::Db::claim_next_due_op
/// [`Db::claim_next_due_op`]: pdfs_store::db::Db::claim_next_due_op
pub(crate) fn run_pending_drain(&self, primary: bool) {
loop {
// Between ops, never inside one: an op that has started is either
@@ -476,8 +535,8 @@ impl Core {
/// where they are either way; this changes only whether the user can see
/// them.
///
/// [`Db::record_op_failure`]: pdfs_core::db::Db::record_op_failure
/// [`FAILING_ATTEMPTS`]: pdfs_core::db::FAILING_ATTEMPTS
/// [`Db::record_op_failure`]: pdfs_store::db::Db::record_op_failure
/// [`FAILING_ATTEMPTS`]: pdfs_store::db::FAILING_ATTEMPTS
fn defer_for_access(&self, op: &PendingOp, reason: AccessDeferral) {
let now = now_millis();
let next_attempt_at = now + DRAIN_ACCESS_RECHECK.as_millis() as i64;
@@ -659,6 +718,7 @@ impl Core {
/// [`DRAIN_REVISION_DEBOUNCE_MAX`]: super::DRAIN_REVISION_DEBOUNCE_MAX
pub(crate) fn revision_debounce(&self, uid: &NodeUid) -> Duration {
let measured = self
.drain
.upload_times
.lock()
.get(&uid.to_string())
@@ -674,7 +734,7 @@ impl Core {
/// takes to send, and feeding that back would let one network fault widen
/// the debounce for good.
fn record_upload_time(&self, uid: &NodeUid, took: Duration) {
let mut times = self.upload_times.lock();
let mut times = self.drain.upload_times.lock();
let now = now_millis();
if times.len() >= UPLOAD_TIME_MEMORY
&& !times.contains_key(&uid.to_string())
@@ -697,9 +757,12 @@ impl Core {
/// leave the newer upload uncancellable.
fn begin_cancellable_upload(&self, uid: &NodeUid) -> UploadCancel {
let flag = Arc::new(AtomicBool::new(false));
self.upload_cancel.lock().insert(uid.clone(), flag.clone());
self.drain
.upload_cancel
.lock()
.insert(uid.clone(), flag.clone());
UploadCancel {
registry: self.upload_cancel.clone(),
registry: self.drain.upload_cancel.clone(),
uid: uid.clone(),
flag,
}
@@ -712,7 +775,7 @@ impl Core {
/// 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.upload_cancel.lock().get(uid) {
if let Some(flag) = self.drain.upload_cancel.lock().get(uid) {
flag.store(true, Ordering::Relaxed);
debug!(%uid, "cancelling a superseded upload");
}
@@ -722,7 +785,7 @@ impl Core {
/// the shortest outstanding backoff elapsing.
pub(crate) fn wait_for_drain_work(&self) {
sleep_for_drain_work(
&self.drain_wake,
&self.drain.drain_wake,
|| self.shutdown.is_stopping(),
DRAIN_IDLE_POLL,
);
@@ -741,7 +804,11 @@ impl Core {
None
};
let timeout = idle_wait(claiming, earliest, now_millis());
sleep_for_drain_work(&self.drain_wake, || self.shutdown.is_stopping(), timeout);
sleep_for_drain_work(
&self.drain.drain_wake,
|| self.shutdown.is_stopping(),
timeout,
);
}
/// Perform one queued op and retire it.
@@ -767,7 +834,7 @@ impl Core {
let Some(real) = parse_node_uid(&op.uid) else {
return Ok(());
};
let local = match self.unadopted.lock().get(&real).cloned() {
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
@@ -779,7 +846,7 @@ impl Core {
if self.fetch_node_remote(&real)?.is_some() {
self.adopt_real_uid(&local, &real, |_| {})?;
}
self.unadopted.lock().remove(&real);
self.drain.unadopted.lock().remove(&real);
debug!(%local, %real, "adopted a landed create");
Ok(())
}
@@ -1176,12 +1243,13 @@ impl Core {
if let (Some(parent), Some(name)) = (op.parent_uid.as_deref(), op.name.as_deref())
&& let Some(parent) = parse_node_uid(parent)
{
self.creating
self.drain
.creating
.lock()
.insert(op.id, (parent, name.to_string()));
}
let created = self.create_local_node(op);
self.creating.lock().remove(&op.id);
self.drain.creating.lock().remove(&op.id);
created
}
@@ -1317,7 +1385,7 @@ impl Core {
// 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.landing_uploads);
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);
@@ -1345,7 +1413,10 @@ impl Core {
}
}) {
warn!(%local, %real, error = %e, "reading back a landed create failed; adopting it later");
self.unadopted.lock().insert(real.clone(), local.clone());
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`).
@@ -1390,6 +1461,7 @@ impl Core {
return Ok(false);
}
let creating = self
.drain
.creating
.lock()
.iter()
@@ -1400,7 +1472,8 @@ impl Core {
/// Whether a create other than `op` is on the wire under `name`, in any
/// folder.
fn creating_named(&self, op: &PendingOp, name: &str) -> bool {
self.creating
self.drain
.creating
.lock()
.iter()
.any(|(id, (_, n))| *id != op.id && n == name)
@@ -1503,6 +1576,7 @@ impl Core {
// first one's rename took the second one's bytes along
// (docs/BUGS.md B147).
let racing = self
.drain
.creating
.lock()
.iter()
@@ -1953,7 +2027,7 @@ impl Core {
// 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.sealed_unread.lock().get(uid).cloned();
let sealed = self.drain.sealed_unread.lock().get(uid).cloned();
if meta.complete
&& let Some(sealed) = sealed
&& let NodeKind::File {
@@ -2394,7 +2468,7 @@ impl Core {
// 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.landing_uploads);
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.
@@ -2479,7 +2553,7 @@ impl Core {
.unwrap_or(false);
let fetched = self.fetch_node_remote(uid);
if fetched.is_ok() {
self.sealed_unread.lock().remove(uid);
self.drain.sealed_unread.lock().remove(uid);
}
let node = match fetched {
Ok(Some(node)) => node,
@@ -2495,10 +2569,10 @@ impl Core {
the next write to this file may conflict with itself");
match staged_sha1(blob) {
Ok(sha) => {
self.sealed_unread.lock().insert(uid.clone(), sha);
self.drain.sealed_unread.lock().insert(uid.clone(), sha);
}
Err(_) => {
self.sealed_unread.lock().remove(uid);
self.drain.sealed_unread.lock().remove(uid);
}
}
// No newer write took over, so the tree's stamp is this upload's.
@@ -2553,14 +2627,14 @@ impl Core {
// 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.landed.lock().insert(uid.clone(), node.clone());
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.landed.lock().remove(uid);
self.drain.landed.lock().remove(uid);
Some(node)
}
@@ -2968,7 +3042,7 @@ mod tests {
use super::*;
use crate::state::WriteHandle;
use pdfs_core::Access;
use pdfs_core::db::Db;
use pdfs_store::db::Db;
use proton_drive_rs::NodeKind;
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
use std::cell::Cell;
+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,
);
}
}
}
}
+11 -16
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
+1 -1
View File
@@ -15,7 +15,7 @@
use std::process::{Child, Command, Stdio};
use std::time::Duration;
use pdfs_core::db::PendingCounts;
use pdfs_store::db::PendingCounts;
use tracing::{debug, warn};
use super::Core;
+141 -5575
View File
File diff suppressed because it is too large. Load diff
+1 -19
View File
@@ -84,25 +84,7 @@ impl Link {
}
}
/// Whether a failed call failed because Proton could not be reached, rather
/// than because it answered and refused.
///
/// A transport error is the network. So is a request timeout: the SDK reports
/// Proton's own "try again" codes that way, and [`no_answer`] reports our
/// deadline that way. Anything else Proton actually said, and says again on a
/// retry, so it must reach the caller rather than be queued.
pub(crate) fn is_network_error(e: &ProtonError) -> bool {
match e {
ProtonError::Transport(_) => true,
ProtonError::Api(api) => {
matches!(
api.code,
ResponseCode::RequestTimeout | ResponseCode::Timeout
)
}
_ => false,
}
}
pub(crate) use pdfs_drive::is_network_error;
/// The error a call reports when it runs past `after` without an answer.
pub(crate) fn no_answer(after: Duration) -> ProtonError {
+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>>,
}
+126 -132
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).
@@ -291,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))),
}
}
@@ -466,6 +467,12 @@ pub(crate) fn mount_with(
// Start the uptime clock here rather than at the first `pdfs diagnostics`,
// so the age it reports is the daemon's own.
super::diagnostics::start_clock();
// Count every call to Drive from the first, the root lookup included.
let drive_calls = Arc::new(pdfs_drive::counted::CallStats::default());
let drive: Arc<dyn DriveApi> = Arc::new(pdfs_drive::counted::Counted::new(
drive,
drive_calls.clone(),
));
check_mountpoint(mountpoint)?;
let (root, start) = fetch_or_recall_root(drive.as_ref(), &rt, &db)?;
let online = start == Start::Online;
@@ -485,78 +492,68 @@ pub(crate) fn mount_with(
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())),
drain: super::drain::DrainState::new(),
pin_work: Arc::new(Mutex::new(Default::default())),
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,
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
@@ -584,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);
@@ -611,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)?;
}
@@ -622,9 +637,9 @@ 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)?;
}
@@ -633,9 +648,9 @@ pub(crate) fn mount_with(
// B282). Its own thread: a check lists folders and downloads files.
{
let keeper_core = core.clone();
let spawned = std::thread::Builder::new()
.name("pdfs-pin-keeper".into())
.spawn(move || keeper_core.run_pin_keeper());
let spawned = workers.spawn("pdfs-pin-keeper", None, move || {
keeper_core.run_pin_keeper()
});
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
}
@@ -650,9 +665,9 @@ pub(crate) fn mount_with(
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)?;
}
@@ -696,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.
@@ -727,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
@@ -743,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
@@ -797,10 +818,9 @@ pub(crate) fn mount_with(
// 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) = std::thread::Builder::new()
.name("pdfs-inhibit".into())
.spawn(move || crate::inhibit::run(inhibit_core))
{
if let Err(error) = workers.spawn("pdfs-inhibit", None, move || {
crate::inhibit::run(inhibit_core)
}) {
warn!(%error, "start the shutdown inhibitor failed");
}
}
@@ -932,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();
@@ -947,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);
}
@@ -956,37 +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();
///
/// 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();
}
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);
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(","),
@@ -1003,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() {
+188 -61
View File
@@ -1,7 +1,7 @@
//! The photos timeline and its thumbnails.
//!
//! The timeline is a flat, newest-first projection of the photo share, persisted
//! by [`pdfs_core::db`] so the gallery opens instantly and refreshes behind the
//! by [`pdfs_store::db`] so the gallery opens instantly and refreshes behind the
//! user. Thumbnails the server has none for (anything a camera wrote rather than
//! a phone) are generated locally and stored as if the server had served them.
@@ -12,18 +12,19 @@ use std::io::{Read as _, Write as _};
use std::os::unix::fs::{FileExt as _, OpenOptionsExt as _};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Once, OnceLock};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Once, OnceLock};
use std::time::{Duration, Instant};
use base64::Engine as _;
use parking_lot::Mutex;
use pdfs_core::control::{
FileThumbRequest, MappingProgress, PhotoItem, PhotoKind, PhotoLocation, PhotoThumb, PlaceInfo,
ThumbnailBuildStatus, Topic, is_audio_file_name, is_raw_image_name, is_thumbnail_image_name,
is_thumbnail_media_name,
};
use pdfs_core::db::{self, StoredPhoto};
use pdfs_core::{CoreError, CoreResult};
use pdfs_store::db::{self, StoredPhoto};
use proton_drive_rs::proton_sdk::error::Result as DriveResult;
use proton_drive_rs::proton_sdk::ids::NodeUid;
@@ -32,8 +33,8 @@ use tracing::{debug, info, warn};
use super::drive::RevisionRead;
use super::{
Core, PHOTOS_AVAILABLE, PHOTOS_SYNCED_MS, TIMELINE_ENRICH_CHUNK, WriteAuthority, link,
node_size, now_ms, parse_uid,
Core, PHOTOS_AVAILABLE, PHOTOS_SYNCED_MS, TIMELINE_ENRICH_CHUNK, ThumbnailMissCaches,
WriteAuthority, link, node_size, now_ms, parse_uid,
};
/// Longest edge, in px, of a thumbnail generated locally for a photo the server
@@ -46,6 +47,7 @@ const THUMB_QUALITY: u8 = 82;
/// thumbnails. Bounded: a screenful of 20 MB digicam JPEGs would otherwise
/// saturate the link and starve the rest of the daemon.
pub(crate) const THUMB_GEN_CONCURRENCY: usize = 4;
/// Shots the similar-photo pass fetches thumbnails for at a time.
const SIMILAR_CHUNK: usize = 64;
/// Images processed between recursive-build progress updates.
@@ -127,6 +129,75 @@ const DECODE_BUDGET_BYTES: u64 = 512 * 1024 * 1024;
/// The process-wide [`DecodeBudget`] every thumbnail decode draws from.
static DECODE_BUDGET: DecodeBudget = DecodeBudget::new(DECODE_BUDGET_BYTES);
/// What the Photos and thumbnail jobs are doing right now: which refreshes
/// and builds are running, how far they got, and which thumbnails are known
/// to be missing. Shared by every mount of the daemon; only this module and
/// the status reports read it.
#[derive(Clone)]
pub(crate) struct PhotoJobs {
/// True while a background refresh of the photos timeline is already
/// running, so a burst of page requests against a stale listing kicks off
/// one refresh rather than one per request.
pub(crate) timeline_refreshing: Arc<AtomicBool>,
/// How far the running timeline refresh has got resolving photo metadata,
/// as `(done, total)` photos; `None` when no refresh is resolving any. The
/// Places view shows it while a library's locations are first read.
pub(crate) timeline_progress: Arc<Mutex<Option<(usize, usize)>>>,
/// The same, for the album listing.
pub(crate) albums_refreshing: Arc<AtomicBool>,
/// True while the similar-photo pass hashes thumbnails (see
/// [`Core::photo_similar`]), so asking again doesn't start a second one.
pub(crate) similar_hashing: Arc<AtomicBool>,
/// Photos whose missing thumbnail is being generated right now. A tile that is
/// still on screen asks for its thumbnail again every few seconds, and each of
/// those downloads is a full-size photo — so an in-flight uid is never started
/// twice.
pub(crate) thumb_gen: Arc<Mutex<HashSet<NodeUid>>>,
/// Global permit pool for locally generated thumbnails. The old per-request
/// limit multiplied when the GUI sent several batches, allowing dozens of
/// full-size images to download at once.
pub(crate) thumb_gen_budget: Arc<tokio::sync::Semaphore>,
/// Current ordinary-file listing generation and a wake-up for tasks waiting
/// on a permit or a download when that listing is abandoned.
pub(crate) file_thumb_generation: Arc<AtomicU64>,
pub(crate) file_thumb_cancel: Arc<tokio::sync::Notify>,
/// Progress of the explicit recursive build started from the Files toolbar.
pub(crate) thumbnail_build: Arc<Mutex<ThumbnailBuildStatus>>,
/// Cancellation for the explicit recursive build. Separate from ordinary
/// listing cancellation because the two jobs have independent lifetimes.
pub(crate) thumbnail_build_cancelled: Arc<AtomicBool>,
pub(crate) thumbnail_build_cancel: Arc<tokio::sync::Notify>,
/// Negative thumbnail knowledge, separated by whether the remote lacked a
/// thumbnail or local decoding proved this revision unsupported.
///
/// Absence has to be cached or it costs a round trip every time it is asked
/// for, and it is asked for constantly: an `ls -l` from an xattr-aware lister
/// issues a `getxattr` per advertised name per entry, so a 65-file directory
/// of videos re-probed 130 times per listing at ~186 ms each (B5). The mtime
/// is the validity tag — a new revision may well have a thumbnail — matching
/// how [`ContentCache::read_thumbnail`] validates the positive side.
pub(crate) thumbnail_misses: Arc<Mutex<ThumbnailMissCaches>>,
}
impl PhotoJobs {
pub(crate) fn new() -> Self {
Self {
timeline_refreshing: Arc::new(AtomicBool::new(false)),
timeline_progress: Arc::new(Mutex::new(None)),
albums_refreshing: Arc::new(AtomicBool::new(false)),
similar_hashing: Arc::new(AtomicBool::new(false)),
thumb_gen: Arc::new(Mutex::new(HashSet::new())),
thumb_gen_budget: Arc::new(tokio::sync::Semaphore::new(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())),
}
}
}
/// A counting gate over bytes: [`acquire`](Self::acquire) waits until the cost
/// fits beside what is already held.
struct DecodeBudget {
@@ -1301,6 +1372,7 @@ impl Core {
let sets = self.db.photo_similar().map_err(CoreError::from)?;
let (done, total) = self.db.similar_progress().map_err(CoreError::from)?;
let hashing = self
.photo_jobs
.similar_hashing
.load(Ordering::SeqCst)
.then_some(MappingProgress { done, total });
@@ -1313,7 +1385,7 @@ impl Core {
}
fn spawn_similar_hashing(&self) {
if self.similar_hashing.swap(true, Ordering::SeqCst) {
if self.photo_jobs.similar_hashing.swap(true, Ordering::SeqCst) {
return;
}
let core = self.clone();
@@ -1323,11 +1395,15 @@ impl Core {
if let Err(e) = core.hash_similar() {
warn!(error = %e, "similar-photo hashing failed");
}
core.similar_hashing.store(false, Ordering::SeqCst);
core.photo_jobs
.similar_hashing
.store(false, Ordering::SeqCst);
});
if let Err(e) = spawned {
warn!(error = %e, "could not start similar-photo hashing");
self.similar_hashing.store(false, Ordering::SeqCst);
self.photo_jobs
.similar_hashing
.store(false, Ordering::SeqCst);
}
}
@@ -1697,7 +1773,7 @@ impl Core {
}
}
let pending = self.thumb_gen.lock();
let pending = self.photo_jobs.thumb_gen.lock();
requested
.iter()
.zip(uids)
@@ -1748,8 +1824,8 @@ impl Core {
items: &[FileThumbRequest],
generation: u64,
) -> Option<Vec<PhotoThumb>> {
let current =
generation != 0 && self.file_thumb_generation.load(Ordering::SeqCst) == generation;
let current = generation != 0
&& self.photo_jobs.file_thumb_generation.load(Ordering::SeqCst) == generation;
if !current {
return None;
}
@@ -1781,6 +1857,7 @@ impl Core {
.cached_thumbnail_path(uid, ttype, *modified)
.is_some()
|| self
.photo_jobs
.thumbnail_misses
.lock()
.local_contains(&(uid.clone(), ttype), *modified)
@@ -1795,7 +1872,7 @@ impl Core {
self.spawn_generate_thumbs(wanted, &tags, &names, ThumbJob::Files(generation));
}
let pending = self.thumb_gen.lock();
let pending = self.photo_jobs.thumb_gen.lock();
Some(
items
.iter()
@@ -1821,13 +1898,14 @@ impl Core {
pub(crate) fn reserve_file_thumb_generation(&self) -> u64 {
let next = |current| if current == u64::MAX { 1 } else { current + 1 };
let previous = self
.photo_jobs
.file_thumb_generation
.try_update(Ordering::SeqCst, Ordering::SeqCst, |current| {
Some(next(current))
})
.expect("generation update always succeeds");
let generation = next(previous);
self.file_thumb_cancel.notify_waiters();
self.photo_jobs.file_thumb_cancel.notify_waiters();
generation
}
@@ -1836,10 +1914,11 @@ impl Core {
/// recursive builds do not use this generation and continue normally.
pub(crate) fn cancel_file_thumbs(&self, generation: u64) {
let previous = self
.photo_jobs
.file_thumb_generation
.fetch_max(generation, Ordering::SeqCst);
if generation > previous {
self.file_thumb_cancel.notify_waiters();
self.photo_jobs.file_thumb_cancel.notify_waiters();
}
}
@@ -1854,7 +1933,7 @@ impl Core {
job: ThumbJob,
) {
let fresh: Vec<NodeUid> = {
let mut inflight = self.thumb_gen.lock();
let mut inflight = self.photo_jobs.thumb_gen.lock();
uids.into_iter()
.filter(|uid| inflight.insert(uid.clone()))
.collect()
@@ -1872,7 +1951,7 @@ impl Core {
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
core.generate_thumbs(&fresh, &tags, &names, job)
}));
let mut inflight = core.thumb_gen.lock();
let mut inflight = core.photo_jobs.thumb_gen.lock();
for uid in &fresh {
inflight.remove(uid);
}
@@ -1894,10 +1973,13 @@ impl Core {
fn thumb_job_current(&self, job: ThumbJob) -> bool {
match job {
ThumbJob::Files(generation) => {
self.file_thumb_generation.load(Ordering::SeqCst) == generation
self.photo_jobs.file_thumb_generation.load(Ordering::SeqCst) == generation
}
ThumbJob::Photos => true,
ThumbJob::Build => !self.thumbnail_build_cancelled.load(Ordering::SeqCst),
ThumbJob::Build => !self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst),
}
}
@@ -1934,13 +2016,13 @@ impl Core {
// One shared permit pool bounds all thumbnail batches,
// rather than multiplying the limit by every control
// request the GUI happens to have in flight.
let acquire = core.thumb_gen_budget.clone().acquire_owned();
let acquire = core.photo_jobs.thumb_gen_budget.clone().acquire_owned();
tokio::pin!(acquire);
let _permit = match job {
ThumbJob::Files(_) => loop {
tokio::select! {
permit = &mut acquire => break permit.ok(),
_ = core.file_thumb_cancel.notified() => {
_ = core.photo_jobs.file_thumb_cancel.notified() => {
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
@@ -1955,7 +2037,7 @@ impl Core {
ThumbJob::Build => loop {
tokio::select! {
permit = &mut acquire => break permit.ok(),
_ = core.thumbnail_build_cancel.notified() => {
_ = core.photo_jobs.thumbnail_build_cancel.notified() => {
if !core.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
@@ -2015,7 +2097,7 @@ impl Core {
ThumbJob::Files(_) => loop {
tokio::select! {
result = &mut download => break Some(result),
_ = core.file_thumb_cancel.notified() => {
_ = core.photo_jobs.file_thumb_cancel.notified() => {
if !core.thumb_job_current(job) {
break None;
}
@@ -2030,7 +2112,7 @@ impl Core {
ThumbJob::Build => loop {
tokio::select! {
result = &mut download => break Some(result),
_ = core.thumbnail_build_cancel.notified() => {
_ = core.photo_jobs.thumbnail_build_cancel.notified() => {
if !core.thumb_job_current(job) {
break None;
}
@@ -2120,7 +2202,8 @@ impl Core {
match self.cache.store_thumbnail(&uid, ttype, tag, &thumb.bytes) {
Ok(()) => {
summary.made += 1;
self.thumbnail_misses
self.photo_jobs
.thumbnail_misses
.lock()
.forget_local(&(uid.clone(), ttype));
self.record_thumb(&uid, db::THUMB_HAVE, Some(thumb.ratio));
@@ -2136,7 +2219,8 @@ impl Core {
ThumbAttempt::Undecodable => {
summary.undecodable += 1;
if let Some(&tag) = tags.get(&uid.to_string()) {
self.thumbnail_misses
self.photo_jobs
.thumbnail_misses
.lock()
.remember_local((uid.clone(), ttype), tag);
}
@@ -2229,7 +2313,7 @@ impl Core {
}
pub(crate) fn thumbnail_build_status(&self) -> ThumbnailBuildStatus {
self.thumbnail_build.lock().clone()
self.photo_jobs.thumbnail_build.lock().clone()
}
/// Start one recursive local-thumbnail build. A request for the same root
@@ -2238,11 +2322,12 @@ impl Core {
pub(crate) fn start_thumbnail_build(&self, root: PathBuf) -> CoreResult<ThumbnailBuildStatus> {
let path = root.to_string_lossy().into_owned();
let status = {
let mut status = self.thumbnail_build.lock();
let mut status = self.photo_jobs.thumbnail_build.lock();
if !thumbnail_build_may_start(&status, &path)? {
return Ok(status.clone());
}
self.thumbnail_build_cancelled
self.photo_jobs
.thumbnail_build_cancelled
.store(false, Ordering::SeqCst);
*status = ThumbnailBuildStatus {
running: true,
@@ -2264,11 +2349,12 @@ impl Core {
}))
.is_err()
{
let mut status = core.thumbnail_build.lock();
let mut status = core.photo_jobs.thumbnail_build.lock();
status.running = false;
status.scanning = false;
status.message = Some("Thumbnail generation stopped unexpectedly".to_string());
core.thumbnail_build_cancelled
core.photo_jobs
.thumbnail_build_cancelled
.store(false, Ordering::SeqCst);
warn!(path = %status.path, "recursive thumbnail build panicked");
}
@@ -2278,22 +2364,27 @@ impl Core {
pub(crate) fn cancel_thumbnail_build(&self) -> ThumbnailBuildStatus {
let (status, cancelled) = {
let status = self.thumbnail_build.lock();
let status = self.photo_jobs.thumbnail_build.lock();
let cancelled = status.running;
if cancelled {
self.thumbnail_build_cancelled.store(true, Ordering::SeqCst);
self.photo_jobs
.thumbnail_build_cancelled
.store(true, Ordering::SeqCst);
}
(status.clone(), cancelled)
};
if cancelled {
self.thumbnail_build_cancel.notify_waiters();
self.photo_jobs.thumbnail_build_cancel.notify_waiters();
}
status
}
fn finish_thumbnail_build(&self) {
let mut status = self.thumbnail_build.lock();
let cancelled = self.thumbnail_build_cancelled.swap(false, Ordering::SeqCst);
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 {
@@ -2315,19 +2406,23 @@ impl Core {
let mut seen_images = HashSet::new();
while let Some(folder) = folders.pop() {
if self.thumbnail_build_cancelled.load(Ordering::SeqCst) {
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.thumbnail_build.lock();
let mut status = self.photo_jobs.thumbnail_build.lock();
status.folders_scanned += 1;
}
let entries = match listing {
Ok(entries) => entries,
Err(error) => {
let mut status = self.thumbnail_build.lock();
let mut status = self.photo_jobs.thumbnail_build.lock();
if status.message.is_none() {
status.message = Some(format!(
"Some folders could not be read ({}: {error})",
@@ -2359,14 +2454,18 @@ impl Core {
}
}
}
let mut status = self.thumbnail_build.lock();
let mut status = self.photo_jobs.thumbnail_build.lock();
status.images_found += found_here;
status.completed += invalid_here;
status.failed += invalid_here;
}
self.thumbnail_build.lock().scanning = false;
if self.thumbnail_build_cancelled.load(Ordering::SeqCst) {
self.photo_jobs.thumbnail_build.lock().scanning = false;
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
self.finish_thumbnail_build();
return;
}
@@ -2378,13 +2477,14 @@ impl Core {
.cached_thumbnail_path(&uid, ttype, modified)
.is_some()
{
self.thumbnail_build.lock().completed += 1;
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.thumbnail_build.lock();
let mut status = self.photo_jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
} else {
@@ -2393,7 +2493,11 @@ impl Core {
}
for chunk in todo.chunks(THUMB_BUILD_CHUNK) {
if self.thumbnail_build_cancelled.load(Ordering::SeqCst) {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
self.finish_thumbnail_build();
return;
}
@@ -2406,7 +2510,11 @@ impl Core {
// than downloading the full image twice.
let waiting_since = Instant::now();
loop {
if self.thumbnail_build_cancelled.load(Ordering::SeqCst) {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
self.finish_thumbnail_build();
return;
}
@@ -2415,27 +2523,28 @@ impl Core {
.cached_thumbnail_path(uid, ttype, *modified)
.is_some()
{
self.thumbnail_build.lock().completed += 1;
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.thumbnail_build.lock();
let mut status = self.photo_jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
break;
}
if self.thumb_gen.lock().insert(uid.clone()) {
if self.photo_jobs.thumb_gen.lock().insert(uid.clone()) {
tags.insert(uid.to_string(), *modified);
names.insert(uid.to_string(), name.clone());
claimed.push(uid.clone());
break;
}
if waiting_since.elapsed() >= THUMB_BUILD_CLAIM_TIMEOUT {
let mut status = self.thumbnail_build.lock();
let mut status = self.photo_jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
if status.message.is_none() {
@@ -2456,12 +2565,12 @@ impl Core {
self.generate_thumbs(&claimed, &tags, &names, ThumbJob::Build)
}));
{
let mut inflight = self.thumb_gen.lock();
let mut inflight = self.photo_jobs.thumb_gen.lock();
for uid in &claimed {
inflight.remove(uid);
}
}
let mut status = self.thumbnail_build.lock();
let mut status = self.photo_jobs.thumbnail_build.lock();
match result {
Ok(summary) => {
status.completed += summary.processed();
@@ -2544,7 +2653,7 @@ impl Core {
let total = self.db.photos_count().map_err(CoreError::from)?;
let skipped = total.saturating_sub(pending.len());
let mut resolved = 0;
let progress = ProgressGuard(&self.timeline_progress);
let progress = ProgressGuard(&self.photo_jobs.timeline_progress);
for (index, chunk) in pending.chunks(TIMELINE_ENRICH_CHUNK).enumerate() {
if self.shutdown.is_stopping() {
break;
@@ -2613,8 +2722,14 @@ impl Core {
/// whole library at once, sharing the session's rate limit and taking
/// minutes. Returns whether the account has a photos library.
pub(crate) fn refresh_timeline_joined(&self) -> CoreResult<bool> {
if self.timeline_refreshing.swap(true, Ordering::SeqCst) {
while self.timeline_refreshing.load(Ordering::SeqCst) && !self.shutdown.is_stopping() {
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
@@ -2625,13 +2740,18 @@ impl Core {
.state_i64(PHOTOS_SYNCED_MS)
.map_err(CoreError::from)?
.is_some()
|| self.timeline_refreshing.swap(true, Ordering::SeqCst)
|| self
.photo_jobs
.timeline_refreshing
.swap(true, Ordering::SeqCst)
{
return Ok(self.db.state_i64(PHOTOS_AVAILABLE).ok().flatten() != Some(0));
}
}
let refreshed = self.rt.block_on(self.refresh_timeline());
self.timeline_refreshing.store(false, Ordering::SeqCst);
self.photo_jobs
.timeline_refreshing
.store(false, Ordering::SeqCst);
if refreshed.is_ok() {
self.events.publish(&[Topic::Photos]);
}
@@ -2639,13 +2759,19 @@ impl Core {
}
pub(crate) fn spawn_timeline_refresh(&self) {
if self.timeline_refreshing.swap(true, Ordering::SeqCst) {
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.timeline_refreshing.store(false, Ordering::SeqCst);
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 {
@@ -2658,7 +2784,8 @@ impl Core {
/// How far the running timeline refresh has got reading photo metadata, or
/// `None` when no refresh is reading any.
pub(crate) fn timeline_progress(&self) -> Option<MappingProgress> {
self.timeline_progress
self.photo_jobs
.timeline_progress
.lock()
.map(|(done, total)| MappingProgress { done, total })
}
@@ -2666,7 +2793,7 @@ impl Core {
/// Whether a timeline refresh is running. A front-end that asked for one
/// watches this to know when the new timeline is worth re-reading.
pub(crate) fn timeline_refreshing(&self) -> bool {
self.timeline_refreshing.load(Ordering::SeqCst)
self.photo_jobs.timeline_refreshing.load(Ordering::SeqCst)
}
/// Download a photo's full content into the content cache, returning its
+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
}
}
+5 -5
View File
@@ -453,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:?}")));
}
};
@@ -463,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 {
@@ -479,7 +479,7 @@ impl Core {
}
/// Only device backups belong in the device's cross-machine profile.
fn profile_folders(folders: Vec<pdfs_core::db::StoredSyncFolder>) -> Vec<ProfileFolder> {
fn profile_folders(folders: Vec<pdfs_store::db::StoredSyncFolder>) -> Vec<ProfileFolder> {
folders
.into_iter()
.filter(|f| f.kind == "device")
@@ -556,7 +556,7 @@ mod tests {
#[test]
fn attached_my_files_folders_are_not_in_the_device_profile() {
let dir = crate::sim::daemon::scratch("profile-folder-kinds");
let db = pdfs_core::db::Db::open(&dir.join("cache.db")).unwrap();
let db = pdfs_store::db::Db::open(&dir.join("cache.db")).unwrap();
db.sync_folder_add("/backup", "vol~backup", "device-share")
.unwrap();
db.sync_folder_attach("/work", "vol~work", "my-files-share")
+1 -1
View File
@@ -11,7 +11,7 @@ use super::*;
use std::io::Write;
use pdfs_core::control::{PendingOpInfo, SyncIssue};
use pdfs_core::db::{FAILING_ATTEMPTS, PARK_UNTIL};
use pdfs_store::db::{FAILING_ATTEMPTS, PARK_UNTIL};
impl Core {
/// Every queued op, oldest first, with a path a person can read.
+62 -15
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>>>,
@@ -296,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 =>
@@ -355,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
@@ -421,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.
@@ -551,7 +594,8 @@ impl Core {
cache_blocks: bool,
) -> BlockResult {
let key: BlockKey = (uid.clone(), mtime, fsize, span);
self.block_flight
self.reads
.block_flight
.join(key, || {
self.read_block(reader, uid, mtime, fsize, span, cache_blocks)
})
@@ -625,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)
@@ -665,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;
@@ -746,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);
@@ -775,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;
}
@@ -787,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()
@@ -809,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());
@@ -870,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;
@@ -878,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)
@@ -1152,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");
}
}
}
}
+3 -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(|| {
+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))
}
}
+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(())
}
}
+42 -4
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
@@ -701,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))
}
@@ -714,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),
+495 -2
View File
@@ -13,10 +13,10 @@ use std::sync::mpsc::SyncSender;
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use pdfs_core::cache::ContentCache;
use pdfs_core::config::AppConfig;
use pdfs_core::control::{self, PendingOpInfo, Request, Response};
use pdfs_core::db::Db;
use pdfs_store::cache::ContentCache;
use pdfs_store::db::Db;
use proton_drive_rs::ProtonDriveClient;
use proton_drive_rs::proton_sdk::config::ProtonClientConfiguration;
use proton_drive_rs::proton_sdk::session::{PasswordMode, ProtonApiSession, ResumeParameters};
@@ -30,6 +30,16 @@ const MOUNT_DEADLINE: Duration = Duration::from_secs(20);
/// How long a restart may wait for the last run to let go of its database.
const LAST_RUN_DEADLINE: Duration = Duration::from_secs(30);
/// How long a stop may wait for the mount to end before it aborts the FUSE
/// connection. A mount that stops answering otherwise hangs the test, and the
/// whole run with it (`docs/BUGS.md` B297).
const STOP_DEADLINE: Duration = Duration::from_secs(60);
/// How long one daemon may live. Past this, its FUSE connection is aborted, so
/// a test blocked on a request the mount never answers fails with `ENOTCONN`
/// instead of hanging the run. The whole suite takes about 15 minutes in CI.
const LIFETIME_LIMIT: Duration = Duration::from_secs(20 * 60);
pub(crate) struct Daemon {
pub(crate) client: FakeClient,
pub(crate) mountpoint: PathBuf,
@@ -38,6 +48,13 @@ pub(crate) struct Daemon {
stop: SyncSender<()>,
mount: Option<JoinHandle<io::Result<MountOutcome>>>,
rt: Option<tokio::runtime::Runtime>,
/// The mount's FUSE connection, as `/sys/fs/fuse/connections` names it.
connection: u64,
/// Dropped with the daemon, which ends the thread enforcing
/// [`LIFETIME_LIMIT`].
_alive: std::sync::mpsc::Sender<()>,
/// Dropped after `shut_down`, so the next simulation waits for this one.
_turn: Turn,
}
impl Daemon {
@@ -45,6 +62,7 @@ impl Daemon {
/// A later start on the same `dir` is a restart: it finds the queue, the
/// cache and the database the last run left.
pub(crate) fn start(dir: &Path, client: FakeClient) -> io::Result<Self> {
let turn = Turn::take();
log_to_test_output();
isolate_from_the_developer();
let mountpoint = dir.join("mnt");
@@ -112,6 +130,27 @@ impl Daemon {
}
std::thread::sleep(Duration::from_millis(20));
}
let connection = {
use std::os::unix::fs::MetadataExt;
u64::from(libc::minor(std::fs::metadata(&mountpoint)?.dev()))
};
let (alive, dropped) = std::sync::mpsc::channel::<()>();
{
let mountpoint = mountpoint.clone();
std::thread::Builder::new()
.name("sim-lifetime".into())
.spawn(move || {
if let Err(std::sync::mpsc::RecvTimeoutError::Timeout) =
dropped.recv_timeout(LIFETIME_LIMIT)
{
eprintln!(
"{}: the daemon outlived {LIFETIME_LIMIT:?}; aborting its FUSE connection",
mountpoint.display()
);
abort_connection(connection);
}
})?;
}
Ok(Self {
client,
mountpoint,
@@ -120,6 +159,9 @@ impl Daemon {
stop,
mount: Some(mount),
rt: Some(rt),
connection,
_alive: alive,
_turn: turn,
})
}
@@ -215,6 +257,21 @@ impl Daemon {
return Ok(MountOutcome::Shutdown);
};
let _ = self.stop.try_send(());
if !wait_until(STOP_DEADLINE, || mount.is_finished()) {
abort_connection(self.connection);
let _ = wait_until(STOP_DEADLINE, || mount.is_finished());
if !mount.is_finished() {
// Joining would hang the run; leak the thread instead.
return Err(io::Error::other(format!(
"{}: the mount did not end after its FUSE connection was aborted",
self.mountpoint.display()
)));
}
return Err(io::Error::other(format!(
"{}: the mount did not stop within {STOP_DEADLINE:?}, so its FUSE connection was aborted",
self.mountpoint.display()
)));
}
let outcome = mount
.join()
.unwrap_or_else(|_| Err(io::Error::other("mount thread panicked")));
@@ -231,6 +288,61 @@ impl Drop for Daemon {
}
}
/// Abort FUSE connection `connection`: every request waiting on it fails with
/// `ENOTCONN`, and the mount's session ends. The connection belongs to the
/// user who mounted it, so this needs no privileges.
fn abort_connection(connection: u64) {
let path = format!("/sys/fs/fuse/connections/{connection}/abort");
if let Err(error) = std::fs::write(&path, "1") {
eprintln!("could not abort {path}: {error}");
}
}
/// One simulation's turn to run daemons. The simulations share the process:
/// its environment (see [`isolate_from_the_developer`]), its cores and its
/// mounts. Run side by side, as plain `cargo test` does, they miss their
/// deadlines and can hang (`docs/BUGS.md` B297). So a daemon started on one
/// test thread waits while another test thread still has one.
struct Turn;
/// The test thread whose daemons run now, and how many it has.
static TURN: parking_lot::Mutex<Option<(std::thread::ThreadId, usize)>> =
parking_lot::Mutex::new(None);
static TURN_FREE: parking_lot::Condvar = parking_lot::Condvar::new();
impl Turn {
fn take() -> Self {
let me = std::thread::current().id();
let mut turn = TURN.lock();
loop {
match turn.as_mut() {
None => {
*turn = Some((me, 1));
return Turn;
}
Some((owner, count)) if *owner == me => {
*count += 1;
return Turn;
}
Some(_) => TURN_FREE.wait(&mut turn),
}
}
}
}
impl Drop for Turn {
fn drop(&mut self) {
let mut turn = TURN.lock();
if let Some((_, count)) = turn.as_mut() {
*count -= 1;
if *count == 0 {
*turn = None;
TURN_FREE.notify_all();
}
}
}
}
/// Whether a file system is mounted at `path`: it sits on another device than
/// its parent.
fn is_mounted(path: &Path) -> bool {
@@ -369,6 +481,63 @@ mod tests {
use pdfs_core::control::{RefreshScope, SyncIssue};
use std::collections::BTreeMap;
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_simulation_on_another_thread_waits_for_this_ones_daemons() {
// Side by side, the simulations missed their deadlines and could hang
// on a mount (B297).
let drive = FakeDrive::new();
let first = Daemon::start(&scratch("turn-first"), drive.client(1, Faults::lan())).unwrap();
let second_up = Arc::new(std::sync::atomic::AtomicBool::new(false));
let other = {
let drive = drive.clone();
let second_up = second_up.clone();
std::thread::spawn(move || {
let second =
Daemon::start(&scratch("turn-second"), drive.client(2, Faults::lan())).unwrap();
second_up.store(true, std::sync::atomic::Ordering::SeqCst);
second.stop().unwrap();
})
};
std::thread::sleep(Duration::from_secs(2));
assert!(!second_up.load(std::sync::atomic::Ordering::SeqCst));
// A second daemon on this thread does not wait for the first.
let restarted = first.restart().unwrap();
assert!(!second_up.load(std::sync::atomic::Ordering::SeqCst));
restarted.stop().unwrap();
other.join().unwrap();
assert!(second_up.load(std::sync::atomic::Ordering::SeqCst));
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn diagnostics_count_the_calls_made_to_drive() {
let drive = FakeDrive::new();
let daemon =
Daemon::start(&scratch("drive-calls"), drive.client(1, Faults::lan())).unwrap();
std::fs::write(daemon.mountpoint.join("a.txt"), b"a").unwrap();
assert!(wait_until(Duration::from_secs(30), || drive
.tree()
.contains_key("a.txt")));
let Ok(Response::Diagnostics { diagnostics }) = daemon.request(&Request::Diagnostics)
else {
panic!("no diagnostics");
};
let calls: BTreeMap<_, _> = diagnostics
.drive_calls
.iter()
.map(|stat| (stat.call.as_str(), stat))
.collect();
assert!(calls.contains_key("get_my_files_folder"), "{calls:?}");
let uploads = calls
.get("upload_file_from")
.or_else(|| calls.get("upload_file_replacing_draft_from"))
.unwrap_or_else(|| panic!("no upload counted: {calls:?}"));
assert!(uploads.count >= 1);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_daemon_on_the_fake_drive_syncs_both_ways() {
@@ -1647,6 +1816,245 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
/// The trace of the last finished pass over `folder` that `done` accepts.
fn traced_pass(
daemon: &Daemon,
folder: i64,
done: impl Fn(&control::SyncPassTrace) -> bool,
) -> Option<control::SyncPassTrace> {
let mut found = None;
wait_until(Duration::from_secs(30), || {
let Ok(Response::Diagnostics { diagnostics }) = daemon.request(&Request::Diagnostics)
else {
return false;
};
found = diagnostics.sync.and_then(|sync| {
sync.traces
.into_iter()
.find(|t| t.folder_id == folder && t.ended == "finished" && done(t))
});
found.is_some()
});
found
}
fn calls(trace: &control::SyncPassTrace, name: &str) -> u64 {
trace
.calls
.iter()
.find(|c| c.name == name)
.map_or(0, |c| c.count)
}
/// Ask for passes over `folder` until one lists nothing on Drive, and
/// return its trace. The passes right after a change list the folders
/// it touched once more, for the echo of their own changes.
fn quiet_pass(daemon: &Daemon, folder: i64) -> Option<control::SyncPassTrace> {
let mut quiet = None;
wait_until(Duration::from_secs(90), || {
// Spaced out: the engine waits for requests to settle before it
// starts a pass.
let _ = daemon.request(&Request::SyncNow { id: Some(folder) });
std::thread::sleep(Duration::from_secs(4));
let Ok(Response::Diagnostics { diagnostics }) = daemon.request(&Request::Diagnostics)
else {
return false;
};
quiet = diagnostics.sync.and_then(|sync| {
sync.traces.into_iter().find(|t| {
t.folder_id == folder
&& t.ended == "finished"
&& counted(t, "remote folders") == 0
&& counted(t, "reused") > 0
})
});
quiet.is_some()
});
quiet
}
fn counted(trace: &control::SyncPassTrace, name: &str) -> u64 {
trace
.counts
.iter()
.find(|c| c.name == name)
.map_or(0, |c| c.value)
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_mirror_pass_reports_where_its_time_went() {
// A pass over a large folder said only that it started and, hours
// later, that a stop cut it short (B294). Its trace says what each
// stage did, in `pdfs diagnostics` and in the journal.
let drive = FakeDrive::new();
let dir = scratch("mirror-pass-trace");
let (daemon, folder, _client) = start_mirror(
&drive,
&dir,
&[("a.txt", b"one"), ("b.txt", b"two"), ("c.txt", b"three")],
);
let first = traced_pass(&daemon, folder, |t| calls(t, "upload") > 0)
.expect("the first pass is traced");
assert_eq!(calls(&first, "upload"), 3);
assert_eq!(counted(&first, "local entries"), 3);
assert!(counted(&first, "remote folders") >= 1);
for phase in ["baseline", "local walk", "remote walk", "apply"] {
assert!(
first.phases.iter().any(|p| p.name == phase),
"no {phase} in {first}"
);
}
assert!(
take_logged()
.iter()
.any(|line| line.contains("sync: pass trace"))
);
// Drive does not list a node it has just made at once, so the read
// back after an upload has no revision id to record. The next pass
// reads those files in full, one key unlock each, and records it.
daemon
.request(&Request::SyncNow { id: Some(folder) })
.unwrap();
let filled = traced_pass(&daemon, folder, |t| counted(t, "revisions recorded") == 3)
.expect("the pass after the uploads is traced");
assert_eq!(counted(&filled, "nodes full"), 3, "{filled}");
// Once nothing changes, a pass lists nothing on Drive: it starts from
// the last walk, which Drive's event stream keeps up to date.
let quiet = quiet_pass(&daemon, folder).expect("a quiet pass is traced");
assert_eq!(counted(&quiet, "reused"), 3, "{quiet}");
assert_eq!(calls(&quiet, "upload"), 0, "{quiet}");
assert_eq!(counted(&quiet, "queued"), 0, "{quiet}");
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_walk_of_drive_cut_short_resumes_where_it_stopped() {
// A pass over a large folder lists Drive folder by folder before it
// applies anything. A stop threw all of that away, and a folder too
// large to walk between two restarts never synced (B294). Now each
// listing is saved, and the next pass lists only what is left.
let drive = FakeDrive::new();
let dir = scratch("mirror-walk-resume");
let local = dir.join("local");
std::fs::create_dir_all(&local).unwrap();
for sub in ["a", "b", "c"] {
std::fs::create_dir(local.join(sub)).unwrap();
std::fs::write(local.join(sub).join("f.txt"), sub.as_bytes()).unwrap();
}
let (daemon, folder, _client) = start_mirror(&drive, &dir, &[]);
assert!(wait_until(Duration::from_secs(30), || {
["a", "b", "c"]
.iter()
.all(|sub| drive.lookup(&format!("mirrored/{sub}/f.txt")).is_some())
}));
assert!(wait_for_pass(&daemon, folder, 0));
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
// As after a gap in the event stream: the next pass walks all of
// Drive again.
reopen(&dir).sync_walks_clear_all().unwrap();
// The next start's pass is stopped while it lists the second folder.
let client = drive.client(1, Faults::lan());
let b = drive.lookup("mirrored/b").unwrap();
let listing = client.hold_next_children_of(&b);
let daemon = Daemon::start(&dir, client).unwrap();
assert!(wait_until(Duration::from_secs(30), || listing.reached()));
let socket = daemon.socket.clone();
let stopping = std::thread::spawn(move || daemon.stop());
assert!(wait_until(Duration::from_secs(30), || !socket.exists()));
drop(listing);
assert!(matches!(
stopping.join().unwrap(),
Ok(MountOutcome::Shutdown)
));
let saved = reopen(&dir).sync_walk_load(folder).unwrap();
let saved = saved.expect("the walk was saved");
// Which folders were listed depends on the order Drive lists them
// in; what matters is that the walk did not end.
assert!(saved.dirs.iter().any(|d| d.rel_path.is_empty() && d.listed));
assert!(!saved.complete, "{:?}", saved.dirs);
// The start after that picks the walk up instead of starting over.
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
let resumed = traced_pass(&daemon, folder, |t| counted(t, "resumed") > 0)
.expect("the resumed pass finishes");
assert!(
counted(&resumed, "remote folders") < 4,
"listed everything again: {resumed}"
);
assert!(wait_for_pass(&daemon, folder, 0));
// Nothing moved: the walk read every path, and the complete walk is
// kept as the next pass's picture of Drive.
assert_eq!(counted(&resumed, "queued"), 0, "{resumed}");
for sub in ["a", "b", "c"] {
assert_eq!(
std::fs::read(local.join(sub).join("f.txt")).unwrap(),
sub.as_bytes()
);
}
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let kept = reopen(&dir).sync_walk_load(folder).unwrap();
assert!(kept.is_some_and(|walk| walk.complete));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_pass_lists_only_the_folders_changed_on_drive() {
// Every pass listed every folder on Drive to find a few changes, so
// its cost grew with the size of the folder, not of the change. On a
// folder of 500k files that was hours per pass (#53). Now a pass
// starts from the last walk and lists only the folders Drive's event
// stream reported a change in.
let drive = FakeDrive::new();
let dir = scratch("mirror-dirty-folders");
let local = dir.join("local");
std::fs::create_dir_all(&local).unwrap();
for sub in ["a", "b", "c"] {
std::fs::create_dir(local.join(sub)).unwrap();
std::fs::write(local.join(sub).join("f.txt"), sub.as_bytes()).unwrap();
}
let (daemon, folder, client) = start_mirror(&drive, &dir, &[]);
assert!(wait_until(Duration::from_secs(30), || {
["a", "b", "c"]
.iter()
.all(|sub| drive.lookup(&format!("mirrored/{sub}/f.txt")).is_some())
}));
quiet_pass(&daemon, folder).expect("the folder settles");
// A listing of the folder nothing changes in would wait here.
let untouched = client.hold_next_children_of(&drive.lookup("mirrored/a").unwrap());
// Another computer edits a file, adds a folder with a folder in it,
// and deletes a folder.
drive
.device()
.write("mirrored/b/f.txt", b"edited elsewhere");
drive.device().mkdir("mirrored/new");
drive.device().mkdir("mirrored/new/deep");
drive.device().write("mirrored/new/deep/g.txt", b"new");
drive.device().trash("mirrored/c");
assert!(wait_until(Duration::from_secs(60), || {
std::fs::read(local.join("b/f.txt")).is_ok_and(|b| b == b"edited elsewhere")
&& std::fs::read(local.join("new/deep/g.txt")).is_ok_and(|b| b == b"new")
&& !local.join("c").exists()
}));
assert_eq!(std::fs::read(local.join("a/f.txt")).unwrap(), b"a");
// The passes that brought them listed the changed folders, and the
// new ones whole, but not the folder nothing changed in.
let quiet = quiet_pass(&daemon, folder).expect("the folder settles again");
assert!(counted(&quiet, "reused") > 0, "{quiet}");
assert!(!untouched.reached(), "listed a folder nothing changed in");
drop(untouched);
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_mirror_edit_does_not_replace_a_revision_another_computer_made_since() {
@@ -1702,6 +2110,46 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_mirror_edit_whose_reply_was_lost_is_not_kept_as_a_conflict() {
// Drive made the revision, but the answer never came back. The next
// pass saw both sides changed since the baseline and kept a conflict
// copy of this computer's own edit.
let drive = FakeDrive::new();
let dir = scratch("mirror-lost-revision-reply");
let (daemon, folder, client) = start_mirror(&drive, &dir, &[("a.txt", b"one")]);
let local = dir.join("local");
assert!(wait_until(Duration::from_secs(30), || drive
.lookup("mirrored/a.txt")
.is_some()));
assert!(wait_for_pass(&daemon, folder, 0));
client.lose_reply_to_next_revision();
std::fs::write(local.join("a.txt"), b"two").unwrap();
assert!(wait_until(Duration::from_secs(30), || {
on_drive(&drive, "mirrored/a.txt").is_some_and(|bytes| bytes == b"two")
}));
daemon
.request(&Request::SyncNow { id: Some(folder) })
.unwrap();
assert!(wait_for_pass(&daemon, folder, 0));
daemon
.request(&Request::SyncNow { id: Some(folder) })
.unwrap();
assert!(wait_for_pass(&daemon, folder, 0));
assert!(conflict_copies(&local, "a").is_empty());
assert!(
!drive.tree().keys().any(|k| k.contains("sync-conflict")),
"{:?}",
drive.tree()
);
assert_eq!(std::fs::read(local.join("a.txt")).unwrap(), b"two");
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_revision_made_during_a_mirror_download_still_arrives() {
@@ -3264,6 +3712,51 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "mounts FUSE: run explicitly on an isolated fake Drive"]
fn a_synced_folder_trashed_on_drive_does_not_block_attaching_another() {
let drive = FakeDrive::new();
let dir = scratch("attach-past-trash");
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
for folder in ["Gone", "Next", "Parent", "Parent/Old"] {
std::fs::create_dir(daemon.mountpoint.join(folder)).unwrap();
}
assert!(wait_until(Duration::from_secs(30), || {
daemon.pending().is_ok_and(|items| items.is_empty())
&& drive.lookup("Parent/Old").is_some()
&& drive.lookup("Next").is_some()
}));
let attach = |local: &str, remote: &str| {
let path = dir.join(local);
std::fs::create_dir_all(&path).unwrap();
daemon.request(&Request::AttachSyncFolder {
local_path: path.to_str().unwrap().into(),
remote_path: remote.into(),
})
};
attach("gone", "Gone").unwrap();
attach("old", "Parent/Old").unwrap();
drive.device().trash("Gone");
drive.device().trash("Parent/Old");
// Reads lag the server: wait until this client sees both in the trash.
assert!(wait_until(Duration::from_secs(60), || {
!daemon.mountpoint.join("Gone").exists()
&& !daemon.mountpoint.join("Parent/Old").exists()
}));
// B299: the first synced folder in the trash failed every later attach
// with "remote sync folder is in the trash".
attach("next", "Next").expect("a trashed synced folder blocked an unrelated attach");
// Its place on Drive still counts: the folder above it overlaps it.
assert!(
attach("parent", "Parent").is_err(),
"attached a folder above a synced folder in the trash"
);
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let _ = std::fs::remove_dir_all(&dir);
}
fn attached_my_files(daemon: &Daemon, drive: &FakeDrive, local: &Path) -> i64 {
std::fs::create_dir(daemon.mountpoint.join("Work")).unwrap();
assert!(wait_until(Duration::from_secs(30), || {
+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;
+29 -4
View File
@@ -239,9 +239,11 @@ fn stack_signal() -> i32 {
fn install_stack_handler() {
static INSTALLED: std::sync::Once = std::sync::Once::new();
extern "C" fn handler(_: i32) {
// Not async-signal-safe: the capture allocates. The process is being
// taken down for a hang anyway, and a thread interrupted inside the
// allocator only fails to answer.
// Not async-signal-safe: the capture allocates, and a thread caught
// inside the allocator never comes back. That is only acceptable in a
// process that is hung already and being taken down; never fire it
// in one whose other threads must go on (the stack test runs alone
// for this reason).
let stack = std::backtrace::Backtrace::force_capture();
STACKS.lock().insert(gettid(), stack);
}
@@ -288,9 +290,32 @@ mod tests {
use super::*;
use crate::sim::daemon::scratch;
/// Set in the child process the stack test runs in.
const ALONE: &str = "PDFS_SIM_WATCHDOG_ALONE";
#[test]
#[ignore = "signals every thread of the test process: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
#[ignore = "mounts nothing, but runs beside the sims: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_call_past_its_limit_is_reported_with_the_stacks() {
// Taking stacks signals every thread of the process, and the handler
// allocates. In the test process that is every other sim's daemon: a
// thread caught inside the allocator, or holding the database, never
// came back, and the sims beside this test hung. So it runs alone, in
// a process of its own.
if std::env::var_os(ALONE).is_none() {
let name = "sim::watchdog::tests::a_call_past_its_limit_is_reported_with_the_stacks";
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--ignored", "--exact", "--nocapture", name])
.env(ALONE, "1")
.output()
.expect("run the test in a process of its own");
let out = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && out.contains("1 passed"),
"{out}{}",
String::from_utf8_lossy(&output.stderr)
);
return;
}
let dir = scratch("watchdog");
let mut watchdog = Watchdog::new(&dir);
{
+897
View File
@@ -0,0 +1,897 @@
//! File sizes filled in after a cheap listing: one batch per folder, the
//! `getattr`s and `lookup`s that need a real size parked on it, and the
//! results applied to the tree as each chunk lands (`docs/BUGS.md` B14).
use super::*;
/// The size upgrades running now, and the replies parked on them. Shared
/// by every mount: the bound that matters is per daemon.
#[derive(Clone)]
pub(crate) struct SizeState {
/// Folders whose listing was enumerated cheaply and is having its file sizes
/// filled in right now, so a burst of `stat`s over a fresh listing starts one
/// upgrade rather than one per entry. See [`Core::spawn_size_upgrade`].
/// Size upgrades currently running, per folder inode, across every mount. A `getattr` that
/// needs a real size waits on the entry rather than issuing its own fetch —
/// `ls -l` of a folder is one `getattr` per file, and they must collapse
/// onto a single batch (`docs/BUGS.md` B14).
pub(crate) size_upgrades: Arc<Mutex<HashMap<u64, Arc<SizeUpgrade>>>>,
/// Replies parked on those upgrades. Shared across every mount for the same
/// reason the pool is: the bound that matters is per daemon.
pub(crate) size_waiters: Arc<SizeWaitQueue>,
}
impl SizeState {
pub(crate) fn new() -> Self {
Self {
size_upgrades: Arc::new(Mutex::new(HashMap::new())),
size_waiters: Arc::new(Default::default()),
}
}
}
impl Core {
/// Resolve the real size of every file in `parent`'s listing still carrying
/// a provisional one, returning when they are in `state`.
///
/// Called when a `stat` lands on such a file. That covers the paths
/// [`Core::ensure_children`] cannot: a listing rebuilt from the DB, or one
/// restored by [`Core::hydrate`] on mount, whose rows were persisted before
/// an earlier upgrade had a chance to run. Gathers the whole folder rather
/// than the one file asked for, because a `stat` of one entry in a listing
/// almost always means a `stat` of all of them.
pub(super) fn upgrade_sizes_for_parent(
&self,
ino: u64,
uid: &NodeUid,
parent: u64,
) -> Option<Arc<SizeUpgrade>> {
let provisional = |e: &Entry| {
matches!(
&e.node.kind,
NodeKind::File {
claimed_size: None,
..
}
)
};
let (key, mut missing): (u64, Vec<NodeUid>) = {
let st = self.state();
match st.children.get(&parent) {
// The listing is resident: batch the whole folder under its
// inode, so the rest of an `ls -l` rides along on this fetch.
Some(kids) => (
parent,
kids.iter()
.filter_map(|k| st.entries.get(k))
.filter(|e| provisional(e))
.map(|e| e.uid.clone())
.collect(),
),
// It is not, and returning here is what let a provisional size
// reach the caller anyway: a rename invalidates its parents'
// listings, so a freshly renamed file always landed in this
// branch. Resolve the single node instead, keyed by its own
// inode — folder and file inodes share one space, so the two
// single-flight keys cannot collide. (Same shape as B4: an
// early return that assumed the hot cache was authoritative.)
None => (ino, Vec::new()),
}
};
// The node that was actually asked about is never optional, whichever
// branch produced the batch.
if !missing.iter().any(|u| u == uid) {
missing.push(uid.clone());
}
// Returned, not awaited here: the caller is a `getattr` that must not
// answer with a provisional size (`docs/BUGS.md` B14), and it parks its reply
// on this batch rather than holding a thread until it lands.
self.upgrade_sizes(key, missing)
}
/// Fill in the true sizes of files a `Light` enumeration returned without
/// one, on a worker, after the listing has already been served.
///
/// This is the other half of the split in [`Core::ensure_children`]. The
/// listing itself needs only names and parentage, so it is served from the
/// cheap enumeration immediately; the S2K-per-file work that produces
/// `claimed_size` happens here, off the path the user is waiting on.
///
/// **Sizes are provisional until this lands.** `node_size` falls back to
/// `total_size_on_storage`, the *ciphertext* size, which is slightly larger
/// than the real one. A read must not plan on it: since B84 a size the
/// revision disagrees with fails the read, so `read` settles the size first
/// ([`Core::resolve_provisional_size`], `docs/BUGS.md` B100). In `stat` it is a
/// discrepancy that closes within a round trip, not a repeat of B11 (which
/// reported **0** and so suppressed reads entirely).
///
/// Single-flight per folder: a `stat` of every entry in a fresh listing is
/// the normal case, and each one must not start its own upgrade.
pub(super) fn spawn_size_upgrade(&self, folder_ino: u64, uids: Vec<NodeUid>) {
self.upgrade_sizes(folder_ino, uids);
}
/// Start (or join) the size upgrade for `key`, returning the batch a caller
/// can wait on — `None` when there was nothing to upgrade.
///
/// Single-flight per `key`. The fetch runs on its own thread rather than on
/// the [`Workers`] pool: callers wait on `Lane::Meta`, so a batch queued onto
/// that lane could have a wide enough `ls -l` fill it with threads waiting
/// for a job that can never be scheduled. `Lane::Transfer` would swap that
/// for starvation behind bulk reads. One short-lived thread per folder,
/// bounded by the single-flight, avoids both.
pub(super) fn upgrade_sizes(&self, key: u64, uids: Vec<NodeUid>) -> Option<Arc<SizeUpgrade>> {
if uids.is_empty() {
return None;
}
let claim = claim_size_upgrade(&mut self.sizes.size_upgrades.lock(), key, uids);
match claim {
SizeUpgradeClaim::Joined(slot) | SizeUpgradeClaim::Queued(slot) => Some(slot),
SizeUpgradeClaim::Start(slot, uids) => {
let core = self.clone();
let worker = slot.clone();
std::thread::spawn(move || core.run_size_upgrade(key, uids, worker));
Some(slot)
}
}
}
/// Hold `respond` back until `ino` has a real size, `slot`'s batch ends, or
/// [`SizeUpgrade::WAIT`] elapses — then run it, on the queue's thread.
///
/// The caller returns immediately. That is the whole point: the thread it
/// was running on is a FUSE dispatch thread or a [`Workers`] one, and both
/// are needed by everything else on the mount (audit F4).
pub(super) fn await_size(
&self,
ino: u64,
slot: Arc<SizeUpgrade>,
respond: impl FnOnce() + Send + 'static,
) {
let core = self.clone();
let waiter = SizeWaiter {
slot,
resolved: Box::new(move || core.size_is_real(ino)),
deadline: Instant::now() + SizeUpgrade::WAIT,
respond: Box::new(respond),
};
if !self.sizes.size_waiters.park(waiter) {
return;
}
let queue = self.sizes.size_waiters.clone();
if let Err(error) = std::thread::Builder::new()
.name("pdfs-size-waiters".into())
.spawn(move || queue.serve())
{
// Without a thread nothing would ever answer these. A provisional
// size is wrong; a `stat` that never returns wedges the caller.
warn!(%error, "no thread for parked size waiters; answering provisionally");
self.sizes.size_waiters.answer_all();
}
}
/// Fetch `uids` in chunks, applying and announcing each one as it lands.
///
/// Chunked so a waiter is released as soon as *its* file is resolved. A
/// single 793-node batch took ~80 s, which outran [`SizeUpgrade::WAIT`] and
/// put provisional sizes back in front of callers — the bug this was
/// supposed to fix (`docs/BUGS.md` B14).
///
/// When the batch ends, the thread takes over the oldest batch the cap held
/// back, so at most [`MAX_SIZE_UPGRADES`] threads run however many folders
/// a recursive walk touches (`docs/BUGS.md` B100).
pub(super) fn run_size_upgrade(&self, key: u64, uids: Vec<NodeUid>, slot: Arc<SizeUpgrade>) {
let (mut key, mut uids, mut slot) = (key, uids, slot);
loop {
for chunk in uids.chunks(SIZE_UPGRADE_CHUNK) {
let result =
self.block_on_within(BATCH_CALL_TIMEOUT, self.drive.enumerate_nodes(chunk));
self.apply_size_upgrade(key, result);
slot.chunk_done();
}
// Both of these must happen however the loop ended: a folder whose
// upgrade failed has to be retryable, and its waiters released.
let next = next_size_upgrade(&mut self.sizes.size_upgrades.lock(), key);
slot.finish();
let Some(next) = next else {
return;
};
(key, uids, slot) = next;
}
}
/// Settle the size of a file whose listing only carries the provisional
/// one, before a read plans its blocks on it or a write handle starts from
/// it. Returns the real size, or `None` when the fetch did not produce one.
///
/// A provisional size is the ciphertext size. The read path checks the
/// size it is given against the revision's own block table and fails the
/// read on a mismatch (B84), so reading on the provisional size is an `EIO`
/// every time. `getattr` usually settles the size first, but not when its
/// wait times out, so the read cannot rely on it (`docs/BUGS.md` B100).
pub(super) fn resolve_provisional_size(&self, ino: u64, uid: &NodeUid) -> Option<u64> {
let parent = self.state().entries.get(&ino)?.parent;
// Without a network the answer is `None` either way; the bound keeps a
// dead link from holding the open or read for the SDK's two minutes.
if !self.is_online() {
return None;
}
let result = self.block_on_bounded(self.drive.enumerate_nodes(std::slice::from_ref(uid)));
if let Err(e) = &result {
self.lost_link(e, "settle a provisional size");
}
self.apply_size_upgrade(parent, result);
let st = self.state();
match &st.entries.get(&ino)?.node.kind {
NodeKind::File {
claimed_size: Some(size),
..
} => Some((*size).max(0) as u64),
_ => None,
}
}
/// Wait, up to [`SizeUpgrade::WAIT`] as a `stat` would, for the real size
/// of every file in `ino`'s listing that still carries a provisional one.
///
/// For callers that read a whole listing's sizes straight from `state` and
/// do not run on a FUSE thread: `pdfs ls` and the app's file browser. A
/// listing just fetched has the ciphertext size of every file in it until
/// its upgrade lands, and they showed those (`docs/BUGS.md` B115).
pub(super) fn settle_listing_sizes(&self, ino: u64) {
// Offline the fetch cannot succeed; the wait would only delay the
// answer it ends up giving anyway.
if !self.is_online() {
return;
}
let missing: Vec<NodeUid> = {
let st = self.state();
st.children
.get(&ino)
.map(|kids| {
kids.iter()
.filter_map(|k| st.entries.get(k))
.filter(|e| {
!is_local_uid(&e.uid)
&& matches!(
&e.node.kind,
NodeKind::File {
claimed_size: None,
..
}
)
})
.map(|e| e.uid.clone())
.collect()
})
.unwrap_or_default()
};
if let Some(slot) = self.upgrade_sizes(ino, missing) {
slot.wait_finished(Instant::now() + SizeUpgrade::WAIT);
}
}
/// Whether `ino` has a real size — the condition a waiter is waiting on.
/// A node that vanished counts as resolved; there is nothing left to wait
/// for, and its caller will find the `ENOENT` for itself.
pub(super) fn size_is_real(&self, ino: u64) -> bool {
let st = self.state();
st.entries.get(&ino).is_none_or(|e| {
!matches!(
&e.node.kind,
NodeKind::File {
claimed_size: None,
..
}
)
})
}
/// Adopt the sizes a completed upgrade fetched. Split from
/// [`Core::upgrade_sizes`] so the single-flight bookkeeping there has one
/// exit path rather than one per early return.
pub(super) fn apply_size_upgrade(
&self,
folder_ino: u64,
result: Result<Vec<Node>, ProtonError>,
) {
let core = self;
{
let mut nodes = match result {
Ok(nodes) => nodes,
Err(e) => {
// Not fatal: the listing stands, sizes just stay provisional
// until something invalidates and re-enumerates it.
warn!(folder_ino, error = %e, "size upgrade failed; sizes stay provisional");
return;
}
};
// A queued write is ahead of anything the server can report, so its
// optimistic size must survive this just as it survives a re-listing
// (B11).
core.stamp_pending_sizes(&mut nodes);
let mut changed: Vec<u64> = Vec::new();
let mut st = core.state();
for node in nodes {
// Only adopt the size. Re-interning wholesale would also adopt a
// name or parent that a rename/move may have changed locally
// while this was in flight, undoing it.
let Some(&ino) = st.by_uid.get(&node.uid) else {
continue;
};
changed.push(ino);
// An open write handle is ahead of the server too (B109).
if st.active_writes.contains_key(&ino) {
continue;
}
let NodeKind::File { claimed_size, .. } = &node.kind else {
continue;
};
let (Some(size), Some(entry)) = (*claimed_size, st.entries.get_mut(&ino)) else {
continue;
};
if let NodeKind::File { claimed_size, .. } = &mut entry.node.kind {
*claimed_size = Some(size);
}
}
let updated: Vec<Node> = st
.children
.get(&folder_ino)
.map(|kids| {
kids.iter()
.filter_map(|k| st.entries.get(k).map(|e| e.node.clone()))
.collect()
})
.unwrap_or_default();
drop(st);
if let Err(e) = core.db.upsert_nodes(&updated) {
warn!(folder_ino, error = %e, "persisting upgraded sizes failed");
}
// Without this the corrected size is invisible for the length of the
// attr TTL: the kernel answers `stat` from the provisional attrs it
// cached while the listing was being served, so `ls -l` reports the
// ciphertext size for up to 30 s even though the daemon has had the
// real one all along. Notify *after* the DB write, so a re-`getattr`
// provoked by the invalidation cannot race the persistence.
//
// Attributes only (offset -1): the content did not change, and a
// page-cache invalidation deadlocks when this runs inside a `read`
// (B100 resolves sizes there). The kernel holds the page lock of
// that read until we reply, and the invalidation waits for the
// same lock, so the read never answered (docs/BUGS.md B110).
for mount in core.states.live() {
if let Some(notifier) = mount.notifier.get() {
for &ino in &changed {
let _ = notifier.inval_attrs(ino);
}
}
}
debug!(folder_ino, files = updated.len(), "filled in listing sizes");
}
}
}
/// A size upgrade in flight for one folder, so the `getattr`s that need its
/// result wait for the one batch instead of each fetching its own node.
///
/// A plain `Condvar` rather than a channel: the waiters do not want a value,
/// only the edge, and there may be hundreds of them for one folder.
#[derive(Default)]
pub(super) struct Progress {
/// The whole batch has been applied (or failed). Nothing more is coming.
done: bool,
/// Bumped every time a chunk lands, so a waiter can tell "no progress since
/// I last looked" from "progress happened while I was looking".
generation: u64,
}
/// A size upgrade in flight for one folder, so the `getattr`s and `lookup`s that
/// need its result wait for the one batch instead of each fetching its own node.
///
/// Waiters are released **per chunk**, not once at the end: a waiter only cares
/// about its own file, and waiting for the other 792 is what let a large folder
/// outrun the timeout (`docs/BUGS.md` B14).
#[derive(Default)]
pub(super) struct SizeUpgrade {
inner: Mutex<Progress>,
ready: Condvar,
/// The batch, while it waits for a thread because [`MAX_SIZE_UPGRADES`]
/// were already running, with when it was queued so the oldest goes first.
/// `None` once a thread has it.
queued: Mutex<Option<(Instant, Vec<NodeUid>)>>,
}
/// What [`Core::upgrade_sizes`] does with one folder's batch.
pub(super) enum SizeUpgradeClaim {
/// A batch for this folder is already running or queued; wait on it.
Joined(Arc<SizeUpgrade>),
/// The cap is reached. The batch waits for a running thread to take it.
Queued(Arc<SizeUpgrade>),
/// Start a thread for the batch.
Start(Arc<SizeUpgrade>, Vec<NodeUid>),
}
/// Register the batch for `key` in `in_flight` and decide who runs it.
///
/// Past the cap this used to return nothing, and the caller answered with the
/// provisional size at once. Nothing retried the folder until the next `stat`,
/// so a recursive walk over more than [`MAX_SIZE_UPGRADES`] fresh folders showed
/// ciphertext sizes for most of them (`docs/BUGS.md` B100). Queued, the batch is still
/// fetched, and a waiter gets the real size unless [`SizeUpgrade::WAIT`] runs out.
pub(super) fn claim_size_upgrade(
in_flight: &mut HashMap<u64, Arc<SizeUpgrade>>,
key: u64,
uids: Vec<NodeUid>,
) -> SizeUpgradeClaim {
if let Some(existing) = in_flight.get(&key) {
return SizeUpgradeClaim::Joined(existing.clone());
}
let running = in_flight
.values()
.filter(|slot| slot.queued.lock().is_none())
.count();
let slot = Arc::new(SizeUpgrade::default());
in_flight.insert(key, slot.clone());
if running >= MAX_SIZE_UPGRADES {
*slot.queued.lock() = Some((Instant::now(), uids));
return SizeUpgradeClaim::Queued(slot);
}
SizeUpgradeClaim::Start(slot, uids)
}
/// Retire the finished batch for `done` and hand its thread the oldest queued
/// batch, if there is one.
pub(super) fn next_size_upgrade(
in_flight: &mut HashMap<u64, Arc<SizeUpgrade>>,
done: u64,
) -> Option<(u64, Vec<NodeUid>, Arc<SizeUpgrade>)> {
in_flight.remove(&done);
let (key, slot) = in_flight
.iter()
.filter_map(|(key, slot)| slot.queued.lock().as_ref().map(|(at, _)| (*at, *key, slot)))
.min_by_key(|(at, _, _)| *at)
.map(|(_, key, slot)| (key, slot.clone()))?;
let (_, uids) = slot.queued.lock().take()?;
Some((key, uids, slot))
}
impl SizeUpgrade {
/// How long a caller will wait for a real size before answering with the
/// provisional one.
///
/// A `stat` that never returns is far worse than one that is briefly wrong:
/// on timeout the caller falls back to the pre-fix behaviour rather than
/// wedging whatever is listing the directory.
const WAIT: Duration = Duration::from_secs(10);
/// Whether the batch has ended, however it ended. A waiter that sees this
/// has nothing left to wait for.
fn is_finished(&self) -> bool {
self.inner.lock().done
}
/// Announce that a chunk has been applied. Every waiter re-checks its own
/// node; the ones it resolved return, the rest go back to sleep.
fn chunk_done(&self) {
self.inner.lock().generation += 1;
self.ready.notify_all();
}
/// Block until the batch has ended or `deadline` has passed. Only for a
/// caller that is not on a FUSE or [`Workers`] thread; those park their
/// reply with [`Core::await_size`] instead.
fn wait_finished(&self, deadline: Instant) {
let mut progress = self.inner.lock();
while !progress.done {
if self.ready.wait_until(&mut progress, deadline).timed_out() {
return;
}
}
}
/// Release every waiter for good. The worker must reach this on all paths.
fn finish(&self) {
let mut progress = self.inner.lock();
progress.done = true;
progress.generation += 1;
drop(progress);
self.ready.notify_all();
}
}
/// How often [`SizeWaitQueue::serve`] re-tests its parked waiters.
///
/// The predicates read `state`, which the applying thread writes under its own
/// lock, so this polls rather than waiting on each slot's condvar: one thread
/// cannot wait on a hundred condvars, and the whole point of the queue is that
/// there is only one thread. Twenty milliseconds is far below the round trip a
/// waiter is waiting on and only ticks while something is actually parked.
pub(super) const SIZE_WAIT_POLL: Duration = Duration::from_millis(20);
/// A reply held back until a size upgrade resolves the node it describes.
pub(super) struct SizeWaiter {
/// The batch this reply is waiting on. When it ends, so does the wait.
slot: Arc<SizeUpgrade>,
/// Whether *this* waiter's node now has a real size.
///
/// Called with no queue lock held: it reaches into `state`, and the thread
/// applying a chunk holds `state` before it announces the chunk — taking
/// them in the other order would close the cycle.
resolved: Box<dyn Fn() -> bool + Send>,
/// When to answer with the provisional size anyway. A `stat` that never
/// returns is far worse than one that is briefly wrong.
deadline: Instant,
/// Sends the FUSE reply. Runs on the serving thread.
respond: Box<dyn FnOnce() + Send>,
}
#[derive(Default)]
pub(super) struct Parked {
waiters: Vec<SizeWaiter>,
/// Whether a thread is currently serving `waiters`. The thread clears this
/// as it retires, so the next park starts a new one.
running: bool,
}
/// Every reply parked on a size upgrade, served by at most one thread.
///
/// This exists because waiting used to happen on the [`Workers`] pool. Sizes
/// are single-flighted per folder, so an `ls -l` across N cold folders parks a
/// waiter per entry — and each of those held a pool thread asleep on a condvar
/// for up to [`SizeUpgrade::WAIT`]. With enough folders that is every thread in
/// both lanes, including the ones reserved for metadata precisely so that this
/// could not happen (audit F4). Parking the `Reply` instead costs one thread
/// for the whole mount, and only while something is parked.
#[derive(Default)]
pub(super) struct SizeWaitQueue {
parked: Mutex<Parked>,
/// Woken when a waiter is added, so a serving thread re-computes how long
/// it may sleep.
added: Condvar,
}
impl SizeWaitQueue {
/// Park `waiter`. Returns whether the caller must start a serving thread.
fn park(&self, waiter: SizeWaiter) -> bool {
let mut parked = self.parked.lock();
parked.waiters.push(waiter);
if parked.running {
drop(parked);
self.added.notify_all();
return false;
}
parked.running = true;
true
}
/// Answer every waiter whose node has resolved, whose batch has ended, or
/// whose deadline has passed; sleep until the next one might. Returns when
/// nothing is parked any more.
fn serve(&self) {
loop {
// Taken out of the lock wholesale: the predicates and the replies
// both take locks of their own, and none of them may be called
// while this one is held.
let taken = std::mem::take(&mut self.parked.lock().waiters);
let now = Instant::now();
let mut keep = Vec::with_capacity(taken.len());
for waiter in taken {
if now >= waiter.deadline || waiter.slot.is_finished() || (waiter.resolved)() {
(waiter.respond)();
} else {
keep.push(waiter);
}
}
let mut parked = self.parked.lock();
parked.waiters.append(&mut keep);
if parked.waiters.is_empty() {
parked.running = false;
return;
}
let until = parked
.waiters
.iter()
.map(|w| w.deadline)
.min()
.unwrap_or(now)
.min(Instant::now() + SIZE_WAIT_POLL);
self.added.wait_until(&mut parked, until);
}
}
/// Answer everything parked, immediately, and retire the serving thread.
/// Used when there is no thread to serve with: a provisional size now beats
/// a reply that never comes.
fn answer_all(&self) {
let taken = {
let mut parked = self.parked.lock();
parked.running = false;
std::mem::take(&mut parked.waiters)
};
for waiter in taken {
(waiter.respond)();
}
}
}
#[cfg(test)]
mod tests {
use super::{
LinkId, MAX_SIZE_UPGRADES, NodeUid, SizeUpgrade, SizeUpgradeClaim, SizeWaitQueue,
SizeWaiter, VolumeId, claim_size_upgrade, next_size_upgrade,
};
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::time::{Duration, Instant};
/// Park a waiter the way [`Core::await_size`] does, and hand back the
/// channel its reply is sent down, so a test can time the release.
fn park(
queue: &Arc<SizeWaitQueue>,
slot: Arc<SizeUpgrade>,
resolved: impl Fn() -> bool + Send + 'static,
deadline: Instant,
) -> mpsc::Receiver<()> {
let (tx, rx) = mpsc::channel();
let waiter = SizeWaiter {
slot,
resolved: Box::new(resolved),
deadline,
respond: Box::new(move || {
let _ = tx.send(());
}),
};
if queue.park(waiter) {
let queue = queue.clone();
std::thread::spawn(move || queue.serve());
}
rx
}
/// Long enough that a test never trips the deadline by accident, short
/// enough that one which is *meant* to does not take ten seconds.
fn far_off() -> Instant {
Instant::now() + Duration::from_secs(30)
}
/// The point of the per-chunk design: a waiter is answered as soon as *its
/// own* file is resolved, without waiting for the rest of the folder. A
/// single batch over 793 nodes took ~80 s, which outran the timeout and
/// handed back the provisional size this is all meant to prevent.
#[test]
fn a_waiter_returns_on_the_chunk_that_resolves_it() {
let queue = Arc::new(SizeWaitQueue::default());
let slot = Arc::new(SizeUpgrade::default());
let mine = Arc::new(AtomicBool::new(false));
let worker = slot.clone();
let flag = mine.clone();
let t = std::thread::spawn(move || {
// Our node lands in the first chunk; two more follow.
std::thread::sleep(Duration::from_millis(30));
flag.store(true, Ordering::SeqCst);
worker.chunk_done();
std::thread::sleep(Duration::from_millis(300));
worker.chunk_done();
worker.finish();
});
let started = Instant::now();
let rx = park(&queue, slot, move || mine.load(Ordering::SeqCst), far_off());
rx.recv().expect("the waiter is answered");
// Released by the first chunk, not the last.
assert!(started.elapsed() < Duration::from_millis(200));
t.join().unwrap();
}
/// `pdfs ls` waits for the whole batch, so it lists no ciphertext size
/// (`docs/BUGS.md` B115), but no longer than a `stat` would.
#[test]
fn a_listing_waits_for_the_whole_size_batch_but_not_forever() {
let slot = Arc::new(SizeUpgrade::default());
let worker = slot.clone();
// Read before the spawn: the worker's sleeps can start before this
// thread runs again, which made the bound below fail on a busy runner.
let started = Instant::now();
let t = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(30));
worker.chunk_done();
std::thread::sleep(Duration::from_millis(60));
worker.finish();
});
slot.wait_finished(started + Duration::from_secs(5));
// Past the first chunk, up to the end of the batch.
assert!(started.elapsed() >= Duration::from_millis(90));
assert!(slot.is_finished());
t.join().unwrap();
let stuck = SizeUpgrade::default();
let started = Instant::now();
stuck.wait_finished(started + Duration::from_millis(50));
assert!(started.elapsed() < Duration::from_secs(1));
assert!(!stuck.is_finished());
}
/// A chunk that does not resolve this waiter must not answer it.
#[test]
fn an_unrelated_chunk_does_not_release_a_waiter() {
let queue = Arc::new(SizeWaitQueue::default());
let slot = Arc::new(SizeUpgrade::default());
let worker = slot.clone();
let t = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(30));
worker.chunk_done();
std::thread::sleep(Duration::from_millis(120));
worker.finish();
});
let started = Instant::now();
// Never resolved: only `finish` can end this wait.
let rx = park(&queue, slot, || false, far_off());
rx.recv().expect("the waiter is answered");
assert!(started.elapsed() >= Duration::from_millis(140));
t.join().unwrap();
}
/// A batch that ends without resolving the node — a failed fetch — still
/// answers its waiters, who fall back to the provisional size.
#[test]
fn finish_releases_a_waiter_that_was_never_resolved() {
let queue = Arc::new(SizeWaitQueue::default());
let slot = Arc::new(SizeUpgrade::default());
let worker = slot.clone();
let t = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(30));
worker.finish();
});
let started = Instant::now();
let rx = park(&queue, slot, || false, far_off());
rx.recv().expect("the waiter is answered");
assert!(started.elapsed() < SizeUpgrade::WAIT);
t.join().unwrap();
}
/// Already resolved before parking: answered on the first pass. This is the
/// follower that arrives after the chunk it needed has landed.
#[test]
fn an_already_resolved_waiter_does_not_block() {
let queue = Arc::new(SizeWaitQueue::default());
let started = Instant::now();
let rx = park(&queue, Arc::new(SizeUpgrade::default()), || true, far_off());
rx.recv().expect("the waiter is answered");
assert!(started.elapsed() < Duration::from_millis(100));
}
/// Finishing before anyone parks must not strand the late arrival — the
/// flag is what is checked, not the notification, which it would miss.
#[test]
fn waiting_after_finish_returns_at_once() {
let queue = Arc::new(SizeWaitQueue::default());
let slot = Arc::new(SizeUpgrade::default());
slot.finish();
let started = Instant::now();
let rx = park(&queue, slot, || false, far_off());
rx.recv().expect("the waiter is answered");
assert!(started.elapsed() < Duration::from_millis(100));
}
/// Every waiter is answered, not just the first: one `ls -l` puts one
/// waiter per file on the same folder.
#[test]
fn all_waiters_are_released() {
let queue = Arc::new(SizeWaitQueue::default());
let slot = Arc::new(SizeUpgrade::default());
let waiters: Vec<_> = (0..8)
.map(|_| park(&queue, slot.clone(), || false, far_off()))
.collect();
std::thread::sleep(Duration::from_millis(20));
slot.finish();
for rx in waiters {
rx.recv().expect("every waiter is answered");
}
}
/// The deadline is the backstop: a batch that never finishes must not wedge
/// the caller's `stat` forever.
#[test]
fn a_waiter_gives_up_at_the_deadline() {
let queue = Arc::new(SizeWaitQueue::default());
let started = Instant::now();
// Nothing will ever resolve or finish this.
let rx = park(
&queue,
Arc::new(SizeUpgrade::default()),
|| false,
Instant::now() + Duration::from_millis(120),
);
rx.recv().expect("the waiter is answered");
assert!(started.elapsed() >= Duration::from_millis(120));
}
/// The serving thread retires when nothing is parked, and a later park
/// starts a new one — otherwise the second `ls -l` of the session would
/// hang forever.
#[test]
fn the_queue_serves_again_after_it_has_drained() {
let queue = Arc::new(SizeWaitQueue::default());
for _ in 0..3 {
let rx = park(&queue, Arc::new(SizeUpgrade::default()), || true, far_off());
rx.recv().expect("the waiter is answered");
}
}
/// With no thread to serve them, waiters are answered on the spot rather
/// than never: a provisional size beats a `stat` that does not return.
#[test]
fn answer_all_releases_everything_parked() {
let queue = SizeWaitQueue::default();
let (tx, rx) = mpsc::channel();
for _ in 0..4 {
let tx = tx.clone();
queue.park(SizeWaiter {
slot: Arc::new(SizeUpgrade::default()),
resolved: Box::new(|| false),
deadline: far_off(),
respond: Box::new(move || {
let _ = tx.send(());
}),
});
}
drop(tx);
queue.answer_all();
assert_eq!(rx.into_iter().count(), 4);
}
fn uids(links: &[&str]) -> Vec<NodeUid> {
links
.iter()
.map(|link| NodeUid::new(VolumeId::from("vol"), LinkId::from(*link)))
.collect()
}
/// Past the cap a folder used to get no upgrade at all, so a recursive
/// walk reported ciphertext sizes for most of what it listed (`docs/BUGS.md` B100).
#[test]
fn a_folder_past_the_cap_is_queued_not_dropped() {
let mut in_flight = HashMap::new();
for key in 0..MAX_SIZE_UPGRADES as u64 {
let claim = claim_size_upgrade(&mut in_flight, key, uids(&["a"]));
assert!(matches!(claim, SizeUpgradeClaim::Start(..)));
}
let key = MAX_SIZE_UPGRADES as u64;
let claim = claim_size_upgrade(&mut in_flight, key, uids(&["late"]));
let SizeUpgradeClaim::Queued(slot) = claim else {
panic!("expected the batch to be queued");
};
assert!(Arc::ptr_eq(&slot, &in_flight[&key]));
// A second caller for the queued folder waits on the same batch.
let again = claim_size_upgrade(&mut in_flight, key, uids(&["late"]));
assert!(matches!(again, SizeUpgradeClaim::Joined(s) if Arc::ptr_eq(&s, &slot)));
}
#[test]
fn a_finished_batch_hands_its_thread_the_oldest_queued_one() {
let mut in_flight = HashMap::new();
for key in 0..MAX_SIZE_UPGRADES as u64 {
claim_size_upgrade(&mut in_flight, key, uids(&["a"]));
}
let first = MAX_SIZE_UPGRADES as u64;
claim_size_upgrade(&mut in_flight, first, uids(&["first"]));
std::thread::sleep(Duration::from_millis(2));
claim_size_upgrade(&mut in_flight, first + 1, uids(&["second"]));
let (key, taken, slot) = next_size_upgrade(&mut in_flight, 0).expect("a queued batch");
assert_eq!((key, taken), (first, uids(&["first"])));
assert!(slot.queued.lock().is_none());
assert!(!in_flight.contains_key(&0));
// Still at the cap: the handed-over batch counts as running.
let running = in_flight
.values()
.filter(|s| s.queued.lock().is_none())
.count();
assert_eq!(running, MAX_SIZE_UPGRADES);
let (key, _, _) = next_size_upgrade(&mut in_flight, 1).expect("the other one");
assert_eq!(key, first + 1);
assert!(next_size_upgrade(&mut in_flight, 2).is_none());
}
}
+48 -7
View File
@@ -7,9 +7,9 @@ use std::fs::File;
use std::path::PathBuf;
use std::sync::Arc;
use pdfs_core::cache::StagedWrite;
use pdfs_core::db::Db;
use pdfs_core::{Access, access_for};
use pdfs_store::cache::StagedWrite;
use pdfs_store::db::Db;
#[cfg(test)]
use proton_drive_rs::MemberRole;
use proton_drive_rs::proton_sdk::ids::NodeUid;
@@ -167,6 +167,27 @@ impl WriteHandle {
self.base_revision_id = crate::node_revision_id(node);
}
/// Resize the file to `size`, as `setattr` does through an open handle.
///
/// The scratch file goes first: a resize it refuses (a full disk on a
/// grow) fails with nothing recorded. Otherwise the length and the
/// authored ranges would describe bytes the scratch file does not hold,
/// and the call would have succeeded.
pub(crate) fn resize(&mut self, size: u64) -> std::io::Result<()> {
self.file.set_len(size)?;
if size < self.len {
// Shrink: drop authored ranges past the new end.
self.written.clip(size);
} else if size > self.len {
// Grow: the new tail is defined as zeros, so claim it as authored
// rather than base content.
self.written.add(self.len, size);
}
self.len = size;
self.dirty = true;
Ok(())
}
/// Account for `[offset, end)` having been written through this handle.
///
/// A write past the end leaves a hole that reads as zeros, exactly like a
@@ -353,12 +374,12 @@ impl DbWrite {
/// write still happens synchronously on this thread before the caller proceeds,
/// so a read that follows a mutation still sees it.
pub(crate) struct StateGuard<'a> {
guard: Option<parking_lot::MutexGuard<'a, State>>,
guard: Option<pdfs_core::lockrank::RankedGuard<'a, State>>,
db: &'a Arc<Db>,
}
impl<'a> StateGuard<'a> {
pub(crate) fn new(guard: parking_lot::MutexGuard<'a, State>, db: &'a Arc<Db>) -> Self {
pub(crate) fn new(guard: pdfs_core::lockrank::RankedGuard<'a, State>, db: &'a Arc<Db>) -> Self {
Self {
guard: Some(guard),
db,
@@ -1620,7 +1641,7 @@ mod tests {
let (st, _dir) = state();
let db = st.db.clone();
let root = uid("root").to_string();
let state = parking_lot::Mutex::new(st);
let state = pdfs_core::lockrank::Ranked::new(pdfs_core::lockrank::Rank::State, st);
{
let mut guard = StateGuard::new(state.lock(), &db);
guard.intern(0, node("root", "none", "My Files", true));
@@ -1749,9 +1770,9 @@ mod tests {
node("shared-child", "shared", "pending.txt", false),
);
st.flushed_db()
.enqueue_op(&pdfs_core::db::PendingOp {
.enqueue_op(&pdfs_store::db::PendingOp {
id: 0,
kind: pdfs_core::db::OP_RENAME.to_string(),
kind: pdfs_store::db::OP_RENAME.to_string(),
uid: uid("shared-child").to_string(),
parent_uid: Some(shared.uid.to_string()),
name: Some("pending-renamed.txt".to_string()),
@@ -2304,6 +2325,26 @@ mod tests {
}
}
#[test]
fn a_resize_the_scratch_file_refuses_changes_nothing() {
let mut h = handle(4, 4);
h.written.add(0, 4);
// A read-only descriptor refuses `ftruncate`, as a full disk does a grow.
let path = std::env::temp_dir().join(format!("pdfs-resize-test-{}", std::process::id()));
std::fs::write(&path, b"kept").unwrap();
h.file = Arc::new(File::open(&path).unwrap());
let _ = std::fs::remove_file(&path);
assert!(h.resize(10).is_err());
assert_eq!((h.len, h.dirty), (4, false));
assert_eq!(h.written.segments(4, 10), vec![(4, 10, false)]);
let mut h = handle(4, 4);
h.resize(10).unwrap();
assert_eq!((h.len, h.dirty), (10, true));
assert_eq!(h.written.segments(4, 10), vec![(4, 10, true)]);
}
/// A file created offline is written while its queued create lands. The
/// placeholder had no revision, so the handle takes the empty file the
/// create made as its base (docs/BUGS.md B113).
+54 -3
View File
@@ -15,6 +15,7 @@
//! 3. **Sample memory.** That hang peaked at 5.2 GiB resident, and nobody knew
//! until it was over.
use std::collections::HashSet;
use std::io::{BufRead, BufReader, Write as _};
use std::os::unix::net::UnixStream;
use std::path::{Path, PathBuf};
@@ -64,16 +65,18 @@ pub(crate) fn run(core: Core, control_socket: PathBuf) {
// Per-lane completion counts from the previous tick, to tell a queue that is
// being worked through from one that is not moving at all.
let mut last_completed = (0_u64, 0_u64);
// The services already reported as ended, so each is reported once.
let mut ended = HashSet::new();
while core.shutdown.sleep(TICK) {
let report = core.diagnostics();
let stalled = report_stalls(&report, last_completed);
let stalled = report_stalls(&report, last_completed) | report_ended(&report, &mut ended);
last_completed = (report.meta_completed, report.transfer_completed);
if last_rss.elapsed() >= RSS_EVERY {
info!(
rss_bytes = report.rss_bytes,
pending_ops = report.pending_ops,
pending_ops = ?report.pending_ops,
meta_queued = report.meta_queued,
transfer_queued = report.transfer_queued,
stalled,
@@ -174,6 +177,24 @@ fn report_stalls(report: &pdfs_core::control::Diagnostics, last_completed: (u64,
stalled
}
/// WARN once about each service thread that has ended. Every one of them runs
/// until the mount stops, and the supervisor stops looking once a stop
/// begins, so an ended one died early: a panic, or a loop that gave up.
/// Returns whether any is ended.
fn report_ended(report: &pdfs_core::control::Diagnostics, reported: &mut HashSet<String>) -> bool {
let mut any = false;
for service in report.services.iter().filter(|service| !service.running) {
any = true;
if reported.insert(service.name.clone()) {
warn!(
service = %service.name,
"a daemon service has ended while the mount runs; it does not restart until the daemon does"
);
}
}
any
}
/// Whether the watchdog wants its next ping. The first one is due at once.
fn ping_due(last_ping: Option<Instant>, period: Duration) -> bool {
last_ping.is_none_or(|at| at.elapsed() >= period)
@@ -208,7 +229,36 @@ fn probe(control_socket: &Path) -> bool {
#[cfg(test)]
mod tests {
use super::*;
use pdfs_core::control::{Diagnostics, InflightRequest, SyncEngineState, WorkerState};
use pdfs_core::control::{
Diagnostics, InflightRequest, ServiceState, SyncEngineState, WorkerState,
};
/// A service that ended is reported, once, and one still running is not.
#[test]
fn an_ended_service_is_reported_once() {
let service = |name: &str, running| ServiceState {
name: name.into(),
running,
age_secs: 60,
};
let report = Diagnostics {
services: vec![
service("pdfs-sync", true),
service("pdfs-pin-keeper", false),
],
..Default::default()
};
let mut reported = HashSet::new();
assert!(report_ended(&report, &mut reported));
assert_eq!(reported, HashSet::from(["pdfs-pin-keeper".to_string()]));
assert!(report_ended(&report, &mut reported));
assert_eq!(reported.len(), 1);
let healthy = Diagnostics {
services: vec![service("pdfs-sync", true)],
..Default::default()
};
assert!(!report_ended(&healthy, &mut HashSet::new()));
}
fn busy_worker(age_secs: u64) -> WorkerState {
WorkerState {
@@ -305,6 +355,7 @@ mod tests {
pass_age_secs: SYNC_STALL_AFTER.as_secs() * 4,
pass_idle_secs: 5,
panics: 0,
traces: Vec::new(),
};
assert!(!report_stalls(&with_sync(busy.clone()), (0, 0)));
let quiet = SyncEngineState {
+32 -4
View File
@@ -18,7 +18,10 @@
//! copy whose sibling has no recorded SHA-1 is treated as divergent — the sweep
//! never removes a file it cannot prove is a duplicate.
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use parking_lot::Mutex;
use std::time::Duration;
use pdfs_core::batch;
@@ -29,6 +32,31 @@ use tracing::{debug, info, warn};
use super::{Core, node_content_sha1, node_revision_id, node_size};
/// What the conflict sweep may do, and the copies it already checked this
/// run.
#[derive(Clone)]
pub(crate) struct SweepState {
/// Whether the conflict sweep may actually trash the duplicates it finds, or
/// only report them. Resolved once at mount from config + environment
/// ([`AppConfig::resolved_conflict_sweep`]); [`SweepMode::Off`] means the
/// sweep thread is never spawned at all. See `docs/BUGS.md` B71.
pub(crate) sweep_mode: SweepMode,
/// Conflict copies the sweep has already checked against the activity log
/// this run, so each pass does not ask the database again. The log itself
/// is what keeps a copy from being flagged again after a restart. See
/// [`Core::run_conflict_sweep_loop`] and `docs/BUGS.md` B99.
pub(crate) conflict_notified: Arc<Mutex<HashSet<NodeUid>>>,
}
impl SweepState {
pub(crate) fn new(sweep_mode: SweepMode) -> Self {
Self {
sweep_mode,
conflict_notified: Arc::new(Mutex::new(HashSet::new())),
}
}
}
/// Time between sweeps. Conflicts are rare and non-urgent; a slow cadence keeps
/// the sweep off the hot path while still cleaning up within a few minutes.
const CONFLICT_SWEEP_INTERVAL: Duration = Duration::from_secs(300);
@@ -141,7 +169,7 @@ impl Core {
.unwrap_or_default();
let sibling = by_parent_name.get(&(parent, base.as_str())).copied();
match decide(node, sibling, &base, self.sweep_mode) {
match decide(node, sibling, &base, self.sweep.sweep_mode) {
SweepAction::Remove => {
// Only while online — the remote trash is the point. Offline,
// it waits for a later pass.
@@ -210,7 +238,7 @@ impl Core {
warn!(%uid, error = ?e, "conflict sweep: db delete after trash failed");
}
self.invalidate_trash();
self.conflict_notified.lock().remove(uid);
self.sweep.conflict_notified.lock().remove(uid);
self.log_activity(
ActivityKind::Trash,
name,
@@ -303,7 +331,7 @@ impl Core {
/// what keeps a restart from logging the same copy again (`docs/BUGS.md`
/// B99). A copy's name carries its own timestamp, so the name identifies it.
fn flag_conflict(&self, uid: &NodeUid, name: &str, detail: String) {
if !self.conflict_notified.lock().insert(uid.clone()) {
if !self.sweep.conflict_notified.lock().insert(uid.clone()) {
return;
}
match self.db.activity_has(ActivityKind::Conflict, name) {
File diff suppressed because it is too large. Load diff
+61
View File
@@ -102,6 +102,44 @@ pub fn idle_sleep(duration: Duration) {
}
}
/// Keep a cold daemon available for a service restart after key recovery.
pub fn wait_for_restart() -> std::io::Result<()> {
use tokio::signal::unix::{SignalKind, signal};
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?
.block_on(async {
let mut terminate = signal(SignalKind::terminate())?;
let mut interrupt = signal(SignalKind::interrupt())?;
let stop = async {
tokio::select! {
_ = terminate.recv() => {}
_ = interrupt.recv() => {}
}
};
park_until(stop, Duration::from_secs(10), watchdog_ping).await;
Ok(())
})
}
/// Call `ping` every `every` until `stop` completes. The parked daemon's whole
/// loop, apart from which signals end it.
async fn park_until(
stop: impl std::future::Future<Output = ()>,
every: Duration,
mut ping: impl FnMut(),
) {
let mut tick = tokio::time::interval(every);
tokio::pin!(stop);
loop {
tokio::select! {
_ = &mut stop => return,
_ = tick.tick() => ping(),
}
}
}
/// How long a mount may take to start before the watchdog counts it as hung.
///
/// Startup has no control socket to probe yet, and on a large account it is
@@ -156,3 +194,26 @@ pub(crate) fn watchdog_period() -> Option<Duration> {
let usec: u64 = std::env::var("WATCHDOG_USEC").ok()?.parse().ok()?;
(usec > 0).then(|| Duration::from_micros(usec / 2))
}
#[cfg(test)]
mod tests {
use super::*;
/// A parked daemon keeps the watchdog fed and returns once stopped, so the
/// restart after key recovery is a clean exit, not a kill.
#[test]
fn a_parked_daemon_pings_until_it_is_stopped() {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_time()
.start_paused(true)
.build()
.unwrap();
let pings = std::cell::Cell::new(0);
runtime.block_on(async {
let stop = tokio::time::sleep(Duration::from_secs(35));
park_until(stop, Duration::from_secs(10), || pings.set(pings.get() + 1)).await;
});
// Ticks at 0, 10, 20 and 30 seconds, then the stop at 35.
assert_eq!(pings.get(), 4);
}
}
+2 -26
View File
@@ -43,9 +43,10 @@ use pdfs_core::{CoreError, CoreResult};
use proton_drive_rs::proton_sdk::ids::NodeUid;
use proton_drive_rs::{PhotoLocation, PhotoTag, PhotoTagsUpdate, PhotoUploadMetadata};
use serde::{Deserialize, Serialize};
use sha1::{Digest, Sha1};
use tracing::{info, warn};
pub(crate) use pdfs_drive::digest::sha1_of;
use super::Core;
use crate::photos::can_make_thumbnail;
use crate::transfers::CountingReader;
@@ -1234,31 +1235,6 @@ fn open_archive(
.map_err(|e| CoreError::invalid(format!("{} is not a readable zip: {e}", path.display())))
}
/// The lowercase-hex SHA-1 of everything `reader` yields — the digest Proton's
/// photo duplicate detection is keyed on.
pub(crate) 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()))
}
pub(crate) 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::*;
+620
View File
@@ -0,0 +1,620 @@
//! The Drive trash as the front-ends see it: listing it, refreshing that
//! listing in the background, restoring from it, deleting from it for good.
use super::*;
/// Whether a trash refresh is running, and the wake-up for requests waiting
/// on its progress.
#[derive(Clone)]
pub(crate) struct TrashState {
/// True while a background refresh of the trash is already running, so a
/// burst of requests against a stale listing starts one refresh.
pub(crate) trash_refreshing: Arc<AtomicBool>,
/// Fires whenever a trash refresh persists a batch or finishes, so a
/// `ListTrash` request waiting on a first-ever refresh wakes on progress
/// instead of polling or blocking for the whole run. See
/// [`Core::await_trash_refresh`].
pub(crate) trash_progress: Arc<tokio::sync::Notify>,
}
impl TrashState {
pub(crate) fn new() -> Self {
Self {
trash_refreshing: Arc::new(AtomicBool::new(false)),
trash_progress: Arc::new(tokio::sync::Notify::new()),
}
}
}
impl Core {
/// List the account's trash, from the DB. Trashed nodes are outside the
/// mounted tree — the FUSE side forgot them when they were trashed — so the
/// listing is persisted in its own table rather than derived from `State`, and
/// each entry is identified by its uid (its only remaining handle) with an
/// empty path.
///
/// Stale-while-revalidate, like the photos timeline: a persisted listing comes
/// back at DB speed and is refreshed in the background past [`TRASH_TTL`].
/// Our own trash mutations invalidate it outright (see
/// [`Core::invalidate_trash`]), so the TTL only covers changes made elsewhere.
///
/// The refresh always runs *off* the request: a never-fetched trash waits for
/// it, but only for [`TRASH_FIRST_WAIT`], and then answers with the batches
/// that have landed so far. Blocking the request on the whole refresh is what
/// made a large trash unlistable — the refresh outran the front-end's read
/// timeout, the user asked again, and each attempt left another full refresh
/// grinding in the daemon (`docs/BUGS.md` B72).
pub(super) fn list_trash(&self) -> CoreResult<Vec<DirEntry>> {
let never_fetched = self.db.state_i64(TRASH_SYNCED_MS).ok().flatten().is_none();
if never_fetched || self.listing_stale(TRASH_SYNCED_MS, TRASH_TTL) {
self.spawn_trash_refresh();
}
if never_fetched {
self.await_trash_refresh(TRASH_FIRST_WAIT);
}
let items = self.db.trash_list().map_err(CoreError::from)?;
let trashed: HashSet<&str> = items.iter().map(|item| item.uid.as_str()).collect();
let trashed_parents: Vec<Option<String>> = items
.iter()
.map(|item| {
item.parent_uid
.clone()
.filter(|parent| trashed.contains(parent.as_str()))
})
.collect();
// Most of a trash comes from a handful of folders.
let mut origins: HashMap<String, Option<String>> = HashMap::new();
Ok(items
.into_iter()
.zip(trashed_parents)
.map(|(item, trashed_parent)| DirEntry {
trashed_from: item.parent_uid.as_ref().and_then(|parent| {
origins
.entry(parent.clone())
.or_insert_with(|| self.db.node_path(parent).ok().flatten())
.clone()
}),
trashed_parent,
trashed_at: item.trashed_at.unwrap_or(0),
name: item.name,
is_dir: item.is_dir,
size: item.size.max(0) as u64,
modified: item.mtime,
// A trashed node can't be pinned or served from the mount, so its
// content is never current cache: report neither.
pinned: false,
pinned_by_folder: false,
cached: false,
uid: item.uid,
path: String::new(),
role: String::new(),
shared_by: String::new(),
shared_at: 0,
shared_by_unverified: false,
issue: None,
})
.collect())
}
/// What a trashed folder holds: its children on the server, and the
/// stored trash entries trashed inside it before it went.
pub(super) fn list_trashed_folder(&self, uid: &str) -> CoreResult<Vec<DirEntry>> {
let folder =
parse_uid(uid).ok_or_else(|| CoreError::invalid(format!("invalid uid: {uid}")))?;
let children = self
.rt
.block_on(within_trash_call(
"enumerate trashed folder",
self.drive.enumerate_folder_children_node_uids(&folder),
))?
.map_err(|e| CoreError::from_api(&e, "enumerate trashed folder"))?;
let mut nodes = Vec::with_capacity(children.len());
for chunk in children.chunks(TRASH_MATERIALIZE_CHUNK) {
nodes.extend(
self.rt
.block_on(within_trash_call(
"enumerate nodes",
self.drive.enumerate_trashed_nodes_light(chunk),
))?
.map_err(|e| CoreError::from_api(&e, "enumerate nodes"))?,
);
}
let stored = self.db.trash_list().map_err(CoreError::from)?;
let stored_at: HashMap<&str, Option<i64>> = stored
.iter()
.map(|item| (item.uid.as_str(), item.trashed_at))
.collect();
let mut entries: Vec<DirEntry> = nodes
.iter()
.map(|TrashedNode { node, trash_time }| {
let uid = node.uid.to_string();
let trashed_at = trash_time
.or_else(|| stored_at.get(uid.as_str()).copied().flatten())
.unwrap_or(0);
trashed_entry(
uid,
node.name.clone(),
node.is_folder(),
node_size(node) as i64,
node.modification_time,
trashed_at,
folder.to_string(),
)
})
.collect();
let listed: HashSet<String> = entries.iter().map(|e| e.uid.clone()).collect();
entries.extend(
stored
.into_iter()
.filter(|item| {
item.parent_uid.as_deref() == Some(uid) && !listed.contains(&item.uid)
})
.map(|item| {
trashed_entry(
item.uid,
item.name,
item.is_dir,
item.size,
item.mtime,
item.trashed_at.unwrap_or(0),
folder.to_string(),
)
}),
);
entries.sort_by(|a, b| {
b.is_dir
.cmp(&a.is_dir)
.then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
});
Ok(entries)
}
/// Re-fetch the trash listing from the server and persist it.
///
/// Only nodes the stored listing does not hold yet are read, and light: a
/// trashed file needs no content key, so none is unlocked. Each chunk of
/// [`TRASH_MATERIALIZE_CHUNK`] is stored as it lands, so a large trash
/// fills the page while it loads. Rows the server no longer lists go once
/// the whole listing is in, never earlier.
pub(super) async fn refresh_trash(&self) -> CoreResult<()> {
let started = Instant::now();
let uids = within_trash_call("enumerate trash", self.drive.enumerate_trash_node_uids())
.await?
.map_err(|e| CoreError::from_api(&e, "enumerate trash"))?;
info!(
count = uids.len(),
elapsed_ms = started.elapsed().as_millis() as u64,
"trash refresh: enumerated"
);
let seen = self.db.trash_seen().unwrap_or_default();
let complete = self
.db
.state_i64(TRASH_COMPLETE_MS)
.ok()
.flatten()
.is_some();
let now = now_secs();
let listed: HashSet<String> = uids.iter().map(ToString::to_string).collect();
let removed = self.db.trash_retain(&listed).map_err(CoreError::from)?;
if removed > 0 {
self.trash.trash_progress.notify_waiters();
}
let missing: Vec<NodeUid> = uids
.into_iter()
.filter(|uid| !seen.contains_key(&uid.to_string()))
.collect();
let mut materialized = 0usize;
for chunk in missing.chunks(TRASH_MATERIALIZE_CHUNK) {
let chunk_started = Instant::now();
let nodes = within_trash_call(
"enumerate nodes",
self.drive.enumerate_trashed_nodes_light(chunk),
)
.await?
.map_err(|e| CoreError::from_api(&e, "enumerate nodes"))?;
let items: Vec<StoredTrash> = nodes
.into_iter()
.map(|TrashedNode { node, trash_time }| {
let uid = node.uid.to_string();
StoredTrash {
trashed_at: trash_time
.or_else(|| first_seen_in_trash(&seen, &uid, complete, now)),
uid,
name: node.name.clone(),
is_dir: node.is_folder(),
size: node_size(&node) as i64,
mtime: node.modification_time,
// The folder the node will go back to, which is also what
// tells a restore whether that folder is itself in the trash.
parent_uid: node.parent_uid.as_ref().map(|uid| uid.to_string()),
}
})
.collect();
materialized += items.len();
self.db.trash_upsert(&items).map_err(CoreError::from)?;
self.trash.trash_progress.notify_waiters();
self.events.publish(&[Topic::Trash]);
debug!(
materialized,
total = missing.len(),
chunk_ms = chunk_started.elapsed().as_millis() as u64,
"trash refresh: batch"
);
}
let _ = self.db.set_state_i64(TRASH_SYNCED_MS, now_ms());
let _ = self.db.set_state_i64(TRASH_COMPLETE_MS, now_ms());
info!(
count = listed.len(),
new = materialized,
removed,
elapsed_ms = started.elapsed().as_millis() as u64,
"trash refresh: done"
);
Ok(())
}
/// Refresh the trash off the request path. At most one refresh at a time —
/// including the one a first-ever [`Core::list_trash`] waits on, so a burst
/// of requests against an unfetched trash joins one refresh instead of
/// starting one apiece.
pub(super) fn spawn_trash_refresh(&self) {
if self.trash.trash_refreshing.swap(true, Ordering::SeqCst) {
return;
}
let core = self.clone();
self.rt.spawn(async move {
let refreshed = core.refresh_trash().await;
core.trash.trash_refreshing.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => core.events.publish(&[Topic::Trash]),
Err(e) => warn!(error = %e, "background trash refresh failed"),
}
// After the flag, so a waiter that wakes on this sees it cleared.
core.trash.trash_progress.notify_waiters();
});
}
/// Wait for the in-flight trash refresh to make progress, for at most
/// `budget`. Returns early when it finishes; never cancels it — the refresh
/// is a detached task, so giving up here costs the work nothing.
pub(super) fn await_trash_refresh(&self, budget: Duration) {
let deadline = Instant::now() + budget;
self.rt.block_on(async {
while self.trash.trash_refreshing.load(Ordering::SeqCst) {
let Some(left) = deadline.checked_duration_since(Instant::now()) else {
break;
};
let notified = self.trash.trash_progress.notified();
tokio::pin!(notified);
// Register before re-checking the flag: a refresh that finishes
// in between must not leave us waiting for a notify that has
// already fired.
notified.as_mut().enable();
if !self.trash.trash_refreshing.load(Ordering::SeqCst) {
break;
}
if tokio::time::timeout(left, notified).await.is_err() {
warn!(
budget_s = budget.as_secs(),
"trash refresh still running; answering with what has materialized"
);
break;
}
}
});
}
/// Drop the persisted trash listing's freshness stamp after we changed the
/// trash ourselves. The next Trash page then *waits* for a fresh listing
/// rather than painting one from before the mutation — the user just made the
/// change and is about to look straight at it.
pub(super) fn invalidate_trash(&self) {
let _ = self.db.clear_state(TRASH_SYNCED_MS);
}
/// Restore trashed nodes to the folders they were trashed from, together
/// with the rest of the trashed tree they belong to.
///
/// The trash is a flat list, but a user deletes a shape: a folder, and often
/// items inside it that were trashed separately beforehand. Restoring one of
/// those in isolation is not what anyone means by it — a folder would come
/// back without the contents that were deleted with it, and a file would come
/// back inside a folder that is still in the trash, which is to say nowhere
/// the user can see. So a restore takes the whole connected piece:
/// every trashed descendant of what was asked for, and every trashed ancestor
/// above it. See [`expand_restore`] for the exact rule.
///
/// The waves are restored shallowest first, because a node cannot be put back
/// under a parent that is still trashed.
///
/// The destination parents are read *before* the restore — a restored node
/// reappears in a listing the daemon may already have cached, so each one is
/// invalidated and re-enumerated on next access.
pub(super) fn restore(&self, uids: &[String]) -> CoreResult<usize> {
let requested = Self::parse_uids(uids)?;
// A listing we could not read is not a reason to refuse the restore: it
// only costs the expansion, and the requested nodes still go back.
let relations = self.db.trash_parents().unwrap_or_default();
let waves = expand_restore(uids, &relations);
let waves: Vec<Vec<NodeUid>> = if waves.is_empty() {
vec![requested.clone()]
} else {
waves
.iter()
.map(|wave| {
wave.iter()
.filter_map(|uid| parse_uid(uid))
.collect::<Vec<_>>()
})
.filter(|wave: &Vec<NodeUid>| !wave.is_empty())
.collect()
};
let all: Vec<NodeUid> = waves.iter().flatten().cloned().collect();
let parents: Vec<NodeUid> = self
.rt
.block_on(self.drive.enumerate_nodes(&all))
.map_err(|e| CoreError::from_api(&e, "enumerate nodes"))?
.into_iter()
.filter_map(|n| n.parent_uid)
.collect();
// Streamed per-node outcomes: a uid the server refuses (already restored,
// gone) leaves the rest of the batch restored, and each node is unhidden
// as *its* batch lands rather than after the last one — a daemon killed
// half way through a large restore leaves local state describing what the
// server actually did. Only a batch that restored nothing is an error the
// caller can act on.
let mut restored: Vec<NodeUid> = Vec::with_capacity(all.len());
let mut first_error: Option<ProtonError> = None;
for wave in &waves {
self.rt
.block_on(async {
let mut outcomes = std::pin::pin!(self.drive.restore_nodes_streaming(wave));
while let Some(item) = outcomes.next().await {
let (uid, outcome) = item?;
match outcome {
Ok(()) => {
self.hidden.lock().remove(&uid);
restored.push(uid);
}
Err(e) => {
warn!(%uid, error = %e, "restore failed for a node");
first_error.get_or_insert(e);
}
}
}
Ok::<(), ProtonError>(())
})
.map_err(|e| CoreError::from_api(&e, "restore"))?;
}
if restored.is_empty()
&& let Some(error) = first_error
{
return Err(CoreError::from_api(&error, "restore"));
}
// Keyed by uid, so it applies to every mount: a restored node reappears
// in whichever mounts show its parent, not only the primary one.
self.for_each_state(|st| {
for parent in &parents {
if let Some(&ino) = st.by_uid.get(parent) {
st.invalidate_listing(ino);
}
}
});
let back: Vec<String> = restored.iter().map(ToString::to_string).collect();
let _ = self.db.trash_remove(&back);
self.invalidate_trash();
Ok(restored.len())
}
/// Permanently delete trashed nodes. Irreversible on the server; locally it
/// drops any metadata and cached content the node still owns.
pub(super) fn delete_forever(&self, uids: &[String]) -> CoreResult<usize> {
let parsed = Self::parse_uids(uids)?;
// Streamed, and each node's local state is dropped as its batch lands.
// A permanent delete is irreversible, so the useful property is that a
// daemon interrupted mid-batch has already forgotten exactly the nodes
// the server destroyed — never more, never fewer.
let mut deleted = 0usize;
let mut gone: Vec<String> = Vec::new();
let mut first_error: Option<ProtonError> = None;
self.rt
.block_on(async {
let mut outcomes = std::pin::pin!(self.drive.delete_nodes_streaming(&parsed));
while let Some(item) = outcomes.next().await {
let (uid, outcome) = item?;
match outcome {
Ok(()) => {
self.drop_local(std::slice::from_ref(&uid));
gone.push(uid.to_string());
deleted += 1;
}
Err(e) => {
warn!(%uid, error = %e, "permanent delete failed for a node");
first_error.get_or_insert(e);
}
}
}
Ok::<(), ProtonError>(())
})
.map_err(|e| CoreError::from_api(&e, "delete"))?;
if deleted == 0
&& let Some(error) = first_error
{
return Err(CoreError::from_api(&error, "delete"));
}
let _ = self.db.trash_remove(&gone);
self.invalidate_trash();
Ok(deleted)
}
/// Permanently delete everything in the trash.
///
/// The stored listing says what goes, so the blobs of items trashed by
/// another client, which this daemon may still hold, are reclaimed too. It
/// is not read from the server again first: on a large trash that listing
/// is what kept the delete from ever being sent (`docs/BUGS.md` B293).
/// The stored listing is cleared at once, and the server is asked again
/// after [`TRASH_TTL`], so anything it still holds then shows up again.
pub(super) fn empty_trash(&self) -> CoreResult<usize> {
let uids: Vec<String> = self
.db
.trash_seen()
.map_err(CoreError::from)?
.into_keys()
.collect();
self.rt
.block_on(within_trash_call("empty trash", self.drive.empty_trash()))?
.map_err(|e| CoreError::from_api(&e, "empty trash"))?;
let parsed: Vec<NodeUid> = uids.iter().filter_map(|uid| parse_uid(uid)).collect();
self.drop_local(&parsed);
let _ = self.db.trash_replace(&[]);
let _ = self.db.set_state_i64(TRASH_SYNCED_MS, now_ms());
self.events.publish(&[Topic::Trash]);
Ok(uids.len())
}
}
/// An entry inside a trashed folder, for [`Core::list_trashed_folder`].
pub(super) fn trashed_entry(
uid: String,
name: String,
is_dir: bool,
size: i64,
mtime: i64,
trashed_at: i64,
parent: String,
) -> DirEntry {
DirEntry {
name,
is_dir,
size: size.max(0) as u64,
modified: mtime,
pinned: false,
pinned_by_folder: false,
cached: false,
uid,
path: String::new(),
role: String::new(),
shared_by: String::new(),
shared_at: 0,
shared_by_unverified: false,
trashed_at,
trashed_from: None,
trashed_parent: Some(parent),
issue: None,
}
}
/// When a node a trash refresh found went to the trash, as far as the daemon
/// can tell. A node the stored listing already had keeps the time it had. A new
/// one went there since the last refresh, so now is close, but only when that
/// refresh saw the whole trash (`complete`): after a first or interrupted one,
/// a node missing from the listing may be years old, and no date beats a wrong
/// one.
pub(super) fn first_seen_in_trash(
seen: &HashMap<String, Option<i64>>,
uid: &str,
complete: bool,
now: i64,
) -> Option<i64> {
match seen.get(uid) {
Some(at) => *at,
None if complete => Some(now),
None => None,
}
}
/// Expand a restore request across the trashed tree, and order it so a parent is
/// always restored before its children.
///
/// `relations` is the persisted trash listing as `(uid, parent_uid)` pairs; a
/// parent that is not itself in the listing is a live folder, which ends the
/// walk upward. The rule is:
///
/// - every trashed descendant of a requested node joins the restore, so a folder
/// comes back with the items that were trashed inside it;
/// - every trashed ancestor of a requested node joins it too, so a file never
/// lands in a folder that is still in the trash;
/// - a requested uid the listing does not know about is restored on its own,
/// because a stale or half-materialised listing must not silently drop it.
///
/// The result is one wave per depth, shallowest first. Waves are disjoint and
/// together contain each uid exactly once.
pub(super) fn expand_restore(
requested: &[String],
relations: &[(String, Option<String>)],
) -> Vec<Vec<String>> {
let parents: HashMap<&str, Option<&str>> = relations
.iter()
.map(|(uid, parent)| (uid.as_str(), parent.as_deref()))
.collect();
let mut children: HashMap<&str, Vec<&str>> = HashMap::new();
for (uid, parent) in relations {
// Only a trashed parent: a live one keeps its child as a root here.
if let Some(parent) = parent.as_deref()
&& parents.contains_key(parent)
{
children.entry(parent).or_default().push(uid.as_str());
}
}
let mut selected: HashSet<&str> = HashSet::new();
for uid in requested {
let uid = uid.as_str();
if !parents.contains_key(uid) {
selected.insert(uid);
continue;
}
// Upward: every trashed ancestor, so the destination folder exists again.
let mut cursor = Some(uid);
while let Some(current) = cursor {
// A parent outside the listing is live: the walk stops under it.
if !parents.contains_key(current) || !selected.insert(current) {
break;
}
cursor = parents.get(current).copied().flatten();
}
// Downward: the whole trashed subtree, so the folder comes back full.
let mut stack = vec![uid];
while let Some(current) = stack.pop() {
for child in children.get(current).into_iter().flatten() {
if selected.insert(child) {
stack.push(child);
}
}
}
}
// Depth within the *trash*, not within the drive: a node whose parent is live
// (or unknown) is at depth 0 and can be restored straight away.
let mut waves: Vec<Vec<String>> = Vec::new();
for uid in &selected {
let mut depth = 0usize;
let mut cursor = parents.get(uid).copied().flatten();
// Only trashed ancestors count, and the walk is bounded by the listing's
// size: server data that somehow describes a cycle must not spin here.
while let Some(current) = cursor
&& parents.contains_key(current)
&& depth < parents.len()
{
depth += 1;
cursor = parents.get(current).copied().flatten();
}
if waves.len() <= depth {
waves.resize(depth + 1, Vec::new());
}
waves[depth].push((*uid).to_string());
}
// Stable output, so a restore of the same trash is the same sequence of calls
// every time — the batches are what shows up in the log and in the tests.
for wave in &mut waves {
wave.sort();
}
waves.retain(|wave| !wave.is_empty());
waves
}
+2
View File
@@ -58,6 +58,8 @@ scale.browser-status-meter trough { min-width: 140px; min-height: 6px; }
.dropzone { border: 2px dashed alpha(currentColor, 0.25); border-radius: 16px; padding: 28px 18px; transition: background 160ms ease, border-color 160ms ease; }
.dropzone-active { border-color: var(--accent-bg-color); background: color-mix(in srgb, var(--accent-bg-color) 10%, transparent); }
.files-drop-active { outline: 2px dashed var(--accent-bg-color); outline-offset: -4px; border-radius: 12px; background: color-mix(in srgb, var(--accent-bg-color) 6%, transparent); }
.files-drop-folder { border-radius: 8px; background: color-mix(in srgb, var(--accent-bg-color) 22%, transparent); box-shadow: inset 0 0 0 2px var(--accent-bg-color); }
.file-pending { opacity: 0.45; }
/* Photo viewer: always light-on-dark, whatever the system style */
.photo-viewer-window { background-color: #111014; }
+11
View File
@@ -530,6 +530,8 @@ fn build_window(app: &adw::Application) {
summary: browser_widgets.summary.clone(),
zoom: browser_widgets.zoom.clone(),
zoom_save: RefCell::new(None),
pending_uploads: RefCell::new(Vec::new()),
pending_watch: Cell::new(false),
},
details: DetailsState {
details: browser_widgets.details,
@@ -1993,6 +1995,15 @@ pub(crate) fn service_unreachable(
offer_not_empty(&ui, found);
}
}
Some(failure) if failure.awaiting_keys => status(
&ui,
"dialog-warning-symbolic",
&gettext("Can't open your Drive"),
&gettext(
"Your account keys could not open My Files. After recovering your keys, choose Retry.",
),
true,
),
Some(failure) => status(
&ui,
"dialog-warning-symbolic",
+469 -54
View File
@@ -94,6 +94,12 @@ pub(crate) struct BrowserState {
pub(crate) zoom: gtk4::Scale,
/// Saves the zoom once the slider rests, not on every step.
pub(crate) zoom_save: RefCell<Option<glib::SourceId>>,
/// Files handed to the daemon for upload that its listings do not show
/// yet, drawn faded in their folder until they do (see
/// [`with_pending_uploads`]).
pub(crate) pending_uploads: RefCell<Vec<PendingUpload>>,
/// Whether the timer that retires [`BrowserState::pending_uploads`] runs.
pub(crate) pending_watch: Cell<bool>,
}
/// Idle pause after the last keystroke before a search query is sent, so typing
@@ -532,7 +538,13 @@ pub(crate) fn browser_status(ui: &Rc<Ui>, icon: &str, title: &str, description:
/// Every entry highlighted in My files, in model order.
pub(crate) fn selected_entries(ui: &Rc<Ui>) -> Vec<DirEntry> {
ui.browser.files.selected()
// A placeholder for an upload is not a node: no bulk action applies to it.
ui.browser
.files
.selected()
.into_iter()
.filter(|entry| !is_pending_upload(entry))
.collect()
}
/// Drop the selection, which also retracts the bulk bar.
@@ -1055,6 +1067,9 @@ pub(crate) fn open_entry_with(ui: &Rc<Ui>, entry: &DirEntry) {
/// password of. A listed link carries no URL, since the password fragment is
/// only known when the link is made, so otherwise open the Share dialog.
pub(crate) fn copy_entry_link(ui: &Rc<Ui>, entry: &DirEntry) {
if is_pending_upload(entry) {
return;
}
let req = if entry.path.is_empty() && !entry.uid.is_empty() {
Request::ListShareByUid {
uid: entry.uid.clone(),
@@ -1098,6 +1113,10 @@ pub(crate) fn entry_at(model: Option<&impl IsA<gio::ListModel>>, pos: u32) -> Op
/// Open an entry the Nautilus way: folders descend, media plays in the app,
/// streamed from the mount, other files download-and-open.
pub(crate) fn activate_entry(ui: &Rc<Ui>, entry: &DirEntry) {
if is_pending_upload(entry) {
// Nothing to open until Proton Drive has it.
return;
}
let rel = entry_rel(ui, entry);
if entry.is_dir {
// Descending into a search hit: clear the query so the folder listing
@@ -1375,16 +1394,19 @@ pub(crate) fn wire_browser_actions(ui: &Rc<Ui>, build_thumbnails: &gtk4::Button)
});
ui.browser.content.add_controller(buttons);
// Files dropped in from a file manager upload into the folder on screen.
// Files dropped in from a file manager upload into the folder on screen;
// rows dragged from this page (dropped anywhere but onto a folder) move
// into it. See [`drop_files`].
let drop = gtk4::DropTarget::new(
gtk4::gdk::FileList::static_type(),
gtk4::gdk::DragAction::COPY,
gtk4::gdk::DragAction::COPY | gtk4::gdk::DragAction::MOVE,
);
let ui_enter = ui.clone();
drop.connect_enter(move |_, _, _| {
ui_enter.browser.content.add_css_class("files-drop-active");
gtk4::gdk::DragAction::COPY
browser_drop_action()
});
drop.connect_motion(|_, _, _| browser_drop_action());
let ui_leave = ui.clone();
drop.connect_leave(move |_| {
ui_leave
@@ -1393,7 +1415,7 @@ pub(crate) fn wire_browser_actions(ui: &Rc<Ui>, build_thumbnails: &gtk4::Button)
.remove_css_class("files-drop-active");
});
let ui_drop = ui.clone();
drop.connect_drop(move |_, value, _, _| {
drop.connect_drop(move |target, value, _, _| {
ui_drop
.browser
.content
@@ -1401,18 +1423,12 @@ pub(crate) fn wire_browser_actions(ui: &Rc<Ui>, build_thumbnails: &gtk4::Button)
let Ok(files) = value.get::<gtk4::gdk::FileList>() else {
return false;
};
let sources: Vec<String> = files
.files()
.iter()
.filter_map(|f| f.path())
.filter_map(|p| p.to_str().map(str::to_string))
.collect();
if sources.is_empty() || !ui_drop.browser.search.text().trim().is_empty() {
if !ui_drop.browser.search.text().trim().is_empty() {
// Search results have no one folder to upload into.
return false;
}
start_upload(&ui_drop, sources);
true
let dest = ui_drop.browser.path.borrow().clone();
drop_files(&ui_drop, &dest, &files, from_this_app(target))
});
ui.browser.content.add_controller(drop);
}
@@ -2682,6 +2698,176 @@ pub(crate) fn prompt_upload_folder(ui: &Rc<Ui>) {
/// hand-off with a toast; the Activity group then shows live progress and the
/// listing refreshes itself when the transfers finish (see [`repaint_transfers`]).
pub(crate) fn start_upload(ui: &Rc<Ui>, sources: Vec<String>) {
let parent = ui.browser.path.borrow().clone();
start_upload_into(ui, parent, sources);
}
/// [`start_upload`] into `parent`, a mountpoint-relative folder that need not be
/// the one on screen (a folder that files were dropped onto).
pub(crate) fn start_upload_into(ui: &Rc<Ui>, parent: String, sources: Vec<String>) {
let paths = sources.clone();
start_upload_request(ui, parent.clone(), sources, move |ui| {
// A dropped path can sit on a slow or stalled mount (sshfs, NFS, a
// phone over MTP), so it is read off the main thread.
let ui = ui.clone();
glib::spawn_future_local(async move {
let placeholders = gio::spawn_blocking(move || {
paths
.iter()
.filter_map(|source| pending_entry(Path::new(source)))
.collect::<Vec<_>>()
})
.await
.unwrap_or_default();
add_pending_uploads(&ui, &parent, placeholders);
});
});
}
/// The `uid` of a placeholder row for a file on its way up. No node has it, so
/// nothing that acts on nodes mistakes the row for one.
pub(crate) const PENDING_UPLOAD_UID: &str = "pending-upload";
/// How long a placeholder stays once no transfer is running, so the daemon can
/// scan what it was handed and start on it.
const PENDING_UPLOAD_GRACE: Duration = Duration::from_secs(10);
/// Whether `entry` is a placeholder for an upload rather than a node.
pub(crate) fn is_pending_upload(entry: &DirEntry) -> bool {
entry.uid == PENDING_UPLOAD_UID
}
/// A file or folder handed to the daemon for upload into `parent`
/// (mountpoint-relative), shown there before Proton Drive lists it.
#[derive(Clone, Debug)]
pub(crate) struct PendingUpload {
pub(crate) parent: String,
pub(crate) entry: DirEntry,
pub(crate) since: Instant,
}
/// The placeholder row for uploading the local `source`: its name, size and
/// modification time, and [`PENDING_UPLOAD_UID`]. None for a symlink, which
/// the daemon does not upload, so its placeholder would never be replaced.
/// Blocks on the file system: call it off the main thread.
fn pending_entry(source: &Path) -> Option<DirEntry> {
let name = source.file_name()?.to_str()?.to_string();
let meta = std::fs::symlink_metadata(source).ok();
if meta
.as_ref()
.is_some_and(|meta| meta.file_type().is_symlink())
{
return None;
}
let is_dir = meta.as_ref().is_some_and(|meta| meta.is_dir());
let size = meta
.as_ref()
.filter(|_| !is_dir)
.map_or(0, |meta| meta.len());
let modified = meta
.and_then(|meta| meta.modified().ok())
.and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
.map_or(0, |since| since.as_secs() as i64);
Some(DirEntry {
name,
is_dir,
size,
modified,
uid: PENDING_UPLOAD_UID.to_string(),
..DirEntry::default()
})
}
/// `entries` of the folder `parent`, plus a placeholder for each upload into it
/// that they do not list yet. A placeholder whose name the listing now has is
/// done, and is forgotten.
pub(crate) fn with_pending_uploads(
pending: &mut Vec<PendingUpload>,
parent: &str,
entries: &[DirEntry],
) -> Vec<DirEntry> {
pending.retain(|upload| {
upload.parent != parent || !entries.iter().any(|entry| entry.name == upload.entry.name)
});
let mut shown = entries.to_vec();
shown.extend(
pending
.iter()
.filter(|upload| upload.parent == parent)
.map(|upload| upload.entry.clone()),
);
shown
}
/// Show `placeholders` in `parent` until the daemon lists them, and repaint
/// that folder now if it is on screen.
fn add_pending_uploads(ui: &Rc<Ui>, parent: &str, placeholders: Vec<DirEntry>) {
if placeholders.is_empty() {
return;
}
let since = Instant::now();
ui.browser
.pending_uploads
.borrow_mut()
.extend(placeholders.into_iter().map(|entry| PendingUpload {
parent: parent.to_string(),
entry,
since,
}));
let showing = ui.browser.listed.borrow().as_deref() == Some(parent)
&& ui.browser.search.text().trim().is_empty();
if showing {
let listing = ui.browser.listing.borrow().clone();
repaint_browser(ui, &listing);
}
watch_pending_uploads(ui);
}
/// Retire placeholders the daemon never lists: an upload that failed, or one
/// that finished without the listing on screen being reloaded. Once nothing
/// is transferring and a placeholder is past [`PENDING_UPLOAD_GRACE`], the
/// listing is reloaded, which shows the real file if it arrived.
fn watch_pending_uploads(ui: &Rc<Ui>) {
if ui.browser.pending_watch.replace(true) {
return;
}
let ui = ui.clone();
glib::timeout_add_local(Duration::from_secs(2), move || {
if ui.status.active_transfers.get() > 0 {
// The daemon is still working through what it was handed (a big
// folder can take a while to walk), so the grace starts over.
let now = Instant::now();
for upload in ui.browser.pending_uploads.borrow_mut().iter_mut() {
upload.since = now;
}
} else {
let expired = {
let mut pending = ui.browser.pending_uploads.borrow_mut();
let before = pending.len();
pending.retain(|upload| upload.since.elapsed() < PENDING_UPLOAD_GRACE);
pending.len() != before
};
if expired {
reload_listing(&ui);
}
}
if ui.browser.pending_uploads.borrow().is_empty() {
ui.browser.pending_watch.set(false);
glib::ControlFlow::Break
} else {
glib::ControlFlow::Continue
}
});
}
/// Send the daemon an upload of `sources` into `parent`, then confirm the
/// hand-off and run `accepted` once the daemon has taken it.
fn start_upload_request(
ui: &Rc<Ui>,
parent: String,
sources: Vec<String>,
accepted: impl FnOnce(&Rc<Ui>) + 'static,
) {
if sources.is_empty() {
return;
}
@@ -2693,7 +2879,6 @@ pub(crate) fn start_upload(ui: &Rc<Ui>, sources: Vec<String>) {
);
return;
}
let parent = ui.browser.path.borrow().clone();
let n = sources.len();
let rx = spawn_request(
ui.dirs.control_socket(),
@@ -2712,6 +2897,7 @@ pub(crate) fn start_upload(ui: &Rc<Ui>, sources: Vec<String>) {
toast_action(&ui, &what, &pgettext("verb", "View"), |ui| {
ui.stack.set_visible_child_name("locations")
});
accepted(&ui);
}
Ok(Ok(Response::Error { message, kind })) => {
toast_failure(&ui, &gettext("Couldn't upload"), &message, kind)
@@ -2766,62 +2952,211 @@ pub(crate) fn apply_badge(badge: &gtk4::Image, entry: &DirEntry) {
}
}
/// Make a browser cell draggable, carrying the bound entry's mountpoint-relative
/// path as the drag payload. Reads the entry live at drag time (via the captured
/// [`gtk4::ListItem`]) so a recycled cell drags whatever it currently shows.
/// Make a browser cell draggable. The drag carries the bound entry, or the
/// whole selection when the entry is part of it, as files under the mountpoint:
/// a file manager or any other app that takes files gets the real thing (read on
/// demand through the mount), and a drop back onto this page moves it inside
/// Proton Drive (see [`drop_files`]). Reads the entry live at drag time (via the
/// captured [`gtk4::ListItem`]) so a recycled cell drags whatever it currently
/// shows.
pub(crate) fn attach_drag(ui: &Rc<Ui>, item: &gtk4::ListItem, anchor: &gtk4::Box) {
let source = gtk4::DragSource::new();
source.set_actions(gtk4::gdk::DragAction::MOVE);
// Copy only. A file manager that is offered a move (Shift in Nautilus, a
// drop on the Trash) takes the file out of the mount, which deletes it from
// Proton Drive. A drop back onto this page still moves: it checks where the
// drag came from, not the action (see [`drop_files`]).
source.set_actions(gtk4::gdk::DragAction::COPY);
let ui = ui.clone();
let item = item.clone();
source.connect_prepare(move |_, _, _| {
source.connect_prepare(move |source, x, y| {
if !*ui.mounted.borrow() {
// No mount, nothing another app could read.
return None;
}
let obj = item.item().and_downcast::<BoxedAnyObject>()?;
let rel = entry_rel(&ui, &obj.borrow::<DirEntry>());
Some(gtk4::gdk::ContentProvider::for_value(&glib::Value::from(
rel.as_str(),
)))
if is_pending_upload(&obj.borrow::<DirEntry>()) {
// Not in the mount yet, so nothing to hand over.
return None;
}
let rels: Vec<String> = if item.is_selected() {
selected_entries(&ui)
.iter()
.map(|entry| entry_rel(&ui, entry))
.collect()
} else {
vec![entry_rel(&ui, &obj.borrow::<DirEntry>())]
};
let mountpoint = ui.dirs.resolved_mountpoint(&ui.dirs.load_config());
let files: Vec<gtk4::gio::File> = rels
.iter()
.map(|rel| gtk4::gio::File::for_path(mounted_path(&mountpoint, rel)))
.collect();
if let Some(cell) = source.widget() {
let icon = gtk4::WidgetPaintable::new(Some(&cell));
source.set_icon(Some(&icon), x as i32, y as i32);
}
let files = gtk4::gdk::FileList::from_array(&files);
Some(gtk4::gdk::ContentProvider::for_value(&files.to_value()))
});
anchor.add_controller(source);
}
/// Make a browser cell a drop target: dropping a dragged path onto a *folder* cell
/// moves the source into it through the daemon. Drops onto files, onto the item
/// itself, or that would move a folder into its own subtree are rejected.
/// Make a browser cell a drop target for its *folder*: files dropped onto it
/// upload into that folder, and rows of this page move into it (see
/// [`drop_files`]). A file cell does not accept a drop at all, so the drop falls
/// through to the page, which takes it for the folder on screen.
pub(crate) fn attach_drop(ui: &Rc<Ui>, item: &gtk4::ListItem, anchor: &gtk4::Box) {
let target = gtk4::DropTarget::new(glib::types::Type::STRING, gtk4::gdk::DragAction::MOVE);
let target = gtk4::DropTarget::new(
gtk4::gdk::FileList::static_type(),
gtk4::gdk::DragAction::COPY | gtk4::gdk::DragAction::MOVE,
);
let item_accept = item.clone();
target.connect_accept(move |_, drop| {
let is_dir = item_accept
.item()
.and_downcast::<BoxedAnyObject>()
.is_some_and(|obj| {
let entry = obj.borrow::<DirEntry>();
entry.is_dir && !is_pending_upload(&entry)
});
is_dir
&& drop
.formats()
.contains_type(gtk4::gdk::FileList::static_type())
});
let anchor_enter = anchor.clone();
target.connect_enter(move |_, _, _| {
anchor_enter.add_css_class("files-drop-folder");
browser_drop_action()
});
target.connect_motion(|_, _, _| browser_drop_action());
let anchor_leave = anchor.clone();
target.connect_leave(move |_| anchor_leave.remove_css_class("files-drop-folder"));
let ui = ui.clone();
let item = item.clone();
target.connect_drop(move |_, value, _, _| {
let anchor_drop = anchor.clone();
target.connect_drop(move |target, value, _, _| {
anchor_drop.remove_css_class("files-drop-folder");
let Some(obj) = item.item().and_downcast::<BoxedAnyObject>() else {
return false;
};
let dest = obj.borrow::<DirEntry>();
if !dest.is_dir {
return false;
}
let Ok(src) = value.get::<String>() else {
let dest = {
let entry = obj.borrow::<DirEntry>();
if !entry.is_dir {
return false;
}
entry_rel(&ui, &entry)
};
let Ok(files) = value.get::<gtk4::gdk::FileList>() else {
return false;
};
let dest_path = entry_rel(&ui, &dest);
// No-op onto self, and never move a folder into itself or a descendant.
if src == dest_path || dest_path.starts_with(&format!("{src}/")) {
return false;
}
let done = gettext_f("Moved into “{name}”", &[("name", &dest.name)]);
run_mutation(
&ui,
Request::Move {
path: src,
new_parent: dest_path,
},
done,
gettext_noop("Couldn't move"),
);
true
drop_files(&ui, &dest, &files, from_this_app(target))
});
anchor.add_controller(target);
}
/// The action to answer a drag over the browser with: always a copy. Rows
/// dragged from this app offer nothing else (see [`attach_drag`]), and an
/// outside drag is never answered with a move, which would have the source
/// delete what it handed over. What a drop does is decided in [`drop_files`].
///
/// The answer is not checked against [`gtk4::gdk::Drop::actions`]: on Wayland
/// that is the one action the compositor has picked so far (a file manager's
/// drag shows up as MOVE alone), not every action the source supports. The
/// answer is what makes the compositor pick again, so a copy has to be asked
/// for even while the drop says move, or the drop is refused.
fn browser_drop_action() -> gtk4::gdk::DragAction {
gtk4::gdk::DragAction::COPY
}
/// Whether the drop on `target` is rows dragged from this app, as opposed to
/// files from a file manager or another app.
fn from_this_app(target: &gtk4::DropTarget) -> bool {
target
.current_drop()
.is_some_and(|drop| drop.drag().is_some())
}
/// Act on `files` dropped into `dest`, a mountpoint-relative folder. Files
/// from outside Proton Drive upload into it. Files already in Proton Drive move
/// there when they are rows dragged within this app, and are copied there when
/// they come from a file manager browsing the mount: a drag from outside the
/// app is always a copy (see [`browser_drop_action`]). Sources that cannot go
/// to `dest` (into themselves, or a move into the folder they are in) are left
/// out. Returns whether anything was done, which is what the drop reports back.
fn drop_files(ui: &Rc<Ui>, dest: &str, files: &gtk4::gdk::FileList, from_app: bool) -> bool {
let mountpoint = ui.dirs.resolved_mountpoint(&ui.dirs.load_config());
let (in_drive, uploads) =
split_dropped(&mountpoint, files.files().iter().filter_map(|f| f.path()));
let in_drive = drop_targets(in_drive, dest, from_app);
if in_drive.is_empty() && uploads.is_empty() {
return false;
}
if !in_drive.is_empty() {
if from_app {
run_bulk_move(ui, in_drive, dest.to_string());
} else {
run_bulk_copy(ui, in_drive, dest.to_string());
}
}
start_upload_into(ui, dest.to_string(), uploads);
true
}
/// Which of `sources`, mountpoint-relative, can go to `dest`: none into
/// itself or its own subtree, and for a move none already in `dest`.
pub(crate) fn drop_targets(sources: Vec<String>, dest: &str, moving: bool) -> Vec<String> {
sources
.into_iter()
.filter(|src| {
let one = std::slice::from_ref(src);
if moving {
move_target_allowed(one, dest)
} else {
copy_target_allowed(one, dest)
}
})
.collect()
}
/// Split dropped local paths into those inside the mount at `mountpoint`, as
/// mountpoint-relative paths to move, and those from anywhere else, as absolute
/// paths to upload. The mountpoint itself is neither: it cannot be moved.
pub(crate) fn split_dropped(
mountpoint: &Path,
paths: impl IntoIterator<Item = PathBuf>,
) -> (Vec<String>, Vec<String>) {
let mut moves = Vec::new();
let mut uploads = Vec::new();
for path in paths {
// A path with `..` in it could name something other than it seems to
// once made relative; file managers never send one, so it is not
// worth resolving. (`components` already drops an inner `.`.)
let plain = path.components().all(|part| {
matches!(
part,
std::path::Component::RootDir | std::path::Component::Normal(_)
)
});
if !plain {
continue;
}
match path.strip_prefix(mountpoint) {
Ok(rel) => {
if let Some(rel) = rel.to_str().filter(|rel| !rel.is_empty()) {
moves.push(rel.to_string());
}
}
Err(_) => {
if let Some(path) = path.to_str() {
uploads.push(path.to_string());
}
}
}
}
(moves, uploads)
}
/// The full-colour icon for an entry: [`icon_base_for`], except that folders
/// are Proton's own purple ones while the Proton theme is on.
pub(crate) fn icon_for(entry: &DirEntry) -> &'static str {
@@ -2974,6 +3309,8 @@ pub(crate) fn repaint_browser(ui: &Rc<Ui>, entries: &[DirEntry]) {
// any other load forgot it (see `load_browser`).
let path = ui.browser.path.borrow().clone();
let another_folder = ui.browser.listed.replace(Some(path.clone())).as_ref() != Some(&path);
// The rows on screen: the listing, and what is on its way up into it.
let shown = with_pending_uploads(&mut ui.browser.pending_uploads.borrow_mut(), &path, entries);
ui.browser.summary.set_label(&listing_summary(
entries.iter().filter(|entry| !entry.is_dir).count(),
entries.iter().filter(|entry| entry.is_dir).count(),
@@ -2983,7 +3320,7 @@ pub(crate) fn repaint_browser(ui: &Rc<Ui>, entries: &[DirEntry]) {
.map(|entry| entry.size)
.sum(),
));
if entries.is_empty() {
if shown.is_empty() {
browser_status(
ui,
"folder-open-symbolic",
@@ -2997,7 +3334,7 @@ pub(crate) fn repaint_browser(ui: &Rc<Ui>, entries: &[DirEntry]) {
}
browser_views(ui);
let mut sorted = entries.to_vec();
let mut sorted = shown;
sort_entries(&mut sorted, ui.browser.view.get());
// Only the rows that changed are swapped, so a refresh keeps the
// selection, the scroll position and the thumbnails already drawn.
@@ -3227,9 +3564,87 @@ fn listing_summary(files: usize, folders: usize, file_bytes: u64) -> String {
#[cfg(test)]
mod tests {
use super::{
MoveTarget, badge_for, copy_target_allowed, hit_location, icon_base_for, listing_summary,
move_target_allowed, show_thumbnail_build_progress, sort_entries,
MoveTarget, badge_for, copy_target_allowed, drop_targets, hit_location, icon_base_for,
listing_summary, move_target_allowed, show_thumbnail_build_progress, sort_entries,
split_dropped,
};
use std::path::{Path, PathBuf};
#[test]
fn pending_uploads_show_until_listed() {
use super::{PENDING_UPLOAD_UID, PendingUpload, is_pending_upload, with_pending_uploads};
let placeholder = |parent: &str, name: &str| PendingUpload {
parent: parent.to_string(),
entry: DirEntry {
name: name.to_string(),
uid: PENDING_UPLOAD_UID.to_string(),
..DirEntry::default()
},
since: std::time::Instant::now(),
};
let mut pending = vec![
placeholder("Docs", "a.pdf"),
placeholder("Docs", "b.pdf"),
placeholder("", "c.txt"),
];
let listed = DirEntry {
name: "a.pdf".to_string(),
uid: "vol~a".to_string(),
..DirEntry::default()
};
// a.pdf has arrived; b.pdf is still on its way; c.txt is elsewhere.
let shown = with_pending_uploads(&mut pending, "Docs", std::slice::from_ref(&listed));
let names: Vec<(&str, bool)> = shown
.iter()
.map(|entry| (entry.name.as_str(), is_pending_upload(entry)))
.collect();
assert_eq!(names, [("a.pdf", false), ("b.pdf", true)]);
let left: Vec<&str> = pending.iter().map(|p| p.entry.name.as_str()).collect();
assert_eq!(left, ["b.pdf", "c.txt"]);
}
#[test]
fn dropped_paths_split_into_moves_and_uploads() {
let (moves, uploads) = split_dropped(
Path::new("/home/me/ProtonDrive"),
[
PathBuf::from("/home/me/ProtonDrive/Docs/a.pdf"),
PathBuf::from("/home/me/Documents/b.txt"),
PathBuf::from("/home/me/ProtonDrive"),
PathBuf::from("/home/me/ProtonDriveOther/c.txt"),
PathBuf::from("/home/me/ProtonDrive/Photos"),
PathBuf::from("/home/me/ProtonDrive/../.ssh/id_ed25519"),
],
);
assert_eq!(moves, ["Docs/a.pdf", "Photos"]);
assert_eq!(
uploads,
[
"/home/me/Documents/b.txt",
"/home/me/ProtonDriveOther/c.txt"
]
);
}
#[test]
fn a_drop_leaves_out_only_the_sources_that_cannot_go() {
let sources = || {
vec![
"Docs/a.pdf".to_string(),
"Photos/b.jpg".to_string(),
"Docs".to_string(),
]
};
// Moving into Docs: a.pdf is already there, and Docs cannot go into
// itself; b.jpg still moves.
assert_eq!(drop_targets(sources(), "Docs", true), ["Photos/b.jpg"]);
// A copy into the folder it is in is fine; into itself is not.
assert_eq!(
drop_targets(sources(), "Docs", false),
["Docs/a.pdf", "Photos/b.jpg"]
);
}
use pdfs_core::config::{FileSort, FilesView};
use pdfs_core::control::{DirEntry, SyncIssue, ThumbnailBuildStatus};
+23 -2
View File
@@ -316,7 +316,7 @@ pub(crate) fn login_error_message(error: &pdfs_core::Error) -> String {
// Proton's text for this one asks the user to update an app that is
// already current.
pdfs_core::Error::Proton(e) if pdfs_core::error::sign_in_blocked(e) => gettext(
"Proton is temporarily refusing sign-in from this device. Your app version is not the problem. Wait several hours, up to a day, without trying again, then sign in.",
"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.",
),
pdfs_core::Error::Proton(ProtonError::Api(api)) if !api.message.is_empty() => {
api.message.clone()
@@ -770,10 +770,31 @@ mod tests {
details: None,
}));
let message = login_error_message(&error);
assert!(message.contains("temporarily refusing"), "{message}");
assert!(message.contains("code 2028"), "{message}");
assert!(!message.contains("update"), "{message}");
}
#[test]
fn outdated_clients_and_rate_limits_keep_their_own_guidance() {
use pdfs_core::proton_sdk::{ProtonApiError, ProtonError, api::ResponseCode};
for (code, status, expected) in [
(ResponseCode::OutdatedApp, 422, "Please update the app"),
(
ResponseCode::TooManyRequests,
429,
"Too many sign-in attempts",
),
] {
let error = ProtonError::Api(ProtonApiError {
code,
http_status: status,
message: "Please update the app".into(),
details: None,
});
assert!(login_error_message(&error.into()).contains(expected));
}
}
#[test]
fn an_unmapped_error_keeps_its_text() {
let error = pdfs_core::Error::Other("something odd".into());
+12 -3
View File
@@ -1430,6 +1430,7 @@ pub(crate) fn paint_disconnected(ui: &Rc<Ui>) {
match failure {
Some(failure) => SyncState::CannotOpen {
not_empty: failure.not_empty.is_some(),
waiting_for_keys: failure.awaiting_keys,
},
None => SyncState::Disconnected,
},
@@ -1482,6 +1483,7 @@ pub(crate) enum SyncState {
/// it refuses a folder that already has files in it.
CannotOpen {
not_empty: bool,
waiting_for_keys: bool,
},
/// The daemon is running but didn't answer in time.
NotResponding,
@@ -1586,11 +1588,18 @@ fn paint_sync_status(ui: &Rc<Ui>, state: SyncState) {
gettext("Not connected"),
Some(gettext("Proton Drive isn't running")),
),
SyncState::CannotOpen { not_empty } => (
SyncState::CannotOpen {
not_empty,
waiting_for_keys,
} => (
"dialog-warning-symbolic",
Some("warning"),
gettext("Can't open your Drive"),
Some(if not_empty {
Some(if waiting_for_keys {
gettext(
"Your account keys could not open My Files. After recovering your keys, choose Retry.",
)
} else if not_empty {
gettext("Your Proton Drive folder isn't empty")
} else {
gettext("Proton Drive keeps trying to start")
@@ -1663,7 +1672,7 @@ pub(crate) fn clock_time(unix: i64) -> String {
/// the set is unchanged (the common case on the 2s tick) it only flips the unpin
/// buttons' `sensitive` flag, avoiding the rebuild that used to flicker the list
/// and drop scroll/selection every tick.
pub(crate) fn repaint_pins(ui: &Rc<Ui>, pins: &[pdfs_core::cache::Pin], mounted: bool) {
pub(crate) fn repaint_pins(ui: &Rc<Ui>, pins: &[pdfs_core::control::Pin], mounted: bool) {
let desired: Vec<String> = pins.iter().map(|p| p.path.clone()).collect();
if ui.status.pins_state.borrow().as_ref() == Some(&desired) {
for r in ui.status.pin_rows.borrow().iter() {
@@ -436,6 +436,10 @@ pub(crate) fn show_details(ui: &Rc<Ui>, entry: &DirEntry) {
/// Fill the Sharing and Versions rows, and a folder's size, which need the
/// network. The answers land only if the pane still shows the same entry.
fn load_details_extras(ui: &Rc<Ui>, entry: &DirEntry) {
if is_pending_upload(entry) {
// Proton Drive has no such node yet: nothing to ask about.
return;
}
let by_uid = entry.path.is_empty() && !entry.uid.is_empty();
let rel = entry_rel(ui, entry);
let share_req = if by_uid {
@@ -182,6 +182,7 @@ impl FileList {
bind_file_thumbnail(&ui, &thumbnail, &entry, false);
label.set_label(&entry.name);
label.set_tooltip_text(Some(&entry.name));
mark_pending_upload(&tile, &entry);
if behavior.badges {
apply_badge(&badge, &entry);
}
@@ -350,6 +351,9 @@ impl FileList {
.ellipsize(gtk4::pango::EllipsizeMode::End)
.build();
let cell = gtk4::Box::new(gtk4::Orientation::Horizontal, 8);
// The whole Name column, not just the icon and the name, is
// where a row is dragged from and dropped onto.
cell.set_hexpand(true);
cell.append(&thumbnail);
cell.append(&label);
list.attach_context_menu(&ui, item, &cell, behavior);
@@ -379,6 +383,7 @@ impl FileList {
bind_file_thumbnail(&ui, &thumbnail, &entry, true);
label.set_label(&entry.name);
label.set_tooltip_text(Some(&entry.name));
mark_pending_upload(&cell, &entry);
if behavior.badges {
apply_badge(&badge, &entry);
}
@@ -408,6 +413,10 @@ impl FileList {
gesture.set_state(gtk4::EventSequenceState::Claimed);
if let Some(obj) = item.item().and_downcast::<BoxedAnyObject>() {
let entry = obj.borrow::<DirEntry>().clone();
if is_pending_upload(&entry) {
// No action applies to a file Proton Drive does not have yet.
return;
}
// Right-clicking a row that is part of a multi-selection acts on
// the batch; right-clicking outside one acts on the row.
let selected = list.selected();
@@ -515,10 +524,23 @@ pub(crate) fn text_column(
let text = render(&entry);
label.set_tooltip_text(Some(&text));
label.set_label(&text);
mark_pending_upload(&label, &entry);
});
gtk4::ColumnViewColumn::new(Some(title), Some(factory))
}
/// Fade a cell bound to a placeholder for an upload, and say why; clear both
/// otherwise, since list factories recycle cells.
fn mark_pending_upload(cell: &impl IsA<gtk4::Widget>, entry: &DirEntry) {
if is_pending_upload(entry) {
cell.add_css_class("file-pending");
cell.set_tooltip_text(Some(&gettext("Uploading…")));
} else if cell.has_css_class("file-pending") {
cell.remove_css_class("file-pending");
cell.set_tooltip_text(None);
}
}
fn resize_grid_tile(thumbnail: &gtk4::Overlay, label: &gtk4::Label, size: i32) {
resize_file_thumbnail(thumbnail, size, grid_fallback_size(size));
let name_width = (size / 6 + 1).clamp(8, 40);
@@ -319,6 +319,7 @@ pub(crate) fn bind_file_thumbnail(
if entry.is_dir
|| !is_thumbnail_media_name(&entry.name, Some(entry.size))
|| entry.uid.is_empty()
|| is_pending_upload(entry)
{
return;
}
+13 -10
View File
@@ -197,18 +197,21 @@ fn poll_state(socket: &Path, default_mountpoint: &Path) -> DriveState {
// A daemon whose mount fails on every try never opens the
// socket; the app says why (B263).
Ok(s)
if socket
.parent()
.and_then(pdfs_core::mountfail::read)
.is_some() =>
if let Some(failure) = socket.parent().and_then(pdfs_core::mountfail::read) =>
{
(
// Translators: {username} is the Proton account name. The
// service keeps failing to start; the app shows the error.
gettext_f(
"Signed in as {username} — can't open your Drive",
&[("username", &s.username)],
),
if failure.awaiting_keys {
gettext(
"Your account keys could not open My Files. After recovering your keys, choose Retry.",
)
} else {
// Translators: {username} is the Proton account name. The
// service keeps failing to start; the app shows the error.
gettext_f(
"Signed in as {username} — can't open your Drive",
&[("username", &s.username)],
)
},
Phase::Attention,
)
}
+22
View File
@@ -0,0 +1,22 @@
[package]
name = "pdfs-store"
version.workspace = true
edition.workspace = true
license.workspace = true
authors.workspace = true
rust-version.workspace = true
repository.workspace = true
homepage.workspace = true
description = "SQLite metadata and the content cache for the Proton Drive Linux client"
[dependencies]
pdfs-core.workspace = true
proton-drive-rs.workspace = true
proton-gallery-rs.workspace = true
rusqlite.workspace = true
serde.workspace = true
serde_json.workspace = true
tracing.workspace = true
parking_lot.workspace = true
sha2.workspace = true
libc.workspace = true
@@ -13,7 +13,7 @@
//! the mtime, so a stale blob is detected and ignored (and the event poller
//! evicts it eagerly anyway).
//!
//! [`AppDirs::cache_dir`]: crate::config::AppDirs::cache_dir
//! [`AppDirs::cache_dir`]: pdfs_core::config::AppDirs::cache_dir
//! [`Node`]: proton_drive_rs::Node
use std::collections::{BTreeMap, HashMap, HashSet};
@@ -33,7 +33,8 @@ use tracing::debug;
use parking_lot::Mutex;
use crate::db::{CacheEntryInput, Db};
use crate::error::{Error, Result};
pub use pdfs_core::control::Pin;
use pdfs_core::error::{Error, Result};
/// `cache_entries.kind` tag for whole-file content blobs.
const KIND_BLOB: &str = "blob";
@@ -276,34 +277,6 @@ struct GeometryMeta {
sizes: Vec<u64>,
}
/// One pin, as carried over the control socket and listed in `status`.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Pin {
/// Node uid in `volume~link` display form.
pub uid: String,
/// Last path the node was pinned under, for display in `status`. Advisory
/// only — the uid is the identity.
pub path: String,
/// A folder pin whose whole subtree is kept on disk. `false` for a single
/// file. Defaulted so a legacy `pins.json` (file pins only) still parses.
#[serde(default)]
pub recursive: bool,
/// Whether the pinned node is a folder, when the node cache knows.
///
/// `recursive` is pin *policy*, not node kind: a folder pinned
/// non-recursively has `recursive: false`, and a front-end reading it as
/// "this is a file" draws a file icon and sends an invalid `OpenFile`. This
/// is resolved from the `nodes` row at list time, so it is `None` for a pin
/// whose node is not cached — and absent from an older daemon's reply,
/// which is why it is defaulted.
#[serde(default)]
pub is_dir: Option<bool>,
/// A pinned file whose content is on disk right now. The daemon fills it
/// in when it answers `ListPins`; folders and older daemons say `false`.
#[serde(default)]
pub cached: bool,
}
/// The legacy JSON pin registry, kept only to import a pre-P5 `pins.json` into
/// the DB once on open. Live pins are owned by the `pins` table.
#[derive(Serialize, Deserialize, Default)]
@@ -3,8 +3,8 @@
use rusqlite::params;
use super::Db;
use crate::Result;
use crate::control::{ActivityEntry, ActivityKind};
use pdfs_core::Result;
use pdfs_core::control::{ActivityEntry, ActivityKind};
/// How many activity rows to keep. Older rows are pruned on insert, so the feed
/// stays a bounded "recent history" rather than growing without limit.
@@ -34,7 +34,7 @@ impl Db {
/// run, without keeping a second table in step with the log.
pub fn activity_has(&self, kind: ActivityKind, target: &str) -> Result<bool> {
let kind = serde_json::to_string(&kind)?;
let conn = self.read();
let conn = self.read()?;
let mut stmt =
conn.prepare("SELECT 1 FROM activity WHERE kind = ?1 AND target = ?2 LIMIT 1")?;
Ok(stmt.exists(params![kind, target])?)
@@ -44,7 +44,7 @@ impl Db {
/// whose stored `kind` no longer parses (written by an older build) are
/// skipped rather than failing the whole read.
pub fn activity_list(&self, limit: usize) -> Result<Vec<ActivityEntry>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT time, kind, target, detail, ok FROM activity
ORDER BY id DESC LIMIT ?1",
@@ -12,7 +12,7 @@ use rusqlite::params;
use std::collections::HashMap;
use super::{Db, StoredPhoto, THUMB_UNKNOWN};
use crate::Result;
use pdfs_core::Result;
/// One album of the persisted listing, ordered newest-activity-first in `seq`.
#[derive(Clone, Debug, PartialEq)]
@@ -105,7 +105,7 @@ impl Db {
/// The persisted album listing, in stored order.
pub fn albums_list(&self) -> Result<Vec<StoredAlbum>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT uid, name, photo_count, cover_uid, last_activity, shared
FROM albums ORDER BY seq",
@@ -127,7 +127,7 @@ impl Db {
/// Number of albums in the persisted listing.
pub fn albums_count(&self) -> Result<usize> {
let conn = self.read();
let conn = self.read()?;
let n: i64 = conn.query_row("SELECT COUNT(*) FROM albums", [], |r| r.get(0))?;
Ok(n.max(0) as usize)
}
@@ -199,7 +199,7 @@ impl Db {
let name = name.clone().or(learned_name);
let media_type = media_type.clone().or(learned_media);
let kind =
crate::control::PhotoKind::classify(name.as_deref(), media_type.as_deref());
pdfs_core::control::PhotoKind::classify(name.as_deref(), media_type.as_deref());
stmt.execute(params![
album_uid,
uid,
@@ -226,7 +226,7 @@ impl Db {
&self,
album: &str,
) -> Result<HashMap<String, (String, Option<String>)>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT uid,name,media_type FROM album_photos
WHERE album_uid=?1 AND resolved=1 AND name IS NOT NULL
@@ -255,7 +255,7 @@ impl Db {
limit: usize,
excluded: &str,
) -> Result<Vec<StoredPhoto>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT uid, capture_time, name, ratio, thumb_state, kind FROM album_photos
WHERE album_uid = ?1 AND uid NOT IN (SELECT value FROM json_each(?4))
@@ -271,7 +271,7 @@ impl Db {
name: r.get(2)?,
ratio: r.get(3)?,
thumb_state: r.get(4)?,
kind: crate::control::PhotoKind::from_i64(r.get(5)?),
kind: pdfs_core::control::PhotoKind::from_i64(r.get(5)?),
// Album rows have no favorite state of their own: an album
// photo on someone else's volume is not in our timeline, and
// favouriting one is not supported yet anyway.
@@ -293,7 +293,7 @@ impl Db {
/// which has to put the re-uploaded copy back into the albums the original
/// was in.
pub fn albums_of_photo(&self, uid: &str) -> Result<Vec<String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt =
conn.prepare("SELECT DISTINCT album_uid FROM album_photos WHERE uid = ?1")?;
let rows = stmt
@@ -304,7 +304,7 @@ impl Db {
/// How many photos of `album_uid` are persisted.
pub fn album_photos_count(&self, album_uid: &str) -> Result<usize> {
let conn = self.read();
let conn = self.read()?;
let n: i64 = conn.query_row(
"SELECT COUNT(*) FROM album_photos WHERE album_uid = ?1",
[album_uid],
@@ -321,7 +321,7 @@ impl Db {
if uids.is_empty() {
return Ok(Vec::new());
}
let conn = self.read();
let conn = self.read()?;
let placeholders = vec!["?"; uids.len()].join(",");
let mut stmt = conn.prepare(&format!(
"SELECT uid, capture_time, name, ratio, thumb_state, kind FROM album_photos
@@ -335,7 +335,7 @@ impl Db {
name: r.get(2)?,
ratio: r.get(3)?,
thumb_state: r.get(4)?,
kind: crate::control::PhotoKind::from_i64(r.get(5)?),
kind: pdfs_core::control::PhotoKind::from_i64(r.get(5)?),
// Album rows have no favorite state of their own: an album
// photo on someone else's volume is not in our timeline, and
// favouriting one is not supported yet anyway.
@@ -4,7 +4,7 @@
use rusqlite::params;
use super::Db;
use crate::Result;
use pdfs_core::Result;
pub struct CacheEntryInput<'a> {
/// On-disk filename of the blob or block.
@@ -99,7 +99,7 @@ impl Db {
/// because `enforce_block_budget` runs on every cached block — once per
/// 4 MiB of every cold read — while holding the shared connection.
pub fn cache_total_bytes(&self, kind: &str) -> Result<u64> {
let conn = self.read();
let conn = self.read()?;
let total: i64 = conn.query_row(
"SELECT COALESCE(SUM(size_bytes), 0) FROM cache_entries WHERE kind = ?1",
params![kind],
@@ -121,7 +121,7 @@ impl Db {
limit: usize,
offset: usize,
) -> Result<Vec<(String, u64)>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare_cached(
"SELECT cache_key, size_bytes FROM cache_entries
WHERE kind = ?1 ORDER BY last_accessed ASC LIMIT ?2 OFFSET ?3",
@@ -141,7 +141,7 @@ impl Db {
/// (`clear_unpinned`); incremental eviction wants
/// [`cache_eviction_candidates`](Self::cache_eviction_candidates).
pub fn cache_entries_by_kind(&self, kind: &str) -> Result<Vec<(String, u64)>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT cache_key, size_bytes FROM cache_entries
WHERE kind = ?1 ORDER BY last_accessed ASC",
@@ -3,7 +3,7 @@
use rusqlite::{OptionalExtension, params};
use super::Db;
use crate::Result;
use pdfs_core::Result;
pub struct StoredDevice {
pub uid: String,
@@ -15,7 +15,7 @@ pub struct StoredDevice {
impl Db {
pub fn device_get(&self) -> Result<Option<StoredDevice>> {
let conn = self.read();
let conn = self.read()?;
conn.query_row(
"SELECT uid, share_id, root_uid, name, created FROM device LIMIT 1",
[],
@@ -4,8 +4,8 @@
use rusqlite::{OptionalExtension, params};
use super::Db;
use crate::Result;
use crate::localindex::LocalEntry;
use pdfs_core::Result;
use pdfs_core::localindex::LocalEntry;
use super::nodes::candidate_trigrams;
use super::utils::{TRIGRAM_MIN, like_escape};
@@ -152,7 +152,7 @@ impl Db {
pub fn compact_search_indexes_if_due(&self, now: i64) -> Result<()> {
const EVERY_SECS: i64 = 24 * 60 * 60;
let last: i64 = self
.read()
.read()?
.query_row(
"SELECT value FROM sync_state WHERE key = 'fts_compacted_at'",
[],
@@ -189,7 +189,7 @@ impl Db {
/// has never been built. The daemon uses this to decide whether a fresh mount
/// needs an immediate rescan or can serve the existing index.
pub fn local_indexed_at(&self) -> Result<Option<i64>> {
let conn = self.read();
let conn = self.read()?;
Ok(conn
.query_row(
"SELECT value FROM sync_state WHERE key = 'local_indexed_at'",
@@ -209,7 +209,7 @@ impl Db {
if query.is_empty() {
return Ok(Vec::new());
}
let conn = self.read();
let conn = self.read()?;
let mut stmt;
let rows = if query.chars().count() < TRIGRAM_MIN {
let pat = format!("%{}%", like_escape(query));
@@ -248,7 +248,7 @@ impl Db {
if query.is_empty() || limit == 0 {
return Ok(Vec::new());
}
let conn = self.read();
let conn = self.read()?;
let terms = candidate_trigrams(query);
let lane_limit = limit.div_ceil(2);
let mut rows: Vec<LocalFileHit> = if terms.is_empty() {
@@ -10,7 +10,7 @@
use rusqlite::OptionalExtension;
use super::Db;
use crate::Result;
use pdfs_core::Result;
/// A point-in-time picture of the database's size and contents.
///
@@ -97,7 +97,7 @@ impl Db {
/// waited that long behind it (`docs/BUGS.md` B218). WAL lets it read a
/// consistent snapshot while the writer goes on.
pub fn integrity_check(&self) -> Result<Vec<String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare("PRAGMA integrity_check")?;
let rows = stmt.query_map([], |r| r.get::<_, String>(0))?;
let mut problems = Vec::new();
@@ -116,7 +116,7 @@ impl Db {
/// connection, for the reason [`integrity_check`](Self::integrity_check)
/// gives: counting the rows of every table reads most of the file.
pub fn stats(&self) -> Result<DbStats> {
let conn = self.read();
let conn = self.read()?;
let page_count: i64 = conn.query_row("PRAGMA page_count", [], |r| r.get(0))?;
let free_pages: i64 = conn.query_row("PRAGMA freelist_count", [], |r| r.get(0))?;
let page_size: i64 = conn.query_row("PRAGMA page_size", [], |r| r.get(0))?;
@@ -8,10 +8,10 @@
use rusqlite::OptionalExtension;
use super::Db;
use crate::Result;
use pdfs_core::Result;
/// Current schema version. Bump on every forward migration added below.
pub(super) const SCHEMA_VERSION: i64 = 47;
pub(super) const SCHEMA_VERSION: i64 = 49;
impl Db {
pub(super) fn migrate(&self) -> Result<()> {
@@ -34,7 +34,7 @@ impl Db {
.unwrap_or(0);
if current > SCHEMA_VERSION {
return Err(crate::Error::Other(format!(
return Err(pdfs_core::Error::Other(format!(
"database schema {current} is newer than this build supports ({SCHEMA_VERSION}); refusing to open it to avoid corrupting user data"
)));
}
@@ -511,6 +511,38 @@ impl Db {
tx.execute_batch(MIGRATION_V47)?;
}
}
if current < 48 {
// The triggers need the tables they watch; a fixture may lack them.
let has_sync: bool = tx.query_row(
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' \
AND name IN ('sync_entry', 'sync_folder')",
[],
|row| row.get::<_, i64>(0).map(|n| n == 2),
)?;
if has_sync {
tx.execute_batch(MIGRATION_V48)?;
}
}
if current < 49 {
let has_walk: bool = tx.query_row(
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'sync_walk'",
[],
|row| row.get::<_, i64>(0).map(|n| n > 0),
)?;
if has_walk {
// A database stamped with an older version over a newer
// schema, as the migration tests build, has the columns.
let has_columns: bool = tx.query_row(
"SELECT COUNT(*) FROM pragma_table_info('sync_walk') WHERE name = 'complete'",
[],
|row| row.get::<_, i64>(0).map(|n| n > 0),
)?;
if !has_columns {
tx.execute_batch(MIGRATION_V49_COLUMNS)?;
}
tx.execute_batch(MIGRATION_V49)?;
}
}
tx.execute(
"INSERT INTO sync_state (key, value) VALUES ('schema_version', ?1)
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
@@ -756,7 +788,7 @@ CREATE INDEX pending_op_parent ON pending_op(parent_uid);
/// Schema v13: photos record their media type and a derived `kind` so the
/// timeline can be split into Photos / Videos / Raw tabs. `media_type` is
/// nullable — it is filled once the daemon resolves a photo's node — while
/// `kind` (see [`crate::control::PhotoKind`]) defaults to `0` (still photo), the
/// `kind` (see [`pdfs_core::control::PhotoKind`]) defaults to `0` (still photo), the
/// classification anything unresolved falls back to. Existing rows are
/// reclassified for free on the next timeline refresh, so no backfill is needed.
const MIGRATION_V13: &str = "
@@ -1205,7 +1237,7 @@ const MIGRATION_V32: &str = "UPDATE {table} SET thumb_state = 0 WHERE kind = 1 A
///
/// `latitude` and `longitude` come from the location other clients write into
/// a photo's extended attributes; `place_id` is the GeoNames id of the nearest
/// town (see `crate::places`), so the Places view is a plain `GROUP BY`.
/// town (see `pdfs_core::places`), so the Places view is a plain `GROUP BY`.
///
/// Every photo is marked unresolved, so the next refresh reads the location of
/// the whole library once. That is the backfill: the metadata is on the node
@@ -1221,7 +1253,7 @@ UPDATE photos SET resolved_at = NULL;
/// Schema v34: what each photo looks like, for finding similar ones.
///
/// `similar_hash` is a 64-bit difference hash of the photo's thumbnail (see
/// `crate::similar`): resized and re-encoded copies of one picture land a few
/// `pdfs_core::similar`): resized and re-encoded copies of one picture land a few
/// bits apart, where the server's `content_hash` only matches byte-identical
/// files. `NULL` until the daemon has hashed the thumbnail, which it does as
/// thumbnails arrive and when the similar-photo finder asks for the rest.
@@ -1491,6 +1523,209 @@ ALTER TABLE album_photos ADD COLUMN resolved INTEGER NOT NULL DEFAULT 0;
UPDATE album_photos SET resolved=1 WHERE name IS NOT NULL;
";
/// Schema 49: a complete walk of Drive stays, as the picture of Drive the
/// next pass starts from, and only the folders marked dirty since are listed
/// again (`docs/SYNC_ENGINE.md`).
///
/// - `sync_walk.complete`: the walk reached every folder once.
/// - `sync_walk.seq`: the last dirty mark made when the walk began. Marks up
/// to it are read by the walk itself, and dropped when it completes.
/// - `sync_remote_dirty`: the folders to list again. The event stream marks
/// the folders Drive reports a change in. The triggers below mark the folder
/// of every baseline row a pass writes, so a pass never relies on the echo
/// of its own change arriving in time.
///
/// While a walk is not complete, a baseline change still drops it, as in
/// schema 48.
///
/// A mark made again takes a new `seq`, so a pass that read the old one does
/// not drop it. The triggers delete and insert rather than `INSERT OR
/// REPLACE`: an upsert on `sync_entry` would override that conflict clause
/// and fail on the second mark of a folder.
const MIGRATION_V49_COLUMNS: &str = "
ALTER TABLE sync_walk ADD COLUMN complete INTEGER NOT NULL DEFAULT 0;
ALTER TABLE sync_walk ADD COLUMN seq INTEGER NOT NULL DEFAULT 0;
";
/// See [`MIGRATION_V49_COLUMNS`].
const MIGRATION_V49: &str = "
CREATE TABLE IF NOT EXISTS sync_remote_dirty (
seq INTEGER PRIMARY KEY AUTOINCREMENT,
folder_id INTEGER NOT NULL,
dir TEXT NOT NULL,
UNIQUE (folder_id, dir)
);
CREATE INDEX IF NOT EXISTS sync_walk_item_uid ON sync_walk_item(uid);
DROP TRIGGER IF EXISTS sync_walk_drop_on_entry_insert;
DROP TRIGGER IF EXISTS sync_walk_drop_on_entry_update;
DROP TRIGGER IF EXISTS sync_walk_drop_on_entry_delete;
DROP TRIGGER IF EXISTS sync_walk_drop_on_folder_update;
DROP TRIGGER IF EXISTS sync_walk_drop_on_folder_delete;
DROP TRIGGER IF EXISTS sync_walk_mark_on_entry_insert;
DROP TRIGGER IF EXISTS sync_walk_mark_on_entry_update;
DROP TRIGGER IF EXISTS sync_walk_mark_on_entry_delete;
CREATE TRIGGER sync_walk_drop_on_entry_insert
AFTER INSERT ON sync_entry
WHEN EXISTS (SELECT 1 FROM sync_walk WHERE folder_id = NEW.folder_id AND complete = 0)
BEGIN
DELETE FROM sync_walk WHERE folder_id = NEW.folder_id;
DELETE FROM sync_walk_dir WHERE folder_id = NEW.folder_id;
DELETE FROM sync_walk_item WHERE folder_id = NEW.folder_id;
END;
CREATE TRIGGER sync_walk_drop_on_entry_update
AFTER UPDATE OF folder_id, rel_path, remote_uid, local_mtime, local_mtime_ns, local_size,
remote_hash, remote_rev
ON sync_entry
WHEN EXISTS (SELECT 1 FROM sync_walk
WHERE folder_id IN (OLD.folder_id, NEW.folder_id) AND complete = 0)
BEGIN
DELETE FROM sync_walk_dir WHERE folder_id IN (
SELECT folder_id FROM sync_walk
WHERE folder_id IN (OLD.folder_id, NEW.folder_id) AND complete = 0);
DELETE FROM sync_walk_item WHERE folder_id IN (
SELECT folder_id FROM sync_walk
WHERE folder_id IN (OLD.folder_id, NEW.folder_id) AND complete = 0);
DELETE FROM sync_walk WHERE folder_id IN (OLD.folder_id, NEW.folder_id) AND complete = 0;
END;
CREATE TRIGGER sync_walk_drop_on_entry_delete
AFTER DELETE ON sync_entry
WHEN EXISTS (SELECT 1 FROM sync_walk WHERE folder_id = OLD.folder_id AND complete = 0)
BEGIN
DELETE FROM sync_walk WHERE folder_id = OLD.folder_id;
DELETE FROM sync_walk_dir WHERE folder_id = OLD.folder_id;
DELETE FROM sync_walk_item WHERE folder_id = OLD.folder_id;
END;
CREATE TRIGGER sync_walk_mark_on_entry_insert
AFTER INSERT ON sync_entry
WHEN EXISTS (SELECT 1 FROM sync_walk WHERE folder_id = NEW.folder_id AND complete = 1)
BEGIN
DELETE FROM sync_remote_dirty
WHERE folder_id = NEW.folder_id AND dir = rtrim(rtrim(NEW.rel_path, replace(NEW.rel_path, '/', '')), '/');
INSERT INTO sync_remote_dirty (folder_id, dir)
SELECT NEW.folder_id, rtrim(rtrim(NEW.rel_path, replace(NEW.rel_path, '/', '')), '/');
END;
CREATE TRIGGER sync_walk_mark_on_entry_update
AFTER UPDATE OF folder_id, rel_path, remote_uid, local_mtime, local_mtime_ns, local_size,
remote_hash, remote_rev
ON sync_entry
BEGIN
DELETE FROM sync_remote_dirty
WHERE folder_id = OLD.folder_id AND dir = rtrim(rtrim(OLD.rel_path, replace(OLD.rel_path, '/', '')), '/')
AND EXISTS (SELECT 1 FROM sync_walk WHERE folder_id = OLD.folder_id AND complete = 1);
INSERT INTO sync_remote_dirty (folder_id, dir)
SELECT OLD.folder_id, rtrim(rtrim(OLD.rel_path, replace(OLD.rel_path, '/', '')), '/')
WHERE EXISTS (SELECT 1 FROM sync_walk WHERE folder_id = OLD.folder_id AND complete = 1);
DELETE FROM sync_remote_dirty
WHERE folder_id = NEW.folder_id AND dir = rtrim(rtrim(NEW.rel_path, replace(NEW.rel_path, '/', '')), '/')
AND EXISTS (SELECT 1 FROM sync_walk WHERE folder_id = NEW.folder_id AND complete = 1);
INSERT INTO sync_remote_dirty (folder_id, dir)
SELECT NEW.folder_id, rtrim(rtrim(NEW.rel_path, replace(NEW.rel_path, '/', '')), '/')
WHERE EXISTS (SELECT 1 FROM sync_walk WHERE folder_id = NEW.folder_id AND complete = 1);
END;
CREATE TRIGGER sync_walk_mark_on_entry_delete
AFTER DELETE ON sync_entry
WHEN EXISTS (SELECT 1 FROM sync_walk WHERE folder_id = OLD.folder_id AND complete = 1)
BEGIN
DELETE FROM sync_remote_dirty
WHERE folder_id = OLD.folder_id AND dir = rtrim(rtrim(OLD.rel_path, replace(OLD.rel_path, '/', '')), '/');
INSERT INTO sync_remote_dirty (folder_id, dir)
SELECT OLD.folder_id, rtrim(rtrim(OLD.rel_path, replace(OLD.rel_path, '/', '')), '/');
END;
CREATE TRIGGER sync_walk_drop_on_folder_update
AFTER UPDATE OF local_path, remote_uid, mode ON sync_folder
BEGIN
DELETE FROM sync_walk WHERE folder_id = OLD.id;
DELETE FROM sync_walk_dir WHERE folder_id = OLD.id;
DELETE FROM sync_walk_item WHERE folder_id = OLD.id;
DELETE FROM sync_remote_dirty WHERE folder_id = OLD.id;
END;
CREATE TRIGGER sync_walk_drop_on_folder_delete
AFTER DELETE ON sync_folder
BEGIN
DELETE FROM sync_walk WHERE folder_id = OLD.id;
DELETE FROM sync_walk_dir WHERE folder_id = OLD.id;
DELETE FROM sync_walk_item WHERE folder_id = OLD.id;
DELETE FROM sync_remote_dirty WHERE folder_id = OLD.id;
END;
";
/// The saved progress of a mirror pass's walk of Drive, so a pass cut short
/// resumes the walk instead of listing everything again (B294).
///
/// A saved listing is only as good as the baseline it was read against: a
/// listing from before a file moved to another synced folder reads that file
/// as deleted on Drive. So any change to a folder's baseline or to the folder
/// itself drops its saved walk. Filling in a revision id is the one exception,
/// since the walk itself does that. The engine drops the walk too once it is
/// complete, before the pass applies anything.
const MIGRATION_V48: &str = "
CREATE TABLE IF NOT EXISTS sync_walk (
folder_id INTEGER PRIMARY KEY,
root_uid TEXT NOT NULL,
started INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS sync_walk_dir (
folder_id INTEGER NOT NULL,
rel_path TEXT NOT NULL,
uid TEXT NOT NULL,
listed INTEGER NOT NULL DEFAULT 0,
short INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (folder_id, rel_path)
);
CREATE TABLE IF NOT EXISTS sync_walk_item (
folder_id INTEGER NOT NULL,
rel_path TEXT NOT NULL,
uid TEXT,
is_dir INTEGER NOT NULL,
mtime INTEGER NOT NULL DEFAULT 0,
size INTEGER NOT NULL DEFAULT 0,
revision TEXT,
sha1 TEXT,
PRIMARY KEY (folder_id, rel_path)
);
CREATE TRIGGER IF NOT EXISTS sync_walk_drop_on_entry_insert
AFTER INSERT ON sync_entry
WHEN EXISTS (SELECT 1 FROM sync_walk WHERE folder_id = NEW.folder_id)
BEGIN
DELETE FROM sync_walk WHERE folder_id = NEW.folder_id;
DELETE FROM sync_walk_dir WHERE folder_id = NEW.folder_id;
DELETE FROM sync_walk_item WHERE folder_id = NEW.folder_id;
END;
CREATE TRIGGER IF NOT EXISTS sync_walk_drop_on_entry_update
AFTER UPDATE OF folder_id, rel_path, remote_uid, local_mtime, local_mtime_ns, local_size,
remote_hash, remote_rev
ON sync_entry
WHEN EXISTS (SELECT 1 FROM sync_walk WHERE folder_id IN (OLD.folder_id, NEW.folder_id))
BEGIN
DELETE FROM sync_walk WHERE folder_id IN (OLD.folder_id, NEW.folder_id);
DELETE FROM sync_walk_dir WHERE folder_id IN (OLD.folder_id, NEW.folder_id);
DELETE FROM sync_walk_item WHERE folder_id IN (OLD.folder_id, NEW.folder_id);
END;
CREATE TRIGGER IF NOT EXISTS sync_walk_drop_on_entry_delete
AFTER DELETE ON sync_entry
WHEN EXISTS (SELECT 1 FROM sync_walk WHERE folder_id = OLD.folder_id)
BEGIN
DELETE FROM sync_walk WHERE folder_id = OLD.folder_id;
DELETE FROM sync_walk_dir WHERE folder_id = OLD.folder_id;
DELETE FROM sync_walk_item WHERE folder_id = OLD.folder_id;
END;
CREATE TRIGGER IF NOT EXISTS sync_walk_drop_on_folder_update
AFTER UPDATE OF local_path, remote_uid, mode ON sync_folder
WHEN EXISTS (SELECT 1 FROM sync_walk WHERE folder_id = OLD.id)
BEGIN
DELETE FROM sync_walk WHERE folder_id = OLD.id;
DELETE FROM sync_walk_dir WHERE folder_id = OLD.id;
DELETE FROM sync_walk_item WHERE folder_id = OLD.id;
END;
CREATE TRIGGER IF NOT EXISTS sync_walk_drop_on_folder_delete
AFTER DELETE ON sync_folder
BEGIN
DELETE FROM sync_walk WHERE folder_id = OLD.id;
DELETE FROM sync_walk_dir WHERE folder_id = OLD.id;
DELETE FROM sync_walk_item WHERE folder_id = OLD.id;
END;
";
/// Index the trash by parent, for browsing it by folder. The rows are dropped
/// so the next refresh reads them again with the time each was trashed, which
/// earlier builds did not get from the server and made up instead.
@@ -24,9 +24,10 @@
//! and never name a submodule.
use parking_lot::Mutex;
use pdfs_core::lockrank::{Rank, Ranked, RankedGuard};
use rusqlite::Connection;
use crate::{Error, Result};
use pdfs_core::{Error, Result};
use std::fs::File;
use std::os::fd::AsRawFd;
use std::path::{Path, PathBuf};
@@ -62,7 +63,7 @@ pub use ops::{
};
pub use photos::{StoredPhoto, StoredPlace, THUMB_HAVE, THUMB_NONE, THUMB_UNKNOWN, TimelineRow};
pub use pins::PinRow;
pub use sync::{StoredSyncEntry, StoredSyncFolder};
pub use sync::{SavedWalk, SavedWalkDir, SavedWalkItem, StoredSyncEntry, StoredSyncFolder};
pub use trash::StoredTrash;
/// Size the WAL is truncated back to after a checkpoint. Comfortably above the
@@ -96,7 +97,7 @@ const WAL_AUTOCHECKPOINT_PAGES: i64 = 500;
/// Cheap to wrap in an `Arc`; clone the `Arc`, not this. All access goes through
/// the inner `Mutex<Connection>`.
pub struct Db {
conn: Mutex<Connection>,
conn: Ranked<Connection>,
/// Read-only connections for `SELECT`-only methods. `None` for an in-memory
/// database, where a second connection would open a different, empty one —
/// those fall back to the write connection.
@@ -126,19 +127,16 @@ struct ReadPool {
const MAX_IDLE_READERS: usize = 4;
impl ReadPool {
fn take(&self) -> Option<Connection> {
/// An idle connection, or a new one. An error when none can be opened:
/// the caller's read fails rather than queueing behind the writer, which
/// can hold its lock for as long as a large transaction takes.
fn take(&self) -> Result<Connection> {
if let Some(conn) = self.idle.lock().pop() {
return Some(conn);
}
match open_read_only(&self.path) {
Ok(conn) => Some(conn),
Err(error) => {
// Falling back to the write connection is correct, just slower,
// so this is a warning and not a failed read.
tracing::warn!(%error, "could not open a read-only connection");
None
}
return Ok(conn);
}
open_read_only(&self.path).inspect_err(|error| {
tracing::warn!(%error, "could not open a read-only connection");
})
}
fn put(&self, conn: Connection) {
@@ -150,13 +148,13 @@ impl ReadPool {
}
/// A connection to read through: one borrowed from [`ReadPool`], or the write
/// connection when there is no pool (in-memory) or opening one failed.
/// connection for an in-memory database, which has no pool.
///
/// Derefs to `Connection`, so a method converts by swapping `self.conn.lock()`
/// for `self.read()` and nothing else.
/// for `self.read()?` and nothing else.
pub(super) struct Reader<'a> {
pooled: Option<Connection>,
writer: Option<parking_lot::MutexGuard<'a, Connection>>,
writer: Option<RankedGuard<'a, Connection>>,
pool: Option<&'a ReadPool>,
}
@@ -188,10 +186,10 @@ impl Drop for Reader<'_> {
/// reachable; losing that row loses a write `close()` already reported as
/// done. A FULL commit syncs the WAL, which covers every NORMAL commit before
/// it as well.
pub(super) struct Durable<'a>(parking_lot::MutexGuard<'a, Connection>);
pub(super) struct Durable<'a>(RankedGuard<'a, Connection>);
impl<'a> Durable<'a> {
pub(super) fn new(conn: parking_lot::MutexGuard<'a, Connection>) -> Result<Self> {
pub(super) fn new(conn: RankedGuard<'a, Connection>) -> Result<Self> {
conn.pragma_update(None, "synchronous", "FULL")?;
Ok(Self(conn))
}
@@ -287,7 +285,7 @@ impl Db {
Err(e) => return Err(e),
};
let db = Self {
conn: Mutex::new(conn),
conn: Ranked::new(Rank::DbWriter, conn),
// No pool for `:memory:`. A second connection to that name is a
// second, empty database rather than another view of this one, so
// every routed read would find a schema that does not exist.
@@ -320,21 +318,19 @@ impl Db {
/// Reads see the last committed state, which is the same thing they saw
/// through the write connection: every method here commits before it
/// returns, and nothing holds a transaction open across calls.
pub(super) fn read(&self) -> Reader<'_> {
if let Some(pool) = &self.readers
&& let Some(conn) = pool.take()
{
return Reader {
pooled: Some(conn),
writer: None,
pool: Some(pool),
};
}
Reader {
pooled: None,
writer: Some(self.conn.lock()),
pool: None,
}
pub(super) fn read(&self) -> Result<Reader<'_>> {
let Some(pool) = &self.readers else {
return Ok(Reader {
pooled: None,
writer: Some(self.conn.lock()),
pool: None,
});
};
Ok(Reader {
pooled: Some(pool.take()?),
writer: None,
pool: Some(pool),
})
}
/// Open the file, apply every PRAGMA, and migrate. Split out of
@@ -385,7 +381,7 @@ impl Db {
conn.pragma_update(None, "wal_autocheckpoint", WAL_AUTOCHECKPOINT_PAGES)?;
let db = Self {
conn: Mutex::new(conn),
conn: Ranked::new(Rank::DbWriter, conn),
readers: None,
_single_writer: None,
};
@@ -409,7 +405,7 @@ impl Db {
// connection unless explicitly enabled.
conn.pragma_update(None, "foreign_keys", "ON")?;
let db = Self {
conn: Mutex::new(conn),
conn: Ranked::new(Rank::DbWriter, conn),
readers: None,
_single_writer: None,
};
@@ -7,8 +7,8 @@
use rusqlite::params;
use super::Db;
use crate::mounts::{MountAccess, MountKind, MountMode, MountSpec};
use crate::{Error, Result};
use pdfs_core::mounts::{MountAccess, MountKind, MountMode, MountSpec};
use pdfs_core::{Error, Result};
impl Db {
/// Project the configured primary mount into the presentation table.
@@ -74,7 +74,7 @@ impl Db {
/// Every local location, with synced-folder fields joined from `sync_folder`.
pub fn mount_list(&self) -> Result<Vec<MountSpec>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT
m.id,
@@ -8,7 +8,7 @@ use rusqlite::{OptionalExtension, Transaction, params};
use super::Db;
use super::ops::{OP_CREATE, OP_MKDIR, OP_RENAME, local_lid, local_uid, wake_ops_waiting_for_tx};
use crate::{Access, Result};
use pdfs_core::{Access, Result};
use proton_drive_rs::proton_sdk::ids::{LinkId, NodeUid, VolumeId};
use proton_drive_rs::{Node, NodeKind};
@@ -65,7 +65,7 @@ impl Db {
/// flag. Synthetic shared listings use this to serve the last completed
/// snapshot while offline, including after a live event expired its TTL.
pub fn visible_children(&self, parent: &NodeUid) -> Result<Vec<Node>> {
let conn = self.read();
let conn = self.read()?;
let (key, parent) = parent_key(&conn, &parent.to_string())?;
let mut stmt = conn.prepare(&format!(
"SELECT {NODE_NOW} FROM nodes n LEFT JOIN nodes p ON p.lid = n.parent_lid
@@ -309,7 +309,7 @@ impl Db {
/// Check if a folder node has any non-trashed children in the database.
pub fn has_children(&self, parent_uid: &NodeUid) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
let (key, parent) = parent_key(&conn, &parent_uid.to_string())?;
let count: i64 = conn.query_row(
&format!(
@@ -329,7 +329,7 @@ impl Db {
/// mountpoint — resolve the roots once through this and do the rest as
/// string arithmetic, instead of a `path_relative_to` walk per pair.
pub fn node_path(&self, uid: &str) -> Result<Option<String>> {
let conn = self.read();
let conn = self.read()?;
let exists: Option<i64> = conn
.query_row(
"SELECT 1 FROM nodes WHERE uid = ?1 AND node_json IS NOT NULL",
@@ -351,7 +351,7 @@ impl Db {
/// chain keeps callers from accidentally joining a Drive-wide path onto the
/// wrong mountpoint. The ancestor itself resolves to the empty path.
pub fn path_relative_to(&self, ancestor_uid: &str, uid: &str) -> Result<Option<String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"WITH RECURSIVE anc(uid, parent_lid, name, depth) AS (
SELECT uid, parent_lid, name, 0 FROM nodes WHERE uid = ?1
@@ -403,7 +403,7 @@ impl Db {
if query.is_empty() {
return Ok(Vec::new());
}
let conn = self.read();
let conn = self.read()?;
let rows: Vec<HitRow> = if query.chars().count() < TRIGRAM_MIN {
let pat = format!("%{}%", like_escape(query));
let mut stmt = conn.prepare(&format!(
@@ -461,7 +461,7 @@ impl Db {
if query.is_empty() || limit == 0 {
return Ok(Vec::new());
}
let conn = self.read();
let conn = self.read()?;
let terms = candidate_trigrams(query);
let lane_limit = limit.div_ceil(2);
let mut rows: Vec<HitRow> = if terms.is_empty() {
@@ -547,7 +547,7 @@ impl Db {
/// local id: a folder that landed has its new uid there, while the node
/// stored below it may still hold the placeholder.
pub fn load_all(&self) -> Result<Vec<StoredNode>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(&format!(
"SELECT {NODE_NOW}, n.listed, n.lid
FROM nodes n LEFT JOIN nodes p ON p.lid = n.parent_lid
@@ -570,7 +570,7 @@ impl Db {
/// Load one persisted node back by uid. Used to recover the My Files root
/// when the API is unreachable, so the mount can still serve the cached tree.
pub fn node_by_uid(&self, uid: &str) -> Result<Option<Node>> {
let conn = self.read();
let conn = self.read()?;
let json: Option<String> = conn
.query_row(
&format!(
@@ -590,7 +590,7 @@ impl Db {
/// The uid of the node with local id `lid`: `None` when it has no row, or
/// is not on Drive yet.
pub fn uid_of_lid(&self, lid: i64) -> Result<Option<String>> {
let conn = self.read();
let conn = self.read()?;
Ok(conn
.query_row("SELECT uid FROM nodes WHERE lid = ?1", params![lid], |r| {
r.get(0)
@@ -604,7 +604,7 @@ impl Db {
/// create lands and the row takes the uid Drive gave it: a node made on
/// this machine is found by its stand-in ([`local_uid`]) before and after.
pub fn lid_of(&self, uid: &str) -> Result<Option<i64>> {
node_lid(&self.read(), uid)
node_lid(&*self.read()?, uid)
}
/// The local id of each node, in order, giving a row to each that has none.
@@ -693,7 +693,7 @@ impl Db {
/// The daemon resumes from this on restart instead of reseeding to the
/// server head, so changes made while unmounted are still applied (P2).
pub fn children_if_listed(&self, parent: &NodeUid) -> Result<Option<Vec<Node>>> {
let conn = self.read();
let conn = self.read()?;
let (key, folder) = row_key(&parent.to_string());
let listed: Option<i64> = conn
.query_row(
@@ -713,7 +713,7 @@ impl Db {
/// listing is still marked complete. Only for when nothing better can be
/// had: a listing dropped as stale may miss or keep a child.
pub fn known_children(&self, parent: &NodeUid) -> Result<Vec<Node>> {
let conn = self.read();
let conn = self.read()?;
let (key, parent) = parent_key(&conn, &parent.to_string())?;
let mut stmt = conn.prepare(&format!(
"SELECT {NODE_NOW} FROM nodes n LEFT JOIN nodes p ON p.lid = n.parent_lid
@@ -736,7 +736,7 @@ impl Db {
/// while a create in it is queued, after a restart say, loses the file
/// until the create lands (`docs/BUGS.md` B132).
pub fn queued_children(&self, parent: &NodeUid) -> Result<(Vec<Node>, HashSet<String>)> {
let conn = self.read();
let conn = self.read()?;
let (key, parent) = parent_key(&conn, &parent.to_string())?;
let mut stmt = conn.prepare(&format!(
"SELECT {NODE_NOW} FROM nodes n LEFT JOIN nodes p ON p.lid = n.parent_lid
@@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize};
use super::Db;
use super::nodes::{adopt_placeholder_row_tx, node_lid};
use crate::Result;
use pdfs_core::Result;
/// The `kind` of a [`PendingOp`] that uploads a staged file as a new revision.
pub const OP_REVISION: &str = "revision";
@@ -503,7 +503,7 @@ impl Db {
/// A folder can look empty locally while Drive still holds the queued
/// moves' source files. A trash has to go through the drain in that case.
pub fn has_pending_moves_out_of(&self, uid: &str) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
Ok(conn
.prepare_cached(&format!(
"SELECT EXISTS (SELECT 1 FROM (SELECT ?1 AS uid) AS source
@@ -520,7 +520,7 @@ impl Db {
/// wait for the trash rather than land under a conflict name. Older rows
/// whose node and parent are unknown are matched by name alone.
pub fn has_pending_trash_named(&self, name: &str, parent_uid: Option<&str>) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
conn.query_row(
"SELECT EXISTS(
SELECT 1 FROM pending_op AS p
@@ -546,7 +546,7 @@ impl Db {
/// and name, so a create of that name there waits for the trash: sent
/// first, it made a node the trash took for the withdrawn one.
pub fn has_withdrawn_create(&self, parent_uid: &str, name: &str) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
conn.query_row(
&format!(
"SELECT EXISTS(
@@ -567,7 +567,7 @@ impl Db {
/// once it lands, so an op that wants the name can wait for it. A create
/// renamed while it was on the wire queues one (`Db::finish_create`).
pub fn has_pending_move_from(&self, name: &str) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
conn.query_row(
&format!("SELECT EXISTS(SELECT 1 FROM pending_op WHERE {MOVES_FROM})"),
params![OP_RENAME, name],
@@ -589,7 +589,7 @@ impl Db {
/// Whether a specific desired-state operation is still queued for a node.
pub fn has_pending_op(&self, uid: &str, kind: &str) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
let lid = node_lid(&conn, uid)?;
conn.query_row(
&format!(
@@ -604,7 +604,7 @@ impl Db {
/// Read an existing operation's metadata before a superseding enqueue.
pub fn pending_op_meta(&self, uid: &str, kind: &str) -> Result<Option<String>> {
let conn = self.read();
let conn = self.read()?;
let lid = node_lid(&conn, uid)?;
conn.query_row(
&format!(
@@ -1099,7 +1099,7 @@ impl Db {
/// Check if a queued create or mkdir op exists for `uid`.
pub fn has_create_op(&self, uid: &str) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
let lid = node_lid(&conn, uid)?;
let count: i64 = conn.query_row(
&format!(
@@ -1119,7 +1119,7 @@ impl Db {
/// bytes are still owed an upload, and dropping it would discard the staged
/// blob that holds them (`docs/BUGS.md` B71).
pub fn has_any_op(&self, uid: &str) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
let lid = node_lid(&conn, uid)?;
let count: i64 = conn.query_row(
&format!("SELECT COUNT(*) FROM pending_op WHERE {}", on_node(2)),
@@ -1227,7 +1227,7 @@ impl Db {
/// sort, and no separate index to maintain. The common case (something is
/// due) exits on the first row.
pub fn next_due_op(&self, now: i64) -> Result<Option<PendingOp>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare_cached(&format!(
"SELECT id, kind, {UID_NOW}, {PARENT_NOW}, name, blob_path, meta_json, created_at,
attempts, last_error, next_attempt_at
@@ -1368,7 +1368,7 @@ impl Db {
/// is not work this worker is waiting for, and counting it would have an
/// idle worker spin on a row it cannot have.
pub fn earliest_due_at(&self) -> Result<Option<i64>> {
let conn = self.read();
let conn = self.read()?;
let ts: Option<i64> = conn
.query_row(
&format!(
@@ -1386,7 +1386,7 @@ impl Db {
/// Every queued op, oldest first. For status read-outs and the CLI — the
/// drain wants [`next_due_op`](Self::next_due_op) instead.
pub fn pending_ops(&self) -> Result<Vec<PendingOp>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(&format!(
"SELECT id, kind, {UID_NOW}, {PARENT_NOW}, name, blob_path, meta_json, created_at,
attempts, last_error, next_attempt_at
@@ -1418,7 +1418,7 @@ impl Db {
/// construction, so nothing else in the drain ever looks at them. This is
/// the one query that does.
pub fn parked_create_ops(&self) -> Result<Vec<PendingOp>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(&format!(
"SELECT id, kind, {UID_NOW}, {PARENT_NOW}, name, blob_path, meta_json, created_at,
attempts, last_error, next_attempt_at
@@ -1453,7 +1453,7 @@ impl Db {
/// mount owes the server, but it carries no bytes and reporting it as an
/// upload is simply untrue.
pub fn pending_op_counts(&self) -> Result<PendingCounts> {
let conn = self.read();
let conn = self.read()?;
let uploads = conn.query_row(
"SELECT COUNT(*) FROM pending_op WHERE kind IN (?1, ?2)",
params![OP_REVISION, OP_CREATE],
@@ -1501,7 +1501,7 @@ impl Db {
/// it gone: the node was deleted, or a newer write superseded it, while the
/// worker was talking to the server.
pub fn op_exists(&self, id: i64) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
let count: i64 = conn.query_row(
"SELECT COUNT(*) FROM pending_op WHERE id = ?1",
params![id],
@@ -1617,7 +1617,7 @@ impl Db {
/// The issue of every op Drive refused, by op id.
pub fn op_issues(&self) -> Result<HashMap<i64, String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare("SELECT id, issue FROM pending_op WHERE issue IS NOT NULL")?;
let rows = stmt
.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?
@@ -1628,7 +1628,7 @@ impl Db {
/// The issue each node with a refused change has, by local id: what the
/// file browser shows on the node itself.
pub fn node_issues(&self) -> Result<HashMap<i64, String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT COALESCE(o.lid, n.lid), o.issue FROM pending_op o
LEFT JOIN nodes n ON o.lid IS NULL AND n.uid = o.uid
@@ -1753,7 +1753,7 @@ impl Db {
/// `staging/`: the difference is bytes the kernel was told were written and
/// that nothing is going to upload.
pub fn op_blob_paths(&self) -> Result<std::collections::HashSet<String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt =
conn.prepare("SELECT blob_path FROM pending_op WHERE blob_path IS NOT NULL")?;
let rows = stmt.query_map([], |r| r.get::<_, String>(0))?;
@@ -1794,7 +1794,7 @@ impl Db {
/// supersedes rather than forking a `(sync-conflict)` copy (docs/BUGS.md
/// B70 layer B).
pub fn own_sealed_rev(&self, uid: &str, now_ms: i64) -> Result<Option<String>> {
let conn = self.read();
let conn = self.read()?;
Ok(conn
.query_row(
"SELECT revision_id FROM own_sealed_rev
@@ -8,7 +8,7 @@ use std::collections::{HashMap, HashSet};
use proton_gallery_rs::grouping::{Grouped, group_photos, name_stem};
use super::Db;
use crate::Result;
use pdfs_core::Result;
/// A photo whose thumbnail state is not known yet: it has never been asked for.
pub const THUMB_UNKNOWN: i64 = 0;
@@ -33,7 +33,7 @@ pub struct StoredPhoto {
pub thumb_state: i64,
/// Which Photos-page tab this entry belongs to, derived from its name and
/// media type when the timeline was last replaced.
pub kind: crate::control::PhotoKind,
pub kind: pdfs_core::control::PhotoKind,
/// Whether the photo carries Proton's `Favorite` tag.
pub favorite: bool,
/// How many photos this photo's group holds — one shot taken as RAW+JPEG is
@@ -46,7 +46,7 @@ pub struct StoredPhoto {
pub place_id: Option<u32>,
}
/// A town photos were taken in: its GeoNames id (see [`crate::places`]), how
/// A town photos were taken in: its GeoNames id (see [`pdfs_core::places`]), how
/// many photos it holds, and the newest of them.
#[derive(Clone, Debug, PartialEq)]
pub struct StoredPlace {
@@ -102,7 +102,7 @@ struct Learned {
content_hash: Option<String>,
main_uid: Option<String>,
location: Option<(f64, f64)>,
/// What its thumbnail looks like (see [`crate::similar`]).
/// What its thumbnail looks like (see [`pdfs_core::similar`]).
similar_hash: Option<i64>,
/// When this photo's node was last resolved, kept so a refresh that skips it
/// does not make it look unresolved again.
@@ -143,7 +143,7 @@ fn stored_photo(r: &rusqlite::Row<'_>) -> rusqlite::Result<StoredPhoto> {
name: r.get(2)?,
ratio: r.get(3)?,
thumb_state: r.get(4)?,
kind: crate::control::PhotoKind::from_i64(r.get(5)?),
kind: pdfs_core::control::PhotoKind::from_i64(r.get(5)?),
favorite: r.get::<_, i64>(6)? != 0,
group_size: r.get::<_, i64>(7)?.max(1) as usize,
has_raw: r.get::<_, i64>(8)? != 0,
@@ -209,7 +209,7 @@ fn photos_delete_tx(tx: &Transaction<'_>, uids: &[String]) -> Result<usize> {
impl Db {
pub fn photo_projection_generation(&self) -> Result<i64> {
Ok(photos_generation(&self.read())?)
Ok(photos_generation(&*self.read()?)?)
}
/// One transaction records the deletion, stale metadata, listing work and feed position.
@@ -265,7 +265,7 @@ impl Db {
}
pub fn photos_need_work(&self) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
Ok(conn.query_row(
"SELECT NOT EXISTS(SELECT 1 FROM sync_state WHERE key=?1)
OR EXISTS(SELECT 1 FROM photos WHERE resolved_at IS NULL)",
@@ -275,7 +275,7 @@ impl Db {
}
pub fn photos_pending(&self) -> Result<Vec<String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt =
conn.prepare("SELECT uid FROM photos WHERE resolved_at IS NULL ORDER BY seq")?;
Ok(stmt
@@ -284,7 +284,7 @@ impl Db {
}
pub fn photo_removed(&self, uid: &str) -> Result<bool> {
Ok(self.read().query_row(
Ok(self.read()?.query_row(
"SELECT EXISTS(SELECT 1 FROM photo_tombstones WHERE uid=?1)",
[uid],
|r| r.get(0),
@@ -292,7 +292,7 @@ impl Db {
}
pub fn photos_contains(&self, uid: &str, album: Option<&str>) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
Ok(match album {
Some(album) => conn.query_row(
"SELECT EXISTS(SELECT 1 FROM album_photos WHERE album_uid=?1 AND uid=?2)",
@@ -324,7 +324,7 @@ impl Db {
resolved_at=?11 WHERE uid=?1",
)?;
for row in rows.iter().filter(|row| row.resolved_at.is_some()) {
let kind = crate::control::PhotoKind::classify(
let kind = pdfs_core::control::PhotoKind::classify(
row.name.as_deref(),
row.media_type.as_deref(),
);
@@ -339,7 +339,7 @@ impl Db {
row.location.map(|p| p.0),
row.location.map(|p| p.1),
row.location
.and_then(|(lat, lon)| crate::places::nearest(lat, lon))
.and_then(|(lat, lon)| pdfs_core::places::nearest(lat, lon))
.map(|city| city.id),
row.resolved_at
])?;
@@ -356,8 +356,8 @@ impl Db {
Ok((
Grouped {
uid: r.get(0)?,
raw: crate::control::PhotoKind::from_i64(r.get(1)?)
== crate::control::PhotoKind::Raw,
raw: pdfs_core::control::PhotoKind::from_i64(r.get(1)?)
== pdfs_core::control::PhotoKind::Raw,
main_uid: r.get(2)?,
day: r.get(3)?,
stem: name_stem(name.as_deref()),
@@ -467,7 +467,7 @@ impl Db {
};
// Everything the insert and the grouping need, resolved once per photo.
let resolved: Vec<(&TimelineRow, Learned, crate::control::PhotoKind)> = items
let resolved: Vec<(&TimelineRow, Learned, pdfs_core::control::PhotoKind)> = items
.iter()
.filter(|row| !tombstones.contains(&row.uid))
.map(|row| {
@@ -502,7 +502,7 @@ impl Db {
// The tab this photo lands in is derived here, once, so a page or
// count query is a plain indexed `WHERE kind = ?` rather than a
// reclassification of every row.
let kind = crate::control::PhotoKind::classify(
let kind = pdfs_core::control::PhotoKind::classify(
carried.name.as_deref(),
carried.media_type.as_deref(),
);
@@ -514,7 +514,7 @@ impl Db {
.iter()
.map(|(row, carried, kind)| Grouped {
uid: row.uid.clone(),
raw: *kind == crate::control::PhotoKind::Raw,
raw: *kind == pdfs_core::control::PhotoKind::Raw,
main_uid: carried.main_uid.clone(),
day: capture_day(&tx, row.capture_time),
stem: name_stem(carried.name.as_deref()),
@@ -553,7 +553,7 @@ impl Db {
carried.location.map(|(_, lon)| lon),
carried
.location
.and_then(|(lat, lon)| crate::places::nearest(lat, lon))
.and_then(|(lat, lon)| pdfs_core::places::nearest(lat, lon))
.map(|city| city.id),
carried.similar_hash,
])?;
@@ -572,7 +572,7 @@ impl Db {
/// one a remote event marked stale — is resolved. That is what keeps a
/// 12k-photo library off 63 round-trips of `enumerate_nodes` every refresh.
pub fn photos_resolved(&self) -> Result<Vec<String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare("SELECT uid FROM photos WHERE resolved_at IS NOT NULL")?;
let rows = stmt.query_map([], |r| r.get::<_, String>(0))?;
let mut uids = Vec::new();
@@ -652,7 +652,7 @@ impl Db {
&self,
offset: usize,
limit: usize,
kind: Option<crate::control::PhotoKind>,
kind: Option<pdfs_core::control::PhotoKind>,
range: Option<(i64, i64)>,
favorites: bool,
not_in_album: bool,
@@ -665,13 +665,13 @@ impl Db {
&self,
offset: usize,
limit: usize,
kind: Option<crate::control::PhotoKind>,
kind: Option<pdfs_core::control::PhotoKind>,
range: Option<(i64, i64)>,
favorites: bool,
not_in_album: bool,
excluded: &str,
) -> Result<Vec<StoredPhoto>> {
let conn = self.read();
let conn = self.read()?;
// Built up so any combination of the optional filters is one indexed
// query rather than a statement per case.
let mut sql = String::from(PHOTO_SELECT);
@@ -681,7 +681,7 @@ impl Db {
binds.push(excluded.to_owned().into());
conds.push("p.uid NOT IN (SELECT value FROM json_each(?1))".to_owned());
}
if kind != Some(crate::control::PhotoKind::Raw) {
if kind != Some(pdfs_core::control::PhotoKind::Raw) {
conds.push("p.uid = COALESCE(p.group_key, p.uid)".to_string());
}
if let Some(k) = kind {
@@ -729,7 +729,7 @@ impl Db {
/// of a shot, or just the photo itself when it stands alone. The lightbox
/// switches between these, and deleting a tile trashes all of them.
pub fn photos_group(&self, uid: &str) -> Result<Vec<StoredPhoto>> {
let conn = self.read();
let conn = self.read()?;
let sql = format!(
"{PHOTO_SELECT} WHERE COALESCE(p.group_key, p.uid) = \
(SELECT COALESCE(group_key, uid) FROM photos WHERE uid = ?1) ORDER BY p.seq"
@@ -748,7 +748,7 @@ impl Db {
return Ok(HashSet::new());
}
let ids = serde_json::to_string(uids).expect("file identifiers serialize");
let conn = self.read();
let conn = self.read()?;
let mut query = conn.prepare(
"SELECT uid FROM photos WHERE COALESCE(group_key, uid) IN (
SELECT COALESCE(group_key, uid) FROM photos
@@ -764,7 +764,7 @@ impl Db {
/// per group. Only for whole-library passes (the photo re-date); the gallery
/// pages with [`Db::photos_page`].
pub fn photos_all(&self) -> Result<Vec<StoredPhoto>> {
let conn = self.read();
let conn = self.read()?;
let sql = format!("{PHOTO_SELECT} ORDER BY p.seq");
let mut stmt = conn.prepare(&sql)?;
let rows = stmt
@@ -780,21 +780,21 @@ impl Db {
/// scopes the counts to one tab when set.
pub fn photos_months(
&self,
kind: Option<crate::control::PhotoKind>,
kind: Option<pdfs_core::control::PhotoKind>,
) -> Result<Vec<(i32, i32, usize)>> {
self.photos_months_visible(kind, "[]")
}
pub fn photos_months_visible(
&self,
kind: Option<crate::control::PhotoKind>,
kind: Option<pdfs_core::control::PhotoKind>,
excluded: &str,
) -> Result<Vec<(i32, i32, usize)>> {
let conn = self.read();
let conn = self.read()?;
// The scrubber has to agree with the page it scrubs, so it counts what
// the page shows: groups everywhere except on the Raw tab.
let filter = match kind {
Some(crate::control::PhotoKind::Raw) => "kind = ?2",
Some(pdfs_core::control::PhotoKind::Raw) => "kind = ?2",
Some(_) => "uid = COALESCE(group_key, uid) AND kind = ?2",
None => "uid = COALESCE(group_key, uid) AND ?2 IS NULL",
};
@@ -837,7 +837,7 @@ impl Db {
limit: usize,
excluded: &str,
) -> Result<Vec<StoredPhoto>> {
let conn = self.read();
let conn = self.read()?;
let sql = format!(
"{PHOTO_SELECT} WHERE p.uid = COALESCE(p.group_key, p.uid) \
AND strftime('%m-%d', p.capture_time, 'unixepoch', 'localtime') \
@@ -863,7 +863,7 @@ impl Db {
pub fn photo_places_visible(&self, excluded: &str) -> Result<Vec<StoredPlace>> {
let rows: Vec<(u32, usize, String)> = {
let conn = self.read();
let conn = self.read()?;
// SQLite fills the bare `uid` from the row `MIN(seq)` picked, which
// is the newest photo of the place.
let mut stmt = conn.prepare(
@@ -912,7 +912,7 @@ impl Db {
limit: usize,
excluded: &str,
) -> Result<Vec<StoredPhoto>> {
let conn = self.read();
let conn = self.read()?;
let sql = format!(
"{PHOTO_SELECT} WHERE p.uid = COALESCE(p.group_key, p.uid) AND p.place_id = ?1
AND p.uid NOT IN (SELECT value FROM json_each(?4))
@@ -934,7 +934,7 @@ impl Db {
pub fn photo_locations_at_place(&self, id: u32) -> Result<Vec<(StoredPhoto, (f64, f64))>> {
let photos = self.photos_at_place(id, 0, usize::MAX >> 1)?;
let located: HashMap<String, (f64, f64)> = {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT uid, latitude, longitude FROM photos \
WHERE place_id = ?1 AND latitude IS NOT NULL AND longitude IS NOT NULL",
@@ -961,7 +961,7 @@ impl Db {
/// set left with one member is no set.
pub fn photo_duplicates(&self) -> Result<Vec<Vec<StoredPhoto>>> {
let rows: Vec<(String, String, String)> = {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT p.uid, p.content_hash, COALESCE(p.group_key, p.uid) AS k FROM photos p \
WHERE p.content_hash IN (SELECT content_hash FROM photos \
@@ -1008,7 +1008,7 @@ impl Db {
/// any of its files is, since they all show one picture.
pub fn photos_unhashed(&self, limit: usize) -> Result<Vec<StoredPhoto>> {
let uids: Vec<String> = {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT COALESCE(group_key, uid) AS k FROM photos \
GROUP BY k \
@@ -1018,7 +1018,7 @@ impl Db {
)?;
stmt.query_map(
params![
crate::control::PhotoKind::Video.as_i64(),
pdfs_core::control::PhotoKind::Video.as_i64(),
THUMB_NONE,
limit as i64
],
@@ -1030,7 +1030,7 @@ impl Db {
}
/// Record the look of photo `uid`: its difference hash, or
/// [`crate::similar::NO_HASH`] when its thumbnail gave none.
/// [`pdfs_core::similar::NO_HASH`] when its thumbnail gave none.
pub fn photo_set_similar_hash(&self, uid: &str, hash: u64) -> Result<()> {
let conn = self.conn.lock();
conn.execute(
@@ -1042,38 +1042,38 @@ impl Db {
/// How many shots have been hashed, out of how many could be.
pub fn similar_progress(&self) -> Result<(usize, usize)> {
let conn = self.read();
let conn = self.read()?;
let (hashed, total): (i64, i64) = conn.query_row(
"SELECT COUNT(*) FILTER (WHERE hashed), COUNT(*) FROM \
(SELECT MAX(similar_hash) IS NOT NULL AS hashed FROM photos \
GROUP BY COALESCE(group_key, uid) \
HAVING MAX(similar_hash) IS NOT NULL \
OR MAX(kind != ?1 AND thumb_state != ?2))",
params![crate::control::PhotoKind::Video.as_i64(), THUMB_NONE],
params![pdfs_core::control::PhotoKind::Video.as_i64(), THUMB_NONE],
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
Ok((hashed.max(0) as usize, total.max(0) as usize))
}
/// Sets of shots that look alike (see [`crate::similar`]), one photo per
/// Sets of shots that look alike (see [`pdfs_core::similar`]), one photo per
/// shot in capture order, and the sets newest first. A set whose photos
/// are all byte-identical copies is left to [`Self::photo_duplicates`].
pub fn photo_similar(&self) -> Result<Vec<Vec<StoredPhoto>>> {
let rows: Vec<(String, u64, Option<String>)> = {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT COALESCE(group_key, uid) AS k, MAX(similar_hash), \
MAX(content_hash) FILTER (WHERE uid = COALESCE(group_key, uid)) \
FROM photos GROUP BY k \
HAVING MAX(similar_hash) IS NOT NULL AND MAX(similar_hash) != ?1",
)?;
stmt.query_map(params![crate::similar::NO_HASH as i64], |r| {
stmt.query_map(params![pdfs_core::similar::NO_HASH as i64], |r| {
Ok((r.get(0)?, r.get::<_, i64>(1)? as u64, r.get(2)?))
})?
.collect::<rusqlite::Result<_>>()?
};
let hashes: Vec<u64> = rows.iter().map(|(_, hash, _)| *hash).collect();
let found: Vec<Vec<usize>> = crate::similar::sets(&hashes)
let found: Vec<Vec<usize>> = pdfs_core::similar::sets(&hashes)
.into_iter()
.filter(|set| {
let first = &rows[set[0]].2;
@@ -1108,8 +1108,8 @@ impl Db {
}
pub fn photos_counts_visible(&self, excluded: &str) -> Result<(usize, usize, usize)> {
use crate::control::PhotoKind;
let conn = self.read();
use pdfs_core::control::PhotoKind;
let conn = self.read()?;
// Photos and Videos count groups — one shot is one entry, however many
// files it was stored as. Raw counts files, because the Raw tab lists
// them individually.
@@ -1140,7 +1140,7 @@ impl Db {
if uids.is_empty() {
return Ok(Vec::new());
}
let conn = self.read();
let conn = self.read()?;
let placeholders = vec!["?"; uids.len()].join(",");
let sql = format!("{PHOTO_SELECT} WHERE p.uid IN ({placeholders})");
let mut stmt = conn.prepare(&sql)?;
@@ -1178,7 +1178,7 @@ impl Db {
/// Number of photos in the persisted timeline.
pub fn photos_count(&self) -> Result<usize> {
let conn = self.read();
let conn = self.read()?;
let n: i64 = conn.query_row("SELECT COUNT(*) FROM photos", [], |r| r.get(0))?;
Ok(n.max(0) as usize)
}
@@ -5,7 +5,7 @@ use rusqlite::{OptionalExtension, params};
use super::Db;
use super::utils::MAX_PATH_DEPTH;
use crate::Result;
use pdfs_core::Result;
/// One row of [`Db::pin_list`]. `recursive` is pin *policy* — whether the whole
/// subtree is kept — while `is_dir` is the node's kind as the node cache knows
@@ -40,7 +40,7 @@ impl Db {
/// Every directly-pinned entry, ordered by uid.
pub fn pin_list(&self) -> Result<Vec<PinRow>> {
let conn = self.read();
let conn = self.read()?;
// `recursive` is pin policy; the node's kind comes from `nodes`, and is
// NULL for a pin whose node was never cached.
let mut stmt = conn.prepare(
@@ -73,7 +73,7 @@ impl Db {
/// terminates — while holding the daemon's only SQLite connection, on a path
/// that runs per cached read.
pub fn is_pinned(&self, uid: &str) -> Result<bool> {
let conn = self.read();
let conn = self.read()?;
let direct: Option<i64> = conn
.query_row("SELECT 1 FROM pins WHERE uid = ?1", params![uid], |r| {
r.get(0)
@@ -107,7 +107,7 @@ impl Db {
/// every descendant of a recursively-pinned folder. Used to build the
/// eviction-exempt set (the budget enforcer hashes these into cache keys).
pub fn pinned_uids(&self) -> Result<Vec<String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"WITH RECURSIVE sub(uid, lid) AS (
SELECT p.uid, n.lid FROM pins p LEFT JOIN nodes n ON n.uid = p.uid
@@ -130,7 +130,7 @@ impl Db {
/// Every descendant uid of `folder` (all depths), via a `parent_lid` CTE.
/// Used to evict a recursively-pinned subtree's cached blobs on unpin.
pub fn descendants(&self, folder: &str) -> Result<Vec<String>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare(
"WITH RECURSIVE sub(uid, lid) AS (
SELECT c.uid, c.lid FROM nodes c JOIN nodes f ON c.parent_lid = f.lid
@@ -6,7 +6,7 @@ use proton_drive_rs::proton_sdk::ids::{LinkId, NodeUid, VolumeId};
use rusqlite::{OptionalExtension, params};
use super::Db;
use crate::{Access, Error, Result};
use pdfs_core::{Access, Error, Result};
impl Db {
/// Load the complete, deliberately small shared-root authority map.
@@ -16,7 +16,7 @@ impl Db {
/// remains the restart/offline authority and every explicit role change is
/// written through before this cache is updated.
pub fn all_share_access(&self) -> Result<HashMap<NodeUid, Access>> {
let conn = self.read();
let conn = self.read()?;
let mut stmt = conn.prepare("SELECT root_uid, access FROM share_access")?;
let rows = stmt.query_map([], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
@@ -42,7 +42,7 @@ impl Db {
/// Read the effective access recorded for a shared-tree root.
pub fn share_access(&self, uid: &NodeUid) -> Result<Option<Access>> {
let conn = self.read();
let conn = self.read()?;
let value = conn
.query_row(
"SELECT access FROM share_access WHERE root_uid = ?1",
@@ -101,7 +101,7 @@ impl Db {
/// Drive gave it. The tree learns that uid a moment later, and a rename in
/// between was refused (`docs/BUGS.md` B174).
pub fn effective_node_access(&self, uid: &NodeUid) -> Result<Option<Access>> {
let conn = self.read();
let conn = self.read()?;
let key = uid.to_string();
let key = match super::local_lid(&key) {
Some(lid) => conn
@@ -4,11 +4,11 @@
use rusqlite::{OptionalExtension, params};
use super::Db;
use crate::Result;
use pdfs_core::Result;
impl Db {
pub fn get_event_cursor(&self) -> Result<Option<String>> {
let conn = self.read();
let conn = self.read()?;
let v = conn
.query_row(
"SELECT value FROM sync_state WHERE key = 'event_cursor'",
@@ -32,7 +32,7 @@ impl Db {
/// Read a `sync_state` value as a string.
pub fn state_str(&self, key: &str) -> Result<Option<String>> {
let conn = self.read();
let conn = self.read()?;
let v = conn
.query_row(
"SELECT value FROM sync_state WHERE key = ?1",
@@ -66,7 +66,7 @@ impl Db {
/// dropping it would leave a file that exists nowhere but this machine with
/// nothing left to create it. (Writes to a node that is itself still queued
pub fn state_i64(&self, key: &str) -> Result<Option<i64>> {
let conn = self.read();
let conn = self.read()?;
let v: Option<String> = conn
.query_row(
"SELECT value FROM sync_state WHERE key = ?1",
Loaded 100 of 138 files, more files were not shown because too many files have changed in this diff. Show more