Compare commits

..
Author SHA1 Message Date
nvrl 62cc85cb06 feat(vfs,fuse): a headless adapter, and conformance scenarios run through it and FUSE
Slice 3 of step 5. pdfs_vfs::headless::Headless serves the open-file
and namespace services by path, with no kernel and no Drive. Its host
queues every create in the real store, as the daemon does offline, and
keeps what each close committed in memory. It does itself what the
kernel does before calling the FUSE adapter: path resolution one name
at a time, refusing a taken name on mkdir, and opening an existing file
on create.

pdfs_vfs::conformance (test-support) holds an Adapter trait and ten
scenarios: a file written, resized, synced, closed and reopened; partial
overwrites; reads while open; holes past a grow; create over a file;
folder listings; renames that move and replace; the renames and removals
POSIX refuses; and an unlinked open file. They run through the headless
adapter in pdfs-vfs's unit tests, and through a FUSE mount over the fake
Drive, online and offline, in two new simulations. Both adapters see the
same outcomes.
2026-11-27 15:08:39 +01:00
nvrl 7d963b3dd7 Merge branch 'refactor/vfs-namespace' into refactor/vfs-rename 2026-11-27 14:09:58 +01:00
nvrl b7af8ae6c2 test(sim): restore a cut-off replace's victim without a listing lag
The simulation trashes the replaced file on Drive just before the
restart. Under the LAN profile a read shows that trash only after the
50 ms listing lag, so a restart quicker than that read the file as never
trashed and left it there. It failed that way in CI twice. A real stop
comes long after its own trash, so the restart now reads Drive without
the lag.
2026-11-27 14:09:55 +01:00
nvrl 5647b8e684 test(sim,store): print the daemon log when the B302 restore simulation fails
It failed once in CI with only the Drive tree to go on, and does not
reproduce locally. Also put next_run's doc comment back above it: it had
split acquire_single_writer_lock from its own.
2026-11-27 13:47:58 +01:00
nvrl b6ce90fcd5 refactor(vfs,fuse): rename through the namespace service
Namespace::rename now holds what serve_rename did: the cycle and
exchange checks, the replace checks and access gate, the B302 journal
around the victim's removal, the rewrite of a queued create's target
(B142, B70), the choice between the queue and Drive, and the restore of
the victim on failure. Drive calls, the queue and the victim's removal
and restore go through new NamespaceHost methods. The FUSE callback
maps the flags, answers, and drops the kernel's stale entries after a
queued rename.

NamespaceHost::lookup_child now returns None for a missing child, so
the service can tell an absent destination from a failed lookup.
2026-11-27 13:31:29 +01:00
nvrl 7adcdd250f refactor(vfs,fuse): create, mkdir, unlink and rmdir through the namespace service
Namespace in pdfs-vfs now decides whether a new node is minted on Drive
or queued, parks a transient name, applies the unlink and rmdir checks,
and orders a trash: Drive first, then the tree, then the queued ops and
the cache. Drive calls, the queue and the access rules go through the
NamespaceHost port, which Core implements. The FUSE callbacks keep the
inode translation, the worker lane and the reply.

The create and mkdir answers now read the new entry under the lock that
made it, so an unlink racing the reply cannot leave the answer without
an entry. Unit tests cover the paths with a recording host.
2026-11-27 13:15:09 +01:00
nvrl 006b6f6926 fix(fuse,vfs,store): settle a replacing rename a stop cut off (B302)
Drive has no replacing rename, so rename(2) over an existing name
removes the destination first and renames the source second. A stop
between the two left the destination in Drive's trash, or with its
trash queued and no rename, and nothing recorded that a rename was
half done.

A replacing rename now writes a journal entry with a synced commit
before it removes the destination, and ends it when it returns. The
entry lives in sync_state, so the schema does not change, and carries
the opening of the database that wrote it, so a rename in progress is
never settled under it.

At mount, and on the drain's idle passes while online, Recovery
settles each entry from an earlier run with the rules in
pdfs_vfs::namespace: a queued rename stands, a queued trash with no
rename is dropped, and otherwise Drive decides whether the rename
happened or the destination comes back from the trash.
2026-11-27 13:01:15 +01:00
nvrl 251655548a docs: describe the open-file service in ARCHITECTURE.md 2026-11-27 12:40:27 +01:00
nvrl 59c6740137 refactor(vfs,fuse): close a file through the open-file service
Files::release does what the release callback and finish_release did:
retire the handle, and on the last close hand what it wrote to the
upload queue, or drop it when the file was unlinked while open. The
read view a release keeps until the revision is queued (B300) is
retired there too.

FilesHost gains commit, which follows a landed create and queues the
revision, and discard_unlinked, which drops an unlinked file's row,
queued changes and cached bytes once nothing needs them. Core
implements both with the code that was in the callback. The release
still runs on the dispatch loop, for the ordering it gives a read that
follows the close.
2026-11-27 12:39:49 +01:00
nvrl ae633c2899 fix(vfs): order overlapping fsyncs on one file (B301)
An fsync copied what the handle held, synced the scratch file and then
wrote that copy as the sidecar a restart recovers from. Two fsyncs on
the same file ran on different workers with nothing ordering them, so
the one that finished last could leave the older record on disk.

Each write handle now counts its changes in a generation and carries
a barrier. An fsync takes the barrier before it reads the handle and
keeps it until the sidecar is written. An fsync with nothing new since
the last durable generation skips the sidecar.
2026-11-27 12:36:35 +01:00
nvrl d14ed56b86 refactor(vfs,fuse): serve open, write, resize, flush and fsync from pdfs-vfs
The open-file service, pdfs_vfs::files::Files, now does what the FUSE
callbacks did inline for a file open for writing:
- a write open, with its re-check of the queued base (B32, B170, B204);
- staging a write;
- a handle-backed resize and fallocate;
- the flush of a dirty scratch file;
- the fsync barrier and its durability sidecar.

It returns FileError, which the adapter maps to the same errno values as
before. What it needs from Drive and the drain goes through FilesHost,
which Core implements: settling a provisional size, filling gaps from
the remote base, and the node an upload just landed.

remote_baseline becomes WriteState::baseline, and is_local_uid moves to
pdfs_vfs::ids. New tests drive the service with an offline host and no
kernel.
2026-11-27 12:32:28 +01:00
nvrl a13ca95a83 refactor(vfs,fuse): move the tree's kernel-free rules into pdfs-vfs
- merge_over_pending and copy_pending_for_truncate, which fold a queued
  revision into a newer write, move to pdfs_vfs::open with their tests.
- The last release of an unlinked inode becomes State::release_unlinked,
  and listed_children moves to pdfs_vfs::tree.
- Which nodes a folder shows, how queued changes lie over a listing, and
  the node a create makes before Drive has seen it move to pdfs_vfs::nodes.
- The component-name and rename-replace checks move to pdfs_vfs::names
  and return NameError and ReplaceError. The FUSE adapter maps them to
  the same errno values as before.
2026-11-27 12:19:11 +01:00
nvrl 7978a40224 refactor(vfs,fuse): let the tree build a directory's listing
The listing a readdir pages through is built from the tree alone, so it
moves from filesystem.rs to State::listing in pdfs-vfs.
2026-11-27 12:13:34 +01:00
nvrl 275f40b24b refactor(vfs,fuse): move the read of an open file into pdfs-vfs
A read of a file open for writing takes the written ranges from the
scratch file, asks the base for the rest, and zero-fills past the base.
That assembly moves to `pdfs_vfs::open::assemble_open_read`, with its
test. It is generic over the base's error. A failed scratch read comes
back as `ReadFailure::Scratch`. The read path maps that to `EIO` and logs
it, as before, and passes the base's own errno through.
2026-11-27 02:10:14 +01:00
nvrl 695a810cea refactor(vfs,fuse): move the write-back's state into pdfs-vfs
`WriteState` holds three things:
- the revisions the mount accepted but has not uploaded;
- the nodes removed here that a stale listing may still return;
- the echoes the event feed owes for changes this daemon made.

It moves from `pdfs-fuse/src/writes.rs` to `pdfs_vfs::writes`. The echo
bookkeeping it uses moves with it, together with its test. `pdfs-fuse`
keeps `Core::note_self_change` and `Core::take_self_change`, which stamp
the time and call it.

There is no behaviour change.
2026-11-27 02:06:07 +01:00
nvrl 9dbb4c9950 fix(vfs,fuse): serve a read during a release from the write it is queueing (B300)
A release took the write state out of the open files, then queued the new
revision. A read that ran on a worker in between found neither, and could
be served the revision on Drive from before the write. An `open` and `read`
issued after `close(2)` are ordered behind the release, because both go
through the dispatch loop. A read through a handle opened earlier is not.

`OpenFiles` now keeps a read view of the writer until `finish_release`:
its scratch file, length, base and written ranges. This replaces the set
of releasing inodes. `OpenFiles::reader` answers from an open writer or
from that view, and both read paths ask it first.
2026-11-27 02:01:38 +01:00
nvrl c5884ba638 refactor(vfs,fuse): move the tree into pdfs-vfs
`State` is the tree every mount shows. It holds the nodes by inode, the
stable inode numbers from local ids, each session's root, and the open
files. It moves from `pdfs-fuse/src/state.rs` to `pdfs_vfs::tree`, with its
tests. `pdfs-fuse` keeps its paths through `use pdfs_vfs::tree as state`.

It needed three things from `pdfs-fuse`, and these move to
`pdfs_vfs::ids`:
- the root inode;
- the orphan inode;
- the check for nodes on the made-up virtual volume.

Its one kernel type was the `fuser::Errno` that `require_writable` returned.
That becomes `tree::NodeError`, which the FUSE adapter maps to `ENOENT` or
`EACCES`, as before.

The helpers other crates' tests use to inspect a tree are behind the
`test-support` feature. `pdfs-fuse` enables it for its tests only.

There is no behaviour change.
2026-11-27 01:57:11 +01:00
nvrl 860593b655 refactor(vfs,fuse): move fallocate rules and directory handles into pdfs-vfs
The rules for which `fallocate` modes a write handle can record, and what
each one does to the authored ranges and the length, lived in the FUSE
callback. They are now `pdfs_vfs::open::Fallocate` and
`WriteHandle::record_fallocate`. The callback runs the syscall and records
the result, as before.

Directory handles join `OpenFiles`. The frozen listing an `opendir` takes,
and the paging of a `readdir` through it (`dir_page`), no longer sit on
`State` and in the reply code. File and directory handles now draw from the
same counter in the same table, which was the reason they had to share one.

There is no behaviour change.
2026-11-27 01:52:04 +01:00
nvrl 4dcc2aa04e refactor(vfs,fuse): keep the open files in one table in pdfs-vfs
`State` carried four loose fields for open files:
- the write state by inode;
- the inode behind each handle;
- the inodes being released;
- the next handle number.

Eleven modules read and changed them directly. The release callback did
the reference counting by hand. Finding unsaved changes meant chaining two
of the maps in two places.

`pdfs_vfs::open::OpenFiles` now owns them. It opens a writer and returns
the handle number, looks a writer up by inode or by handle, and says
whether an inode is busy or owes changes. It hands back the write state
on the last release, and marks the inode as releasing until
`finish_release`. One counter still serves file and directory handles.
The FUSE adapter and the rest of `pdfs-fuse` call these methods. There
is no behaviour change.
2026-11-27 01:47:18 +01:00
nvrl d891e24e96 refactor(vfs,fuse): start pdfs-vfs with the open file
Step 5 of the 4.0 plan moves the mounted-files side out of `pdfs-fuse` into
a service that does not know about the kernel. This starts the `pdfs-vfs`
crate with the open file:
- `Intervals`, the ranges of a scratch file written here;
- `WriteHandle`, a file open for writing;
- `PendingRevision`, a released write waiting for its upload.

They move unchanged from `pdfs-fuse/src/state.rs`, with their tests.

Writing the scratch file moves too. `stage_write` reports a full disk as
`WriteError::NoSpace` instead of an `io::Error` the caller has to inspect.
The FUSE adapter maps it to `ENOSPC` and frees cache space, as before.

`node_size` moves to `pdfs-drive`, next to `node_revision_id`, so both
crates use one copy. `pdfs-vfs` depends on neither `fuser` nor GTK.
2026-11-27 01:42:52 +01:00
nvrl 957a7ff391 Merge pull request #167 from narrrl/refactor/joined-workers
refactor(core,fuse): join jobs on stop and run the mount's loops as services
2026-11-27 01:34:57 +01:00
nvrl d9881810b7 Merge pull request #166 from narrrl/refactor/devices-service
refactor(fuse): make the device records and the profile backup services
2026-11-27 01:33:47 +01:00
nvrl d9dab26e86 docs(architecture): say what is left in Core after step 3 2026-11-26 22:25:14 +01:00
nvrl eae7ce90d2 refactor(fuse): give the hidden gallery its own handles
`gallery::Gallery` took a `&Core` on every call to reach the client, the
event hub and the database. It now holds those three, given when it is
built, and its background refresh no longer needs a `Core` either.
2026-11-26 22:24:40 +01:00
nvrl b674f3eb71 docs(architecture): describe the search and recovery services 2026-11-26 22:19:13 +01:00
nvrl 3a4812baae refactor(fuse): make queue recovery a service
Rebuilding the queue after a restart ran as methods on `Core`.
`recovery::Recovery` now holds the database, the content cache and the
write-back's state. It rebuilds the pending map, reconciles the staging
area and recovers fsynced writes. Queueing a recovered write goes through
`RecoveryHost`, which has one method.

Rebuilding the tree (`Core::hydrate`) stays on `Core`, because the tree is
part of the mounted-files service.
2026-11-26 22:18:46 +01:00
nvrl 3da45c0bf9 refactor(fuse): make search a service
Search ran as methods on `Core`. `search::Search` now holds the database,
the content cache, the on-demand mounts and the home indexer's busy flag,
which is all it reads. `Core::search_roots` stays as a shortcut, because the
conflict listing and the conflict sweep ask it too.
2026-11-26 22:15:24 +01:00
nvrl dc72991da2 docs(architecture): describe the mount's services and their ports 2026-11-26 22:12:45 +01:00
nvrl bdcabed1ee refactor(fuse): give the shutdown inhibitor only the database and the stop signal
The inhibitor took a whole `Core` to read the queue counts and wait on the
stop signal. It now takes those two handles.
2026-11-26 22:12:28 +01:00
nvrl 7def9e903b refactor(fuse): make the pin keeper a service
The pin keeper's loop ran as methods on `Core`. `keeper::PinKeeper` now
holds the content cache, the transfer list, the link, the stop signal and
its queue of work, which `Core::recheck_all_pins` and
`Core::recheck_pinned` still fill. It reaches the tree through
`KeeperHost`, which has five methods:
- find a node's inode, its parent's, and whether it is a folder;
- list every file under a kept folder;
- list a folder again if its listing was dropped;
- describe a file as a pin keeps it;
- download a pinned file.
2026-11-26 22:10:15 +01:00
nvrl bb376d7dc4 refactor(fuse): let the link own its state and make the probe a service
The online flag, the outage start and the condvar lived on `link::Link`, but
`Core` reached into them to flip the flag, log and wait. `Link` now does
that itself: `go_offline`, `go_online`, `wait_online` and the probe's idle
wait. `Core::mark_offline` and `Core::wait_online` delegate to it.

The online probe moves from `Core` to `link::OnlineProbe`, which holds the
link, Drive, the runtime and the stop signal. It reaches the rest of the
daemon through `LinkHost`, which has four methods:
- store the My Files root Drive answered with;
- after the reconnect, relist, retry backed-off ops, wake the drain and
  recheck the pins;
- report a refused session;
- repair the primary root's share id after an offline start.

The order is unchanged: the root is stored, the mount goes online, and then
what waited on the link runs.
2026-11-26 22:06:36 +01:00
nvrl 57e654924a refactor(fuse): make the conflict sweep a service
The conflict sweep ran as methods on `Core`. `sweep::Sweeper` now holds
Drive, the runtime, the database, the stop signal and its own state. It
reaches the mounts through `SweepHost`, which has six methods:
- whether a node is this account's own or virtual;
- whether the mount is online;
- whether a node is being written or held open in any mount;
- for one pass, whether the conflict listing can show a copy;
- unhook a trashed node from every mount and drop its cached content;
- add an activity entry.

`Core::is_busy` stays on `Core`, because resolving a conflict by hand asks
it too.
2026-11-26 22:02:44 +01:00
nvrl e3bc64df54 test(sim): let the short-outage test start from either side of the outage
`a_write_that_failed_on_a_short_outage_goes_out_soon_after_the_link_returns`
waited for the drain to record a failed attempt. When another caller, such
as the event poll or a sync pass, met the outage first and took the mount
offline, the drain claimed nothing, no attempt was ever recorded, and the
test failed after 30 seconds. It failed this way twice in a row in the CI of
#166.

The test now also accepts the mount having gone offline. The rest is
unchanged: the write still has to go out within 3 seconds of the mount
coming back.
2026-11-26 21:57:41 +01:00
nvrl 47576a389e refactor(fuse): make database maintenance a service
`VACUUM` and the deep integrity check were methods on `Core` behind a bare
`Arc<Mutex<Maintenance>>` field. `maintenance::Maintenance` now holds the
database, the transfer list, the board its jobs run on and its own state,
and the control socket calls it directly.
2026-11-26 21:56:04 +01:00
nvrl 7ed07e0056 refactor(core,fuse): start the mount's threads as services
Each long-lived thread the mount ran was a block in `mount.rs` with its own
spawn, wake and failure path, far from the loop it ran. A `Service` trait in
`pdfs_core::lifecycle` now carries the thread's name, whether the mount can
run without it, and the call that wakes it on a stop. The mount's loops are
types in `services.rs`, and `mount.rs` builds a list and starts it with
`Services::start`.

A required service that cannot start fails the mount attempt, as before. An
optional one (the sync engine, the event sampler, the supervisor and the
inhibitor) is logged and skipped, as before.
2026-11-26 21:52:03 +01:00
nvrl be99fffe1b refactor(core,fuse): join one-shot jobs on stop
A stop used to leave one-shot jobs running. A size upgrade still waiting on
Drive when the runtime went away panicked on its next timer ("A Tokio 1.x
context was found, but it is being shutdown"), seen in the simulation of
#166.

`Services::stop` now closes the board to new jobs, aborts the async ones,
and joins the thread jobs before the services, all up to the same deadline,
naming any still running then. A job asked for after the stop began is
refused. The size upgrade checks the stop signal between chunks.

The threads still started by hand go through the board: the parked size
waiters, the diagnostics probe and each control connection are jobs, so a
stop joins them. A subscription waits on its mailbox, so the control
listener's wake now rings every mailbox. The helper reader in `run_bounded`
is a scoped thread.
2026-11-26 21:44:54 +01:00
nvrl 96de4a8f46 refactor(fuse): make the profile backup a service
Saving this machine's profile, reading the profiles of other machines and
listing the folders a device offers for restore move from `Core` onto
`profile::ProfileBackup`. It holds Drive, the runtime, the database, the
service board and the `Devices` service, and needs nothing from the
filesystem, so it has no host port. `Core::profile` builds it on demand.

`restore_sync_folders` stays on `Core`: it creates synced folders and tells
the sync engine about them.
2026-11-26 20:57:37 +01:00
nvrl 97d9d671d2 refactor(fuse): make the device records a service with a host port
Listing, renaming, deleting, adopting and migrating devices, and
registering this computer as one, move from `Core` onto `devices::Devices`.
It holds the client, Drive, the runtime and the database. Migrating moves
another device's folders onto this one, and for that it reaches the rest of
the daemon through `DevicesHost`: move a folder on the server, run a sync
pass for a synced folder, and re-enumerate a folder. `Core::devices` builds
it on demand.

Synced folders, their modes and on-demand mounts stay on `Core`; they are
bound up with the mount registry and the sync engine.
2026-11-26 20:54:00 +01:00
nvrl 45e0b60994 refactor(fuse): make revisions a service that takes resolved nodes
Each revision operation was a method on `Core` in three copies: by path, by
uid, and the one that did the work. `revisions::Revisions` keeps only the
last, and takes the node's uid and the name the activity feed shows.
`control/revisions.rs` resolves the path or the uid once and, for a restore
by path, re-enumerates the parent folder afterwards, as before.

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

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

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

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

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

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

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

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

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

ARCHITECTURE.md describes the three interfaces and what is left in `Core`.
2026-11-26 19:38:03 +01:00
nvrl 24f1f51c2c refactor(fuse): put the write-back's state behind WriteState
`pending`, `hidden` and `self_changes` move off `Core` into
`writes::WriteState`. The read path, listings, the pin keeper and the event
feed now ask it through methods (`queued`, `is_queued`, `queued_len`,
`queued_sizes`, `hidden`, `hide`, `unhide`, `note_echo`, `take_echo`)
instead of taking its locks. `hidden` and `self_changes` are private to the
module. `pending` stays visible to the queue, the drain and recovery, which
update it together with the database under one lock.
2026-11-26 19:29:21 +01:00
nvrl bbaa24e6ce Merge pull request #162 from narrrl/refactor/services
feat(core,fuse): stop the event-stream loops with the mount's other services
2026-11-26 19:18:41 +01:00
nvrl cb6e0e3228 feat(core,fuse): stop the event-stream loops with the mount's other services
The loops that follow the Drive and photos event streams, and the gallery
refresh, were bare tasks on the runtime. A stop ended every thread and left
them running until the process exited, still able to write to the database.

`Services::spawn_task` starts an async task as a service: it shows on the
service board, and a stop aborts it at its next `.await` and waits for it
up to the shared deadline. `ServiceBoard::spawn_task_job` lists the trash,
timeline and album refreshes a listing starts as jobs, and the My Files
share-id repair runs as a job too.

The sims now fail a run whose stops leave a service running.
2026-11-26 18:47:16 +01:00
nvrl a627542c20 Merge pull request #161 from narrrl/refactor/mirror-split
refactor(sync), feat(core,fuse): split mirror.rs; run request work as named jobs
2026-11-26 17:27:38 +01:00
nvrl 58fa3b5953 Merge pull request #160 from narrrl/refactor/cli-split
refactor(cli,fuse): split the CLI's main.rs, the drain and photos by area
2026-11-26 17:01:19 +01:00
nvrl 633e268a7b Merge pull request #159 from narrrl/feat/pdfs-daemon
feat(daemon): add pdfs-daemon, the daemon's composition root
2026-11-26 17:01:07 +01:00
nvrl afbf88aa2d feat(core,fuse): run a request's background work as a named job on the service board
Work a request starts and does not wait for ran on a bare thread::spawn:
unnamed, invisible to diagnostics, and a panic if the thread could not
be started. ServiceBoard::spawn_job starts it on a named thread and
lists it until it ends, by return or by panic.

Twelve sites move to it: the profile backup, the upload, add and restore
of synced folders from the control socket, re-dating, VACUUM, the deep
integrity check, the Google Photos import, the timed pause, a folder
pin, the similar-photo pass, and size upgrades. A job that cannot be
started is logged by name instead of panicking the handler.

pdfs diagnostics gets a jobs field (serde default) and prints the jobs
running with their age. Jobs are not joined on stop, as before.
2026-11-26 16:45:43 +01:00
nvrl e93e2a3ef9 refactor(sync): split mirror.rs into the walks, applying a plan and the push pass
mirror.rs keeps a pass from end to end (reconcile_folder, reconcile_pass,
do_reconcile), the trace, the helpers the parts share, and the tests.
Syncer's methods move, unchanged, into:

- mirror/walk.rs: walking the local tree and Drive's folders, resuming
  a saved walk, walking only the changed folders, listing one (8)
- mirror/apply.rs: applying a plan in batches, uploads, downloads, and
  the baseline each one leaves (12)
- mirror/push.rs: the push pass (1)

No behaviour changes.
2026-11-26 16:39:57 +01:00
nvrl d32f287763 Merge pull request #158 from narrrl/refactor/lib-split
refactor(fuse): split Core's methods by area out of lib.rs into ten modules
2026-11-26 16:31:24 +01:00
nvrl 04fb485e9f Merge pull request #157 from narrrl/refactor/core-groups
refactor(fuse): move five more Core groups, with their code, out of lib.rs
2026-11-26 16:12:03 +01:00
88 changed files with 12944 additions and 7019 deletions

No files matched your search

Generated
+14
View File
@@ -3729,6 +3729,7 @@ dependencies = [
"pdfs-drive",
"pdfs-store",
"pdfs-sync",
"pdfs-vfs",
"proton-drive-rs",
"proton-gallery-app-rs",
"proton-gallery-rs",
@@ -3800,6 +3801,19 @@ dependencies = [
"tracing",
]
[[package]]
name = "pdfs-vfs"
version = "3.10.0"
dependencies = [
"libc",
"parking_lot 0.13.0",
"pdfs-core",
"pdfs-drive",
"pdfs-store",
"proton-drive-rs",
"tracing",
]
[[package]]
name = "pem-rfc7468"
version = "0.7.0"
+2 -1
View File
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["crates/pdfs-core", "crates/pdfs-store", "crates/pdfs-drive", "crates/pdfs-sync", "crates/pdfs-fuse", "crates/pdfs-daemon", "crates/pdfs-cli", "crates/pdfs-gui"]
members = ["crates/pdfs-core", "crates/pdfs-store", "crates/pdfs-drive", "crates/pdfs-sync", "crates/pdfs-vfs", "crates/pdfs-fuse", "crates/pdfs-daemon", "crates/pdfs-cli", "crates/pdfs-gui"]
[workspace.package]
version = "3.10.0"
@@ -27,6 +27,7 @@ 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-vfs = { path = "crates/pdfs-vfs" }
pdfs-fuse = { path = "crates/pdfs-fuse" }
pdfs-daemon = { path = "crates/pdfs-daemon" }
+8
View File
@@ -323,6 +323,14 @@ pub(super) fn cmd_diagnostics() -> Result<()> {
);
}
}
if !d.jobs.is_empty() {
let jobs: Vec<String> = d
.jobs
.iter()
.map(|job| format!("{} ({})", job.name, human_secs(job.age_secs)))
.collect();
println!("jobs: {}", jobs.join(", "));
}
if let Some(sync) = &d.sync {
println!("sync engine: {}", sync_engine_line(sync));
for trace in &sync.traces {
+6 -1
View File
@@ -2378,9 +2378,14 @@ pub struct Diagnostics {
/// still running. Empty from a daemon that predates the field.
#[serde(default)]
pub services: Vec<ServiceState>,
/// The one-shot jobs running now, such as a cache check, an import or a
/// folder pin, oldest first. Empty from a daemon that predates the field.
#[serde(default)]
pub jobs: Vec<ServiceState>,
}
/// One long-lived daemon thread, in [`Diagnostics::services`].
/// One long-lived daemon thread, in [`Diagnostics::services`], or one
/// one-shot job, in [`Diagnostics::jobs`].
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct ServiceState {
/// The thread's name, such as `pdfs-sync`.
+497 -19
View File
@@ -12,9 +12,23 @@
//! 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.
//!
//! A service can also be an async task on the mount's runtime
//! ([`Services::spawn_task`]), such as the loops that follow Drive's event
//! streams. A stop aborts it at its next `.await` and waits for it to go, up
//! to the same deadline. Such a task used to run until the runtime went
//! away, which on a stop is when the process exits.
//!
//! Work a request starts and does not wait for runs as a one-shot job
//! ([`ServiceBoard::spawn_job`] on a thread, [`ServiceBoard::spawn_task_job`]
//! on the runtime): listed on the board while it runs. A stop closes the
//! board to new jobs, aborts the async ones and joins the rest up to the same
//! deadline as the services. A job used to be left running, and one still
//! waiting on Drive when the runtime went away panicked on its next timer.
use std::future::Future;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
@@ -25,6 +39,32 @@ 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>;
/// A long-lived loop a mount runs on a thread of its own.
///
/// Each one says in one place what it is called, how a stop reaches it and
/// whether the mount can do without it, next to the loop itself. The mount
/// starts a list of them with [`Services::start`] instead of spelling out
/// each spawn, wake and failure path.
pub trait Service: Send + 'static {
/// The thread's name, such as `pdfs-sync`.
fn name(&self) -> String;
/// Whether a mount fails when this cannot start. An optional service is
/// logged and skipped: the mount works without it, only less well.
fn required(&self) -> bool {
true
}
/// The call that wakes the loop on a stop, for one that blocks where the
/// [`Shutdown`] signal does not reach: a condvar, a channel, an `accept`.
fn wake(&self) -> Option<Wake> {
None
}
/// Run the loop until the [`Shutdown`] signal or the wake ends it.
fn run(self: Box<Self>);
}
/// Whether one service thread is still running, for diagnostics.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServiceHealth {
@@ -35,10 +75,40 @@ pub struct ServiceHealth {
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.
/// The live view of the service threads, which were started and which are
/// still running, and of the one-shot jobs running now. Cheap to clone and to
/// read; never blocks on a service or a job.
#[derive(Clone, Default)]
pub struct ServiceBoard(Arc<Mutex<Vec<Entry>>>);
pub struct ServiceBoard(Arc<Board>);
#[derive(Default)]
struct Board {
services: Mutex<Vec<Entry>>,
jobs: Mutex<Vec<Job>>,
next_job: AtomicU64,
/// The running jobs' handles, and whether a stop closed the board. One
/// lock for both, so a job is either refused or joined by the stop.
handles: Mutex<JobHandles>,
}
#[derive(Default)]
struct JobHandles {
closed: bool,
running: Vec<Handle>,
}
impl JobHandles {
/// Keep `handle`, dropping the handles of jobs that already ended.
fn keep(&mut self, handle: Handle) {
self.running.retain(|handle| !handle.is_finished());
self.running.push(handle);
}
}
/// Why a job did not start: the board's mount is stopping.
fn closed_error() -> std::io::Error {
std::io::Error::other("the mount is stopping; no new jobs start")
}
struct Entry {
name: String,
@@ -46,10 +116,17 @@ struct Entry {
running: Arc<AtomicBool>,
}
struct Job {
id: u64,
name: String,
started: Instant,
}
impl ServiceBoard {
/// Every service thread started so far, in start order.
pub fn health(&self) -> Vec<ServiceHealth> {
self.0
.services
.lock()
.iter()
.map(|entry| ServiceHealth {
@@ -60,9 +137,107 @@ impl ServiceBoard {
.collect()
}
/// The one-shot jobs running now, oldest first. A job leaves the list
/// when its thread ends.
pub fn jobs(&self) -> Vec<ServiceHealth> {
self.0
.jobs
.lock()
.iter()
.map(|job| ServiceHealth {
name: job.name.clone(),
running: true,
age: job.started.elapsed(),
})
.collect()
}
/// Start `run` on a thread named `name`, as a one-shot job: a request's
/// work that outlasts the request, such as a cache check, an import or a
/// folder pin. It shows in [`jobs`](Self::jobs) until it ends, by return
/// or by panic.
///
/// A stop joins it up to its deadline; a job that may run long checks the
/// [`Shutdown`] signal. Once a stop has begun, no job starts and this
/// returns an error.
pub fn spawn_job<F>(&self, name: &str, run: F) -> std::io::Result<()>
where
F: FnOnce() + Send + 'static,
{
let mut handles = self.0.handles.lock();
if handles.closed {
return Err(closed_error());
}
let guard = self.add_job(name);
let handle = std::thread::Builder::new()
.name(name.to_owned())
.spawn(move || {
let _guard = guard;
run();
})?;
// On an error the closure, and the guard in it, are already dropped,
// so the job is off the list.
handles.keep(Handle::Thread(handle));
Ok(())
}
/// Start `task` on `rt` as a one-shot job, like [`spawn_job`](Self::spawn_job)
/// for work that is async: a refresh a listing starts and does not wait
/// for. It shows in [`jobs`](Self::jobs) until it ends, by return, panic
/// or abort. A stop aborts it at its next `.await`; once a stop has begun,
/// `task` is dropped without running.
pub fn spawn_task_job<F>(&self, rt: &tokio::runtime::Handle, name: &str, task: F)
where
F: Future<Output = ()> + Send + 'static,
{
let mut handles = self.0.handles.lock();
if handles.closed {
tracing::debug!(job = name, "not started: the mount is stopping");
return;
}
let guard = self.add_job(name);
let task = rt.spawn(async move {
let _guard = guard;
task.await;
});
handles.keep(Handle::Task {
name: name.to_owned(),
task,
});
}
/// Close the board to new jobs and abort the async ones. The thread jobs
/// still running are handed back for [`join`](Handle::join_until).
fn close(&self) -> Vec<Handle> {
let running = {
let mut handles = self.0.handles.lock();
handles.closed = true;
std::mem::take(&mut handles.running)
};
for handle in &running {
if let Handle::Task { task, .. } = handle {
task.abort();
}
}
running
}
fn add_job(&self, name: &str) -> JobGuard {
let id = self.0.next_job.fetch_add(1, Ordering::Relaxed);
self.0.jobs.lock().push(Job {
id,
name: name.to_owned(),
started: Instant::now(),
});
JobGuard {
board: self.0.clone(),
id,
}
}
fn add(&self, name: &str) -> Arc<AtomicBool> {
let running = Arc::new(AtomicBool::new(true));
self.0.lock().push(Entry {
self.0.services.lock().push(Entry {
name: name.to_owned(),
started: Instant::now(),
running: running.clone(),
@@ -71,6 +246,18 @@ impl ServiceBoard {
}
}
/// Takes a job off the board when its thread ends, by return or by panic.
struct JobGuard {
board: Arc<Board>,
id: u64,
}
impl Drop for JobGuard {
fn drop(&mut self) {
self.board.jobs.lock().retain(|job| job.id != self.id);
}
}
/// Clears a service's `running` flag when its thread ends, by return or by panic.
struct Running(Arc<AtomicBool>);
@@ -80,15 +267,46 @@ impl Drop for Running {
}
}
struct Service {
handle: JoinHandle<()>,
struct Started {
handle: Handle,
wake: Option<Wake>,
}
/// A service is a thread, or an async task on the mount's runtime.
enum Handle {
Thread(JoinHandle<()>),
Task {
name: String,
task: tokio::task::JoinHandle<()>,
},
}
impl Handle {
fn is_finished(&self) -> bool {
match self {
Handle::Thread(handle) => handle.is_finished(),
Handle::Task { task, .. } => task.is_finished(),
}
}
/// Wait for the thread or task to end, up to `deadline`, and name it if
/// it is still running then.
fn join_until(self, deadline: Instant) -> Option<String> {
while !self.is_finished() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
match self {
Handle::Thread(handle) => join_until([handle], deadline).pop(),
Handle::Task { name, task } if !task.is_finished() => Some(name),
Handle::Task { .. } => None,
}
}
}
/// The service threads one mount started, and how to stop them.
pub struct Services {
board: ServiceBoard,
started: Vec<Service>,
started: Vec<Started>,
}
impl Services {
@@ -117,7 +335,10 @@ impl Services {
});
match spawned {
Ok(handle) => {
self.started.push(Service { handle, wake });
self.started.push(Started {
handle: Handle::Thread(handle),
wake,
});
Ok(())
}
Err(error) => {
@@ -128,31 +349,77 @@ impl Services {
}
}
/// How many threads were started.
/// Start `service` on a thread of its own. A required service that cannot
/// start returns the error; an optional one is logged and skipped.
pub fn start(&mut self, service: Box<dyn Service>) -> std::io::Result<()> {
let name = service.name();
let required = service.required();
let wake = service.wake();
match self.spawn(&name, wake, move || service.run()) {
Err(error) if !required => {
tracing::warn!(service = name, %error, "optional service did not start");
Ok(())
}
started => started,
}
}
/// Start `task` on `rt` as a service named `name`. [`stop`](Self::stop)
/// aborts it, so it ends at its next `.await`; a task does not need to
/// watch the [`Shutdown`] signal itself. Code between two `.await`s runs
/// to its end, so a write it makes there is not cut in half.
pub fn spawn_task<F>(&mut self, rt: &tokio::runtime::Handle, name: &str, task: F)
where
F: Future<Output = ()> + Send + 'static,
{
let guard = Running(self.board.add(name));
let task = rt.spawn(async move {
let _guard = guard;
task.await;
});
self.started.push(Started {
handle: Handle::Task {
name: name.to_owned(),
task,
},
wake: None,
});
}
/// How many services were started.
pub fn len(&self) -> usize {
self.started.len()
}
/// Whether no thread was started.
/// Whether no service 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.
/// Stop every service and every job: signal `shutdown`, close the board
/// to new jobs, wake each thread and abort each task in reverse start
/// order. Then join the jobs, which are the services' clients, and the
/// services in the same reverse order, all until `deadline`. Returns the
/// names of the services and jobs 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();
let jobs = self.board.close();
for service in self.started.iter().rev() {
if let Some(wake) = &service.wake {
wake();
}
if let Handle::Task { task, .. } = &service.handle {
task.abort();
}
}
join_until(
self.started.into_iter().rev().map(|service| service.handle),
deadline,
)
let jobs = jobs.into_iter().filter_map(|job| job.join_until(deadline));
let services = self
.started
.into_iter()
.rev()
.filter_map(|service| service.handle.join_until(deadline));
jobs.chain(services).collect()
}
}
@@ -260,4 +527,215 @@ mod tests {
assert!(left.is_empty());
assert!(!board.health()[0].running);
}
#[test]
fn a_job_shows_while_it_runs_and_leaves_when_it_ends() {
let board = ServiceBoard::default();
let (release, wait) = mpsc::channel::<()>();
let (done_tx, done_rx) = mpsc::channel::<()>();
board
.spawn_job("pdfs-test-job", move || {
let _ = wait.recv();
let _done = done_tx;
})
.unwrap();
let jobs = board.jobs();
assert_eq!(jobs.len(), 1);
assert_eq!(jobs[0].name, "pdfs-test-job");
assert!(board.health().is_empty(), "a job is not a service");
release.send(()).unwrap();
let _ = done_rx.recv_timeout(Duration::from_secs(5));
let deadline = Instant::now() + Duration::from_secs(5);
while !board.jobs().is_empty() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
}
assert!(board.jobs().is_empty());
}
#[test]
fn a_stop_aborts_a_task_and_shows_it_ended() {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.build()
.unwrap();
let board = ServiceBoard::default();
let mut services = Services::new(board.clone());
// Never ends on its own and never looks at the shutdown signal.
services.spawn_task(rt.handle(), "poller", async {
loop {
tokio::time::sleep(Duration::from_millis(5)).await;
}
});
assert_eq!(services.len(), 1);
assert!(board.health()[0].running);
let left = services.stop(
&Shutdown::default(),
Instant::now() + Duration::from_secs(5),
);
assert!(left.is_empty(), "still running: {left:?}");
assert!(!board.health()[0].running);
}
#[test]
fn a_task_stuck_between_awaits_is_named_at_the_deadline() {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.build()
.unwrap();
let mut services = Services::new(ServiceBoard::default());
let (release, wait) = mpsc::channel::<()>();
let (started_tx, started_rx) = mpsc::channel::<()>();
// Blocks its worker thread, so an abort cannot reach it until it yields.
services.spawn_task(rt.handle(), "blocking", async move {
let _ = started_tx.send(());
let _ = wait.recv();
});
started_rx.recv_timeout(Duration::from_secs(5)).unwrap();
let left = services.stop(
&Shutdown::default(),
Instant::now() + Duration::from_millis(100),
);
assert_eq!(left, ["blocking"]);
drop(release);
}
#[test]
fn a_task_job_shows_while_it_runs_and_leaves_when_it_ends() {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.build()
.unwrap();
let board = ServiceBoard::default();
let (release, wait) = tokio::sync::oneshot::channel::<()>();
board.spawn_task_job(rt.handle(), "pdfs-test-refresh", async move {
let _ = wait.await;
});
let jobs = board.jobs();
assert_eq!(jobs.len(), 1);
assert_eq!(jobs[0].name, "pdfs-test-refresh");
release.send(()).unwrap();
let deadline = Instant::now() + Duration::from_secs(5);
while !board.jobs().is_empty() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
}
assert!(board.jobs().is_empty());
}
#[test]
fn a_job_that_panics_leaves_the_list() {
let board = ServiceBoard::default();
board.spawn_job("doomed-job", || panic!("boom")).unwrap();
let deadline = Instant::now() + Duration::from_secs(5);
while !board.jobs().is_empty() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
}
assert!(board.jobs().is_empty());
}
#[test]
fn a_stop_joins_the_running_jobs_and_names_a_stuck_one() {
let board = ServiceBoard::default();
let shutdown = Arc::new(Shutdown::default());
let services = Services::new(board.clone());
let signalled = shutdown.clone();
board
.spawn_job("pdfs-test-polite", move || {
while signalled.sleep(Duration::from_secs(3600)) {}
})
.unwrap();
let (_hold, stuck) = mpsc::channel::<()>();
board
.spawn_job("pdfs-test-stuck", move || {
let _ = stuck.recv();
})
.unwrap();
let left = services.stop(&shutdown, Instant::now() + Duration::from_millis(300));
assert_eq!(left, ["pdfs-test-stuck"]);
let jobs: Vec<_> = board.jobs().into_iter().map(|job| job.name).collect();
assert_eq!(jobs, ["pdfs-test-stuck"]);
}
#[test]
fn a_stop_aborts_a_task_job_and_refuses_new_jobs() {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.build()
.unwrap();
let board = ServiceBoard::default();
let services = Services::new(board.clone());
board.spawn_task_job(rt.handle(), "pdfs-test-poller", async {
loop {
tokio::time::sleep(Duration::from_millis(5)).await;
}
});
let left = services.stop(
&Shutdown::default(),
Instant::now() + Duration::from_secs(5),
);
assert!(left.is_empty(), "still running: {left:?}");
assert!(board.jobs().is_empty());
assert!(board.spawn_job("pdfs-test-late", || {}).is_err());
board.spawn_task_job(rt.handle(), "pdfs-test-late", async {});
assert!(board.jobs().is_empty(), "a job started after the stop");
}
struct Waiter {
name: &'static str,
rx: mpsc::Receiver<()>,
tx: mpsc::Sender<()>,
}
impl Service for Waiter {
fn name(&self) -> String {
self.name.to_owned()
}
fn wake(&self) -> Option<Wake> {
let tx = self.tx.clone();
Some(Box::new(move || {
let _ = tx.send(());
}))
}
fn run(self: Box<Self>) {
let _ = self.rx.recv();
}
}
#[test]
fn a_started_service_is_woken_and_joined_by_a_stop() {
let board = ServiceBoard::default();
let mut services = Services::new(board.clone());
let (tx, rx) = mpsc::channel();
services
.start(Box::new(Waiter {
name: "pdfs-test-waiter",
rx,
tx,
}))
.unwrap();
assert_eq!(board.health()[0].name, "pdfs-test-waiter");
let left = services.stop(
&Shutdown::default(),
Instant::now() + Duration::from_secs(5),
);
assert!(left.is_empty(), "still running: {left:?}");
assert!(!board.health()[0].running);
}
}
+13
View File
@@ -599,6 +599,19 @@ pub fn is_network_error(e: &ProtonError) -> bool {
}
}
/// A node's plaintext size as far as its listing knows: the claimed size when
/// the revision carries one, else the size on storage. Zero for a folder.
pub fn node_size(node: &Node) -> u64 {
match &node.kind {
NodeKind::Folder => 0,
NodeKind::File {
claimed_size,
total_size_on_storage,
..
} => claimed_size.unwrap_or(*total_size_on_storage).max(0) as u64,
}
}
/// 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> {
+2
View File
@@ -13,6 +13,7 @@ description = "FUSE on-demand filesystem for Proton Drive"
pdfs-core.workspace = true
pdfs-drive.workspace = true
pdfs-sync.workspace = true
pdfs-vfs.workspace = true
pdfs-store.workspace = true
zip.workspace = true
sha1.workspace = true
@@ -41,6 +42,7 @@ notify = "8"
parking_lot.workspace = true
[dev-dependencies]
pdfs-vfs = { workspace = true, features = ["test-support"] }
pdfs-drive = { workspace = true, features = ["sim"] }
tracing-subscriber.workspace = true
tokio = { workspace = true, features = ["test-util"] }
+1 -1
View File
@@ -57,7 +57,7 @@ impl Core {
mountpoint: &Path,
) -> CoreResult<StoredSyncFolder> {
let _registration = super::devices::SYNC_ROOT_REGISTRATION.lock();
if !self.primary {
if !self.session.primary {
return Err(CoreError::invalid("attach must use My files"));
}
if remote.is_absolute()
+3 -3
View File
@@ -176,7 +176,7 @@ fn apply_event(core: &Core, event: &DriveEvent, dirty: &mut DirtyParents) -> pdf
// even for a trash, so an echo we no longer care about does not
// linger to suppress a later foreign change.
let echo = core.take_self_change(node_uid);
let ours = !*is_trashed && (echo || core.pending.lock().contains_key(node_uid));
let ours = !*is_trashed && (echo || core.writes.is_queued(node_uid));
if ours {
debug!(uid = %node_uid, "ignoring remote event for a node with a queued write");
}
@@ -568,7 +568,7 @@ pub(super) async fn run_event_sync(
/// Follow the Photos volume and commit changes with its durable event cursor.
pub(super) async fn run_photos_event_sync(core: Core) {
let photos = core.photos();
let photos = core.photos_api();
// The photos volume only exists once the user has used Photos at all, and
// the daemon may well start before the network does.
let scope = loop {
@@ -635,7 +635,7 @@ pub(super) async fn run_photos_event_sync(core: Core) {
}
}
if core.db.photos_need_work().unwrap_or(true) {
core.spawn_timeline_refresh();
core.photos().spawn_timeline_refresh();
}
core.next_poll(POLL_INTERVAL).await;
}
File diff suppressed because it is too large. Load diff
+455
View File
@@ -0,0 +1,455 @@
//! The control requests about Photos: the timeline, albums, thumbnails, the gallery, and Takeout imports and redating.
use super::*;
/// The requests [`answer`] serves, as a pattern, so the control socket's match
/// hands exactly these over and the compiler still checks that it covers every
/// request.
macro_rules! request {
() => {
::pdfs_core::control::Request::PhotosTimeline { .. }
| ::pdfs_core::control::Request::PhotoDuplicates
| ::pdfs_core::control::Request::PhotoSimilar
| ::pdfs_core::control::Request::PhotoPlaces
| ::pdfs_core::control::Request::PlacePhotos { .. }
| ::pdfs_core::control::Request::PlaceLocations { .. }
| ::pdfs_core::control::Request::PhotosOnThisDay { .. }
| ::pdfs_core::control::Request::PhotoGroup { .. }
| ::pdfs_core::control::Request::SetPhotoFavorite { .. }
| ::pdfs_core::control::Request::PhotoAlbums
| ::pdfs_core::control::Request::AlbumPhotos { .. }
| ::pdfs_core::control::Request::CreateAlbum { .. }
| ::pdfs_core::control::Request::RenameAlbum { .. }
| ::pdfs_core::control::Request::DeleteAlbum { .. }
| ::pdfs_core::control::Request::AddToAlbum { .. }
| ::pdfs_core::control::Request::RemoveFromAlbum { .. }
| ::pdfs_core::control::Request::PhotoPresence { .. }
| ::pdfs_core::control::Request::PhotoMonths { .. }
| ::pdfs_core::control::Request::PhotoThumbs { .. }
| ::pdfs_core::control::Request::FileThumbs { .. }
| ::pdfs_core::control::Request::ReserveFileThumbGeneration
| ::pdfs_core::control::Request::CancelFileThumbs { .. }
| ::pdfs_core::control::Request::StartThumbnailBuild { .. }
| ::pdfs_core::control::Request::CancelThumbnailBuild
| ::pdfs_core::control::Request::ThumbnailBuildStatus
| ::pdfs_core::control::Request::PhotosRefreshStatus
| ::pdfs_core::control::Request::OpenPhoto { .. }
| ::pdfs_core::control::Request::DriveGallery { .. }
| ::pdfs_core::control::Request::OpenGalleryVideo { .. }
| ::pdfs_core::control::Request::OpenGalleryImage { .. }
| ::pdfs_core::control::Request::CloseGalleryVideo { .. }
| ::pdfs_core::control::Request::GalleryThumbnail { .. }
| ::pdfs_core::control::Request::ImportTakeout { .. }
| ::pdfs_core::control::Request::ImportStatus
| ::pdfs_core::control::Request::ResumeImport
| ::pdfs_core::control::Request::CancelImport
| ::pdfs_core::control::Request::RedatePhotos { .. }
| ::pdfs_core::control::Request::RedateStatus
| ::pdfs_core::control::Request::CancelRedate
| ::pdfs_core::control::Request::UploadPhoto { .. }
};
}
pub(super) use request;
/// Answer a request that [`request!`] matches.
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
let Ask {
core,
mountpoint,
stream,
visibility,
excluded,
..
} = *ask;
match request {
CtlRequest::PhotosTimeline {
offset,
limit,
kind,
range,
favorites,
not_in_album,
} => match core.photos().photos_timeline(
offset,
clamp_limit(limit),
kind,
range,
favorites,
not_in_album,
excluded,
) {
Ok(Some(items)) => CtlResponse::Photos {
available: true,
items,
counts: core.db.photos_counts_visible(excluded).ok(),
},
Ok(None) => CtlResponse::Photos {
available: false,
items: Vec::new(),
counts: None,
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::PhotoDuplicates => match core.photos().photo_duplicates() {
Ok(sets) => CtlResponse::PhotoDuplicates { sets },
Err(e) => CtlResponse::error(e),
},
CtlRequest::PhotoSimilar => match core.photos().photo_similar() {
Ok((sets, hashing, uncompared)) => CtlResponse::PhotoSimilar {
sets,
hashing,
uncompared,
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::PhotoPlaces => match core.photos().photo_places(excluded) {
Ok(items) => CtlResponse::Places {
items,
mapping: core.photos().timeline_progress(),
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::PlacePhotos { id, offset, limit } => {
match core
.photos()
.place_photos(id, offset, clamp_limit(limit), excluded)
{
Ok(items) => CtlResponse::Photos {
available: true,
items,
counts: None,
},
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::PlaceLocations { id } => match core.photos().place_locations(id) {
Ok(items) => CtlResponse::PhotoLocations { items },
Err(e) => CtlResponse::error(e),
},
CtlRequest::PhotosOnThisDay { limit } => {
match core
.photos()
.photos_on_this_day(clamp_limit(limit), excluded)
{
Ok(items) => CtlResponse::Photos {
available: true,
items,
counts: None,
},
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::PhotoGroup { uid } => match core.photos().photo_group(&uid) {
Ok(items) => CtlResponse::Photos {
available: true,
items,
counts: None,
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::SetPhotoFavorite { uid, favorite } => match parse_uid(&uid) {
Some(node_uid) => match core.photos().set_photo_favorite(&node_uid, favorite) {
Ok(()) => CtlResponse::Ok {
message: if favorite {
"added to favorites".to_string()
} else {
"removed from favorites".to_string()
},
},
Err(e) => CtlResponse::error(e),
},
None => CtlResponse::error(CoreError::invalid(format!("invalid uid: {uid}"))),
},
CtlRequest::PhotoAlbums => match core.photos().albums() {
Ok(Some(items)) => CtlResponse::Albums {
available: true,
items,
},
Ok(None) => CtlResponse::Albums {
available: false,
items: Vec::new(),
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::AlbumPhotos { uid, offset, limit } => match parse_uid(&uid) {
// An album page is a timeline page as far as the front-end is
// concerned, so it comes back in the same reply — with `counts`
// unset, which describe the whole timeline rather than this album.
Some(album) => match visibility.permits(&uid).and_then(|()| {
core.photos()
.album_photos(&album, offset, clamp_limit(limit), excluded)
}) {
Ok(items) => CtlResponse::Photos {
available: true,
items,
counts: None,
},
Err(e) => CtlResponse::error(e),
},
None => CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}"))),
},
CtlRequest::CreateAlbum { name } => match core.photos().create_album(&name) {
Ok(uid) => CtlResponse::AlbumCreated { uid },
Err(e) => CtlResponse::error(e),
},
CtlRequest::RenameAlbum { uid, name } => match parse_uid(&uid) {
Some(album) => match core.photos().rename_album(&album, &name) {
Ok(()) => CtlResponse::Ok {
message: format!("renamed album to {name}"),
},
Err(e) => CtlResponse::error(e),
},
None => CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}"))),
},
CtlRequest::DeleteAlbum { uid, delete_photos } => match parse_uid(&uid) {
Some(album) => match core.photos().delete_album(&album, delete_photos) {
Ok(()) => CtlResponse::Ok {
message: "album deleted".to_string(),
},
Err(e) => CtlResponse::error(e),
},
None => CtlResponse::error(CoreError::invalid(format!("bad album uid: {uid}"))),
},
CtlRequest::AddToAlbum { uid, photos } => album_change(&uid, &photos, |album, photos| {
core.photos().add_to_album(album, photos)
}),
CtlRequest::RemoveFromAlbum { uid, photos } => {
album_change(&uid, &photos, |album, photos| {
core.photos().remove_from_album(album, photos)
})
}
CtlRequest::PhotoPresence { uid, album } => match core.cached_gallery_visibility() {
Ok(visibility)
if visibility.media.contains(&uid)
|| album
.as_ref()
.is_some_and(|uid| visibility.albums.contains(uid)) =>
{
CtlResponse::PhotoPresence { present: false }
}
Ok(_) => match core.db.photos_contains(&uid, album.as_deref()) {
Ok(present) => CtlResponse::PhotoPresence { present },
Err(error) => CtlResponse::error(error.into()),
},
Err(error) => CtlResponse::error(error),
},
CtlRequest::PhotoMonths { .. } => unreachable!("handled before visibility requests"),
CtlRequest::PhotoThumbs { uids } => {
let parsed: Vec<NodeUid> = uids
.iter()
.filter(|uid| !visibility.media.contains(*uid))
.filter_map(|u| parse_uid(u))
.collect();
CtlResponse::Thumbs {
items: core.photos().photo_thumbs(&parsed),
}
}
CtlRequest::FileThumbs { items, generation } => {
match core.photos().file_thumbs(&items, generation) {
Some(items) => CtlResponse::Thumbs { items },
None => CtlResponse::FileThumbsStale,
}
}
CtlRequest::ReserveFileThumbGeneration => CtlResponse::FileThumbGeneration {
generation: core.photos().reserve_file_thumb_generation(),
},
CtlRequest::CancelFileThumbs { generation } => {
core.photos().cancel_file_thumbs(generation);
CtlResponse::Ok {
message: "thumbnail requests cancelled".to_string(),
}
}
CtlRequest::StartThumbnailBuild { path } => match rel_to_mount(mountpoint, &path) {
Ok(rel) => match core.photos().start_thumbnail_build(rel) {
Ok(status) => CtlResponse::ThumbnailBuild { status },
Err(error) => CtlResponse::error(error),
},
Err(error) => CtlResponse::error(error),
},
CtlRequest::CancelThumbnailBuild => CtlResponse::ThumbnailBuild {
status: core.photos().cancel_thumbnail_build(),
},
CtlRequest::ThumbnailBuildStatus => CtlResponse::ThumbnailBuild {
status: core.photos().thumbnail_build_status(),
},
CtlRequest::PhotosRefreshStatus => CtlResponse::PhotosRefresh {
running: core.photos().timeline_refreshing(),
},
CtlRequest::OpenPhoto { uid } => match parse_uid(&uid) {
Some(u) => match visibility
.permits(&uid)
.and_then(|()| core.photos().open_photo(&u))
{
Ok(p) => CtlResponse::FilePath {
path: p.display().to_string(),
},
Err(e) => CtlResponse::error(e),
},
None => CtlResponse::error(CoreError::invalid(format!("bad uid: {uid}"))),
},
CtlRequest::DriveGallery {
action: pdfs_core::control::GalleryAction::AuthenticateHidden,
} => core
.authenticate_hidden_gallery(stream)
.unwrap_or_else(CtlResponse::error),
CtlRequest::DriveGallery { action } => core
.drive_gallery(action)
.unwrap_or_else(CtlResponse::error),
CtlRequest::OpenGalleryVideo { uid, private } => core
.open_gallery_video(&uid, private)
.unwrap_or_else(CtlResponse::error),
CtlRequest::OpenGalleryImage { uid, private: true } => {
core.gallery_image(&uid).unwrap_or_else(CtlResponse::error)
}
CtlRequest::OpenGalleryImage {
uid,
private: false,
} => match visibility
.permits(&uid)
.and_then(|()| core.sharing.open_shared_file(&uid))
{
Ok(path) => CtlResponse::FilePath {
path: path.display().to_string(),
},
Err(error) => CtlResponse::error(error),
},
CtlRequest::CloseGalleryVideo { token } => core
.close_gallery_video(&token)
.unwrap_or_else(CtlResponse::error),
CtlRequest::GalleryThumbnail { uid, private } => core
.gallery_thumbnail(&uid, private)
.unwrap_or_else(CtlResponse::error),
CtlRequest::ImportTakeout { archives, dry_run } => {
if archives.is_empty() {
CtlResponse::error(CoreError::invalid("no Takeout archives given"))
} else {
let paths = archives.into_iter().map(PathBuf::from).collect();
start_takeout_import(core, paths, dry_run)
}
}
CtlRequest::ImportStatus => {
let report = crate::photos::takeout::import_status();
CtlResponse::ImportStatus {
running: report.running,
summary: report.summary,
progress: report.progress,
resumable: report.resumable,
}
}
CtlRequest::ResumeImport => match crate::photos::takeout::resumable_archives() {
None => CtlResponse::error(CoreError::not_found("there is no import to resume")),
Some(paths) => start_takeout_import(core, paths, false),
},
CtlRequest::CancelImport => {
if crate::photos::takeout::cancel_import() {
CtlResponse::Ok {
message: "stopping the import".to_string(),
}
} else {
CtlResponse::error(CoreError::invalid("no import is running"))
}
}
CtlRequest::RedatePhotos {
dry_run,
limit,
range,
} => match core.photos().spawn_redate(dry_run, limit, range) {
Ok(()) => CtlResponse::Ok {
message: if dry_run {
"checking photo dates".to_string()
} else {
"fixing photo dates".to_string()
},
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::RedateStatus => {
let (running, summary) = crate::photos::redate::redate_status();
CtlResponse::RedateStatus { running, summary }
}
CtlRequest::CancelRedate => {
if crate::photos::redate::cancel_redate() {
CtlResponse::Ok {
message: "stopping the re-date".to_string(),
}
} else {
CtlResponse::error(CoreError::invalid("no photo re-date is running"))
}
}
CtlRequest::UploadPhoto {
name,
media_type,
source_path,
capture_time,
} => {
// Streamed off disk rather than carried over the socket: see the note
// on `Request::UploadPhoto`. The length comes from the same handle the
// bytes do, so a file changing size under us cannot make the two
// disagree.
match std::fs::File::open(&source_path).and_then(|f| f.metadata().map(|m| (f, m.len())))
{
Err(e) => CtlResponse::error(CoreError::invalid(format!(
"cannot read {source_path}: {e}"
))),
Ok((file, len)) => {
let photos = core.photos_api();
// Unless the caller knows better: the photo's own EXIF,
// then the file's modification time, which a copy resets.
let capture_time = capture_time.or_else(|| {
let path = Path::new(&source_path);
pdfs_core::exiftime::capture_time_of(path).or_else(|| {
let modified =
std::fs::metadata(path).and_then(|m| m.modified()).ok()?;
let since = modified.duration_since(std::time::UNIX_EPOCH).ok()?;
Some(since.as_secs() as i64)
})
});
let metadata = proton_drive_rs::PhotoUploadMetadata {
capture_time,
last_modification_time: capture_time
.and_then(pdfs_core::timestamp::modification_time),
..Default::default()
};
let thumbnails = core
.photos()
.upload_thumbnails(Path::new(&source_path), &name);
let guard =
core.transfers
.begin(name.clone(), "", TransferDirection::Upload, len);
let reader = CountingReader::new(std::io::BufReader::new(file), &guard);
match core.rt.block_on(photos.upload_photo_from(
&name,
&media_type,
reader,
len as i64,
thumbnails,
metadata,
false,
)) {
Ok(uid) => {
// The photo we just uploaded belongs at the head of the
// timeline, and the GUI reloads the gallery the moment this
// reply lands — so refresh now rather than leaving it to a
// background pass that would land just after that reload.
core.invalidate_photos();
if let Err(e) = core.photos().refresh_timeline_joined() {
warn!(error = %e, "timeline refresh after upload failed");
}
CtlResponse::Ok {
message: format!("uploaded photo with uid {uid}"),
}
}
Err(e) => {
// The reply goes to the app's toast only; without
// this the journal shows a failure and no reason.
warn!(error = %e, "photo upload failed");
CtlResponse::error(CoreError::from_api(&e, "upload photo failed"))
}
}
}
}
}
// `control` only hands over what `request!` matches.
_ => CtlResponse::error(CoreError::internal("not a photos request".to_string())),
}
}
+122
View File
@@ -0,0 +1,122 @@
//! The control requests about a file's earlier revisions: listing, restoring, deleting and saving one as a new file, by path or by uid.
use super::*;
/// The requests [`answer`] serves, as a pattern, so the control socket's match
/// hands exactly these over and the compiler still checks that it covers every
/// request.
macro_rules! request {
() => {
::pdfs_core::control::Request::ListRevisions { .. }
| ::pdfs_core::control::Request::ListRevisionsByUid { .. }
| ::pdfs_core::control::Request::RestoreRevision { .. }
| ::pdfs_core::control::Request::RestoreRevisionByUid { .. }
| ::pdfs_core::control::Request::DeleteRevision { .. }
| ::pdfs_core::control::Request::DeleteRevisionByUid { .. }
| ::pdfs_core::control::Request::SaveRevisionAs { .. }
| ::pdfs_core::control::Request::SaveRevisionAsByUid { .. }
};
}
pub(super) use request;
/// The file a request is about, and how the activity feed names it: the file
/// name under the mount, or the uid.
struct Target {
uid: NodeUid,
name: String,
}
impl Target {
fn path(core: &Core, rel: &Path) -> CoreResult<Self> {
let (_ino, uid) = core.resolve(rel)?;
let name = rel
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| uid.to_string());
Ok(Self { uid, name })
}
fn uid(core: &Core, uid: &str) -> CoreResult<Self> {
let uid = core.resolve_anywhere(uid)?;
let name = uid.to_string();
Ok(Self { uid, name })
}
}
/// Answer a request that [`request!`] matches.
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
let Ask {
core, mountpoint, ..
} = *ask;
let revisions = core.revisions();
let at = |path: &str| rel_to_mount(mountpoint, path);
let reply = |result: CoreResult<String>| match result {
Ok(message) => CtlResponse::Ok { message },
Err(e) => CtlResponse::error(e),
};
match request {
CtlRequest::ListRevisions { path } => {
match at(&path).and_then(|rel| Target::path(core, &rel)) {
Ok(file) => listed(revisions.list(&file.uid)),
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::ListRevisionsByUid { uid } => match Target::uid(core, &uid) {
Ok(file) => listed(revisions.list(&file.uid)),
Err(e) => CtlResponse::error(e),
},
CtlRequest::RestoreRevision { path, revision_id } => reply(at(&path).and_then(|rel| {
let file = Target::path(core, &rel)?;
revisions.restore(&file.uid, &revision_id, &file.name)?;
// The size and mtime a listing shows describe the revision that
// was active a moment ago.
core.invalidate_parent_listing(&rel);
Ok(format!("restoring version {revision_id} of {path}"))
})),
CtlRequest::RestoreRevisionByUid { uid, revision_id } => {
reply(Target::uid(core, &uid).and_then(|file| {
revisions.restore(&file.uid, &revision_id, &file.name)?;
Ok(format!("restoring version {revision_id}"))
}))
}
CtlRequest::DeleteRevision { path, revision_id } => reply(at(&path).and_then(|rel| {
let file = Target::path(core, &rel)?;
revisions.delete(&file.uid, &revision_id, &file.name)?;
Ok(format!("deleted version {revision_id} of {path}"))
})),
CtlRequest::DeleteRevisionByUid { uid, revision_id } => {
reply(Target::uid(core, &uid).and_then(|file| {
revisions.delete(&file.uid, &revision_id, &file.name)?;
Ok(format!("deleted version {revision_id}"))
}))
}
CtlRequest::SaveRevisionAs {
path,
revision_id,
dest,
} => reply(at(&path).and_then(|rel| {
let file = Target::path(core, &rel)?;
let written =
revisions.save_as(&file.uid, &revision_id, &file.name, Path::new(&dest))?;
Ok(format!("wrote {} to {dest}", human_bytes(written)))
})),
CtlRequest::SaveRevisionAsByUid {
uid,
revision_id,
dest,
} => reply(Target::uid(core, &uid).and_then(|file| {
let written =
revisions.save_as(&file.uid, &revision_id, &file.name, Path::new(&dest))?;
Ok(format!("wrote {} to {dest}", human_bytes(written)))
})),
// `control` only hands over what `request!` matches.
_ => CtlResponse::error(CoreError::internal("not a revisions request".to_string())),
}
}
fn listed(result: CoreResult<Vec<pdfs_core::control::RevisionInfo>>) -> CtlResponse {
match result {
Ok(items) => CtlResponse::Revisions { items },
Err(e) => CtlResponse::error(e),
}
}
+371
View File
@@ -0,0 +1,371 @@
//! The control requests about sharing: who a node is shared with, its public
//! link, what others share with this account, invitations and saved links.
//!
//! Most of them come in two forms, one naming the node by its path under the
//! mount and one by its uid. Both are resolved to a uid here, once, and the
//! [`Sharing`](crate::sharing::Sharing) service is only ever asked about a
//! resolved node.
use std::path::Path;
use pdfs_core::CoreResult;
use pdfs_core::control::{ActivityKind, Request as CtlRequest, Response as CtlResponse};
use proton_drive_rs::proton_sdk::ids::NodeUid;
use super::rel_to_mount;
use crate::Core;
use crate::sharing::StopSharingOutcome;
/// The requests [`answer`] serves, as a pattern, so the control socket's
/// match hands exactly these over and the compiler still checks that it covers
/// every request.
macro_rules! request {
() => {
::pdfs_core::control::Request::ShareNode { .. }
| ::pdfs_core::control::Request::ShareNodeByUid { .. }
| ::pdfs_core::control::Request::ListShare { .. }
| ::pdfs_core::control::Request::ListShareByUid { .. }
| ::pdfs_core::control::Request::UpdateShareRole { .. }
| ::pdfs_core::control::Request::UpdateShareRoleByUid { .. }
| ::pdfs_core::control::Request::RemoveShareEntry { .. }
| ::pdfs_core::control::Request::RemoveShareEntryByUid { .. }
| ::pdfs_core::control::Request::CreatePublicLink { .. }
| ::pdfs_core::control::Request::CreatePublicLinkByUid { .. }
| ::pdfs_core::control::Request::UpdatePublicLink { .. }
| ::pdfs_core::control::Request::UpdatePublicLinkByUid { .. }
| ::pdfs_core::control::Request::RemovePublicLink { .. }
| ::pdfs_core::control::Request::RemovePublicLinkByUid { .. }
| ::pdfs_core::control::Request::StopSharing { .. }
| ::pdfs_core::control::Request::StopSharingByUid { .. }
| ::pdfs_core::control::Request::ListSharedWithMe
| ::pdfs_core::control::Request::ListSharedFolder { .. }
| ::pdfs_core::control::Request::OpenSharedFile { .. }
| ::pdfs_core::control::Request::LeaveShared { .. }
| ::pdfs_core::control::Request::ListInvitations
| ::pdfs_core::control::Request::AcceptInvitation { .. }
| ::pdfs_core::control::Request::RejectInvitation { .. }
| ::pdfs_core::control::Request::ListBookmarks
| ::pdfs_core::control::Request::CreateBookmark { .. }
| ::pdfs_core::control::Request::DeleteBookmark { .. }
| ::pdfs_core::control::Request::ListSharedByMe
};
}
pub(super) use request;
/// The node a request is about, and how the activity feed names it: the path
/// the user gave, or the uid.
struct Target {
label: String,
/// The node, or why it could not be resolved. A failure is reported
/// through the request's own reply, so a share that fails here is logged
/// as a failed share, as it was before the split.
node: CoreResult<NodeUid>,
}
impl Target {
/// A node named by its path. A path outside the mount fails the request
/// before it starts, without an activity entry.
fn path(core: &Core, mountpoint: &Path, path: String) -> CoreResult<Self> {
let rel = rel_to_mount(mountpoint, &path)?;
Ok(Self {
node: core.resolve(&rel).map(|(_ino, uid)| uid),
label: path,
})
}
/// A node named by its uid, which one of this daemon's locations, or the
/// Photos timeline, must show to be this account's.
fn uid(core: &Core, uid: String) -> Self {
Self {
node: core.resolve_shareable(&uid),
label: uid,
}
}
}
/// Answer a request that [`request!`] matches.
pub(super) fn answer(ask: &super::Ask<'_>, request: CtlRequest) -> CtlResponse {
let (core, mountpoint) = (ask.core, ask.mountpoint);
match answer_or_refuse(core, mountpoint, request) {
Ok(response) => response,
Err(e) => CtlResponse::error(e),
}
}
fn answer_or_refuse(
core: &Core,
mountpoint: &Path,
request: CtlRequest,
) -> CoreResult<CtlResponse> {
let sharing = &core.sharing;
Ok(match request {
CtlRequest::ShareNode {
path,
emails,
role,
message,
} => share_node(
core,
Target::path(core, mountpoint, path)?,
&emails,
&role,
message,
),
CtlRequest::ShareNodeByUid {
uid,
emails,
role,
message,
} => share_node(core, Target::uid(core, uid), &emails, &role, message),
CtlRequest::ListShare { path } => list_share(core, Target::path(core, mountpoint, path)?),
CtlRequest::ListShareByUid { uid } => list_share(core, Target::uid(core, uid)),
CtlRequest::UpdateShareRole {
path,
id,
kind,
role,
} => {
let target = Target::path(core, mountpoint, path)?;
target
.node
.and_then(|uid| sharing.update_share_role(&uid, &id, kind, &role))?;
role_updated(&role)
}
CtlRequest::UpdateShareRoleByUid {
uid,
id,
kind,
role,
} => {
let target = Target::uid(core, uid);
target
.node
.and_then(|uid| sharing.update_share_role(&uid, &id, kind, &role))?;
role_updated(&role)
}
CtlRequest::RemoveShareEntry { path, id, kind } => {
let target = Target::path(core, mountpoint, path)?;
remove_share_entry(core, target, &id, kind)?
}
CtlRequest::RemoveShareEntryByUid { uid, id, kind } => {
remove_share_entry(core, Target::uid(core, uid), &id, kind)?
}
CtlRequest::CreatePublicLink {
path,
role,
password,
expires,
} => {
let target = Target::path(core, mountpoint, path)?;
create_public_link(core, target, &role, password.as_deref(), expires)
}
CtlRequest::CreatePublicLinkByUid {
uid,
role,
password,
expires,
} => create_public_link(
core,
Target::uid(core, uid),
&role,
password.as_deref(),
expires,
),
CtlRequest::UpdatePublicLink {
path,
id,
role,
password,
expires,
} => {
let uid = Target::path(core, mountpoint, path)?.node?;
let link = sharing.update_public_link(&uid, &id, role.as_deref(), password, expires)?;
CtlResponse::PublicLink { link }
}
CtlRequest::UpdatePublicLinkByUid {
uid,
id,
role,
password,
expires,
} => {
let uid = Target::uid(core, uid).node?;
let link = sharing.update_public_link(&uid, &id, role.as_deref(), password, expires)?;
CtlResponse::PublicLink { link }
}
CtlRequest::RemovePublicLink { path, id } => {
remove_public_link(core, Target::path(core, mountpoint, path)?, &id)?
}
CtlRequest::RemovePublicLinkByUid { uid, id } => {
remove_public_link(core, Target::uid(core, uid), &id)?
}
CtlRequest::StopSharing { path } => {
stop_sharing(core, Target::path(core, mountpoint, path)?)
}
CtlRequest::StopSharingByUid { uid } => stop_sharing(core, Target::uid(core, uid)),
CtlRequest::ListSharedWithMe => CtlResponse::Entries {
entries: sharing.list_shared_with_me()?,
},
CtlRequest::ListSharedFolder { uid } => CtlResponse::Entries {
entries: sharing.list_shared_folder(&uid)?,
},
CtlRequest::OpenSharedFile { uid } => CtlResponse::FilePath {
path: sharing.open_shared_file(&uid)?.display().to_string(),
},
CtlRequest::LeaveShared { uid } => {
sharing.leave_shared(&uid)?;
core.log_activity(ActivityKind::Unshare, "shared item", "left", true);
ok("left shared item")
}
CtlRequest::ListInvitations => CtlResponse::Invitations {
items: sharing.list_invitations()?,
},
CtlRequest::AcceptInvitation { id } => {
sharing.accept_invitation(&id)?;
ok("invitation accepted")
}
CtlRequest::RejectInvitation { id } => {
sharing.reject_invitation(&id)?;
ok("invitation rejected")
}
CtlRequest::ListBookmarks => CtlResponse::Bookmarks {
items: sharing.list_bookmarks()?,
},
CtlRequest::CreateBookmark { url, password } => {
sharing.create_bookmark(&url, password.as_deref())?;
ok("bookmark saved")
}
CtlRequest::DeleteBookmark { token } => {
sharing.delete_bookmark(&token)?;
ok("bookmark removed")
}
CtlRequest::ListSharedByMe => CtlResponse::SharedByMe {
items: sharing.list_shared_by_me()?,
},
// `control` only hands over what `request!` matches.
_ => CtlResponse::error(pdfs_core::CoreError::internal(
"not a sharing request".to_string(),
)),
})
}
fn ok(message: &str) -> CtlResponse {
CtlResponse::Ok {
message: message.to_string(),
}
}
fn role_updated(role: &str) -> CtlResponse {
CtlResponse::Ok {
message: format!("role updated to {role}"),
}
}
fn share_node(
core: &Core,
target: Target,
emails: &[String],
role: &str,
message: Option<String>,
) -> CtlResponse {
let shared = target.node.and_then(|uid| {
core.sharing
.share_node(&uid, emails, role, message.as_deref())
});
match shared {
Ok((proton, external)) => {
core.log_activity(
ActivityKind::Share,
&target.label,
format!("{} recipient(s) as {role}", proton + external),
true,
);
ok(&format!(
"invited {proton} Proton and {external} external user(s)"
))
}
Err(e) => {
core.log_activity(ActivityKind::Share, &target.label, &e, false);
CtlResponse::error(e)
}
}
}
fn list_share(core: &Core, target: Target) -> CtlResponse {
match target.node.and_then(|uid| core.sharing.list_share(&uid)) {
Ok((entries, link)) => CtlResponse::Share { entries, link },
Err(e) => CtlResponse::error(e),
}
}
fn remove_share_entry(
core: &Core,
target: Target,
id: &str,
kind: pdfs_core::control::ShareEntryKind,
) -> CoreResult<CtlResponse> {
target
.node
.and_then(|uid| core.sharing.remove_share_entry(&uid, id, kind))?;
core.log_activity(ActivityKind::Unshare, &target.label, "access removed", true);
Ok(ok("removed"))
}
fn create_public_link(
core: &Core,
target: Target,
role: &str,
password: Option<&str>,
expires: Option<i64>,
) -> CtlResponse {
let created = target.node.and_then(|uid| {
core.sharing
.create_public_link(&uid, role, password, expires)
});
match created {
Ok(link) => {
core.log_activity(
ActivityKind::PublicLink,
&target.label,
"link created",
true,
);
CtlResponse::PublicLink { link }
}
Err(e) => {
core.log_activity(ActivityKind::PublicLink, &target.label, &e, false);
CtlResponse::error(e)
}
}
}
fn remove_public_link(core: &Core, target: Target, id: &str) -> CoreResult<CtlResponse> {
target
.node
.and_then(|uid| core.sharing.remove_public_link(&uid, id))?;
core.log_activity(ActivityKind::Unshare, &target.label, "link removed", true);
Ok(ok("public link removed"))
}
/// Log a stop-sharing request, and turn a partial removal into an error that
/// names what is still shared.
fn stop_sharing(core: &Core, target: Target) -> CtlResponse {
let result: CoreResult<StopSharingOutcome> =
target.node.and_then(|uid| core.sharing.stop_sharing(&uid));
match result.map(|outcome| outcome.into_result()) {
Ok(Ok(message)) => {
core.log_activity(
ActivityKind::Unshare,
&target.label,
"stopped sharing",
true,
);
CtlResponse::Ok { message }
}
Ok(Err(left)) => {
core.log_activity(ActivityKind::Unshare, &target.label, &left, false);
CtlResponse::error(pdfs_core::CoreError::remote(left))
}
Err(e) => CtlResponse::error(e),
}
}
+286
View File
@@ -0,0 +1,286 @@
//! The control requests about synced folders and devices: adding, attaching, switching and removing folders, pausing, conflicts, the pending-change queue, and restoring a device's folders.
use super::*;
/// The requests [`answer`] serves, as a pattern, so the control socket's match
/// hands exactly these over and the compiler still checks that it covers every
/// request.
macro_rules! request {
() => {
::pdfs_core::control::Request::ListDevices
| ::pdfs_core::control::Request::ListLocations
| ::pdfs_core::control::Request::RenameDevice { .. }
| ::pdfs_core::control::Request::DeleteDevice { .. }
| ::pdfs_core::control::Request::AdoptDevice { .. }
| ::pdfs_core::control::Request::MigrateDevice { .. }
| ::pdfs_core::control::Request::AddSyncFolder { .. }
| ::pdfs_core::control::Request::AttachSyncFolder { .. }
| ::pdfs_core::control::Request::ListSyncFolders
| ::pdfs_core::control::Request::RemoveSyncFolder { .. }
| ::pdfs_core::control::Request::SetSyncFolderMode { .. }
| ::pdfs_core::control::Request::SetSyncFolderPaused { .. }
| ::pdfs_core::control::Request::ResetSyncFolder { .. }
| ::pdfs_core::control::Request::SyncNow { .. }
| ::pdfs_core::control::Request::SetSyncPaused { .. }
| ::pdfs_core::control::Request::ListConflicts
| ::pdfs_core::control::Request::ResolveConflict { .. }
| ::pdfs_core::control::Request::ListPendingOps
| ::pdfs_core::control::Request::ExportPendingOp { .. }
| ::pdfs_core::control::Request::DiscardPendingOp { .. }
| ::pdfs_core::control::Request::RetryPendingOp { .. }
| ::pdfs_core::control::Request::ListRestorableFolders
| ::pdfs_core::control::Request::ListDeviceRestorableFolders { .. }
| ::pdfs_core::control::Request::RestoreSyncFolders { .. }
| ::pdfs_core::control::Request::RestoreDeviceFolders { .. }
};
}
pub(super) use request;
/// Answer a request that [`request!`] matches.
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
let Ask {
core, mountpoint, ..
} = *ask;
match request {
CtlRequest::ListDevices => match core.devices().list_devices() {
Ok(items) => CtlResponse::Devices { items },
Err(e) => CtlResponse::error(e),
},
CtlRequest::ListLocations => match core.list_locations() {
Ok(items) => CtlResponse::Locations { items },
Err(e) => CtlResponse::error(e),
},
CtlRequest::RenameDevice { uid, name } => match core.devices().rename_device(&uid, &name) {
Ok(()) => CtlResponse::Ok {
message: format!("renamed device to {name}"),
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::DeleteDevice { uid } => match core.devices().delete_device(&uid) {
Ok(()) => CtlResponse::Ok {
message: "device deleted".to_string(),
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::AdoptDevice { uid } => match core.devices().adopt_device(uid.as_deref()) {
Ok(message) => CtlResponse::Ok { message },
Err(e) => CtlResponse::error(e),
},
CtlRequest::MigrateDevice { uid } => match core.devices().migrate_device(&uid) {
Ok(message) => CtlResponse::Ok { message },
Err(e) => CtlResponse::error(e),
},
CtlRequest::AddSyncFolder { local_path } => {
// Registering the device and uploading a folder tree far outlasts the
// socket read timeout, so ack immediately and work on a background
// thread. The folder appears in ListSyncFolders once the row lands;
// completion (and any failures) go to the activity log.
let core = core.clone();
let path = PathBuf::from(&local_path);
if let Err(error) = core
.services
.clone()
.spawn_job("pdfs-add-sync-folder", move || {
let started = Instant::now();
match core.add_sync_folder(&path) {
Ok(folder) => {
core.profile().touch_profile();
let name = Path::new(&folder.local_path)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or(&folder.local_path)
.to_string();
core.log_activity(
ActivityKind::Upload,
format!("synced {name}"),
human_duration(started.elapsed()),
folder.state != "error",
);
}
Err(e) => {
warn!(error = %e, "add sync folder failed");
core.log_activity(ActivityKind::Upload, "add sync folder", &e, false);
}
}
})
{
tracing::warn!(%error, "could not start pdfs-add-sync-folder");
}
CtlResponse::Ok {
message: format!("adding {local_path}"),
}
}
CtlRequest::AttachSyncFolder {
local_path,
remote_path,
} => {
let result = rel_to_mount(mountpoint, &remote_path).and_then(|remote| {
core.attach_sync_folder(Path::new(&local_path), &remote, mountpoint)
});
match result {
Ok(folder) => CtlResponse::Ok {
message: format!("sync folder {} attached: {}", folder.id, folder.local_path),
},
Err(error) => CtlResponse::error(error),
}
}
CtlRequest::ListSyncFolders => match core.list_sync_folders() {
Ok(items) => CtlResponse::SyncFolders { items },
Err(e) => CtlResponse::error(e),
},
CtlRequest::RemoveSyncFolder { id, delete_remote } => {
match core.remove_sync_folder(id, delete_remote) {
Ok(()) => {
core.profile().touch_profile();
CtlResponse::Ok {
message: "removed synced folder".to_string(),
}
}
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::SetSyncFolderMode { id, mode } => {
match core.request_sync_folder_mode(id, &mode) {
Ok(message) => {
core.profile().touch_profile();
core.log_activity(ActivityKind::Upload, &message, "", true);
CtlResponse::Ok { message }
}
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::SetSyncFolderPaused { id, paused } => {
match core.set_sync_folder_paused(id, paused) {
Ok(()) => CtlResponse::Ok {
message: match paused {
true => format!("folder {id} paused"),
false => format!("folder {id} resumed"),
},
},
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::ResetSyncFolder { id } => match core.reset_sync_folder(id) {
Ok(message) => {
core.log_activity(ActivityKind::Sync, &message, "", true);
CtlResponse::Ok { message }
}
Err(e) => CtlResponse::error(e),
},
CtlRequest::SyncNow { id } => {
core.sync_now(id);
CtlResponse::Ok {
message: match id {
Some(id) => format!("reconciling folder {id}"),
None => "reconciling all folders".to_string(),
},
}
}
CtlRequest::SetSyncPaused { paused, until } => match core.set_sync_paused(paused, until) {
Ok(()) => CtlResponse::Ok {
message: match (paused, until) {
(false, _) => "sync resumed".to_string(),
(true, None) => "sync paused until resumed".to_string(),
(true, Some(_)) => "sync paused".to_string(),
},
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::ListConflicts => match core.list_conflicts() {
Ok(items) => CtlResponse::Conflicts { items },
Err(e) => CtlResponse::error(e),
},
CtlRequest::ResolveConflict { path, keep } => match route_change(core, mountpoint, &path) {
Ok((core, rel)) => match core.resolve_conflict(&rel, &keep) {
Ok(message) => CtlResponse::Ok { message },
Err(e) => CtlResponse::error(e),
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::ListPendingOps => match core.pending_op_infos() {
Ok(items) => CtlResponse::PendingOps { items },
Err(e) => CtlResponse::error(e),
},
CtlRequest::ExportPendingOp { id, dest } => {
match core.export_pending_op(id, Path::new(&dest)) {
Ok(written) => CtlResponse::Ok {
message: format!("wrote {} to {dest}", human_bytes(written)),
},
Err(e) => CtlResponse::error(e),
}
}
CtlRequest::DiscardPendingOp { id } => match core.discard_pending_op(id) {
Ok(path) => CtlResponse::Ok {
message: format!("discarded the queued change to {path}"),
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::RetryPendingOp { id } => match core.retry_pending_ops(id) {
Ok(0) if id.is_some() => CtlResponse::Ok {
message: "nothing to retry: the operation is already due or waiting for a rename"
.to_string(),
},
Ok(moved) => CtlResponse::Ok {
message: format!("retrying {moved} queued operation(s) now"),
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::ListRestorableFolders => match core.profile().list_restorable_folders(None) {
Ok(items) => CtlResponse::RestorableFolders { items },
Err(e) => CtlResponse::error(e),
},
CtlRequest::ListDeviceRestorableFolders { device } => {
match core.profile().list_restorable_folders(Some(&device)) {
Ok(items) => CtlResponse::RestorableFolders { items },
Err(e) => CtlResponse::error(e),
}
}
request @ (CtlRequest::RestoreSyncFolders { .. }
| CtlRequest::RestoreDeviceFolders { .. }) => {
let (device, items) = match request {
CtlRequest::RestoreDeviceFolders { device, items } => (Some(device), items),
CtlRequest::RestoreSyncFolders { items } => (None, items),
_ => unreachable!("matched above"),
};
// Like AddSyncFolder: each restored folder downloads a whole tree,
// which outlasts the socket timeout. Ack, then work.
let core = core.clone();
if let Err(error) =
core.services
.clone()
.spawn_job("pdfs-restore-sync-folders", move || {
match core.restore_sync_folders(&items, device.as_deref()) {
Ok(outcome) => {
core.profile().touch_profile();
if !outcome.complete() {
warn!(skipped = ?outcome.skipped, "restore skipped folders");
}
core.log_activity(
ActivityKind::Download,
outcome.summary(),
outcome.skipped.join("; "),
outcome.complete(),
);
}
Err(e) => {
warn!(error = %e, "restore failed");
core.log_activity(
ActivityKind::Download,
"restore folders",
&e,
false,
);
}
}
})
{
tracing::warn!(%error, "could not start pdfs-restore-sync-folders");
}
CtlResponse::Ok {
message: "restoring folders".to_string(),
}
}
// `control` only hands over what `request!` matches.
_ => CtlResponse::error(CoreError::internal("not a sync request".to_string())),
}
}
+139
View File
@@ -0,0 +1,139 @@
//! The control requests about Drive's trash and the local content cache.
use super::*;
/// The requests [`answer`] serves, as a pattern, so the control socket's match
/// hands exactly these over and the compiler still checks that it covers every
/// request.
macro_rules! request {
() => {
::pdfs_core::control::Request::ListTrash
| ::pdfs_core::control::Request::ListTrashedFolder { .. }
| ::pdfs_core::control::Request::Restore { .. }
| ::pdfs_core::control::Request::DeleteForever { .. }
| ::pdfs_core::control::Request::EmptyTrash
| ::pdfs_core::control::Request::PurgeCache
| ::pdfs_core::control::Request::CacheInspect { .. }
| ::pdfs_core::control::Request::CacheVacuum
| ::pdfs_core::control::Request::SetCacheBudget { .. }
};
}
pub(super) use request;
/// Answer a request that [`request!`] matches.
pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
let Ask { core, .. } = *ask;
match request {
CtlRequest::ListTrash => match core.trash().list_trash() {
Ok(entries) => CtlResponse::Entries { entries },
Err(e) => CtlResponse::error(e),
},
CtlRequest::ListTrashedFolder { uid } => match core.trash().list_trashed_folder(&uid) {
Ok(entries) => CtlResponse::Entries { entries },
Err(e) => CtlResponse::error(e),
},
CtlRequest::Restore { uids } => match core.trash().restore(&uids) {
Ok(n) => {
core.log_activity(ActivityKind::Restore, format!("{n} item(s)"), "", true);
CtlResponse::Ok {
message: format!("restored {n} item(s)"),
}
}
Err(e) => CtlResponse::error(e),
},
CtlRequest::DeleteForever { uids } => match core.trash().delete_forever(&uids) {
Ok(n) => {
core.log_activity(
ActivityKind::DeleteForever,
format!("{n} item(s)"),
"",
true,
);
CtlResponse::Ok {
message: format!("permanently deleted {n} item(s)"),
}
}
Err(e) => CtlResponse::error(e),
},
CtlRequest::EmptyTrash => match core.trash().empty_trash() {
Ok(n) => {
let items = if n == 1 {
"1 item".to_string()
} else {
format!("{n} items")
};
core.log_activity(ActivityKind::EmptyTrash, items.clone(), "", true);
CtlResponse::Ok {
message: format!("emptied trash ({items})"),
}
}
Err(e) => CtlResponse::error(e),
},
CtlRequest::PurgeCache => {
let freed = core.cache.clear_unpinned();
CtlResponse::Ok {
message: format!(
"purged {:.1} MiB of unpinned cache",
freed as f64 / 1_048_576.0
),
}
}
CtlRequest::CacheInspect { deep } => match core.db.stats() {
Ok(stats) => {
// The deep check reads every page — tens of seconds on a real
// database, all of it holding the connection every FUSE handler
// needs — so it runs on a thread and this request returns
// whatever the last completed check found. `integrity_checked`
// tells the caller which answer it is holding, since "no
// problems found" and "never looked" are both an empty list;
// `integrity_running` says a fresh answer is on its way.
let (integrity_problems, integrity_checked, integrity_running) = if deep {
core.maintenance.start_or_read_integrity_check()
} else {
(Vec::new(), false, false)
};
CtlResponse::CacheReport {
integrity_running,
schema_version: stats.schema_version,
db_bytes: stats.total_bytes(),
db_reclaimable_bytes: stats.reclaimable_bytes(),
tables: stats.tables,
cache_used: core.cache.usage(),
cache_budget: core.cache.budget(),
integrity_problems,
integrity_checked,
}
}
Err(e) => CtlResponse::error(CoreError::internal(format!("read db stats: {e:?}"))),
},
CtlRequest::CacheVacuum => match core.maintenance.start_vacuum() {
Ok(()) => CtlResponse::Ok {
message: "compacting the cache database in the background".into(),
},
Err(e) => CtlResponse::error(e),
},
CtlRequest::SetCacheBudget { bytes } => {
core.cache.set_budget(bytes);
// Persist so the next mount keeps the new cap. Best-effort: a config
// write failure is reported but the live cap is already applied.
match AppDirs::new()
.map(|dirs| dirs.update_config(|cfg| cfg.cache_budget = Some(bytes)))
{
Ok(Ok(())) => {
core.profile().touch_profile();
CtlResponse::Ok {
message: format!("cache budget set to {bytes} bytes"),
}
}
Ok(Err(e)) => CtlResponse::error(CoreError::internal(format!(
"budget applied but config write failed: {e}"
))),
Err(e) => CtlResponse::error(CoreError::internal(format!(
"budget applied but config unavailable: {e}"
))),
}
}
// `control` only hands over what `request!` matches.
_ => CtlResponse::error(CoreError::internal("not a trash request".to_string())),
}
}
+99 -35
View File
@@ -9,7 +9,6 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use parking_lot::Mutex;
use pdfs_core::batch;
@@ -21,9 +20,9 @@ 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::error::ProtonError;
use proton_drive_rs::proton_sdk::ids::{DeviceUid, NodeUid};
use proton_drive_rs::{DeviceType, Node};
use std::sync::OnceLock;
use tracing::{info, warn};
use super::sync::{self, base_name};
@@ -148,28 +147,70 @@ fn migrated_name(name: &str, device: &str, taken: &[String]) -> Option<String> {
.find(|candidate| free(candidate))
}
impl Core {
// ---- devices ----------------------------------------------------------
/// This account's devices on Drive, and which one is this computer: listing,
/// renaming, deleting, adopting and migrating them, and registering this one.
///
/// It reaches the rest of the daemon through [`DevicesHost`]. [`Core::devices`]
/// builds one on demand with the daemon as its host.
#[derive(Clone)]
pub(crate) struct Devices {
client: proton_drive_rs::ProtonDriveClient,
drive: std::sync::Arc<dyn crate::drive::DriveApi>,
rt: tokio::runtime::Handle,
db: std::sync::Arc<pdfs_store::db::Db>,
host: std::sync::Arc<dyn DevicesHost>,
}
/// Unified local-location listing for the control protocol.
pub(crate) fn list_locations(&self) -> CoreResult<Vec<MountSpec>> {
let progress = self.sync.progress.lock();
let mut locations = self
.db
.mount_list()
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
for location in &mut locations {
location.mounted = self.states.is_mounted_at(Path::new(&location.local_path));
if let MountKind::Device { sync_folder_id } | MountKind::Attached { sync_folder_id } =
&location.kind
{
location.progress = progress.get(sync_folder_id).cloned();
location.paused = self.sync_folder_paused(*sync_folder_id);
}
}
Ok(locations)
/// What [`Devices`] needs from the rest of the daemon, to migrate a device's
/// folders onto this one.
pub(crate) trait DevicesHost: Send + Sync {
/// Move a node under `parent` on the server, renaming it to `name` if
/// given, and update the tree to match.
fn move_node(
&self,
uid: &NodeUid,
parent: &NodeUid,
name: Option<&str>,
) -> Result<(), ProtonError>;
/// Run a sync pass for one synced folder now.
fn sync_now(&self, id: Option<i64>);
/// Re-enumerate a folder's children on next access.
fn invalidate_children_of(&self, parent: &NodeUid);
}
impl DevicesHost for Core {
fn move_node(
&self,
uid: &NodeUid,
parent: &NodeUid,
name: Option<&str>,
) -> Result<(), ProtonError> {
self.move_rename_remote(uid, parent, name)
}
fn sync_now(&self, id: Option<i64>) {
Core::sync_now(self, id);
}
fn invalidate_children_of(&self, parent: &NodeUid) {
Core::invalidate_children_of(self, parent);
}
}
impl Core {
/// The devices service, with this daemon as its host.
pub(crate) fn devices(&self) -> Devices {
Devices {
client: self.client.clone(),
drive: self.drive.clone(),
rt: self.rt.clone(),
db: self.db.clone(),
host: std::sync::Arc::new(self.clone()),
}
}
}
impl Devices {
/// List the account's registered devices, flagging the one *this* machine
/// syncs to so a front-end can treat it as more than another computer in the
/// list — deleting it takes this machine's synced folders down with it.
@@ -356,7 +397,10 @@ impl Core {
continue;
}
let new_name = migrated_name(&node.name, &source.name, &taken);
if let Err(e) = self.move_rename_remote(&node.uid, &target_root, new_name.as_deref()) {
if let Err(e) = self
.host
.move_node(&node.uid, &target_root, new_name.as_deref())
{
warn!(name = %node.name, error = %e, "migrate: could not move folder");
failed.push(format!("{}: {e}", node.name));
continue;
@@ -373,11 +417,11 @@ impl Core {
if let Err(e) = self.db.sync_folder_set_share(folder.id, &target.share_id) {
warn!(id = folder.id, error = ?e, "migrate: could not re-point sync folder");
}
self.sync_now(Some(folder.id));
self.host.sync_now(Some(folder.id));
}
}
self.invalidate_children_of(&source_root);
self.invalidate_children_of(&target_root);
self.host.invalidate_children_of(&source_root);
self.host.invalidate_children_of(&target_root);
let mut message = format!("moved {moved} folder(s) from {}", source.name);
if !renamed.is_empty() {
@@ -397,8 +441,6 @@ impl Core {
Ok(message)
}
// ---- device folder sync -------------------------
/// Auto-register (or recover) this machine as a Proton Drive Device, caching
/// it so restarts reuse the same device. Recovery matches an existing remote
/// Linux device by name before creating a new one, so a lost local record
@@ -505,7 +547,7 @@ impl Core {
}
/// Everything directly under a device root, trashed nodes included.
pub(super) fn device_root_nodes(&self, root_uid: &NodeUid) -> CoreResult<Vec<Node>> {
pub(crate) fn device_root_nodes(&self, root_uid: &NodeUid) -> CoreResult<Vec<Node>> {
let uids = self
.rt
.block_on(self.drive.enumerate_folder_children_node_uids(root_uid))
@@ -517,6 +559,31 @@ impl Core {
.block_on(self.drive.enumerate_nodes(&uids))
.map_err(|e| CoreError::from_api(&e, "resolve device root children"))
}
}
impl Core {
// ---- devices ----------------------------------------------------------
/// Unified local-location listing for the control protocol.
pub(crate) fn list_locations(&self) -> CoreResult<Vec<MountSpec>> {
let progress = self.sync.progress.lock();
let mut locations = self
.db
.mount_list()
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?;
for location in &mut locations {
location.mounted = self.states.is_mounted_at(Path::new(&location.local_path));
if let MountKind::Device { sync_folder_id } | MountKind::Attached { sync_folder_id } =
&location.kind
{
location.progress = progress.get(sync_folder_id).cloned();
location.paused = self.sync_folder_paused(*sync_folder_id);
}
}
Ok(locations)
}
// ---- device folder sync -------------------------
/// Add a local folder to this device's sync set: register the device if
/// needed, create a matching folder under the device root, upload the local
@@ -570,7 +637,7 @@ impl Core {
)));
}
let device = self.ensure_device()?;
let device = self.devices().ensure_device()?;
let root_uid = parse_uid(&device.root_uid).ok_or_else(|| {
CoreError::internal(format!("bad device root uid: {}", device.root_uid))
})?;
@@ -582,7 +649,7 @@ impl Core {
// original, not leave the user with two "Downloads" in their Drive. The
// reconcile treats an existing remote tree correctly: unmatched paths read as
// a conflict, not as data loss.
let remote_root = match self.find_device_child_folder(&root_uid, &name)? {
let remote_root = match self.devices().find_device_child_folder(&root_uid, &name)? {
Some(uid) => {
info!(name, "reusing existing device folder");
uid
@@ -782,10 +849,7 @@ impl Core {
/// kernel channel, both filled in when the session is built.
pub(crate) fn fork_state(&self) -> Core {
let mut fork = self.clone();
fork.primary = false;
fork.root = Arc::new(OnceLock::new());
fork.notifier = Arc::new(OnceLock::new());
fork.session_live = Arc::new(std::sync::atomic::AtomicBool::new(false));
fork.session = self.session.fork();
fork
}
@@ -1173,7 +1237,7 @@ impl Core {
root: Node,
) -> CoreResult<SecondaryMount> {
let core = self.fork_state();
let session_live = core.session_live.clone();
let session_live = core.session.session_live.clone();
// The fork owns this state/path registration. `spawn_session` only
// marks it live after FUSE has spawned successfully.
core.register_state(local);
+31 -14
View File
@@ -20,6 +20,8 @@ use std::time::{Duration, Instant};
use parking_lot::Mutex;
use pdfs_core::control::{Diagnostics, DriveCallStat, InflightRequest, ServiceState, WorkerState};
use pdfs_core::lifecycle::ServiceBoard;
use super::Core;
/// When this process started. Read at the first touch, which
@@ -174,6 +176,16 @@ impl Core {
age_secs: service.age.as_secs(),
})
.collect(),
jobs: self
.services
.jobs()
.into_iter()
.map(|job| ServiceState {
name: job.name,
running: job.running,
age_secs: job.age.as_secs(),
})
.collect(),
drive_calls: self
.drive_calls
.snapshot()
@@ -197,10 +209,15 @@ impl Core {
/// is not started until the first one has returned.
fn pending_ops_quickly(&self) -> Option<u64> {
let db = self.db.clone();
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)
})
probe_once(
&self.services,
&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)
},
)
}
}
@@ -209,6 +226,7 @@ impl Core {
/// `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>(
board: &ServiceBoard,
busy: &Arc<AtomicBool>,
deadline: Duration,
probe: impl FnOnce() -> Option<T> + Send + 'static,
@@ -218,13 +236,11 @@ fn probe_once<T: Send + 'static>(
}
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);
});
let spawned = board.spawn_job("pdfs-diagnostics", move || {
let answer = probe();
done.store(false, Ordering::Release);
let _ = tx.send(answer);
});
if spawned.is_err() {
busy.store(false, Ordering::Release);
return None;
@@ -300,11 +316,12 @@ mod tests {
#[test]
fn a_stuck_probe_is_not_started_again() {
let board = ServiceBoard::default();
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 stuck = probe_once(&board, &busy, short, move || {
let _ = wait.recv();
Some(1)
});
@@ -312,7 +329,7 @@ mod tests {
let started = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&started);
let second = probe_once(&busy, short, move || {
let second = probe_once(&board, &busy, short, move || {
flag.store(true, Ordering::SeqCst);
Some(2)
});
@@ -329,7 +346,7 @@ mod tests {
std::thread::yield_now();
}
assert_eq!(
probe_once(&busy, Duration::from_secs(10), || Some(3)),
probe_once(&board, &busy, Duration::from_secs(10), || Some(3)),
Some(3)
);
}
+10 -6
View File
@@ -41,8 +41,7 @@ use proton_drive_rs::{Node, NodeKind};
use tracing::{debug, error, info, warn};
use super::link::{self, is_network_error};
use super::state::{Intervals, PendingRevision};
use super::takeout::sha1_of;
use super::photos::sha1_of;
use super::transfers::CountingReader;
use super::{
Core, DRAIN_BACKOFF_MAX, DRAIN_BACKOFF_MIN, DRAIN_IDLE_POLL, DRAIN_REVISION_DEBOUNCE,
@@ -50,6 +49,7 @@ use super::{
is_already_exists, is_gone, is_local_uid_str, media_type_for, node_revision_id, node_size,
now_millis, now_secs, parse_node_uid,
};
use pdfs_vfs::open::{Intervals, PendingRevision};
use proton_drive_rs::proton_sdk::api::ResponseCode;
use proton_drive_rs::proton_sdk::error::ProtonError;
@@ -394,7 +394,7 @@ impl Core {
// the wire, so trashing its folder kept it as a trash; claimed
// only to be handed back, it was kept although nothing had sent
// it (`docs/BUGS.md` B178).
let online = self.online.load(Ordering::Relaxed);
let online = self.is_online();
let paused = self.sync_paused();
// One row, chosen and *claimed* by the database. Reading the whole
// queue to pick one op made a long queue quadratic to drain, and
@@ -420,7 +420,11 @@ impl Core {
// touches get written (`ContentCache::flush_touches`).
// Cheap and a no-op when empty.
self.cache.flush_touches();
self.recover_fsynced_writes();
self.recovery().recover_fsynced_writes();
// One a stop cut off that waited for Drive.
if online {
self.recovery().settle_replaces();
}
// Parked rows are invisible to `claim_next_due_op`, so
// an idle queue is exactly when a park that has outlived
// its writer has to be noticed.
@@ -773,7 +777,7 @@ impl Core {
/// is disarmed, letting a gap-fill read from a revision that no longer
/// describes the file.
pub(crate) fn release_pending(&self, uid: &NodeUid, blob: &Path) {
let mut pending = self.pending.lock();
let mut pending = self.writes.pending.lock();
if let Some(current) = pending.get(uid)
&& current.path == blob
{
@@ -1135,9 +1139,9 @@ fn placed_in(st: &crate::state::State, uid: &NodeUid) -> Option<(String, Option<
#[cfg(test)]
mod tests {
use super::*;
use crate::state::WriteHandle;
use pdfs_core::Access;
use pdfs_store::db::Db;
use pdfs_vfs::open::WriteHandle;
use proton_drive_rs::NodeKind;
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
use std::cell::Cell;
+5 -5
View File
@@ -233,7 +233,7 @@ impl Core {
.insert(real.clone(), local.clone());
}
// The feed will report this create back to us; the tree already has it
// under its real uid, so that event is ours to ignore (`Core::self_changes`).
// under its real uid, so that event is ours to ignore (`WriteState::note_echo`).
self.note_self_change(&real);
// The uploaded blob is done with either way: a write that replaced it
// while it was on the wire already discarded it when it attached.
@@ -358,7 +358,7 @@ impl Core {
// while its trash is on the wire or a listing still shows it. Taking a
// folder removed and made again put the new one's contents into the
// old one, and its trash took them along (docs/BUGS.md B162).
let hidden = self.hidden.lock().clone();
let hidden = self.writes.hidden();
let Some(twin) = children
.into_iter()
.find(|node| node.name == name && !node.trashed && !hidden.contains(&node.uid))
@@ -475,7 +475,7 @@ impl Core {
// a newer blob by the time it is retried (`Core::adoptable_twin`).
let sha = staged_sha1(Path::new(blob))?;
self.db.note_create_sent(op.id, &sha)?;
let thumbnails = self.upload_thumbnails(Path::new(blob), name);
let thumbnails = self.photos().upload_thumbnails(Path::new(blob), name);
let guard = self
.transfers
.begin(name, op.uid.clone(), TransferDirection::Upload, meta.len);
@@ -514,7 +514,7 @@ impl Core {
real: &NodeUid,
) -> Result<CreateRetired, Box<dyn std::error::Error>> {
let retired = {
let mut pending = self.pending.lock();
let mut pending = self.writes.pending.lock();
let retired = self.db.finish_create(op.id, uploaded, landing, |json| {
let mut meta: StagedWrite = serde_json::from_str(json).ok()?;
meta.uid = landing.real.to_string();
@@ -564,7 +564,7 @@ impl Core {
}
}
}
for aw in st.active_writes.values_mut() {
for aw in st.open.writers_mut() {
if aw.uid == *local {
aw.uid = real.clone();
}
+5 -5
View File
@@ -232,7 +232,7 @@ impl Core {
}
let alt = conflict_name(&name, now_secs());
let thumbnails = self.upload_thumbnails(blob, &alt);
let thumbnails = self.photos().upload_thumbnails(blob, &alt);
let guard =
self.transfers
.begin(&alt, meta.uid.clone(), TransferDirection::Upload, meta.len);
@@ -377,7 +377,7 @@ impl Core {
}
let name = self.node_name(&uid);
let thumbnails = self.upload_thumbnails(&blob, &name);
let thumbnails = self.photos().upload_thumbnails(&blob, &name);
let guard =
self.transfers
.begin(&name, meta.uid.clone(), TransferDirection::Upload, meta.len);
@@ -552,7 +552,7 @@ impl Core {
// This function's whole job is to bring the tree level with the revision
// we just sealed, so the feed's report of that revision has nothing left
// to tell us. Claimed here rather than at the upload call so it is only
// recorded when the node was actually re-read (`Core::self_changes`).
// recorded when the node was actually re-read (`WriteState::note_echo`).
self.note_self_change(uid);
// Rebase any *open* write handles targeting this node. A handle opened
// before this upload carries a stale base — its `base_mtime`/`base_size`
@@ -647,7 +647,7 @@ impl Core {
/// daemon has just put there itself (`WriteHandle::rebase_onto`).
pub(crate) fn rebase_open_writes(&self, uid: &NodeUid, node: &Node) {
self.for_each_state(|st| {
for aw in st.active_writes.values_mut() {
for aw in st.open.writers_mut() {
if aw.uid == *uid {
aw.rebase_onto(node);
debug!(%uid, mtime = aw.base_mtime, size = aw.base_size,
@@ -680,7 +680,7 @@ impl Core {
hash: None,
revision_id: node_revision_id(sealed),
};
let mut pending = self.pending.lock();
let mut pending = self.writes.pending.lock();
let Some(p) = pending.get_mut(uid) else {
return false;
};
+3 -3
View File
@@ -19,7 +19,7 @@ impl Core {
if is_local_uid_str(&op.uid) {
match self.withdrawn_twin(op)? {
Some(twin) => {
self.hidden.lock().insert(twin.clone());
self.writes.hide(&twin);
match self
.block_on_bounded(self.drive.trash_nodes(std::slice::from_ref(&twin)))
.and_then(batch::into_unit)
@@ -131,7 +131,7 @@ impl Core {
// mount trashed is not one, and a node in the tree was answered for.
// A file of the user's renamed to the name the create was sent under
// was taken for it, and trashed (`docs/BUGS.md` B193).
let hidden = self.hidden.lock().clone();
let hidden = self.writes.hidden();
let Some(twin) = children
.into_iter()
.find(|node| node.name == name && !node.trashed && !hidden.contains(&node.uid))
@@ -191,7 +191,7 @@ impl Core {
real: &NodeUid,
name: &str,
) -> Result<(), Box<dyn std::error::Error>> {
self.hidden.lock().insert(real.clone());
self.writes.hide(real);
self.note_self_change(real);
let trash = PendingOp {
id: trash,
+3 -59
View File
@@ -7,71 +7,15 @@ impl Core {
/// Record that this daemon just changed `uid` on the remote, so the event
/// feed's echo of that change is recognised instead of re-applied. Called
/// from the drain once the remote has actually accepted the change and the
/// tree has been brought level with it. See [`Core::self_changes`].
/// tree has been brought level with it. See [`writes::WriteState`].
pub(crate) fn note_self_change(&self, uid: &NodeUid) {
note_self_change(&mut self.self_changes.lock(), uid, now_millis());
self.writes.note_echo(uid, now_millis());
}
/// Claim one outstanding echo for `uid`, reporting whether this event is one
/// this daemon caused. Consuming rather than merely testing is what bounds
/// the suppression: the next event for the node applies normally.
pub(super) fn take_self_change(&self, uid: &NodeUid) -> bool {
take_self_change(&mut self.self_changes.lock(), uid, now_millis())
self.writes.take_echo(uid, now_millis())
}
}
/// How long a change this daemon made stays recognisable as its own. Generous
/// against a feed that can lag, but finite: past it, an event for the node is
/// applied like any other. See [`Core::self_changes`].
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
}
+17 -26
View File
@@ -15,12 +15,12 @@ impl Core {
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))
let writers = st.open.take_all();
writers
.into_iter()
.map(|h| {
let unlinked = st.entries.get(&h.ino).is_some_and(|e| e.unlinked);
(h, unlinked)
})
.collect()
};
@@ -201,18 +201,8 @@ impl Core {
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,
}),
}
self.writes
.baseline(uid, base_mtime, base_size, base_revision_id)
}
/// Move a file holding a node's intended new content into staging and queue
@@ -247,7 +237,7 @@ impl Core {
// of exactly the ranges this write did not touch, and what neither wrote
// is still the remote content that the earlier write was based on, which
// is why the baseline is inherited along with them.
let previous = self.pending.lock().get(uid).cloned();
let previous = self.writes.queued(uid);
if !meta.complete
&& let Some(previous) = previous
&& let Err(error) = merge_over_pending(&mut meta, src, &previous)
@@ -302,7 +292,7 @@ impl Core {
// carries it over, or has already finished and this write
// queues against the real uid below (`Core::retire_create`).
let meta_json = serde_json::to_string(&meta).unwrap_or_default();
let mut pending = self.pending.lock();
let mut pending = self.writes.pending.lock();
let attached = self
.db
.attach_blob_to_create(&uid.to_string(), &path.to_string_lossy(), &meta_json)
@@ -325,7 +315,7 @@ impl Core {
debug!(local = %uid, %real, "create landed under an open write; queueing a revision");
uid = real;
meta.uid = uid.to_string();
let previous = self.pending.lock().get(&uid).cloned();
let previous = self.writes.queued(&uid);
meta.based_on = previous.as_ref().and_then(|p| p.meta.based_on.clone());
if !meta.complete
&& let Some(previous) = previous
@@ -353,7 +343,8 @@ impl Core {
error!(%uid, error = %e, "queueing upload failed");
Errno::EIO
})?;
self.pending
self.writes
.pending
.lock()
.insert(uid.clone(), PendingRevision { path, meta });
superseded
@@ -436,7 +427,7 @@ impl Core {
// case the remote is *not* our base: the complete staged revision is.
// Compose from those local bytes so the truncate can supersede the
// queued upload without fetching stale remote content or returning EIO.
let pending_base = self.pending.lock().get(&uid).cloned();
let pending_base = self.writes.queued(&uid);
if pending_base
.as_ref()
.is_some_and(|pending| !pending.meta.complete)
@@ -726,7 +717,7 @@ impl Core {
} else {
self.release_dropped_ops(uid, blobs);
}
self.hidden.lock().insert(uid.clone());
self.writes.hide(uid);
// Withdrawn from the tree, which every mount serves from, so no other
// mount goes on serving a file the user just trashed (`docs/BUGS.md`
// B74).
@@ -786,7 +777,7 @@ impl Core {
/// (`docs/BUGS.md` B102), so the entries to forget are found by blob, not
/// only by `uid`.
pub(super) fn release_dropped_ops(&self, uid: &NodeUid, blobs: Vec<String>) {
self.pending.lock().remove(uid);
self.writes.pending.lock().remove(uid);
self.release_dropped_below(blobs);
}
@@ -794,7 +785,7 @@ impl Core {
/// entry.
pub(super) fn release_dropped_below(&self, blobs: Vec<String>) {
let below: Vec<NodeUid> = {
let mut pending = self.pending.lock();
let mut pending = self.writes.pending.lock();
let below: Vec<NodeUid> = pending
.iter()
.filter(|(_, p)| blobs.iter().any(|b| p.path == Path::new(b)))
+8
View File
@@ -116,6 +116,14 @@ impl EventHub {
.retain(|other| !Arc::ptr_eq(other, mailbox));
}
/// Wake every subscription waiting on its mailbox, so it sees a stop
/// now rather than at its next heartbeat.
pub(crate) fn wake_all(&self) {
for mailbox in self.mailboxes.lock().iter() {
mailbox.ready.notify_one();
}
}
fn has_subscribers(&self) -> bool {
!self.mailboxes.lock().is_empty()
}
File diff suppressed because it is too large. Load diff
+41 -33
View File
@@ -14,6 +14,8 @@ use pdfs_core::control::{
GalleryAction, GalleryAlbum, GalleryFolder, GalleryPlace, PhotoItem, PhotoKind, Response,
};
use pdfs_core::{CoreError, CoreResult};
use pdfs_store::db::Db;
use proton_drive_rs::ProtonDriveClient;
use proton_drive_rs::proton_sdk::session::ProtonApiSession;
use proton_gallery_app_rs::{App, View};
use proton_gallery_rs::CancellationToken;
@@ -32,6 +34,9 @@ pub(super) struct Gallery {
refresh: Notify,
access: AtomicU64,
video: video::Server,
client: ProtonDriveClient,
events: Arc<super::events::EventHub>,
db: Arc<Db>,
}
#[derive(Default, PartialEq, Eq)]
@@ -50,8 +55,17 @@ impl Visibility {
}
impl Gallery {
pub(super) fn new(root: PathBuf, session: ProtonApiSession) -> Self {
pub(super) fn new(
root: PathBuf,
session: ProtonApiSession,
client: ProtonDriveClient,
events: Arc<super::events::EventHub>,
db: Arc<Db>,
) -> Self {
Self {
client,
events,
db,
root,
session,
cancel: CancellationToken::new(),
@@ -69,13 +83,13 @@ impl Gallery {
self.video.close_all();
}
async fn app(&self, core: &Core) -> CoreResult<&App> {
async fn app(&self) -> CoreResult<&App> {
self.app
.get_or_try_init(|| async {
App::open_hosted(
self.root.clone(),
self.session.clone(),
core.client.clone(),
self.client.clone(),
self.cancel.child_token(),
)
.await
@@ -84,12 +98,7 @@ impl Gallery {
.await
}
async fn ensure_visibility(
&self,
core: &Core,
app: &App,
force: bool,
) -> CoreResult<Arc<Visibility>> {
async fn ensure_visibility(&self, app: &App, force: bool) -> CoreResult<Arc<Visibility>> {
if self.cancel.is_cancelled() {
return Err(CoreError::remote("The Gallery session expired"));
}
@@ -111,7 +120,7 @@ impl Gallery {
.await
.map_err(gallery_error)?
{
self.publish_visibility(core, self.read_visibility(core, app).await?);
self.publish_visibility(self.read_visibility(app).await?);
}
let started = Instant::now();
let result = tokio::select! {
@@ -119,7 +128,7 @@ impl Gallery {
_ = self.cancel.cancelled() => Err(CoreError::remote("The Gallery session expired")),
result = tokio::time::timeout(Duration::from_secs(20), async {
app.refresh_gallery_configuration(false).await.map_err(gallery_error)?;
self.read_visibility(core, app).await
self.read_visibility(app).await
}) => result.unwrap_or_else(|_| Err(CoreError::remote("Gallery visibility check timed out"))),
};
tracing::debug!(
@@ -129,7 +138,7 @@ impl Gallery {
);
*checked = Some(Instant::now());
if let Ok(visibility) = result {
self.publish_visibility(core, visibility.clone());
self.publish_visibility(visibility.clone());
return Ok(visibility);
}
if !force && let Some(visibility) = self.snapshot() {
@@ -145,18 +154,18 @@ impl Gallery {
.clone()
}
fn publish_visibility(&self, core: &Core, visibility: Arc<Visibility>) {
fn publish_visibility(&self, visibility: Arc<Visibility>) {
let mut snapshot = self.visibility.write().unwrap_or_else(|e| e.into_inner());
if snapshot.as_ref() != Some(&visibility) {
*snapshot = Some(visibility);
drop(snapshot);
self.video.close_all();
core.events
self.events
.publish(&[pdfs_core::control::Topic::GalleryVisibilitySynced]);
}
}
async fn read_visibility(&self, core: &Core, app: &App) -> CoreResult<Arc<Visibility>> {
async fn read_visibility(&self, app: &App) -> CoreResult<Arc<Visibility>> {
let account = self.account()?;
let mut visibility = Visibility::default();
for (volume, node) in app
@@ -170,7 +179,7 @@ impl Gallery {
.insert(NodeUid::new(volume.into(), node.into()).to_string());
}
visibility.media.extend(
core.db
self.db
.photo_group_members_for(&visibility.media)
.map_err(CoreError::from)?,
);
@@ -328,7 +337,7 @@ impl Gallery {
Ok(())
}
pub(super) async fn poll(self: Arc<Self>, core: Core) {
pub(super) async fn poll(self: Arc<Self>) {
loop {
tokio::select! {
biased;
@@ -336,9 +345,8 @@ impl Gallery {
_ = self.refresh.notified() => {},
_ = tokio::time::sleep(Duration::from_secs(60)) => {}
}
if let Ok(Ok(app)) = tokio::time::timeout(Duration::from_secs(5), self.app(&core)).await
{
let _ = self.ensure_visibility(&core, app, false).await;
if let Ok(Ok(app)) = tokio::time::timeout(Duration::from_secs(5), self.app()).await {
let _ = self.ensure_visibility(app, false).await;
}
}
}
@@ -422,8 +430,8 @@ impl Core {
}
let gallery = self.gallery_host()?;
self.rt.block_on(async {
let app = gallery.app(self).await?;
gallery.ensure_visibility(self, app, false).await
let app = gallery.app().await?;
gallery.ensure_visibility(app, false).await
})
}
@@ -475,9 +483,9 @@ impl Core {
other => other,
};
self.rt.block_on(async {
let app = gallery.app(self).await?;
let app = gallery.app().await?;
gallery
.ensure_visibility(self, app, matches!(action, GalleryAction::Refresh))
.ensure_visibility(app, matches!(action, GalleryAction::Refresh))
.await?;
match action {
GalleryAction::AuthenticateHidden | GalleryAction::Lock => unreachable!(),
@@ -517,14 +525,14 @@ impl Core {
app.add_drive_folder(uid(&node)?)
.await
.map_err(gallery_error)?;
gallery.ensure_visibility(self, app, true).await?;
gallery.ensure_visibility(app, true).await?;
Ok(done())
}
GalleryAction::Remove { gallery: id } => {
app.forget_drive_gallery(SourceId::new(id).map_err(gallery_error)?)
.await
.map_err(gallery_error)?;
gallery.ensure_visibility(self, app, true).await?;
gallery.ensure_visibility(app, true).await?;
Ok(done())
}
GalleryAction::Refresh => {
@@ -535,7 +543,7 @@ impl Core {
);
app.scan_drive_folder(root).await.map_err(gallery_error)?;
}
gallery.ensure_visibility(self, app, true).await?;
gallery.ensure_visibility(app, true).await?;
Ok(done())
}
GalleryAction::Cover { album, uid: node } => {
@@ -565,7 +573,7 @@ impl Core {
.set_album_settings_at(Some(root), id, settings)
.await
.map_err(gallery_error)?;
gallery.ensure_visibility(self, app, true).await?;
gallery.ensure_visibility(app, true).await?;
Ok(done())
}
}
@@ -576,8 +584,8 @@ impl Core {
let gallery = self.gallery_host()?;
let uid = uid(node)?;
self.rt.block_on(async {
let app = gallery.app(self).await?;
let visibility = gallery.ensure_visibility(self, app, false).await?;
let app = gallery.app().await?;
let visibility = gallery.ensure_visibility(app, false).await?;
let access = if private {
Some(gallery.private_access()?)
} else {
@@ -605,7 +613,7 @@ impl Core {
let access = gallery.private_access()?;
let asset = gallery.asset(&uid(node)?)?;
self.rt.block_on(async {
let app = gallery.app(self).await?;
let app = gallery.app().await?;
let bytes = tokio::time::timeout(Duration::from_secs(30), async {
if let Some(bytes) = app.preview(&asset).await? {
Ok(bytes)
@@ -633,8 +641,8 @@ impl Core {
let gallery = self.gallery_host()?;
let asset = gallery.asset(&uid(node)?)?;
self.rt.block_on(async {
let app = gallery.app(self).await?;
let visibility = gallery.ensure_visibility(self, app, false).await?;
let app = gallery.app().await?;
let visibility = gallery.ensure_visibility(app, false).await?;
let access = if private {
Some(gallery.private_access()?)
} else {
+5 -7
View File
@@ -15,11 +15,10 @@
use std::process::{Child, Command, Stdio};
use std::time::Duration;
use pdfs_store::db::PendingCounts;
use pdfs_core::shutdown::Shutdown;
use pdfs_store::db::{Db, PendingCounts};
use tracing::{debug, warn};
use super::Core;
/// How often the queue is looked at.
const CHECK_EVERY: Duration = Duration::from_secs(5);
@@ -29,11 +28,10 @@ fn sendable(counts: &PendingCounts) -> i64 {
}
/// Run until the daemon stops, holding the inhibitor while changes wait.
pub(crate) fn run(core: Core) {
pub(crate) fn run(db: &Db, shutdown: &Shutdown) {
let mut held: Option<Child> = None;
loop {
let waiting = core
.db
let waiting = db
.pending_op_counts()
.map(|counts| sendable(&counts))
.unwrap_or(0);
@@ -52,7 +50,7 @@ pub(crate) fn run(core: Core) {
}
_ => {}
}
if !core.shutdown.sleep(CHECK_EVERY) {
if !shutdown.sleep(CHECK_EVERY) {
break;
}
}
+98 -23
View File
@@ -22,6 +22,16 @@ use proton_drive_rs::NodeKind;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use tracing::{debug, info, warn};
use std::sync::Arc;
use fuser::Errno;
use parking_lot::Mutex;
use pdfs_core::CoreResult;
use pdfs_core::shutdown::Shutdown;
use pdfs_store::cache::ContentCache;
use super::link::Link;
use super::transfers::TransferRegistry;
use super::{Core, is_local_uid, node_size, parse_uid};
/// How often the keeper looks for work.
@@ -59,32 +69,76 @@ pub(crate) struct KeptFile {
pub(crate) size: u64,
}
impl Core {
/// Have the keeper check every pin.
pub(crate) fn recheck_all_pins(&self) {
self.pin_work.lock().all = true;
/// What the pin keeper needs from the tree.
pub(crate) trait KeeperHost: Send + Sync {
/// Where `uid` is in the tree: its inode, its parent's, and whether it is
/// a folder.
fn locate(&self, uid: &NodeUid) -> Option<(u64, u64, bool)>;
/// Every file under the folder at `ino`, listing what is not listed yet.
fn pin_subtree_files(&self, ino: u64) -> CoreResult<Vec<u64>>;
/// List the folder at `ino` again if its listing was dropped.
fn ensure_children(&self, ino: u64) -> Result<(), Errno>;
/// The file at `ino`, as a pin keeps it. See [`Core::kept_file`].
fn kept_file(&self, ino: u64) -> Option<KeptFile>;
/// Download a pinned file and keep it.
fn fetch_pinned(&self, uid: &NodeUid, name: &str, mtime: i64, size: u64) -> CoreResult<()>;
}
impl KeeperHost for Core {
fn locate(&self, uid: &NodeUid) -> Option<(u64, u64, bool)> {
let st = self.state();
st.by_uid.get(uid).and_then(|&ino| {
let e = st.entries.get(&ino)?;
Some((ino, e.parent, e.node.is_folder()))
})
}
/// Have the keeper check the pinned file or folder `uid`.
pub(crate) fn recheck_pinned(&self, uid: &NodeUid) {
self.pin_work.lock().nodes.insert(uid.clone());
fn pin_subtree_files(&self, ino: u64) -> CoreResult<Vec<u64>> {
Core::pin_subtree_files(self, ino)
}
fn ensure_children(&self, ino: u64) -> Result<(), Errno> {
Core::ensure_children(self, ino)
}
fn kept_file(&self, ino: u64) -> Option<KeptFile> {
Core::kept_file(self, ino)
}
fn fetch_pinned(&self, uid: &NodeUid, name: &str, mtime: i64, size: u64) -> CoreResult<()> {
Core::fetch_pinned(self, uid, name, mtime, size)
}
}
/// Checks pins again and downloads what is missing or stale (the module
/// documentation says when). Holds the content cache, the transfer list, the
/// link, the stop signal and the queue of work; it reaches the tree through
/// [`KeeperHost`].
pub(crate) struct PinKeeper {
cache: Arc<ContentCache>,
transfers: Arc<TransferRegistry>,
link: Arc<Link>,
shutdown: Arc<Shutdown>,
work: Arc<Mutex<PinWork>>,
host: Arc<dyn KeeperHost>,
}
impl PinKeeper {
/// The keeper's loop, until the daemon stops. Starts with a check of every
/// pin, which catches up on whatever changed while the daemon was down.
///
/// Work that failed waits out a backoff of its own. New work does not wait
/// for it, so a file that keeps failing does not hold up the next change.
pub(crate) fn run_pin_keeper(&self) {
self.recheck_all_pins();
pub(crate) fn run(&self) {
self.work.lock().all = true;
let mut backlog = PinWork::default();
let mut backlog_due = Instant::now();
let mut retry = RETRY_FIRST;
while self.shutdown.sleep(KEEPER_TICK) {
if !self.is_online() {
if !self.link.is_online() {
continue;
}
let mut work = std::mem::take(&mut *self.pin_work.lock());
let mut work = std::mem::take(&mut *self.work.lock());
let retrying = !backlog.is_empty() && Instant::now() >= backlog_due;
if retrying {
work.merge(std::mem::take(&mut backlog));
@@ -128,19 +182,13 @@ impl Core {
if !self.cache.is_pinned(&uid) {
continue;
}
let found = {
let st = self.state();
st.by_uid.get(&uid).and_then(|&ino| {
let e = st.entries.get(&ino)?;
Some((ino, e.parent, e.node.is_folder()))
})
};
let found = self.host.locate(&uid);
let Some((ino, parent, is_folder)) = found else {
debug!(%uid, "pin keeper: pinned node is not in the tree");
continue;
};
if is_folder {
match self.pin_subtree_files(ino) {
match self.host.pin_subtree_files(ino) {
Ok(inos) => files.extend(inos.into_iter().filter(|i| seen.insert(*i))),
Err(e) => {
warn!(%uid, error = %e, "pin keeper: listing a kept folder failed");
@@ -154,7 +202,7 @@ impl Core {
// now, which is what the cached copy is checked against.
if !work.all
&& parent != ino
&& let Err(e) = self.ensure_children(parent)
&& let Err(e) = self.host.ensure_children(parent)
{
warn!(%uid, error = ?e, "pin keeper: listing a kept file's folder failed");
failed.nodes.insert(uid);
@@ -167,7 +215,7 @@ impl Core {
let stale: Vec<KeptFile> = files
.into_iter()
.filter_map(|ino| self.kept_file(ino))
.filter_map(|ino| self.host.kept_file(ino))
.filter(|f| !self.cache.is_cached(&f.uid, f.mtime, f.size))
.collect();
if stale.is_empty() {
@@ -186,7 +234,10 @@ impl Core {
continue;
}
job.detail(file.name.clone());
match self.fetch_pinned(&file.uid, &file.name, file.mtime, file.size) {
match self
.host
.fetch_pinned(&file.uid, &file.name, file.mtime, file.size)
{
Ok(()) => fetched += 1,
Err(e) => {
warn!(uid = %file.uid, error = %e, "pin keeper: download failed");
@@ -203,6 +254,30 @@ impl Core {
);
failed
}
}
impl Core {
/// The pin keeper, with this daemon as its host.
pub(crate) fn pin_keeper(&self) -> PinKeeper {
PinKeeper {
cache: self.cache.clone(),
transfers: self.transfers.clone(),
link: self.link.clone(),
shutdown: self.shutdown.clone(),
work: self.pin_work.clone(),
host: Arc::new(self.clone()),
}
}
/// Have the keeper check every pin.
pub(crate) fn recheck_all_pins(&self) {
self.pin_work.lock().all = true;
}
/// Have the keeper check the pinned file or folder `uid`.
pub(crate) fn recheck_pinned(&self, uid: &NodeUid) {
self.pin_work.lock().nodes.insert(uid.clone());
}
/// The file at `ino`, as a pin keeps it. `None` for a folder, a file this
/// daemon still owes an upload for, or a file whose real size cannot be
@@ -231,7 +306,7 @@ impl Core {
claimed_size.is_none(),
)
};
if is_local_uid(&uid) || self.pending.lock().contains_key(&uid) {
if is_local_uid(&uid) || self.writes.is_queued(&uid) {
return None;
}
let size = match provisional {
File diff suppressed because it is too large. Load diff
+180 -85
View File
@@ -18,6 +18,11 @@ use proton_drive_rs::proton_sdk::api::ResponseCode;
use proton_drive_rs::proton_sdk::error::{ProtonApiError, ProtonError};
use tracing::{debug, info, warn};
use std::sync::Arc;
use pdfs_core::shutdown::Shutdown;
use pdfs_drive::DriveApi;
use crate::{Core, ONLINE_PROBE_MAX, ONLINE_PROBE_MIN};
/// How long a remote call a FUSE handler is waiting on may take before the link
@@ -58,6 +63,11 @@ const IDLE_CHECK: Duration = Duration::from_secs(1);
/// that fires on every change so waiters need not poll.
#[derive(Default)]
pub(crate) struct Link {
/// False while the API is unreachable and we are serving the cached tree.
/// Set by the probe thread; read by front-ends through
/// `Response::Status` so the UI can say so rather than leaving the user to
/// infer it from a wall of EIO.
online: AtomicBool,
lost_at: Mutex<Option<Instant>>,
changed: Condvar,
/// Folders listed from the DB alone while offline, to relist once back.
@@ -74,14 +84,84 @@ pub(crate) struct Link {
}
impl Link {
/// The link of a mount that comes up with Proton refusing its session, or
/// not.
pub(crate) fn starting(session_expired: bool) -> Self {
/// The link of a mount that comes up online or from the cache, with
/// Proton refusing its session or not.
pub(crate) fn starting(online: bool, session_expired: bool) -> Self {
Self {
online: AtomicBool::new(online),
session_expired: AtomicBool::new(session_expired),
..Default::default()
}
}
/// Whether the mount currently believes Proton is reachable.
pub(crate) fn is_online(&self) -> bool {
self.online.load(Ordering::Relaxed)
}
/// Whether Proton refused the session itself, so the mount stays offline
/// until the user signs in again.
pub(crate) fn session_expired(&self) -> bool {
self.session_expired.load(Ordering::Relaxed)
}
/// Flip the mount offline and wake the probe. Only the first caller of an
/// outage logs it; the rest are the same outage.
pub(crate) fn go_offline(&self, what: &str, error: &dyn std::fmt::Display) {
let mut lost_at = self.lost_at.lock();
if self.online.swap(false, Ordering::Relaxed) {
*lost_at = Some(Instant::now());
warn!(during = what, %error,
"lost the connection to Proton; queueing changes until it returns");
self.changed.notify_all();
}
}
/// Flip the mount back online and wake everything waiting for it.
fn go_online(&self) {
let mut lost_at = self.lost_at.lock();
self.online.store(true, Ordering::Relaxed);
match lost_at.take() {
Some(since) => {
info!(
offline_secs = since.elapsed().as_secs(),
"connection to Proton is back"
)
}
None => info!("back online"),
}
self.changed.notify_all();
}
/// Wait up to `budget` for the link to come back. Returns whether it is up.
pub(crate) fn wait_online(&self, budget: Duration, shutdown: &Shutdown) -> bool {
let deadline = Instant::now() + budget;
let mut lost_at = self.lost_at.lock();
while !self.is_online() {
if shutdown.is_stopping() || self.changed.wait_until(&mut lost_at, deadline).timed_out()
{
return self.is_online();
}
}
true
}
/// Wait while the link is up. Returns `false` if the daemon is stopping.
fn wait_offline(&self, shutdown: &Shutdown) -> bool {
let mut lost_at = self.lost_at.lock();
while self.is_online() {
if shutdown.is_stopping() {
return false;
}
self.changed.wait_for(&mut lost_at, IDLE_CHECK);
}
true
}
/// When the current outage began, if the link is down.
fn lost_at(&self) -> Option<Instant> {
*self.lost_at.lock()
}
}
pub(crate) use pdfs_drive::is_network_error;
@@ -154,7 +234,7 @@ fn next_probe_delay(delay: Duration, outage: Duration) -> Duration {
impl Core {
/// Whether the mount currently believes Proton is reachable.
pub(crate) fn is_online(&self) -> bool {
self.online.load(Ordering::Relaxed)
self.link.is_online()
}
/// Whether a namespace change through the mount goes to Drive inside the
@@ -189,7 +269,7 @@ impl Core {
/// Whether Proton refused the session itself, so nothing reaches it until
/// the user signs in again.
pub(crate) fn session_expired(&self) -> bool {
self.link.session_expired.load(Ordering::Relaxed)
self.link.session_expired()
}
/// Report a failed remote call. Returns whether it failed for want of a
@@ -233,65 +313,14 @@ impl Core {
self.mark_offline(what, error);
}
/// Flip the mount offline and wake the probe. Only the first caller of an
/// outage logs it; the rest are the same outage.
/// Flip the mount offline and wake the probe. See [`Link::go_offline`].
pub(crate) fn mark_offline(&self, what: &str, error: &dyn std::fmt::Display) {
let mut lost_at = self.link.lost_at.lock();
if self.online.swap(false, Ordering::Relaxed) {
*lost_at = Some(Instant::now());
warn!(during = what, %error,
"lost the connection to Proton; queueing changes until it returns");
self.link.changed.notify_all();
}
}
/// Flip the mount back online, wake everything waiting for it, and let the
/// queue drain.
fn mark_online(&self) {
{
let mut lost_at = self.link.lost_at.lock();
self.online.store(true, Ordering::Relaxed);
match lost_at.take() {
Some(since) => {
info!(
offline_secs = since.elapsed().as_secs(),
"connection to Proton is back"
)
}
None => info!("back online"),
}
self.link.changed.notify_all();
}
self.relist_offline_listings();
// Anything written while offline is queued and waiting on exactly this,
// including ops that failed on the way down and are sitting out a
// backoff sized for a server that keeps refusing. Ops Drive refused
// keep theirs: the link was not why.
if let Err(e) = self.db.retry_unrefused_ops_now(crate::now_millis()) {
warn!(error = %e, "moving backed-off ops up after a reconnect failed");
}
self.wake_drain();
// Downloads for pins failed while the link was down, and the events
// that would have named the files are behind us (`docs/BUGS.md` B282).
self.recheck_all_pins();
self.link.go_offline(what, error);
}
/// Wait up to `budget` for the link to come back. Returns whether it is up.
pub(crate) fn wait_online(&self, budget: Duration) -> bool {
let deadline = Instant::now() + budget;
let mut lost_at = self.link.lost_at.lock();
while !self.is_online() {
if self.shutdown.is_stopping()
|| self
.link
.changed
.wait_until(&mut lost_at, deadline)
.timed_out()
{
return self.is_online();
}
}
true
self.link.wait_online(budget, &self.shutdown)
}
/// Wait out `interval` before a background poll of Proton, and while the
@@ -312,29 +341,103 @@ impl Core {
}
}
/// The online probe, with this daemon as its host.
pub(crate) fn online_probe(&self) -> OnlineProbe {
OnlineProbe {
link: self.link.clone(),
drive: self.drive.clone(),
rt: self.rt.clone(),
shutdown: self.shutdown.clone(),
host: Arc::new(self.clone()),
}
}
/// The link is back: let everything that waited on it go. Anything
/// written while offline is queued and waiting on exactly this, including
/// ops that failed on the way down and are sitting out a backoff sized
/// for a server that keeps refusing. Ops Drive refused keep theirs: the
/// link was not why.
fn after_reconnect(&self) {
self.relist_offline_listings();
if let Err(e) = self.db.retry_unrefused_ops_now(crate::now_millis()) {
warn!(error = %e, "moving backed-off ops up after a reconnect failed");
}
self.wake_drain();
// Downloads for pins failed while the link was down, and the events
// that would have named the files are behind us (`docs/BUGS.md` B282).
self.recheck_all_pins();
}
}
/// What the online probe needs from the rest of the daemon.
pub(crate) trait LinkHost: Send + Sync {
/// Drive answered with the My Files root: store it in the tree and the
/// database before the mount goes online.
fn refresh_root(&self, root: &proton_drive_rs::Node);
/// The mount is online again: relist, retry and refetch what waited.
fn reconnected(&self);
/// Proton refused the session.
fn session_refused(&self, what: &str, error: &ProtonError);
/// Repair the primary root's share id, which an offline start could not.
fn repair_share_id(&self);
}
impl LinkHost for Core {
fn refresh_root(&self, root: &proton_drive_rs::Node) {
{
let root_ino = self.root_ino();
let mut st = self.state();
if let Some(e) = st.entries.get_mut(&root_ino) {
e.node = root.clone();
}
}
if let Err(e) = self.db.upsert_node(root) {
warn!(error = %e, "refresh root after reconnect failed");
}
}
fn reconnected(&self) {
self.after_reconnect();
}
fn session_refused(&self, what: &str, error: &ProtonError) {
self.mark_session_expired(what, error);
}
fn repair_share_id(&self) {
self.repair_primary_share_id(&self.primary_root_uid);
}
}
/// Watches the link for the life of the mount and probes it back while it is
/// down. Holds the link, Drive, the runtime and the stop signal; it reaches
/// the tree and the queue through [`LinkHost`].
pub(crate) struct OnlineProbe {
link: Arc<Link>,
drive: Arc<dyn DriveApi>,
rt: tokio::runtime::Handle,
shutdown: Arc<Shutdown>,
host: Arc<dyn LinkHost>,
}
impl OnlineProbe {
/// Watch the link for the life of the mount: sleep while it is up, and
/// probe it back while it is down.
///
/// A mount that started from the cache is down from the first moment; one
/// that started online goes down when [`Core::mark_offline`] says so.
pub(crate) fn run_online_probe(&self) {
/// that started online goes down when [`Link::go_offline`] says so.
pub(crate) fn run(&self) {
// Only an offline start never had a chance to repair its share id.
let mut repair_share_id = !self.is_online();
let mut repair_share_id = !self.link.is_online();
loop {
{
let mut lost_at = self.link.lost_at.lock();
while self.is_online() {
if self.shutdown.is_stopping() {
return;
}
self.link.changed.wait_for(&mut lost_at, IDLE_CHECK);
}
if !self.link.wait_offline(&self.shutdown) {
return;
}
if !self.probe_until_online() {
return;
}
if std::mem::take(&mut repair_share_id) {
self.repair_primary_share_id(&self.primary_root_uid);
self.host.repair_share_id();
}
}
}
@@ -345,7 +448,7 @@ impl Core {
/// A refused session is not probed: every probe would be refused the same
/// way, forever (issue #35). The thread waits for the stop instead.
fn probe_until_online(&self) -> bool {
let started = self.link.lost_at.lock().unwrap_or_else(Instant::now);
let started = self.link.lost_at().unwrap_or_else(Instant::now);
let mut delay = if started.elapsed() < YOUNG_OUTAGE {
PROBE_AFTER_DROP
} else {
@@ -355,7 +458,7 @@ impl Core {
if !self.shutdown.sleep(delay) {
return false;
}
if self.session_expired() {
if self.link.session_expired() {
delay = ONLINE_PROBE_MAX;
continue;
}
@@ -367,20 +470,12 @@ impl Core {
});
match probe {
Ok(root) => {
{
let root_ino = self.root_ino();
let mut st = self.state();
if let Some(e) = st.entries.get_mut(&root_ino) {
e.node = root.clone();
}
}
if let Err(e) = self.db.upsert_node(&root) {
warn!(error = %e, "refresh root after reconnect failed");
}
self.mark_online();
self.host.refresh_root(&root);
self.link.go_online();
self.host.reconnected();
return true;
}
Err(e) if session_revoked(&e) => self.mark_session_expired("online probe", &e),
Err(e) if session_revoked(&e) => self.host.session_refused("online probe", &e),
Err(e) => {
debug!(error = %e, ?delay, "online probe failed; still offline");
delay = next_probe_delay(delay, started.elapsed());
+20 -26
View File
@@ -32,10 +32,7 @@ impl Core {
None
};
freshness.is_none_or(|key| {
!listing_needs_refresh(
self.online.load(Ordering::Relaxed),
self.shared_listing_stale(&key),
)
!listing_needs_refresh(self.is_online(), self.shared_listing_stale(&key))
})
}
@@ -58,16 +55,10 @@ impl Core {
/// lock: no site in the daemon holds `pending` and `state` at once, and this
/// is not the place to become the first.
pub(super) fn stamp_pending_sizes(&self, nodes: &mut [Node]) {
let sizes: HashMap<NodeUid, u64> = {
let pending = self.pending.lock();
if pending.is_empty() {
return;
}
pending
.iter()
.map(|(uid, pr)| (uid.clone(), pr.meta.len))
.collect()
};
let sizes = self.writes.queued_sizes();
if sizes.is_empty() {
return;
}
apply_pending_sizes(nodes, &sizes);
}
@@ -167,7 +158,7 @@ impl Core {
// Before the lock: a DB row carries the size the server last
// sealed, which a queued write is ahead of (B11).
self.stamp_pending_sizes(&mut nodes);
let hidden = self.hidden.lock().clone();
let hidden = self.writes.hidden();
let mut st = self.state();
if st.children.contains_key(&ino) {
return Ok(());
@@ -235,14 +226,11 @@ impl Core {
}
let primary_root =
is_primary_root_listing(self.primary, &folder_uid, &self.primary_root_uid);
is_primary_root_listing(self.session.primary, &folder_uid, &self.primary_root_uid);
let foreign = !self.is_own_or_virtual(&folder_uid) && !is_local_uid(&folder_uid);
let foreign_key = foreign.then(|| Self::shared_folder_freshness_key(&folder_uid));
let refresh_foreign = foreign_key.as_deref().is_some_and(|key| {
listing_needs_refresh(
self.online.load(Ordering::Relaxed),
self.shared_listing_stale(key),
)
listing_needs_refresh(self.is_online(), self.shared_listing_stale(key))
});
if cached && !refresh_foreign {
if primary_root {
@@ -334,7 +322,7 @@ impl Core {
// Same as the DB path above: the remote's size for a file with a write
// still queued is the pre-write one (B11).
self.stamp_pending_sizes(&mut nodes);
let hidden = self.hidden.lock().clone();
let hidden = self.writes.hidden();
let mut filtered_nodes: Vec<Node> = nodes
.into_iter()
.filter(|node| node_visible(node, &folder_uid, &hidden))
@@ -446,11 +434,17 @@ impl Core {
///
/// Metadata only: a thumbnail path is attached for photos whose thumbnail is
/// already cached, and nothing is downloaded here — the front-end pulls the
/// thumbnails it actually paints via [`Core::photo_thumbs`].
/// thumbnails it actually paints via [`Photos::photo_thumbs`](crate::photos::Photos::photo_thumbs).
pub(super) fn listing_stale(&self, key: &str, ttl: Duration) -> bool {
match self.db.state_i64(key).ok().flatten() {
Some(ms) => now_ms().saturating_sub(ms) >= ttl.as_millis() as i64,
None => true,
}
listing_stale(&self.db, key, ttl)
}
}
/// Whether the listing stamped under `key` is older than `ttl`, or was never
/// stamped.
pub(crate) fn listing_stale(db: &Db, key: &str, ttl: Duration) -> bool {
match db.state_i64(key).ok().flatten() {
Some(ms) => now_ms().saturating_sub(ms) >= ttl.as_millis() as i64,
None => true,
}
}
+46 -18
View File
@@ -3,7 +3,31 @@
use super::*;
impl Core {
/// Runs `VACUUM` and the deep integrity check as jobs, one at a time, and
/// keeps the last check's findings. Holds the database, the transfer list for
/// the job's entry, and the board the job runs on.
#[derive(Clone)]
pub(crate) struct Maintenance {
db: Arc<Db>,
transfers: Arc<TransferRegistry>,
services: pdfs_core::lifecycle::ServiceBoard,
state: Arc<Mutex<MaintenanceState>>,
}
impl Maintenance {
pub(crate) fn new(
db: Arc<Db>,
transfers: Arc<TransferRegistry>,
services: pdfs_core::lifecycle::ServiceBoard,
) -> Self {
Self {
db,
transfers,
services,
state: Arc::default(),
}
}
/// Start a background `VACUUM`, or refuse because maintenance is already
/// running.
///
@@ -11,9 +35,9 @@ impl Core {
/// 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<()> {
pub(crate) fn start_vacuum(&self) -> CoreResult<()> {
{
let mut m = self.maintenance.lock();
let mut m = self.state.lock();
if m.running {
return Err(CoreError::conflict(
"database maintenance is already running",
@@ -21,12 +45,12 @@ impl Core {
}
m.running = true;
}
let core = self.clone();
std::thread::spawn(move || {
let job = core.transfers.begin_job("Compacting the cache database");
let this = self.clone();
if let Err(error) = self.services.spawn_job("pdfs-vacuum", move || {
let job = this.transfers.begin_job("Compacting the cache database");
job.detail("Rewriting the database file");
let started = Instant::now();
match core.db.vacuum() {
match this.db.vacuum() {
Ok(outcome) => info!(
freed_bytes = outcome.freed_bytes(),
before_bytes = outcome.before_bytes,
@@ -37,8 +61,10 @@ impl Core {
),
Err(e) => warn!(error = %e, "vacuum failed"),
}
core.maintenance.lock().running = false;
});
this.state.lock().running = false;
}) {
tracing::warn!(%error, "could not start pdfs-vacuum");
}
Ok(())
}
@@ -49,8 +75,8 @@ impl Core {
/// `(_, 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();
pub(crate) fn start_or_read_integrity_check(&self) -> (Vec<String>, bool, bool) {
let mut m = self.state.lock();
if let Some(problems) = m.integrity.clone() {
return (problems, true, m.running);
}
@@ -60,13 +86,13 @@ impl Core {
m.running = true;
drop(m);
let core = self.clone();
std::thread::spawn(move || {
let job = core
let this = self.clone();
if let Err(error) = self.services.spawn_job("pdfs-integrity-check", move || {
let job = this
.transfers
.begin_background_job("Checking the cache database");
job.detail("Verifying every page");
let problems = match core.db.integrity_check() {
let problems = match this.db.integrity_check() {
Ok(problems) => problems,
Err(e) => vec![format!("integrity check failed: {e:?}")],
};
@@ -75,10 +101,12 @@ impl Core {
} else {
warn!(problems = problems.len(), "cache database integrity check");
}
let mut m = core.maintenance.lock();
let mut m = this.state.lock();
m.integrity = Some(problems);
m.running = false;
});
}) {
tracing::warn!(%error, "could not start pdfs-integrity-check");
}
(Vec::new(), false, true)
}
}
@@ -90,7 +118,7 @@ impl Core {
/// 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 {
struct MaintenanceState {
/// A vacuum or integrity check is running right now.
running: bool,
/// Findings of the most recent completed deep check. `None` means none has
+140 -168
View File
@@ -1,7 +1,7 @@
//! Mount lifecycle and background-service orchestration.
use super::*;
use pdfs_core::lifecycle::{ServiceBoard, Services, Wake};
use pdfs_core::lifecycle::{Service, ServiceBoard, Services};
/// Why a [`mount`] call returned. Lets the daemon decide whether to exit (clean
/// shutdown) or remount (the mount went away under it).
@@ -351,16 +351,17 @@ pub(super) fn spawn_session(
clear_stale_mount(mountpoint);
info!(mountpoint = %mountpoint.display(), "mounting Proton Drive location");
let fs = ProtonFs::new(core.clone(), root);
if core.primary {
if core.session.primary {
// Only My Files rehydrates the daemon-wide node cache, once. A
// secondary mount shares the tree it fills.
core.hydrate();
}
let session = Session::new(fs, mountpoint, &config)?.spawn()?;
let _ = core
.session
.notifier
.set(KernelChannel::new(session.notifier(), core.root_ino()));
core.session_live.store(true, Ordering::Release);
core.session.session_live.store(true, Ordering::Release);
Ok(session)
}
@@ -488,13 +489,22 @@ pub(crate) fn mount_with(
// handlers can trigger reconciles.
let (sync_tx, sync_rx) = std::sync::mpsc::channel::<sync::SyncMsg>();
let paused_until = pause::load_paused_until(&db);
let pause = pause::SyncPause::load(db.clone());
let events: Arc<events::EventHub> = Arc::default();
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 gallery = gallery_session.map(|session| {
Arc::new(super::gallery::Gallery::new(
gallery_dir,
session,
client.clone(),
events.clone(),
db.clone(),
))
});
let cache = Arc::new(cache);
let shutdown = Arc::new(crate::shutdown::Shutdown::default());
let transfers = TransferRegistry::new();
let services = ServiceBoard::default();
let sync = sync::SyncParts {
store: db.clone(),
drive: drive.clone(),
@@ -511,46 +521,54 @@ pub(crate) fn mount_with(
abandon: Arc::default(),
events_read_at: Arc::new(AtomicI64::new(0)),
};
let state = Arc::new(Ranked::new(
Rank::State,
State::new(db.clone(), share_access),
));
let sharing = super::sharing::Sharing::new(
client.clone(),
drive.clone(),
rt.clone(),
cache.clone(),
transfers.clone(),
state.clone(),
);
let core = Core {
drive,
drive_calls,
client,
gallery,
rt: rt.clone(),
maintenance: Arc::new(Mutex::new(Default::default())),
maintenance: super::maintenance::Maintenance::new(
db.clone(),
transfers.clone(),
services.clone(),
),
primary_root_uid: root.uid.clone(),
primary: true,
state: Arc::new(Ranked::new(
Rank::State,
State::new(db.clone(), share_access),
)),
root: Arc::new(OnceLock::new()),
state: state.clone(),
cache,
reads: super::reads::ReadState::new(),
workers: Arc::new(Workers::new(FUSE_WORKERS)?),
db,
online: Arc::new(AtomicBool::new(online)),
link: Arc::new(link::Link::starting(start == Start::SessionExpired)),
sync_paused_until: Arc::new(AtomicI64::new(paused_until)),
pending: Arc::new(Mutex::new(HashMap::new())),
hidden: Arc::new(Mutex::new(HashSet::new())),
link: Arc::new(link::Link::starting(online, start == Start::SessionExpired)),
pause,
drain: super::drain::DrainState::new(),
pin_work: Arc::new(Mutex::new(Default::default())),
sizes: super::sizes::SizeState::new(),
trash: super::trash::TrashState::new(),
trash_jobs: super::trash::TrashState::new(),
shared: super::shared::SharedState::new(),
quota_cache: super::sharing::QuotaCache::new(),
quota: super::quota::QuotaCache::new(),
sharing,
sweep: super::sweep::SweepState::new(sweep_mode),
writes: super::writes::WriteState::new(),
session: super::session::SessionCells::new(),
shutdown,
services: ServiceBoard::default(),
services: services.clone(),
photo_jobs: super::photos::PhotoJobs::new(),
local_first,
self_changes: Arc::new(Mutex::new(HashMap::new())),
notifier: Arc::new(OnceLock::new()),
session_live: Arc::new(AtomicBool::new(false)),
transfers,
sync,
events: Arc::new(Default::default()),
events,
indexing: Arc::new(AtomicBool::new(false)),
pending_probe: Arc::default(),
mounts: Arc::new(Mutex::new(SecondaryMountRegistry::default())),
@@ -563,14 +581,17 @@ pub(crate) fn mount_with(
// Writes queued by a previous run (or left behind by a crash) are still owed
// an upload, and reads must be served from their staged blobs until they land.
core.hydrate_pending();
core.recovery().hydrate_pending();
// A replacing rename a stop cut off: its victim comes back, or its end
// state stands. After `hydrate_pending`, which hides queued trashes.
core.recovery().settle_replaces();
// Then the writes that were fsynced but never closed, which the cache moved
// aside at open. After `hydrate_pending`, so a recovered partial write can
// see an already-queued write to the same node.
core.recover_fsynced_writes();
core.recovery().recover_fsynced_writes();
// And finally the staged blobs neither of those accounts for: bytes a
// failed release left behind with nothing pointing at them.
core.reconcile_staging();
core.recovery().reconcile_staging();
// Several drain workers over one queue. One thread meant a single large
// upload held every queued rename, trash and small write behind it for as
// long as it ran; the claim column (`Db::claim_next_due_op`) keeps the
@@ -582,93 +603,49 @@ pub(crate) fn mount_with(
// 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 = Services::new(core.services.clone());
for worker in 0..DRAIN_WORKERS {
let drain_core = core.clone();
// 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)?;
let mut list: Vec<Box<dyn Service>> = Vec::new();
for index in 0..DRAIN_WORKERS {
list.push(Box::new(services::DrainWorker {
core: core.clone(),
index,
}));
}
// 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.
// 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);
}
// Reconcile leftover `(sync-conflict …)` copies: drop the ones that turned
// out identical to the live file, surface the ones that genuinely diverge.
// Its own thread — it enumerates and trashes, and must never block a FUSE call.
list.push(Box::new(services::SyncEngine {
syncer: core.syncer(),
tx: core.sync.tx.clone(),
rx: sync_rx,
}));
// `Off` skips the thread entirely rather than starting an idle one, so the
// setting is verifiable from the outside (`ls /proc/<pid>/task/*/comm`).
if sweep_mode == SweepMode::Off {
info!("conflict sweep disabled by configuration");
} else {
info!(mode = ?sweep_mode, "conflict sweep enabled");
let sweep_core = core.clone();
let spawned = workers.spawn("pdfs-conflict-sweep", None, move || {
sweep_core.run_conflict_sweep_loop()
});
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
list.push(Box::new(services::ConflictSweep(core.sweeper())));
}
// Watch the link for the life of the mount: a mount from the cache waits for
// the network to come back, and an online one can lose it at any moment and
// must notice it coming back just the same.
{
let probe_core = core.clone();
let spawned = workers.spawn("pdfs-online-probe", None, move || {
probe_core.run_online_probe()
});
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
}
// Keep pinned files on this computer through changes made elsewhere, and
// fetch the ones a failed or missed download left out (`docs/BUGS.md`
// B282). Its own thread: a check lists folders and downloads files.
{
let keeper_core = core.clone();
let spawned = workers.spawn("pdfs-pin-keeper", None, move || {
keeper_core.run_pin_keeper()
});
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
}
// Keep the launcher prompt's "This computer" index fresh. Its own thread:
// the walk is I/O-heavy and must never sit in front of a FUSE callback.
list.push(Box::new(services::OnlineProbe(core.online_probe())));
list.push(Box::new(services::PinKeeper(core.pin_keeper())));
if matches!(host, Host::Daemon) {
if let Some(gallery) = &core.gallery {
rt.spawn(gallery.clone().poll(core.clone()));
}
let db = core.db.clone();
let indexing = core.indexing.clone();
let transfers = core.transfers.clone();
let mountpoint = mountpoint.to_path_buf();
let shutdown = core.shutdown.clone();
let spawned = workers.spawn("pdfs-localindex", None, move || {
run_local_index(db, indexing, transfers, mountpoint, shutdown)
});
keep_or_abandon(&core, control_socket, &mut workers, spawned)?;
list.push(Box::new(services::LocalIndex {
db: core.db.clone(),
indexing: core.indexing.clone(),
transfers: core.transfers.clone(),
mountpoint: mountpoint.to_path_buf(),
shutdown: core.shutdown.clone(),
}));
}
for service in list {
let started = workers.start(service);
keep_or_abandon(&core, control_socket, &mut workers, started)?;
}
if matches!(host, Host::Daemon)
&& let Some(gallery) = &core.gallery
{
workers.spawn_task(&rt, "pdfs-gallery", gallery.clone().poll());
}
// A timed pause persisted by an earlier run still has to end on time.
if let Some(until) = core.pause.deadline() {
core.arm_pause_timer(until);
}
// Bind the control socket before the FUSE session takes over the thread. A
@@ -708,23 +685,14 @@ pub(crate) fn mount_with(
// mid-transfer can abort it rather than block `join` (see `abort_fuse_connection`).
let main_conn = fuse_connection_id(mountpoint);
{
let control_core = core.clone();
let username = username.clone();
let mountpoint = mountpoint.to_path_buf();
// 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)
}) {
let control = services::ControlListener {
core: core.clone(),
username: username.clone(),
mountpoint: mountpoint.to_path_buf(),
listener,
socket: control_socket.to_path_buf(),
};
match workers.start(Box::new(control)) {
Ok(()) => {}
Err(error) => {
// A failure here abandons the mount, so the background threads
@@ -736,7 +704,7 @@ pub(crate) fn mount_with(
warn!(id, error = %unmount_error, "secondary teardown after control startup failure failed");
}
}
if let Err(unmount_error) = teardown_session(&core.session_live, || {
if let Err(unmount_error) = teardown_session(&core.session.session_live, || {
umount_session_unblocked(bg, main_conn)
}) {
warn!(error = %unmount_error, "unmount after control startup failure failed");
@@ -746,34 +714,19 @@ pub(crate) fn mount_with(
}
}
}
// Publishes what changes without one place to publish it from (status,
// transfers, sync progress) to the front-ends subscribed on that socket.
{
let sampler_core = core.clone();
let username = username.clone();
let mountpoint = mountpoint.to_path_buf();
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.
warn!(error = %error, "could not start the event sampler");
}
}
// The supervisor watches the pool and answers the systemd watchdog. Started
// after the listener, because its liveness probe is a round trip over that
// socket.
{
let supervisor_core = core.clone();
let socket = control_socket.to_path_buf();
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.
warn!(error = %error, "could not start the daemon supervisor");
}
}
// The supervisor's liveness probe is a round trip over the control socket,
// so it starts after the listener. Both are optional.
let sampler = services::EventSampler {
core: core.clone(),
username: username.clone(),
mountpoint: mountpoint.to_path_buf(),
};
let watchdog = services::Supervisor {
core: core.clone(),
socket: control_socket.to_path_buf(),
};
start_late(&mut workers, Box::new(sampler));
start_late(&mut workers, Box::new(watchdog));
// The mount is live and the control socket answers: this is the moment the
// unit is actually usable, which is what `Type=notify` reports. Whatever
// failure an earlier attempt recorded for the front ends is over.
@@ -798,31 +751,41 @@ pub(crate) fn mount_with(
}
}
};
rt.spawn(run_event_sync(core.drive.clone(), scope, core.clone()));
// Services rather than bare tasks: a stop aborts them. Before, they ran
// until the runtime went away, which on a stop is when the process exits.
workers.spawn_task(
&rt,
"pdfs-event-sync",
run_event_sync(core.drive.clone(), scope, core.clone()),
);
// The photos volume has its own event stream; without it the gallery only
// learns about a phone-side deletion when the timeline goes stale.
rt.spawn(run_photos_event_sync(core.clone()));
workers.spawn_task(
&rt,
"pdfs-photo-events",
run_photos_event_sync(core.clone()),
);
// Not in a simulation: `client` there reaches no API, and the thread, still
// waiting on it after the stop, held the database a test opens next.
if online && matches!(host, Host::Daemon) {
let repair_core = core.clone();
let root_uid = core.primary_root_uid.clone();
if let Err(error) = std::thread::Builder::new()
.name("pdfs-share-id".into())
.spawn(move || repair_core.repair_primary_share_id(&root_uid))
{
if let Err(error) = core.services.spawn_job("pdfs-share-id", move || {
repair_core.repair_primary_share_id(&root_uid)
}) {
warn!(%error, "start My Files share-id repair failed");
}
}
// Hold off a shutdown while changes exist only here (B66). Only the real
// daemon: a simulation's queue is not the user's data.
if matches!(host, Host::Daemon) {
let inhibit_core = core.clone();
if let Err(error) = workers.spawn("pdfs-inhibit", None, move || {
crate::inhibit::run(inhibit_core)
}) {
warn!(%error, "start the shutdown inhibitor failed");
}
start_late(
&mut workers,
Box::new(services::Inhibitor {
db: core.db.clone(),
shutdown: core.shutdown.clone(),
}),
);
}
// Stop signals (SIGTERM from `systemctl --user stop`, SIGINT from Ctrl-C)
@@ -844,7 +807,7 @@ pub(crate) fn mount_with(
Ok(()) => {
info!("stop requested; unmounting");
core.mounts.lock().close();
if let Err(e) = teardown_session(&core.session_live, || {
if let Err(e) = teardown_session(&core.session.session_live, || {
umount_session_unblocked(bg, main_conn)
}) {
warn!(error = %e, "umount_and_join failed");
@@ -856,7 +819,7 @@ pub(crate) fn mount_with(
{
info!("unmounting to resume the stored session");
core.mounts.lock().close();
if let Err(e) = teardown_session(&core.session_live, || {
if let Err(e) = teardown_session(&core.session.session_live, || {
umount_session_unblocked(bg, main_conn)
}) {
warn!(error = %e, "umount_and_join failed");
@@ -867,7 +830,7 @@ pub(crate) fn mount_with(
if bg.guard.is_finished() {
info!("mount ended externally");
core.mounts.lock().close();
if let Err(e) = teardown_session(&core.session_live, || bg.join()) {
if let Err(e) = teardown_session(&core.session.session_live, || bg.join()) {
warn!(error = %e, "session join failed");
}
break MountOutcome::Unmounted;
@@ -876,7 +839,7 @@ pub(crate) fn mount_with(
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
// Signal task gone (failed to install); fall back to join.
core.mounts.lock().close();
let _ = teardown_session(&core.session_live, || bg.join());
let _ = teardown_session(&core.session.session_live, || bg.join());
break MountOutcome::Unmounted;
}
}
@@ -971,6 +934,15 @@ fn abandon_workers(core: &Core, control_socket: &Path, workers: Services) {
halt_workers(core, control_socket, workers);
}
/// Start a service once the session is live. Past that point a failure no
/// longer abandons the mount, so even a required one is only logged.
fn start_late(workers: &mut Services, service: Box<dyn Service>) {
let name = service.name();
if let Err(error) = workers.start(service) {
warn!(service = name, %error, "service did not start");
}
}
/// Keep a worker the mount just spawned, or, if the spawn failed, stop the
/// ones already running and hand the error back.
fn keep_or_abandon(
+92 -45
View File
@@ -51,41 +51,106 @@ fn store_folder_paused(db: &Db, id: i64, paused: bool) -> pdfs_core::Result<()>
/// A pause with no end time: it lasts until the user resumes.
pub(crate) const PAUSED_INDEFINITELY: i64 = i64::MAX;
/// The persisted pause, or `0` when there is none (or it cannot be read — a
/// broken state row must not keep sync paused forever).
pub(crate) fn load_paused_until(db: &Db) -> i64 {
match db.state_i64(PAUSED_UNTIL_KEY) {
Ok(Some(until)) => until,
Ok(None) => 0,
Err(error) => {
warn!(%error, "reading the sync pause failed; treating sync as running");
0
/// The global pause: when it ends, in memory and in the database.
///
/// The value is the Unix second the pause ends, [`PAUSED_INDEFINITELY`] for
/// "until resumed", or `0` when sync runs. Only this type reads or writes it;
/// the rest of the daemon asks [`Core::sync_paused`].
#[derive(Clone)]
pub(crate) struct SyncPause {
until: Arc<AtomicI64>,
db: Arc<Db>,
}
impl SyncPause {
/// The persisted pause, or none when there is no row or it cannot be read:
/// a broken state row must not keep sync paused forever.
pub(crate) fn load(db: Arc<Db>) -> Self {
let until = match db.state_i64(PAUSED_UNTIL_KEY) {
Ok(Some(until)) => until,
Ok(None) => 0,
Err(error) => {
warn!(%error, "reading the sync pause failed; treating sync as running");
0
}
};
Self {
until: Arc::new(AtomicI64::new(until)),
db,
}
}
fn is_paused(&self) -> bool {
paused_at(self.until.load(Ordering::Relaxed), now_secs())
}
/// `None` when not paused, `Some(None)` when paused until resumed,
/// `Some(Some(t))` when it ends at Unix second `t`.
fn status(&self) -> Option<Option<i64>> {
let until = self.until.load(Ordering::Relaxed);
match paused_at(until, now_secs()) {
false => None,
true if until == PAUSED_INDEFINITELY => Some(None),
true => Some(Some(until)),
}
}
/// The end of a timed pause still in force, which needs a timer.
pub(crate) fn deadline(&self) -> Option<i64> {
self.status().flatten()
}
/// Persist `value`, then take it. A pause that cannot be saved is not
/// taken, so what the user sees never outlives a restart by surprise.
fn store(&self, value: i64) -> Result<(), CoreError> {
let persisted = match value {
0 => self.db.clear_state(PAUSED_UNTIL_KEY),
value => self.db.set_state_i64(PAUSED_UNTIL_KEY, value),
};
if let Err(error) = persisted {
return Err(CoreError::internal(format!(
"saving the sync pause: {error}"
)));
}
self.until.store(value, Ordering::Relaxed);
Ok(())
}
/// End the pause that lasts until `until`, if it is still the one in
/// force. Returns whether it was: a later pause or resume replaced it
/// otherwise, and the timer that asks has nothing to do.
fn expire(&self, until: i64) -> bool {
if self
.until
.compare_exchange(until, 0, Ordering::Relaxed, Ordering::Relaxed)
.is_err()
{
return false;
}
if let Err(error) = self.db.clear_state(PAUSED_UNTIL_KEY) {
warn!(%error, "clearing an expired sync pause failed");
}
true
}
}
/// Whether a pause lasting until `until` is still in force at `now` (both Unix
/// seconds). `0` is "not paused".
pub(crate) fn paused_at(until: i64, now: i64) -> bool {
fn paused_at(until: i64, now: i64) -> bool {
until != 0 && now < until
}
impl Core {
/// True while the user has sync paused.
pub(crate) fn sync_paused(&self) -> bool {
paused_at(self.sync_paused_until.load(Ordering::Relaxed), now_secs())
self.pause.is_paused()
}
/// The pause's end, for status reporting: `None` when not paused,
/// `Some(None)` when paused until resumed, `Some(Some(t))` when it ends at
/// Unix second `t`.
pub(crate) fn sync_pause(&self) -> Option<Option<i64>> {
let until = self.sync_paused_until.load(Ordering::Relaxed);
match paused_at(until, now_secs()) {
false => None,
true if until == PAUSED_INDEFINITELY => Some(None),
true => Some(Some(until)),
}
self.pause.status()
}
/// Pause sync until Unix second `until` (`None`: until resumed), or resume
@@ -103,16 +168,7 @@ impl Core {
}
(true, Some(until)) => until,
};
let persisted = match value {
0 => self.db.clear_state(PAUSED_UNTIL_KEY),
value => self.db.set_state_i64(PAUSED_UNTIL_KEY, value),
};
if let Err(error) = persisted {
return Err(CoreError::internal(format!(
"saving the sync pause: {error}"
)));
}
self.sync_paused_until.store(value, Ordering::Relaxed);
self.pause.store(value)?;
match value {
0 => {
info!("sync resumed");
@@ -182,24 +238,15 @@ impl Core {
pub(crate) fn arm_pause_timer(&self, until: i64) {
let core = self.clone();
let wait = Duration::from_secs(until.saturating_sub(now_secs()).max(0) as u64);
let spawned = std::thread::Builder::new()
.name("pdfs-pause".into())
.spawn(move || {
if !core.shutdown.sleep(wait) {
return;
}
if core
.sync_paused_until
.compare_exchange(until, 0, Ordering::Relaxed, Ordering::Relaxed)
.is_ok()
{
if let Err(error) = core.db.clear_state(PAUSED_UNTIL_KEY) {
warn!(%error, "clearing an expired sync pause failed");
}
info!("sync pause ended");
core.resume_sync_work();
}
});
let spawned = self.services.spawn_job("pdfs-pause", move || {
if !core.shutdown.sleep(wait) {
return;
}
if core.pause.expire(until) {
info!("sync pause ended");
core.resume_sync_work();
}
});
if let Err(error) = spawned {
// The drain and the reconcile still read the clock, so the pause
// still ends — just at the next idle poll instead of on time.
+135 -17
View File
@@ -31,11 +31,20 @@ use proton_drive_rs::proton_sdk::ids::NodeUid;
use proton_drive_rs::{NodeKind, PhotoTag, PhotoTagsUpdate, Thumbnail, ThumbnailType};
use tracing::{debug, info, warn};
use super::drive::RevisionRead;
use super::ContentCache;
use super::drive::{DriveApi, RevisionRead};
use super::events::EventHub;
use super::shutdown::Shutdown;
use super::transfers::{CountingWriter, TransferRegistry};
use super::{
Core, PHOTOS_AVAILABLE, PHOTOS_SYNCED_MS, TIMELINE_ENRICH_CHUNK, ThumbnailMissCaches,
WriteAuthority, link, node_size, now_ms, parse_uid,
};
use pdfs_core::control::TransferDirection;
use pdfs_core::control::{ActivityKind, DirEntry};
use pdfs_core::lifecycle::ServiceBoard;
use proton_drive_rs::proton_sdk::error::ProtonError;
use proton_drive_rs::{ProtonDriveClient, ProtonPhotosClient};
/// Longest edge, in px, of a thumbnail generated locally for a photo the server
/// has none for. Matches the server's own thumbnail scale closely enough that a
@@ -129,8 +138,107 @@ const DECODE_BUDGET_BYTES: u64 = 512 * 1024 * 1024;
/// The process-wide [`DecodeBudget`] every thumbnail decode draws from.
static DECODE_BUDGET: DecodeBudget = DecodeBudget::new(DECODE_BUDGET_BYTES);
mod albums;
pub(crate) mod redate;
pub(crate) mod takeout;
pub(crate) use albums::AlbumOutcome;
pub(crate) use takeout::sha1_of;
mod thumbs;
mod timeline;
mod trash;
/// The Photos service: the timeline, albums and thumbnails.
///
/// It holds only the handles it calls, and reaches the filesystem through
/// [`PhotosHost`], so it does not depend on [`Core`]. [`Core::photos`] builds
/// one on demand, the same way [`Core::syncer`] builds the sync engine. A clone
/// shares everything, which is how a refresh or a thumbnail job moves onto a
/// background task.
#[derive(Clone)]
pub(crate) struct Photos {
client: ProtonDriveClient,
drive: Arc<dyn DriveApi>,
rt: tokio::runtime::Handle,
cache: Arc<ContentCache>,
db: Arc<pdfs_store::db::Db>,
shutdown: Arc<Shutdown>,
services: ServiceBoard,
events: Arc<EventHub>,
transfers: Arc<TransferRegistry>,
jobs: PhotoJobs,
host: Arc<dyn PhotosHost>,
}
/// What the Photos service needs from the filesystem.
pub(crate) trait PhotosHost: Send + Sync {
/// List a folder of the mount, for the recursive thumbnail build.
fn list_dir(&self, rel: &Path) -> CoreResult<Vec<DirEntry>>;
/// Record a change this daemon made, so its echo in the event feed is not
/// taken for a remote edit.
fn note_self_change(&self, uid: &NodeUid);
/// Add an entry to the activity log.
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool);
}
impl PhotosHost for Core {
fn list_dir(&self, rel: &Path) -> CoreResult<Vec<DirEntry>> {
Core::list_dir(self, rel)
}
fn note_self_change(&self, uid: &NodeUid) {
Core::note_self_change(self, uid)
}
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool) {
Core::log_activity(self, kind, target, detail, ok);
}
}
impl Core {
/// The Photos service, with this daemon as its host.
pub(crate) fn photos(&self) -> Photos {
Photos {
client: self.client.clone(),
drive: self.drive.clone(),
rt: self.rt.clone(),
cache: self.cache.clone(),
db: self.db.clone(),
shutdown: self.shutdown.clone(),
services: self.services.clone(),
events: self.events.clone(),
transfers: self.transfers.clone(),
jobs: self.photo_jobs.clone(),
host: Arc::new(self.clone()),
}
}
}
impl Photos {
/// The Photos API over the daemon's single authenticated session.
fn photos_api(&self) -> ProtonPhotosClient {
ProtonPhotosClient::from_drive_client(self.client.clone())
}
/// Like [`download_file_tracked_to`] for a photo, streaming through the
/// photos client's [`download_photo_to`].
///
/// [`download_file_tracked_to`]: crate::Core::download_file_tracked_to
/// [`download_photo_to`]: ProtonPhotosClient::download_photo_to
fn download_photo_tracked(
&self,
photos: &ProtonPhotosClient,
uid: &NodeUid,
name: &str,
total: u64,
) -> std::result::Result<Vec<u8>, ProtonError> {
let guard = self
.transfers
.begin(name, uid.to_string(), TransferDirection::Download, total);
let mut out = CountingWriter::new(Vec::with_capacity(total as usize), &guard);
self.rt.block_on(photos.download_photo_to(uid, &mut out))?;
Ok(out.into_inner())
}
}
/// What the Photos and thumbnail jobs are doing right now: which refreshes
/// and builds are running, how far they got, and which thumbnails are known
@@ -149,7 +257,7 @@ pub(crate) struct PhotoJobs {
/// The same, for the album listing.
pub(crate) albums_refreshing: Arc<AtomicBool>,
/// True while the similar-photo pass hashes thumbnails (see
/// [`Core::photo_similar`]), so asking again doesn't start a second one.
/// [`Photos::photo_similar`]), so asking again doesn't start a second one.
pub(crate) similar_hashing: Arc<AtomicBool>,
/// Photos whose missing thumbnail is being generated right now. A tile that is
/// still on screen asks for its thumbnail again every few seconds, and each of
@@ -601,12 +709,32 @@ fn run_bounded(mut command: Command, timeout: Duration) -> Result<Vec<u8>, ToolE
let _ = child.wait();
return Err(ToolError::Unavailable);
};
let reader = std::thread::spawn(move || {
let mut output = Vec::new();
stdout.read_to_end(&mut output).map(|_| output)
});
// Scoped, so the reader cannot outlive the call even when the child
// overruns and is killed.
std::thread::scope(|scope| {
let reader = scope.spawn(move || {
let mut output = Vec::new();
stdout.read_to_end(&mut output).map(|_| output)
});
let status = wait_bounded(&mut child, timeout);
let output = reader
.join()
.ok()
.and_then(Result::ok)
.ok_or(ToolError::Unavailable)?;
match status {
Some(true) => Ok(output),
Some(false) => Err(ToolError::Failed),
None => Err(ToolError::Unavailable),
}
})
}
/// Wait for `child` to exit, up to `timeout`, killing it past that. `None`
/// when it overran or could not be waited for.
fn wait_bounded(child: &mut std::process::Child, timeout: Duration) -> Option<bool> {
let started = Instant::now();
let status = loop {
loop {
match child.try_wait() {
Ok(Some(status)) => break Some(status.success()),
Ok(None) if started.elapsed() < timeout => {
@@ -618,16 +746,6 @@ fn run_bounded(mut command: Command, timeout: Duration) -> Result<Vec<u8>, ToolE
break None;
}
}
};
let output = reader
.join()
.ok()
.and_then(Result::ok)
.ok_or(ToolError::Unavailable)?;
match status {
Some(true) => Ok(output),
Some(false) => Err(ToolError::Failed),
None => Err(ToolError::Unavailable),
}
}
@@ -2,7 +2,7 @@
//!
//! Both are persisted projections of what the photos volume reports, refreshed
//! on the same stale-while-serving rule as the timeline
//! ([`crate::photos`]): a listing already on disk is served immediately and
//! ([`super`]): a listing already on disk is served immediately and
//! refreshed behind the caller, and only an empty one waits on the network.
//!
//! An album is a folder node carrying album properties, so it has a name like
@@ -23,15 +23,16 @@ use proton_drive_rs::NodeKind;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use tracing::warn;
use super::{
ALBUM_SYNCED_PREFIX, ALBUMS_SYNCED_MS, Core, PHOTOS_AVAILABLE, TIMELINE_ENRICH_CHUNK,
TIMELINE_TTL, link, now_ms, parse_uid,
use super::Photos;
use crate::{
ALBUM_SYNCED_PREFIX, ALBUMS_SYNCED_MS, PHOTOS_AVAILABLE, TIMELINE_ENRICH_CHUNK, TIMELINE_TTL,
link, listing::listing_stale, now_ms, parse_uid,
};
impl Core {
impl Photos {
/// The album listing, served from disk and refreshed behind the caller when
/// stale. `None` means the account has no photos volume — the same signal
/// [`Core::photos_timeline`] gives.
/// [`Photos::photos_timeline`] gives.
pub(crate) fn albums(&self) -> CoreResult<Option<Vec<AlbumInfo>>> {
let count = self.db.albums_count().map_err(CoreError::from)?;
if count == 0
@@ -44,13 +45,13 @@ impl Core {
// Nothing on disk, so this one request waits for the fetch — unless
// the account is already known to have no photos volume.
let known_empty = self.db.state_i64(PHOTOS_AVAILABLE).ok().flatten() == Some(0);
if known_empty && !self.listing_stale(ALBUMS_SYNCED_MS, TIMELINE_TTL) {
if known_empty && !listing_stale(&self.db, ALBUMS_SYNCED_MS, TIMELINE_TTL) {
return Ok(None);
}
if !self.rt.block_on(self.refresh_albums())? {
return Ok(None);
}
} else if self.listing_stale(ALBUMS_SYNCED_MS, TIMELINE_TTL) {
} else if listing_stale(&self.db, ALBUMS_SYNCED_MS, TIMELINE_TTL) {
self.spawn_albums_refresh();
}
@@ -66,7 +67,7 @@ impl Core {
.db
.photo_projection_generation()
.map_err(CoreError::from)?;
let photos = self.photos();
let photos = self.photos_api();
if link::bounded(photos.get_photos_root())
.await
.map_err(|e| CoreError::from_api(&e, "photos root"))?
@@ -132,24 +133,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
.photo_jobs
.albums_refreshing
.swap(true, Ordering::SeqCst)
{
if self.jobs.albums_refreshing.swap(true, Ordering::SeqCst) {
return;
}
let core = self.clone();
self.rt.spawn(async move {
let refreshed = core.refresh_albums().await;
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"),
}
});
let this = self.clone();
self.services
.spawn_task_job(&self.rt, "pdfs-albums-refresh", async move {
let refreshed = this.refresh_albums().await;
this.jobs.albums_refreshing.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => this.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background album refresh failed"),
}
});
}
/// A page of one album's photos, newest capture first. The album's contents
@@ -176,14 +172,15 @@ impl Core {
.is_none()
{
self.rt.block_on(self.refresh_album(album))?;
} else if self.listing_stale(&stamp, TIMELINE_TTL) {
let core = self.clone();
} else if listing_stale(&self.db, &stamp, TIMELINE_TTL) {
let this = self.clone();
let album = album.clone();
self.rt.spawn(async move {
if let Err(e) = core.refresh_album(&album).await {
warn!(%album, error = %e, "background album refresh failed");
}
});
self.services
.spawn_task_job(&self.rt, "pdfs-album-refresh", async move {
if let Err(e) = this.refresh_album(&album).await {
warn!(%album, error = %e, "background album refresh failed");
}
});
}
let page = self
@@ -233,7 +230,7 @@ impl Core {
.db
.photo_projection_generation()
.map_err(CoreError::from)?;
let photos = self.photos();
let photos = self.photos_api();
let items = link::bounded(photos.enumerate_album(album))
.await
.map_err(|e| CoreError::from_api(&e, "album"))?;
@@ -283,11 +280,11 @@ impl Core {
}
/// Create an album and return its uid. The listing is refreshed before
/// answering, so the next [`Core::albums`] already shows it.
/// answering, so the next [`Photos::albums`] already shows it.
pub(crate) fn create_album(&self, name: &str) -> CoreResult<String> {
let uid = self
.rt
.block_on(self.photos().create_album(name))
.block_on(self.photos_api().create_album(name))
.map_err(|e| CoreError::from_api(&e, "create album"))?;
self.after_album_change(None);
Ok(uid.to_string())
@@ -295,7 +292,7 @@ impl Core {
pub(crate) fn rename_album(&self, album: &NodeUid, name: &str) -> CoreResult<()> {
self.rt
.block_on(self.photos().rename_album(album, name))
.block_on(self.photos_api().rename_album(album, name))
.map_err(|e| CoreError::from_api(&e, "rename album"))?;
self.after_album_change(None);
Ok(())
@@ -305,7 +302,7 @@ impl Core {
/// which only matters for photos that exist in the album alone.
pub(crate) fn delete_album(&self, album: &NodeUid, delete_photos: bool) -> CoreResult<()> {
self.rt
.block_on(self.photos().delete_album(album, delete_photos))
.block_on(self.photos_api().delete_album(album, delete_photos))
.map_err(|e| CoreError::from_api(&e, "delete album"))?;
let key = album.to_string();
if let Err(error) = self.db.photos_delete(&[key]) {
@@ -323,7 +320,7 @@ impl Core {
) -> CoreResult<AlbumOutcome> {
let outcomes = self
.rt
.block_on(self.photos().add_photos_to_album(album, photos))
.block_on(self.photos_api().add_photos_to_album(album, photos))
.map_err(|e| CoreError::from_api(&e, "add to album"))?;
self.after_album_change(Some(album));
Ok(album_outcome(outcomes))
@@ -338,7 +335,7 @@ impl Core {
) -> CoreResult<AlbumOutcome> {
let outcomes = self
.rt
.block_on(self.photos().remove_photos_from_album(album, photos))
.block_on(self.photos_api().remove_photos_from_album(album, photos))
.map_err(|e| CoreError::from_api(&e, "remove from album"))?;
self.after_album_change(Some(album));
Ok(album_outcome(outcomes))
@@ -361,7 +358,7 @@ impl Core {
}
/// Drop the album listing's and every album's freshness stamp, so the next
/// request re-enumerates. Paired with [`Core::invalidate_photos`] — a change
/// request re-enumerates. Paired with [`Core::invalidate_photos`](crate::Core::invalidate_photos) — a change
/// to the timeline can just as easily be a change to an album.
pub(crate) fn invalidate_albums(&self) {
let _ = self.db.clear_state(ALBUMS_SYNCED_MS);
@@ -27,7 +27,7 @@ use proton_drive_rs::proton_sdk::ids::NodeUid;
use proton_drive_rs::{PhotoTag, PhotoTagsUpdate, PhotoUploadMetadata};
use tracing::{info, warn};
use super::Core;
use super::Photos;
use crate::parse_uid as parse_node_uid;
use crate::transfers::CountingReader;
@@ -84,7 +84,7 @@ struct Candidate {
albums: Vec<String>,
}
impl Core {
impl Photos {
/// Re-date mis-dated photos. Blocking; run on its own thread.
///
/// `cancel` stops the run at the next photo boundary. A photo is only ever
@@ -184,7 +184,7 @@ impl Core {
/// trash the original. Every earlier step failing leaves the account exactly
/// as it was.
fn redate_one(&self, candidate: &Candidate, summary: &mut RedateSummary) -> CoreResult<()> {
let photos = self.photos();
let photos = self.photos_api();
let path = self.open_photo(&candidate.uid)?;
let size = std::fs::metadata(&path)
.map_err(|e| CoreError::internal(format!("stat {}: {e}", path.display())))?
@@ -227,7 +227,7 @@ impl Core {
match self.rt.block_on(photos.update_photos(&[update])) {
// As in `set_photo_favorite`: claim our own echo, so the tag we
// just set does not come back as a remote change.
Ok(_) => self.note_self_change(&new_uid),
Ok(_) => self.host.note_self_change(&new_uid),
Err(e) => {
warn!(name = candidate.name, error = %e, "cannot re-favorite re-dated photo")
}
@@ -287,9 +287,9 @@ impl Core {
state.last = None;
}
let core = self.clone();
std::thread::spawn(move || {
let outcome = core.redate_photos(dry_run, limit, range, cancel);
let this = self.clone();
if let Err(error) = self.services.spawn_job("pdfs-redate", move || {
let outcome = this.redate_photos(dry_run, limit, range, cancel);
let mut state = REDATE.lock();
state.running = false;
state.cancel = None;
@@ -310,7 +310,9 @@ impl Core {
),
Err(e) => warn!(error = %e, "photo re-date failed"),
}
});
}) {
tracing::warn!(%error, "could not start pdfs-redate");
}
Ok(())
}
}
@@ -47,7 +47,7 @@ use tracing::{info, warn};
pub(crate) use pdfs_drive::digest::sha1_of;
use super::Core;
use super::Photos;
use crate::photos::can_make_thumbnail;
use crate::transfers::CountingReader;
@@ -468,7 +468,7 @@ fn read_entry<R>(
Ok(sink(&mut file))
}
impl Core {
impl Photos {
/// Copy archive entry `entry` into the thumbnail staging folder and return
/// its path. The caller removes it.
fn stage_takeout_entry(
@@ -611,7 +611,7 @@ impl Core {
));
}
let photos = self.photos();
let photos = self.photos_api();
if self
.rt
.block_on(photos.get_photos_root())
@@ -668,7 +668,7 @@ impl Core {
report: &Reporter,
) -> CoreResult<()> {
report.phase(ImportPhase::Checking, 0);
let photos = self.photos();
let photos = self.photos_api();
let names: Vec<String> = planned.iter().map(|p| p.photo.name.clone()).collect();
let collisions = self
.rt
@@ -919,7 +919,7 @@ impl Core {
report.step();
match done.result {
Ok(uid) => {
self.note_self_change(&uid);
self.host.note_self_change(&uid);
summary.uploaded += 1;
summary.bytes += done.photo.size;
if done.live {
@@ -954,7 +954,7 @@ impl Core {
tags: Vec<PhotoTag>,
main_uid: Option<NodeUid>,
) -> CoreResult<NodeUid> {
let photos = self.photos();
let photos = self.photos_api();
let guard = self.transfers.begin(
photo.name.clone(),
"",
@@ -1035,7 +1035,7 @@ impl Core {
tags_to_remove: Vec::new(),
})
.collect();
if let Err(e) = self.rt.block_on(self.photos().update_photos(&updates)) {
if let Err(e) = self.rt.block_on(self.photos_api().update_photos(&updates)) {
warn!(error = %e, "marking imported favorites failed");
}
}
@@ -1049,7 +1049,7 @@ impl Core {
summary: &mut ImportSummary,
report: &Reporter,
) -> CoreResult<()> {
let photos = self.photos();
let photos = self.photos_api();
// Existing albums by decrypted name, so a second import of the same
// export adds to the album it made the first time instead of a twin.
@@ -1152,14 +1152,14 @@ impl Core {
state.save();
}
let core = self.clone();
std::thread::spawn(move || {
let this = self.clone();
if let Err(error) = self.services.spawn_job("pdfs-import", move || {
// The job is dropped only after the final state is stored: the
// job leaving the transfer snapshot is the front-ends' cue to ask
// for the result, which must then be there.
let job = core.transfers.begin_job("Importing Google Photos");
let job = this.transfers.begin_job("Importing Google Photos");
let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
core.import_takeout(&archives, dry_run, &cancel, &job)
this.import_takeout(&archives, dry_run, &cancel, &job)
}));
// A panic must not leave the import marked as running for the
// life of the daemon, refusing every later one.
@@ -1179,14 +1179,16 @@ impl Core {
}
drop(job);
if !dry_run {
core.log_activity(
this.host.log_activity(
ActivityKind::Upload,
"Google Photos import",
"Google Photos import".to_string(),
activity_line(&summary),
summary.complete(),
);
}
});
}) {
tracing::warn!(%error, "could not start pdfs-import");
}
Ok(())
}
}
+76 -95
View File
@@ -4,14 +4,14 @@
use super::*;
impl Core {
impl Photos {
/// [`upload_thumbnails`] for a file about to upload, staging any RAW copy
/// under this cache. Blocking.
pub(crate) fn upload_thumbnails(&self, path: &Path, name: &str) -> Vec<Thumbnail> {
upload_thumbnails(path, name, self.cache.raw_thumbnail_staging_dir())
}
/// [`Core::upload_thumbnails`] on the blocking pool, for async callers.
/// [`Photos::upload_thumbnails`] on the blocking pool, for async callers.
pub(crate) async fn upload_thumbnails_async(
&self,
path: PathBuf,
@@ -26,7 +26,7 @@ impl Core {
/// Thumbnails for `uids`, served from the cache, fetched from the server for
/// whatever is missing, and — for the photos the server has no thumbnail for
/// at all — *generated locally* from the full file (see
/// [`Core::generate_thumbs`]). Requested on demand as tiles scroll into view,
/// [`Photos::generate_thumbs`]). Requested on demand as tiles scroll into view,
/// so a cold timeline paints immediately and only the photos actually on
/// screen cost a round-trip.
///
@@ -41,7 +41,7 @@ impl Core {
self.photo_thumbs_with(requested, true)
}
/// [`Core::photo_thumbs`], with local generation only when `generate` is
/// [`Photos::photo_thumbs`], with local generation only when `generate` is
/// set. Without it, a photo the server has no thumbnail for is left
/// without one rather than downloaded whole.
pub(crate) fn photo_thumbs_with(
@@ -117,7 +117,7 @@ impl Core {
if !want.is_empty() {
let mut missing = want.clone();
match self.rt.block_on(
self.photos()
self.photos_api()
.enumerate_thumbnails(&want, ThumbnailType::Thumbnail),
) {
Ok(thumbs) => {
@@ -154,7 +154,7 @@ impl Core {
}
}
let pending = self.photo_jobs.thumb_gen.lock();
let pending = self.jobs.thumb_gen.lock();
requested
.iter()
.zip(uids)
@@ -197,7 +197,7 @@ impl Core {
}
/// Thumbnails for image files shown by the regular file browser, Shared and
/// Trash pages. Unlike [`Core::photo_thumbs`], these nodes need not be in the
/// Trash pages. Unlike [`Photos::photo_thumbs`], these nodes need not be in the
/// Photos timeline: the request supplies each file's modification time as
/// the cache validity tag.
pub(crate) fn file_thumbs(
@@ -205,8 +205,8 @@ impl Core {
items: &[FileThumbRequest],
generation: u64,
) -> Option<Vec<PhotoThumb>> {
let current = generation != 0
&& self.photo_jobs.file_thumb_generation.load(Ordering::SeqCst) == generation;
let current =
generation != 0 && self.jobs.file_thumb_generation.load(Ordering::SeqCst) == generation;
if !current {
return None;
}
@@ -238,7 +238,7 @@ impl Core {
.cached_thumbnail_path(uid, ttype, *modified)
.is_some()
|| self
.photo_jobs
.jobs
.thumbnail_misses
.lock()
.local_contains(&(uid.clone(), ttype), *modified)
@@ -253,7 +253,7 @@ impl Core {
self.spawn_generate_thumbs(wanted, &tags, &names, ThumbJob::Files(generation));
}
let pending = self.photo_jobs.thumb_gen.lock();
let pending = self.jobs.thumb_gen.lock();
Some(
items
.iter()
@@ -279,14 +279,14 @@ impl Core {
pub(crate) fn reserve_file_thumb_generation(&self) -> u64 {
let next = |current| if current == u64::MAX { 1 } else { current + 1 };
let previous = self
.photo_jobs
.jobs
.file_thumb_generation
.try_update(Ordering::SeqCst, Ordering::SeqCst, |current| {
Some(next(current))
})
.expect("generation update always succeeds");
let generation = next(previous);
self.photo_jobs.file_thumb_cancel.notify_waiters();
self.jobs.file_thumb_cancel.notify_waiters();
generation
}
@@ -295,11 +295,11 @@ impl Core {
/// recursive builds do not use this generation and continue normally.
pub(crate) fn cancel_file_thumbs(&self, generation: u64) {
let previous = self
.photo_jobs
.jobs
.file_thumb_generation
.fetch_max(generation, Ordering::SeqCst);
if generation > previous {
self.photo_jobs.file_thumb_cancel.notify_waiters();
self.jobs.file_thumb_cancel.notify_waiters();
}
}
@@ -314,7 +314,7 @@ impl Core {
job: ThumbJob,
) {
let fresh: Vec<NodeUid> = {
let mut inflight = self.photo_jobs.thumb_gen.lock();
let mut inflight = self.jobs.thumb_gen.lock();
uids.into_iter()
.filter(|uid| inflight.insert(uid.clone()))
.collect()
@@ -323,16 +323,16 @@ impl Core {
return;
}
let core = self.clone();
let this = self.clone();
let tags = tags.clone();
let names = names.clone();
// `generate_thumbs` blocks on the runtime itself, so it belongs on the
// blocking pool rather than on an async worker.
self.rt.spawn_blocking(move || {
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
core.generate_thumbs(&fresh, &tags, &names, job)
this.generate_thumbs(&fresh, &tags, &names, job)
}));
let mut inflight = core.photo_jobs.thumb_gen.lock();
let mut inflight = this.jobs.thumb_gen.lock();
for uid in &fresh {
inflight.remove(uid);
}
@@ -354,13 +354,10 @@ impl Core {
pub(super) fn thumb_job_current(&self, job: ThumbJob) -> bool {
match job {
ThumbJob::Files(generation) => {
self.photo_jobs.file_thumb_generation.load(Ordering::SeqCst) == generation
self.jobs.file_thumb_generation.load(Ordering::SeqCst) == generation
}
ThumbJob::Photos => true,
ThumbJob::Build => !self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst),
ThumbJob::Build => !self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst),
}
}
@@ -377,12 +374,12 @@ impl Core {
for chunk in uids.chunks(THUMB_GEN_CONCURRENCY) {
let mut set = tokio::task::JoinSet::new();
for uid in chunk {
let core = self.clone();
let this = self.clone();
let client = self.client.clone();
let uid = uid.clone();
let name = names.get(&uid.to_string()).cloned().unwrap_or_default();
set.spawn(async move {
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
let video = is_video_name(&name);
@@ -397,19 +394,19 @@ impl Core {
// One shared permit pool bounds all thumbnail batches,
// rather than multiplying the limit by every control
// request the GUI happens to have in flight.
let acquire = core.photo_jobs.thumb_gen_budget.clone().acquire_owned();
let acquire = this.jobs.thumb_gen_budget.clone().acquire_owned();
tokio::pin!(acquire);
let _permit = match job {
ThumbJob::Files(_) => loop {
tokio::select! {
permit = &mut acquire => break permit.ok(),
_ = core.photo_jobs.file_thumb_cancel.notified() => {
if !core.thumb_job_current(job) {
_ = this.jobs.file_thumb_cancel.notified() => {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
@@ -418,13 +415,13 @@ impl Core {
ThumbJob::Build => loop {
tokio::select! {
permit = &mut acquire => break permit.ok(),
_ = core.photo_jobs.thumbnail_build_cancel.notified() => {
if !core.thumb_job_current(job) {
_ = this.jobs.thumbnail_build_cancel.notified() => {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
}
@@ -435,12 +432,12 @@ impl Core {
let Some(_permit) = _permit else {
return (uid, ThumbAttempt::Unavailable);
};
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
let download_uid = uid.clone();
let drive = core.drive.clone();
let drive = this.drive.clone();
let audio_name = name.clone();
let download = async move {
// Photos asked the server in one batch already. A
@@ -478,13 +475,13 @@ impl Core {
ThumbJob::Files(_) => loop {
tokio::select! {
result = &mut download => break Some(result),
_ = core.photo_jobs.file_thumb_cancel.notified() => {
if !core.thumb_job_current(job) {
_ = this.jobs.file_thumb_cancel.notified() => {
if !this.thumb_job_current(job) {
break None;
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
break None;
}
}
@@ -493,13 +490,13 @@ impl Core {
ThumbJob::Build => loop {
tokio::select! {
result = &mut download => break Some(result),
_ = core.photo_jobs.thumbnail_build_cancel.notified() => {
if !core.thumb_job_current(job) {
_ = this.jobs.thumbnail_build_cancel.notified() => {
if !this.thumb_job_current(job) {
break None;
}
}
_ = tokio::time::sleep(THUMB_CANCEL_POLL) => {
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
break None;
}
}
@@ -517,12 +514,12 @@ impl Core {
return (uid, ThumbAttempt::Unavailable);
}
};
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
// Decoding + scaling a 20 MP JPEG is CPU-bound and would
// stall the runtime's worker; hand it to the blocking pool.
let staging_dir = core.cache.raw_thumbnail_staging_dir().to_path_buf();
let staging_dir = this.cache.raw_thumbnail_staging_dir().to_path_buf();
let staging = staging_dir.clone();
let made = tokio::task::spawn_blocking(move || match fetched {
Fetched::Audio(sample) => {
@@ -547,12 +544,12 @@ impl Core {
// A song without a picture of its own shows its
// folder's cover.
let made = match made {
ScaleAttempt::Undecodable if audio && core.thumb_job_current(job) => {
core.folder_cover_thumbnail(&uid, staging).await
ScaleAttempt::Undecodable if audio && this.thumb_job_current(job) => {
this.folder_cover_thumbnail(&uid, staging).await
}
made => made,
};
if !core.thumb_job_current(job) {
if !this.thumb_job_current(job) {
return (uid, ThumbAttempt::Cancelled);
}
match made {
@@ -583,7 +580,7 @@ impl Core {
match self.cache.store_thumbnail(&uid, ttype, tag, &thumb.bytes) {
Ok(()) => {
summary.made += 1;
self.photo_jobs
self.jobs
.thumbnail_misses
.lock()
.forget_local(&(uid.clone(), ttype));
@@ -600,7 +597,7 @@ impl Core {
ThumbAttempt::Undecodable => {
summary.undecodable += 1;
if let Some(&tag) = tags.get(&uid.to_string()) {
self.photo_jobs
self.jobs
.thumbnail_misses
.lock()
.remember_local((uid.clone(), ttype), tag);
@@ -698,7 +695,7 @@ impl Core {
}
pub(crate) fn thumbnail_build_status(&self) -> ThumbnailBuildStatus {
self.photo_jobs.thumbnail_build.lock().clone()
self.jobs.thumbnail_build.lock().clone()
}
/// Start one recursive local-thumbnail build. A request for the same root
@@ -707,11 +704,11 @@ impl Core {
pub(crate) fn start_thumbnail_build(&self, root: PathBuf) -> CoreResult<ThumbnailBuildStatus> {
let path = root.to_string_lossy().into_owned();
let status = {
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
if !thumbnail_build_may_start(&status, &path)? {
return Ok(status.clone());
}
self.photo_jobs
self.jobs
.thumbnail_build_cancelled
.store(false, Ordering::SeqCst);
*status = ThumbnailBuildStatus {
@@ -727,18 +724,18 @@ impl Core {
status.clone()
};
let core = self.clone();
let this = self.clone();
self.rt.spawn_blocking(move || {
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
core.run_thumbnail_build(root)
this.run_thumbnail_build(root)
}))
.is_err()
{
let mut status = core.photo_jobs.thumbnail_build.lock();
let mut status = this.jobs.thumbnail_build.lock();
status.running = false;
status.scanning = false;
status.message = Some("Thumbnail generation stopped unexpectedly".to_string());
core.photo_jobs
this.jobs
.thumbnail_build_cancelled
.store(false, Ordering::SeqCst);
warn!(path = %status.path, "recursive thumbnail build panicked");
@@ -749,25 +746,25 @@ impl Core {
pub(crate) fn cancel_thumbnail_build(&self) -> ThumbnailBuildStatus {
let (status, cancelled) = {
let status = self.photo_jobs.thumbnail_build.lock();
let status = self.jobs.thumbnail_build.lock();
let cancelled = status.running;
if cancelled {
self.photo_jobs
self.jobs
.thumbnail_build_cancelled
.store(true, Ordering::SeqCst);
}
(status.clone(), cancelled)
};
if cancelled {
self.photo_jobs.thumbnail_build_cancel.notify_waiters();
self.jobs.thumbnail_build_cancel.notify_waiters();
}
status
}
pub(crate) fn finish_thumbnail_build(&self) {
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
let cancelled = self
.photo_jobs
.jobs
.thumbnail_build_cancelled
.swap(false, Ordering::SeqCst);
status.running = false;
@@ -791,23 +788,19 @@ impl Core {
let mut seen_images = HashSet::new();
while let Some(folder) = folders.pop() {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
self.finish_thumbnail_build();
return;
}
let listing = self.list_dir(&folder);
let listing = self.host.list_dir(&folder);
{
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
status.folders_scanned += 1;
}
let entries = match listing {
Ok(entries) => entries,
Err(error) => {
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
if status.message.is_none() {
status.message = Some(format!(
"Some folders could not be read ({}: {error})",
@@ -839,18 +832,14 @@ impl Core {
}
}
}
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
status.images_found += found_here;
status.completed += invalid_here;
status.failed += invalid_here;
}
self.photo_jobs.thumbnail_build.lock().scanning = false;
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
self.jobs.thumbnail_build.lock().scanning = false;
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
self.finish_thumbnail_build();
return;
}
@@ -862,14 +851,14 @@ impl Core {
.cached_thumbnail_path(&uid, ttype, modified)
.is_some()
{
self.photo_jobs.thumbnail_build.lock().completed += 1;
self.jobs.thumbnail_build.lock().completed += 1;
} else if self
.photo_jobs
.jobs
.thumbnail_misses
.lock()
.local_contains(&(uid.clone(), ttype), modified)
{
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
} else {
@@ -878,11 +867,7 @@ impl Core {
}
for chunk in todo.chunks(THUMB_BUILD_CHUNK) {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
self.finish_thumbnail_build();
return;
}
@@ -895,11 +880,7 @@ impl Core {
// than downloading the full image twice.
let waiting_since = Instant::now();
loop {
if self
.photo_jobs
.thumbnail_build_cancelled
.load(Ordering::SeqCst)
{
if self.jobs.thumbnail_build_cancelled.load(Ordering::SeqCst) {
self.finish_thumbnail_build();
return;
}
@@ -908,28 +889,28 @@ impl Core {
.cached_thumbnail_path(uid, ttype, *modified)
.is_some()
{
self.photo_jobs.thumbnail_build.lock().completed += 1;
self.jobs.thumbnail_build.lock().completed += 1;
break;
}
if self
.photo_jobs
.jobs
.thumbnail_misses
.lock()
.local_contains(&(uid.clone(), ttype), *modified)
{
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
break;
}
if self.photo_jobs.thumb_gen.lock().insert(uid.clone()) {
if self.jobs.thumb_gen.lock().insert(uid.clone()) {
tags.insert(uid.to_string(), *modified);
names.insert(uid.to_string(), name.clone());
claimed.push(uid.clone());
break;
}
if waiting_since.elapsed() >= THUMB_BUILD_CLAIM_TIMEOUT {
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
status.completed += 1;
status.failed += 1;
if status.message.is_none() {
@@ -950,12 +931,12 @@ impl Core {
self.generate_thumbs(&claimed, &tags, &names, ThumbJob::Build)
}));
{
let mut inflight = self.photo_jobs.thumb_gen.lock();
let mut inflight = self.jobs.thumb_gen.lock();
for uid in &claimed {
inflight.remove(uid);
}
}
let mut status = self.photo_jobs.thumbnail_build.lock();
let mut status = self.jobs.thumbnail_build.lock();
match result {
Ok(summary) => {
status.completed += summary.processed();
+35 -149
View File
@@ -3,7 +3,7 @@
use super::*;
impl Core {
impl Photos {
#[allow(clippy::too_many_arguments)]
pub(crate) fn photos_timeline(
&self,
@@ -90,7 +90,7 @@ impl Core {
/// The SDK reports one outcome per photo rather than failing the call, so the
/// single outcome is unwrapped back into this request's result.
pub(crate) fn set_photo_favorite(&self, uid: &NodeUid, favorite: bool) -> CoreResult<()> {
let photos = self.photos();
let photos = self.photos_api();
let update = PhotoTagsUpdate {
node_uid: uid.clone(),
tags_to_add: if favorite {
@@ -114,7 +114,7 @@ impl Core {
// `NodeUpdated`, which is indistinguishable from the same photo being
// favorited on a phone. Claim the echo, or the gallery pays for a
// resolve of a node whose one changed field is already stored below.
self.note_self_change(uid);
self.host.note_self_change(uid);
self.db
.photos_set_favorite(&uid.to_string(), favorite)
.map_err(CoreError::from)?;
@@ -142,7 +142,7 @@ impl Core {
let sets = self.db.photo_similar().map_err(CoreError::from)?;
let (done, total) = self.db.similar_progress().map_err(CoreError::from)?;
let hashing = self
.photo_jobs
.jobs
.similar_hashing
.load(Ordering::SeqCst)
.then_some(MappingProgress { done, total });
@@ -155,25 +155,19 @@ impl Core {
}
pub(crate) fn spawn_similar_hashing(&self) {
if self.photo_jobs.similar_hashing.swap(true, Ordering::SeqCst) {
if self.jobs.similar_hashing.swap(true, Ordering::SeqCst) {
return;
}
let core = self.clone();
let spawned = std::thread::Builder::new()
.name("pdfs-similar".into())
.spawn(move || {
if let Err(e) = core.hash_similar() {
warn!(error = %e, "similar-photo hashing failed");
}
core.photo_jobs
.similar_hashing
.store(false, Ordering::SeqCst);
});
let this = self.clone();
let spawned = self.services.spawn_job("pdfs-similar", move || {
if let Err(e) = this.hash_similar() {
warn!(error = %e, "similar-photo hashing failed");
}
this.jobs.similar_hashing.store(false, Ordering::SeqCst);
});
if let Err(e) = spawned {
warn!(error = %e, "could not start similar-photo hashing");
self.photo_jobs
.similar_hashing
.store(false, Ordering::SeqCst);
self.jobs.similar_hashing.store(false, Ordering::SeqCst);
}
}
@@ -322,100 +316,6 @@ impl Core {
out
}
/// Mutation admission for a photo, which [`Core::require_uid_writable`]
/// cannot answer on its own.
///
/// Photos live on the photo volume, and that volume is not part of the FUSE
/// tree: a photo has no `nodes` row, so every authority comes back
/// [`WriteAuthority::Unknown`] and the plain check refuses the whole
/// library. Membership of our own timeline is the authority that does exist
/// here — the timeline is enumerated from our photo share, so a uid in it is
/// ours to trash. Anything else (an album photo on someone else's volume)
/// still fails closed.
pub(crate) fn require_photo_writable(&self, uid: &NodeUid) -> Result<(), fuser::Errno> {
match self.uid_write_authority(uid) {
WriteAuthority::Writable => Ok(()),
WriteAuthority::Denied => Err(fuser::Errno::EACCES),
WriteAuthority::Unknown => {
let key = uid.to_string();
let known = self
.db
.photos_by_uid(std::slice::from_ref(&key))
.map(|rows| !rows.is_empty())
.unwrap_or(false);
if known {
Ok(())
} else {
Err(fuser::Errno::EACCES)
}
}
}
}
/// Trash photos by uid, and forget them locally.
///
/// The gallery is not part of the FUSE mount, so this is the photos-side
/// counterpart of [`Core::delete`]: same destination (Proton trash, so the
/// Trash page can restore them), addressed by uid because that is all a tile
/// has.
///
/// The server answers per node, and so does this: a batch where one photo
/// fails still removes the ones that went, and the caller is told which is
/// which. Only what actually left the server is forgotten locally.
///
/// A photo that is one file of a group takes its whole group with it. The
/// gallery shows a RAW+JPEG shot as one tile, so deleting that tile has to
/// delete the shot — leaving the RAW behind would put the photo back on the
/// Raw tab and nowhere else. `files_only` turns that off, for removing
/// one copy of a shot that is stored twice.
pub(crate) fn trash_photos(
&self,
uids: &[NodeUid],
files_only: bool,
) -> CoreResult<TrashOutcome> {
if uids.is_empty() {
return Ok((Vec::new(), Vec::new()));
}
let expanded;
let uids = if files_only {
uids
} else {
expanded = self.expand_photo_groups(uids);
&expanded
};
for uid in uids {
self.require_photo_writable(uid)
.map_err(|errno| self.errno_error(errno, "trash access"))?;
}
let outcomes = self
.rt
.block_on(self.drive.trash_nodes(uids))
.map_err(|e| CoreError::from_api(&e, "trash"))?;
let (trashed, failed) = pdfs_core::batch::split(outcomes);
let trashed: Vec<String> = trashed.iter().map(|uid| uid.to_string()).collect();
for uid in &trashed {
if let Some(parsed) = parse_uid(uid) {
self.cache.evict(&parsed);
self.evict_reader(&parsed);
}
}
// The timeline is served from the database, so removing the rows is what
// makes the photos disappear now rather than at the next refresh.
if let Err(error) = self.db.photos_delete(&trashed) {
warn!(%error, "trashed photos could not be removed from the timeline");
}
self.invalidate_photos();
self.invalidate_albums();
self.invalidate_trash();
let failed = failed
.into_iter()
.map(|(uid, error)| (uid.to_string(), error.to_string()))
.collect();
Ok((trashed, failed))
}
/// Commit the lightweight listing before resolving pending nodes. The
/// feed generation fences both commits against events received in flight.
pub(crate) async fn refresh_timeline(&self) -> CoreResult<bool> {
@@ -424,7 +324,7 @@ impl Core {
.db
.photo_projection_generation()
.map_err(CoreError::from)?;
let photos = self.photos();
let photos = self.photos_api();
if self
.db
.state_i64(PHOTOS_SYNCED_MS)
@@ -470,7 +370,7 @@ impl Core {
let total = self.db.photos_count().map_err(CoreError::from)?;
let skipped = total.saturating_sub(pending.len());
let mut resolved = 0;
let progress = ProgressGuard(&self.photo_jobs.timeline_progress);
let progress = ProgressGuard(&self.jobs.timeline_progress);
for (index, chunk) in pending.chunks(TIMELINE_ENRICH_CHUNK).enumerate() {
if self.shutdown.is_stopping() {
break;
@@ -539,12 +439,8 @@ impl Core {
/// whole library at once, sharing the session's rate limit and taking
/// minutes. Returns whether the account has a photos library.
pub(crate) fn refresh_timeline_joined(&self) -> CoreResult<bool> {
if self
.photo_jobs
.timeline_refreshing
.swap(true, Ordering::SeqCst)
{
while self.photo_jobs.timeline_refreshing.load(Ordering::SeqCst)
if self.jobs.timeline_refreshing.swap(true, Ordering::SeqCst) {
while self.jobs.timeline_refreshing.load(Ordering::SeqCst)
&& !self.shutdown.is_stopping()
{
std::thread::sleep(std::time::Duration::from_millis(200));
@@ -557,18 +453,13 @@ impl Core {
.state_i64(PHOTOS_SYNCED_MS)
.map_err(CoreError::from)?
.is_some()
|| self
.photo_jobs
.timeline_refreshing
.swap(true, Ordering::SeqCst)
|| self.jobs.timeline_refreshing.swap(true, Ordering::SeqCst)
{
return Ok(self.db.state_i64(PHOTOS_AVAILABLE).ok().flatten() != Some(0));
}
}
let refreshed = self.rt.block_on(self.refresh_timeline());
self.photo_jobs
.timeline_refreshing
.store(false, Ordering::SeqCst);
self.jobs.timeline_refreshing.store(false, Ordering::SeqCst);
if refreshed.is_ok() {
self.events.publish(&[Topic::Photos]);
}
@@ -576,32 +467,27 @@ impl Core {
}
pub(crate) fn spawn_timeline_refresh(&self) {
if self
.photo_jobs
.timeline_refreshing
.swap(true, Ordering::SeqCst)
{
if self.jobs.timeline_refreshing.swap(true, Ordering::SeqCst) {
return;
}
let core = self.clone();
self.rt.spawn(async move {
let refreshed = core.refresh_timeline().await;
core.photo_jobs
.timeline_refreshing
.store(false, Ordering::SeqCst);
// Only a refresh that landed: a front-end re-reading after a failed
// one would find the timeline still stale and start another.
match refreshed {
Ok(_) => core.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background timeline refresh failed"),
}
});
let this = self.clone();
self.services
.spawn_task_job(&self.rt, "pdfs-timeline-refresh", async move {
let refreshed = this.refresh_timeline().await;
this.jobs.timeline_refreshing.store(false, Ordering::SeqCst);
// Only a refresh that landed: a front-end re-reading after a failed
// one would find the timeline still stale and start another.
match refreshed {
Ok(_) => this.events.publish(&[Topic::Photos]),
Err(e) => warn!(error = %e, "background timeline refresh failed"),
}
});
}
/// How far the running timeline refresh has got reading photo metadata, or
/// `None` when no refresh is reading any.
pub(crate) fn timeline_progress(&self) -> Option<MappingProgress> {
self.photo_jobs
self.jobs
.timeline_progress
.lock()
.map(|(done, total)| MappingProgress { done, total })
@@ -610,13 +496,13 @@ impl Core {
/// Whether a timeline refresh is running. A front-end that asked for one
/// watches this to know when the new timeline is worth re-reading.
pub(crate) fn timeline_refreshing(&self) -> bool {
self.photo_jobs.timeline_refreshing.load(Ordering::SeqCst)
self.jobs.timeline_refreshing.load(Ordering::SeqCst)
}
/// Download a photo's full content into the content cache, returning its
/// on-disk path (served from cache when a fresh blob already exists).
pub(crate) fn open_photo(&self, uid: &NodeUid) -> CoreResult<PathBuf> {
let photos = self.photos();
let photos = self.photos_api();
let node = self
.rt
.block_on(photos.get_node(uid))
+101
View File
@@ -0,0 +1,101 @@
//! Trashing photos by uid. This stays on [`Core`] rather than [`Photos`]: it
//! checks write authority against the tree, drops open readers and clears the
//! trash listing, all of which belong to the filesystem side.
use super::*;
impl Core {
/// Mutation admission for a photo, which [`Core::require_uid_writable`]
/// cannot answer on its own.
///
/// Photos live on the photo volume, and that volume is not part of the FUSE
/// tree: a photo has no `nodes` row, so every authority comes back
/// [`WriteAuthority::Unknown`] and the plain check refuses the whole
/// library. Membership of our own timeline is the authority that does exist
/// here — the timeline is enumerated from our photo share, so a uid in it is
/// ours to trash. Anything else (an album photo on someone else's volume)
/// still fails closed.
pub(crate) fn require_photo_writable(&self, uid: &NodeUid) -> Result<(), fuser::Errno> {
match self.uid_write_authority(uid) {
WriteAuthority::Writable => Ok(()),
WriteAuthority::Denied => Err(fuser::Errno::EACCES),
WriteAuthority::Unknown => {
let key = uid.to_string();
let known = self
.db
.photos_by_uid(std::slice::from_ref(&key))
.map(|rows| !rows.is_empty())
.unwrap_or(false);
if known {
Ok(())
} else {
Err(fuser::Errno::EACCES)
}
}
}
}
/// Trash photos by uid, and forget them locally.
///
/// The gallery is not part of the FUSE mount, so this is the photos-side
/// counterpart of [`Core::delete`]: same destination (Proton trash, so the
/// Trash page can restore them), addressed by uid because that is all a tile
/// has.
///
/// The server answers per node, and so does this: a batch where one photo
/// fails still removes the ones that went, and the caller is told which is
/// which. Only what actually left the server is forgotten locally.
///
/// A photo that is one file of a group takes its whole group with it. The
/// gallery shows a RAW+JPEG shot as one tile, so deleting that tile has to
/// delete the shot — leaving the RAW behind would put the photo back on the
/// Raw tab and nowhere else. `files_only` turns that off, for removing
/// one copy of a shot that is stored twice.
pub(crate) fn trash_photos(
&self,
uids: &[NodeUid],
files_only: bool,
) -> CoreResult<TrashOutcome> {
if uids.is_empty() {
return Ok((Vec::new(), Vec::new()));
}
let expanded;
let uids = if files_only {
uids
} else {
expanded = self.photos().expand_photo_groups(uids);
&expanded
};
for uid in uids {
self.require_photo_writable(uid)
.map_err(|errno| self.errno_error(errno, "trash access"))?;
}
let outcomes = self
.rt
.block_on(self.drive.trash_nodes(uids))
.map_err(|e| CoreError::from_api(&e, "trash"))?;
let (trashed, failed) = pdfs_core::batch::split(outcomes);
let trashed: Vec<String> = trashed.iter().map(|uid| uid.to_string()).collect();
for uid in &trashed {
if let Some(parsed) = parse_uid(uid) {
self.cache.evict(&parsed);
self.evict_reader(&parsed);
}
}
// The timeline is served from the database, so removing the rows is what
// makes the photos disappear now rather than at the next refresh.
if let Err(error) = self.db.photos_delete(&trashed) {
warn!(%error, "trashed photos could not be removed from the timeline");
}
self.invalidate_photos();
self.photos().invalidate_albums();
self.invalidate_trash();
let failed = failed
.into_iter()
.map(|(uid, error)| (uid.to_string(), error.to_string()))
.collect();
Ok((trashed, failed))
}
}
+4 -3
View File
@@ -42,9 +42,10 @@ impl Core {
.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))
self.services
.spawn_job("pdfs-pin-folder", 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"));
}
+367 -325
View File
@@ -21,8 +21,13 @@ use pdfs_core::{CoreError, CoreResult};
use proton_drive_rs::proton_sdk::ids::NodeUid;
use tracing::{info, warn};
use super::devices::Devices;
use super::drive::DriveApi;
use super::sync;
use super::{Core, now_secs, parse_uid, this_hostname};
use pdfs_core::lifecycle::ServiceBoard;
use pdfs_store::db::Db;
use std::sync::Arc;
/// Coalescing flags for background profile saves.
///
@@ -40,331 +45,32 @@ fn save_state() -> &'static (AtomicBool, AtomicBool) {
SAVE_STATE.get_or_init(|| (AtomicBool::new(false), AtomicBool::new(false)))
}
/// The backup of this machine's arrangement on Drive: which folders sync where
/// and in which mode. It writes the profile and reads the ones other machines
/// wrote, to offer their folders for restore.
///
/// It needs nothing from the filesystem. [`Core::profile`] builds one on
/// demand. A clone shares everything, which is how a save moves onto a
/// background job.
#[derive(Clone)]
pub(crate) struct ProfileBackup {
drive: Arc<dyn DriveApi>,
rt: tokio::runtime::Handle,
db: Arc<Db>,
services: ServiceBoard,
devices: Devices,
}
impl Core {
/// Note that the arrangement this machine's profile describes has changed,
/// and upload a fresh profile in the background.
///
/// Fire-and-forget by design: callers are mutation paths (add/remove a sync
/// folder, switch a mode, pin a node, save settings) whose success does not
/// depend on the backup succeeding.
pub(crate) fn touch_profile(&self) {
let (saving, dirty) = save_state();
dirty.store(true, Ordering::SeqCst);
// Someone is already uploading; they will see DIRTY and take another lap.
if saving.swap(true, Ordering::SeqCst) {
return;
/// The profile backup.
pub(crate) fn profile(&self) -> ProfileBackup {
ProfileBackup {
drive: self.drive.clone(),
rt: self.rt.clone(),
db: self.db.clone(),
services: self.services.clone(),
devices: self.devices(),
}
let core = self.clone();
std::thread::spawn(move || {
let (saving, dirty) = save_state();
while dirty.swap(false, Ordering::SeqCst) {
if let Err(e) = core.save_profile() {
warn!(error = %e.message, "profile backup failed");
break;
}
}
saving.store(false, Ordering::SeqCst);
});
}
/// Serialize this machine's arrangement and upload it to its own
/// `profile-<machine id>.json` inside the device's `.proton-drive-linux`
/// folder, replacing any existing one.
///
/// Each machine writes its own file because several computers may sync
/// into one device. They used to share `profile.json`, and each save
/// replaced the other computers' folders with its own (B252). That file is
/// left as it is, so a client before 3.5.0 still finds it.
///
/// Does nothing when no device is registered: a machine that has never
/// synced a folder has nothing to describe, and registering a device just to
/// hold an empty profile would put a stray computer in the user's Drive.
pub(crate) fn save_profile(&self) -> CoreResult<()> {
let Some(device) = self
.db
.device_get()
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?
else {
return Ok(());
};
let root_uid = parse_uid(&device.root_uid).ok_or_else(|| {
CoreError::internal(format!("bad device root uid: {}", device.root_uid))
})?;
let machine_id = pdfs_core::config::AppDirs::new()
.and_then(|dirs| dirs.machine_id())
.map_err(|e| CoreError::internal(format!("machine id: {e}")))?;
let file_name = profile_file_name(&machine_id);
let profile = self.build_profile(&device.uid, &machine_id)?;
let bytes = profile.to_bytes().map_err(CoreError::internal)?;
let len = bytes.len() as i64;
// The device root itself rejects file creation (B78), so the profile
// lives one level down, in a folder created on first save.
let dir_uid = self.ensure_profile_dir(&root_uid)?;
// Replace the existing document rather than adding a second file of the
// same name: the profile is a single mutable record, and a folder with
// `profile.json` and `profile (1).json` in it teaches the restore
// nothing about which to trust.
let existing = self.find_device_child_file(&dir_uid, &file_name)?;
match existing {
Some(uid) => self
.rt
.block_on(self.drive.upload_new_revision_from(
&uid,
Cursor::new(bytes),
len,
Vec::new(),
Some(now_secs()),
))
.map(|_| ())
.map_err(|e| CoreError::from_api(&e, "upload profile revision"))?,
None => {
self.rt
.block_on(self.drive.upload_file_replacing_draft_from(
&dir_uid,
&file_name,
"application/json",
Cursor::new(bytes),
len,
Vec::new(),
Some(now_secs()),
false,
))
.map_err(|e| CoreError::from_api(&e, "upload profile"))?;
}
}
info!(folders = profile.folders.len(), "profile backed up");
Ok(())
}
/// Snapshot the local arrangement into a [`Profile`].
fn build_profile(&self, device_uid: &str, machine_id: &str) -> CoreResult<Profile> {
let folders = profile_folders(
self.db
.sync_folder_list()
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?,
);
let pins = self
.db
.pin_list()
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?
.into_iter()
.map(|row| ProfilePin {
uid: row.uid,
path: row.path,
recursive: row.recursive,
})
.collect();
let cfg = pdfs_core::config::AppDirs::new()
.map(|d| d.load_config())
.unwrap_or_default();
Ok(Profile {
version: PROFILE_VERSION,
device_uid: device_uid.to_string(),
hostname: this_hostname(),
machine_id: Some(machine_id.to_string()),
saved_at: now_secs(),
folders,
pins,
ignore_patterns: cfg.ignore_patterns,
cache_budget: cfg.cache_budget,
mountpoint: cfg.mountpoint,
})
}
/// An untrashed *file* named `name` directly under `parent_uid`.
///
/// The sibling of `find_device_child_folder`; kept separate because a folder
/// named `profile.json` must not be mistaken for the profile.
fn find_device_child_file(
&self,
parent_uid: &NodeUid,
name: &str,
) -> CoreResult<Option<NodeUid>> {
let uids = self
.rt
.block_on(self.drive.enumerate_folder_children_node_uids(parent_uid))
.map_err(|e| CoreError::from_api(&e, "list device root"))?;
if uids.is_empty() {
return Ok(None);
}
let nodes = self
.rt
.block_on(self.drive.enumerate_nodes(&uids))
.map_err(|e| CoreError::from_api(&e, "resolve device root children"))?;
Ok(nodes
.into_iter()
.find(|n| !n.is_folder() && !n.trashed && n.name == name)
.map(|n| n.uid))
}
/// The untrashed files directly under `parent_uid` whose name passes
/// `keep`.
fn device_child_files(
&self,
parent_uid: &NodeUid,
keep: impl Fn(&str) -> bool,
) -> CoreResult<Vec<NodeUid>> {
let uids = self
.rt
.block_on(self.drive.enumerate_folder_children_node_uids(parent_uid))
.map_err(|e| CoreError::from_api(&e, "list device root"))?;
if uids.is_empty() {
return Ok(Vec::new());
}
let nodes = self
.rt
.block_on(self.drive.enumerate_nodes(&uids))
.map_err(|e| CoreError::from_api(&e, "resolve device root children"))?;
Ok(nodes
.into_iter()
.filter(|n| !n.is_folder() && !n.trashed && keep(&n.name))
.map(|n| n.uid)
.collect())
}
/// The device's `.proton-drive-linux` folder, creating it if this is the
/// first save on this device.
///
/// Reused by stable identity rather than recreated: a second folder of the
/// same name would split the profile across two documents, and the restore
/// would have no way to tell which is current.
fn ensure_profile_dir(&self, root_uid: &NodeUid) -> CoreResult<NodeUid> {
if let Some(uid) = self.find_device_child_folder(root_uid, PROFILE_DIR_NAME)? {
return Ok(uid);
}
let uid = self
.rt
.block_on(
self.drive
.create_folder(root_uid, PROFILE_DIR_NAME, Some(now_secs())),
)
.map_err(|e| CoreError::from_api(&e, "create profile folder"))?;
info!(name = PROFILE_DIR_NAME, "created device profile folder");
Ok(uid)
}
/// Download and parse the profiles of every computer that syncs this
/// device.
///
/// Reads every profile in `.proton-drive-linux/`: one per machine, and the
/// shared `profile.json` of clients before 3.5.0. Falls back to the device
/// root, where clients before the B78 fix wrote it. The fallback is
/// read-only: the next save writes to the folder, and the legacy document
/// is left alone rather than trashed, so an older client on another
/// machine keeps working. A profile that cannot be read is left out and
/// logged; the others still count.
fn load_profiles(&self, root_uid: &NodeUid) -> CoreResult<Vec<Profile>> {
let mut uids = match self.find_device_child_folder(root_uid, PROFILE_DIR_NAME)? {
Some(dir_uid) => self.device_child_files(&dir_uid, is_profile_file_name)?,
None => Vec::new(),
};
if uids.is_empty() {
uids = self.device_child_files(root_uid, |name| name == PROFILE_FILE_NAME)?;
if !uids.is_empty() {
info!("reading legacy profile from the device root");
}
}
let mut profiles = Vec::new();
for uid in uids {
let mut buf: Vec<u8> = Vec::new();
let parsed = self
.rt
.block_on(self.drive.download_file_to(&uid, &mut buf))
.map_err(|e| CoreError::from_api(&e, "download profile"))
.and_then(|()| Profile::parse(&buf).map_err(CoreError::invalid));
match parsed {
Ok(profile) => profiles.push(profile),
Err(e) => {
warn!(%uid, error = %e.message, "could not read a profile; leaving it out")
}
}
}
Ok(profiles)
}
// ---- restore ----------------------------------------
/// The folders under a device that could be synced here, each carrying a
/// proposed local path. `device` names another registered device by uid;
/// `None` is this machine's own.
///
/// The proposal comes from the profile when one exists and its path is
/// usable on this machine, and from `~/<name>` otherwise — a restored
/// `/home/other-user/Documents` would be wrong on a machine where that user
/// does not exist, and silently creating it would be worse.
pub(crate) fn list_restorable_folders(
&self,
device: Option<&str>,
) -> CoreResult<Vec<RestorableFolder>> {
let device = self.restore_source(device)?;
let root_uid = parse_uid(&device.root_uid).ok_or_else(|| {
CoreError::internal(format!("bad device root uid: {}", device.root_uid))
})?;
let profiles = match self.load_profiles(&root_uid) {
Ok(p) => p,
// A missing or unreadable profile is not fatal: the remote tree
// alone is enough to offer a restore, just with plainer defaults.
Err(e) => {
warn!(error = %e.message, "could not read profiles; proposing defaults");
Vec::new()
}
};
let hostname = this_hostname();
let uids = self
.rt
.block_on(self.drive.enumerate_folder_children_node_uids(&root_uid))
.map_err(|e| CoreError::from_api(&e, "list device root"))?;
let nodes = if uids.is_empty() {
Vec::new()
} else {
self.rt
.block_on(self.drive.enumerate_nodes(&uids))
.map_err(|e| CoreError::from_api(&e, "resolve device root children"))?
};
// Folders already synced here are not restorable — they are already
// restored — but they are still listed, flagged, so the picker can show
// the whole device rather than a confusing subset.
let existing: Vec<String> = self
.db
.sync_folder_list()
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?
.into_iter()
.map(|f| f.remote_uid)
.collect();
Ok(nodes
.into_iter()
// `.proton-drive-linux` holds the profile itself, not user data:
// offering it as a restorable folder would sync the bookkeeping
// back onto the machine it describes.
.filter(|n| n.is_folder() && !n.trashed && n.name != PROFILE_DIR_NAME)
// The name becomes a folder under the home folder: one with a `/`
// or a `..` in it would put the restore somewhere else.
.filter(|n| crate::remote_name_is_safe(&n.name))
.map(|n| {
let uid = n.uid.to_string();
let saved = saved_folder(&profiles, &uid, &hostname);
let proposed = saved
.map(|f| PathBuf::from(&f.local_path))
.filter(|p| path_is_usable_here(p))
.unwrap_or_else(|| default_local_path(&n.name));
RestorableFolder {
already_synced: existing.iter().any(|e| e == &uid),
remote_uid: uid,
name: n.name,
local_path: proposed.to_string_lossy().to_string(),
mode: saved
.map(|f| f.mode.to_string())
.unwrap_or_else(|| "mirror".into()),
}
})
.collect())
}
/// Attach remote device folders to local paths and let the sync engine fill
@@ -385,7 +91,7 @@ impl Core {
if items.is_empty() {
return Err(CoreError::invalid("nothing to restore"));
}
let device = self.restore_source(device)?;
let device = self.devices().restore_source(device)?;
let existing = self
.db
.sync_folder_list()
@@ -395,7 +101,7 @@ impl Core {
// where destructive device-only operations would otherwise be allowed.
let device_root = super::parse_uid(&device.root_uid)
.ok_or_else(|| CoreError::internal("invalid device root"))?;
let children = self.device_root_nodes(&device_root)?;
let children = self.devices().device_root_nodes(&device_root)?;
let reserved = crate::devices::sync_root_reserved();
let mut roots: Vec<PathBuf> = existing
.iter()
@@ -478,6 +184,342 @@ impl Core {
}
}
impl ProfileBackup {
/// Note that the arrangement this machine's profile describes has changed,
/// and upload a fresh profile in the background.
///
/// Fire-and-forget by design: callers are mutation paths (add/remove a sync
/// folder, switch a mode, pin a node, save settings) whose success does not
/// depend on the backup succeeding.
pub(crate) fn touch_profile(&self) {
let (saving, dirty) = save_state();
dirty.store(true, Ordering::SeqCst);
// Someone is already uploading; they will see DIRTY and take another lap.
if saving.swap(true, Ordering::SeqCst) {
return;
}
let this = self.clone();
if let Err(error) = self.services.spawn_job("pdfs-profile-backup", move || {
let (saving, dirty) = save_state();
while dirty.swap(false, Ordering::SeqCst) {
if let Err(e) = this.save_profile() {
warn!(error = %e.message, "profile backup failed");
break;
}
}
saving.store(false, Ordering::SeqCst);
}) {
tracing::warn!(%error, "could not start pdfs-profile-backup");
}
}
/// Serialize this machine's arrangement and upload it to its own
/// `profile-<machine id>.json` inside the device's `.proton-drive-linux`
/// folder, replacing any existing one.
///
/// Each machine writes its own file because several computers may sync
/// into one device. They used to share `profile.json`, and each save
/// replaced the other computers' folders with its own (B252). That file is
/// left as it is, so a client before 3.5.0 still finds it.
///
/// Does nothing when no device is registered: a machine that has never
/// synced a folder has nothing to describe, and registering a device just to
/// hold an empty profile would put a stray computer in the user's Drive.
pub(crate) fn save_profile(&self) -> CoreResult<()> {
let Some(device) = self
.db
.device_get()
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?
else {
return Ok(());
};
let root_uid = parse_uid(&device.root_uid).ok_or_else(|| {
CoreError::internal(format!("bad device root uid: {}", device.root_uid))
})?;
let machine_id = pdfs_core::config::AppDirs::new()
.and_then(|dirs| dirs.machine_id())
.map_err(|e| CoreError::internal(format!("machine id: {e}")))?;
let file_name = profile_file_name(&machine_id);
let profile = self.build_profile(&device.uid, &machine_id)?;
let bytes = profile.to_bytes().map_err(CoreError::internal)?;
let len = bytes.len() as i64;
// The device root itself rejects file creation (B78), so the profile
// lives one level down, in a folder created on first save.
let dir_uid = self.ensure_profile_dir(&root_uid)?;
// Replace the existing document rather than adding a second file of the
// same name: the profile is a single mutable record, and a folder with
// `profile.json` and `profile (1).json` in it teaches the restore
// nothing about which to trust.
let existing = self.find_device_child_file(&dir_uid, &file_name)?;
match existing {
Some(uid) => self
.rt
.block_on(self.drive.upload_new_revision_from(
&uid,
Cursor::new(bytes),
len,
Vec::new(),
Some(now_secs()),
))
.map(|_| ())
.map_err(|e| CoreError::from_api(&e, "upload profile revision"))?,
None => {
self.rt
.block_on(self.drive.upload_file_replacing_draft_from(
&dir_uid,
&file_name,
"application/json",
Cursor::new(bytes),
len,
Vec::new(),
Some(now_secs()),
false,
))
.map_err(|e| CoreError::from_api(&e, "upload profile"))?;
}
}
info!(folders = profile.folders.len(), "profile backed up");
Ok(())
}
/// Snapshot the local arrangement into a [`Profile`].
pub(crate) fn build_profile(&self, device_uid: &str, machine_id: &str) -> CoreResult<Profile> {
let folders = profile_folders(
self.db
.sync_folder_list()
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?,
);
let pins = self
.db
.pin_list()
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?
.into_iter()
.map(|row| ProfilePin {
uid: row.uid,
path: row.path,
recursive: row.recursive,
})
.collect();
let cfg = pdfs_core::config::AppDirs::new()
.map(|d| d.load_config())
.unwrap_or_default();
Ok(Profile {
version: PROFILE_VERSION,
device_uid: device_uid.to_string(),
hostname: this_hostname(),
machine_id: Some(machine_id.to_string()),
saved_at: now_secs(),
folders,
pins,
ignore_patterns: cfg.ignore_patterns,
cache_budget: cfg.cache_budget,
mountpoint: cfg.mountpoint,
})
}
/// An untrashed *file* named `name` directly under `parent_uid`.
///
/// The sibling of `find_device_child_folder`; kept separate because a folder
/// named `profile.json` must not be mistaken for the profile.
pub(crate) fn find_device_child_file(
&self,
parent_uid: &NodeUid,
name: &str,
) -> CoreResult<Option<NodeUid>> {
let uids = self
.rt
.block_on(self.drive.enumerate_folder_children_node_uids(parent_uid))
.map_err(|e| CoreError::from_api(&e, "list device root"))?;
if uids.is_empty() {
return Ok(None);
}
let nodes = self
.rt
.block_on(self.drive.enumerate_nodes(&uids))
.map_err(|e| CoreError::from_api(&e, "resolve device root children"))?;
Ok(nodes
.into_iter()
.find(|n| !n.is_folder() && !n.trashed && n.name == name)
.map(|n| n.uid))
}
/// The untrashed files directly under `parent_uid` whose name passes
/// `keep`.
pub(crate) fn device_child_files(
&self,
parent_uid: &NodeUid,
keep: impl Fn(&str) -> bool,
) -> CoreResult<Vec<NodeUid>> {
let uids = self
.rt
.block_on(self.drive.enumerate_folder_children_node_uids(parent_uid))
.map_err(|e| CoreError::from_api(&e, "list device root"))?;
if uids.is_empty() {
return Ok(Vec::new());
}
let nodes = self
.rt
.block_on(self.drive.enumerate_nodes(&uids))
.map_err(|e| CoreError::from_api(&e, "resolve device root children"))?;
Ok(nodes
.into_iter()
.filter(|n| !n.is_folder() && !n.trashed && keep(&n.name))
.map(|n| n.uid)
.collect())
}
/// The device's `.proton-drive-linux` folder, creating it if this is the
/// first save on this device.
///
/// Reused by stable identity rather than recreated: a second folder of the
/// same name would split the profile across two documents, and the restore
/// would have no way to tell which is current.
pub(crate) fn ensure_profile_dir(&self, root_uid: &NodeUid) -> CoreResult<NodeUid> {
if let Some(uid) = self
.devices
.find_device_child_folder(root_uid, PROFILE_DIR_NAME)?
{
return Ok(uid);
}
let uid = self
.rt
.block_on(
self.drive
.create_folder(root_uid, PROFILE_DIR_NAME, Some(now_secs())),
)
.map_err(|e| CoreError::from_api(&e, "create profile folder"))?;
info!(name = PROFILE_DIR_NAME, "created device profile folder");
Ok(uid)
}
/// Download and parse the profiles of every computer that syncs this
/// device.
///
/// Reads every profile in `.proton-drive-linux/`: one per machine, and the
/// shared `profile.json` of clients before 3.5.0. Falls back to the device
/// root, where clients before the B78 fix wrote it. The fallback is
/// read-only: the next save writes to the folder, and the legacy document
/// is left alone rather than trashed, so an older client on another
/// machine keeps working. A profile that cannot be read is left out and
/// logged; the others still count.
pub(crate) fn load_profiles(&self, root_uid: &NodeUid) -> CoreResult<Vec<Profile>> {
let mut uids = match self
.devices
.find_device_child_folder(root_uid, PROFILE_DIR_NAME)?
{
Some(dir_uid) => self.device_child_files(&dir_uid, is_profile_file_name)?,
None => Vec::new(),
};
if uids.is_empty() {
uids = self.device_child_files(root_uid, |name| name == PROFILE_FILE_NAME)?;
if !uids.is_empty() {
info!("reading legacy profile from the device root");
}
}
let mut profiles = Vec::new();
for uid in uids {
let mut buf: Vec<u8> = Vec::new();
let parsed = self
.rt
.block_on(self.drive.download_file_to(&uid, &mut buf))
.map_err(|e| CoreError::from_api(&e, "download profile"))
.and_then(|()| Profile::parse(&buf).map_err(CoreError::invalid));
match parsed {
Ok(profile) => profiles.push(profile),
Err(e) => {
warn!(%uid, error = %e.message, "could not read a profile; leaving it out")
}
}
}
Ok(profiles)
}
// ---- restore ----------------------------------------
/// The folders under a device that could be synced here, each carrying a
/// proposed local path. `device` names another registered device by uid;
/// `None` is this machine's own.
///
/// The proposal comes from the profile when one exists and its path is
/// usable on this machine, and from `~/<name>` otherwise — a restored
/// `/home/other-user/Documents` would be wrong on a machine where that user
/// does not exist, and silently creating it would be worse.
pub(crate) fn list_restorable_folders(
&self,
device: Option<&str>,
) -> CoreResult<Vec<RestorableFolder>> {
let device = self.devices.restore_source(device)?;
let root_uid = parse_uid(&device.root_uid).ok_or_else(|| {
CoreError::internal(format!("bad device root uid: {}", device.root_uid))
})?;
let profiles = match self.load_profiles(&root_uid) {
Ok(p) => p,
// A missing or unreadable profile is not fatal: the remote tree
// alone is enough to offer a restore, just with plainer defaults.
Err(e) => {
warn!(error = %e.message, "could not read profiles; proposing defaults");
Vec::new()
}
};
let hostname = this_hostname();
let uids = self
.rt
.block_on(self.drive.enumerate_folder_children_node_uids(&root_uid))
.map_err(|e| CoreError::from_api(&e, "list device root"))?;
let nodes = if uids.is_empty() {
Vec::new()
} else {
self.rt
.block_on(self.drive.enumerate_nodes(&uids))
.map_err(|e| CoreError::from_api(&e, "resolve device root children"))?
};
// Folders already synced here are not restorable — they are already
// restored — but they are still listed, flagged, so the picker can show
// the whole device rather than a confusing subset.
let existing: Vec<String> = self
.db
.sync_folder_list()
.map_err(|e| CoreError::internal(format!("db: {e:?}")))?
.into_iter()
.map(|f| f.remote_uid)
.collect();
Ok(nodes
.into_iter()
// `.proton-drive-linux` holds the profile itself, not user data:
// offering it as a restorable folder would sync the bookkeeping
// back onto the machine it describes.
.filter(|n| n.is_folder() && !n.trashed && n.name != PROFILE_DIR_NAME)
// The name becomes a folder under the home folder: one with a `/`
// or a `..` in it would put the restore somewhere else.
.filter(|n| crate::remote_name_is_safe(&n.name))
.map(|n| {
let uid = n.uid.to_string();
let saved = saved_folder(&profiles, &uid, &hostname);
let proposed = saved
.map(|f| PathBuf::from(&f.local_path))
.filter(|p| path_is_usable_here(p))
.unwrap_or_else(|| default_local_path(&n.name));
RestorableFolder {
already_synced: existing.iter().any(|e| e == &uid),
remote_uid: uid,
name: n.name,
local_path: proposed.to_string_lossy().to_string(),
mode: saved
.map(|f| f.mode.to_string())
.unwrap_or_else(|| "mirror".into()),
}
})
.collect())
}
}
/// Only device backups belong in the device's cross-machine profile.
fn profile_folders(folders: Vec<pdfs_store::db::StoredSyncFolder>) -> Vec<ProfileFolder> {
folders
+1 -1
View File
@@ -172,7 +172,7 @@ impl Core {
CoreError::conflict(format!("{path} is being sent right now; try again"))
})?;
self.release_dropped_ops(uid, blobs);
self.hidden.lock().remove(uid);
self.writes.unhide(uid);
match node {
Some(node) => self.for_each_mount(|st, notify| {
put_back(st, notify, node);
+87
View File
@@ -0,0 +1,87 @@
//! The account's storage quota, as `statfs(2)` and the control socket ask
//! for it.
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use parking_lot::Mutex;
use pdfs_core::{CoreError, CoreResult};
use tracing::debug;
use super::{Core, QUOTA_TTL};
/// The last account quota answer, for `statfs(2)`, and whether a refresh
/// of it is running.
#[derive(Clone)]
pub(crate) struct QuotaCache {
/// Last account quota answer and when it was learned, for `statfs(2)`.
///
/// `df` and the free-space preflight of every file manager and installer ask
/// for this, and the answer costs a round trip — so it is served from here
/// for [`QUOTA_TTL`] and refreshed on a worker afterwards. Total account
/// storage moves slowly enough that a minute-old number is a better answer
/// than either a stall or the zeroes the default implementation returns.
last: Arc<Mutex<Option<(std::time::Instant, i64, i64)>>>,
/// Set while a `statfs` is refreshing [`QuotaCache::last`], so the others serve
/// the last figures instead of each holding a worker on the same request.
refreshing: Arc<AtomicBool>,
}
impl QuotaCache {
pub(crate) fn new() -> Self {
Self {
last: Arc::new(Mutex::new(None)),
refreshing: Arc::new(AtomicBool::new(false)),
}
}
}
impl Core {
/// Total account storage usage `(max_space, used_space)` in bytes, across all
/// Proton products (not Drive-only). A remote round-trip; nothing here is
/// cached.
pub(crate) fn account_quota(&self) -> CoreResult<(i64, i64)> {
let q = self.block_on_bounded(self.drive.quota()).map_err(|e| {
self.lost_link(&e, "account quota");
CoreError::from_api(&e, "account quota")
})?;
*self.quota.last.lock() = Some((std::time::Instant::now(), q.max_space, q.used_space));
Ok((q.max_space, q.used_space))
}
/// The account quota as `statfs(2)` needs it: cached for [`QUOTA_TTL`],
/// refetched after that, and `None` when there is no usable answer at all —
/// offline with nothing cached.
///
/// Never blocks on the network for a *fresh* value when a recent one exists,
/// because the callers are `df` and every "is there room?" preflight, and a
/// stale byte count is worth more to them than a stalled syscall. Offline,
/// the last known figures keep being served rather than degrading to zero.
pub(crate) fn account_quota_cached(&self) -> Option<(i64, i64)> {
if let Some((at, max_space, used_space)) = *self.quota.last.lock()
&& at.elapsed() < QUOTA_TTL
{
return Some((max_space, used_space));
}
let last = || self.quota.last.lock().map(|(_, max, used)| (max, used));
if !self.is_online()
|| self
.quota
.refreshing
.swap(true, std::sync::atomic::Ordering::AcqRel)
{
return last();
}
let refreshed = self.account_quota();
self.quota
.refreshing
.store(false, std::sync::atomic::Ordering::Release);
match refreshed {
Ok(q) => Some(q),
Err(error) => {
debug!(%error, "account quota refresh failed; serving the last known figures");
last()
}
}
}
}
+22 -105
View File
@@ -1,6 +1,7 @@
//! Revision-reader cache and streamed range-read subsystem.
use super::*;
use pdfs_vfs::open::{ReadFailure, assemble_open_read};
/// A read of an unpinned video at least this large streams *without* persisting
/// its blocks to the on-disk cache. Playing a 2 GB film would otherwise pour it
@@ -507,7 +508,7 @@ impl Core {
// A queued write has not reached the remote yet, so the remote's current
// revision is stale and the staged blob is the truth. Serve from it until
// the drain worker lands the upload.
if let Some(pending) = self.pending.lock().get(uid).cloned() {
if let Some(pending) = self.writes.queued(uid) {
return self.read_pending(&pending, offset, len);
}
// A node created offline and never written has no blob and no remote: it
@@ -1049,10 +1050,11 @@ impl Core {
offset: u64,
size: u64,
) -> Result<Vec<u8>, Errno> {
let read = assemble_open_read(file, len, uid, base_size, written, offset, size, |s, n| {
let read = assemble_open_read(file, len, base_size, written, offset, size, |s, n| {
self.read_range(uid, base_mtime, base_size, s, n, true)
.map(Some)
})?;
})
.map_err(|failure| open_read_errno(uid, failure))?;
Ok(read.unwrap_or_default())
}
@@ -1075,9 +1077,10 @@ impl Core {
offset: u64,
size: u64,
) -> Result<Option<Vec<u8>>, Errno> {
assemble_open_read(file, len, uid, base_size, written, offset, size, |s, n| {
assemble_open_read(file, len, base_size, written, offset, size, |s, n| {
Ok(self.cached_range(uid, base_mtime, base_size, s, n))
})
.map_err(|failure| open_read_errno(uid, failure))
}
/// Bytes `[offset, offset + size)` of file `ino` as `read` would serve
@@ -1094,16 +1097,12 @@ impl Core {
offset: u64,
size: u64,
) -> Result<Option<Vec<u8>>, Errno> {
let handle = self.state().active_writes.get(&ino).map(|h| {
(
h.file.clone(),
h.len,
h.uid.clone(),
h.base_mtime,
h.base_size,
h.written.clone(),
)
});
// A writer still open, or one whose release is still queueing it.
let handle = self
.state()
.open
.reader(ino)
.map(|v| (v.file, v.len, v.uid, v.base_mtime, v.base_size, v.written));
if let Some((file, len, uid, base_mtime, base_size, written)) = handle {
return self.serve_open_read_local(
&file, len, &uid, base_mtime, base_size, &written, offset, size,
@@ -1132,7 +1131,7 @@ impl Core {
true => self.landed_stand_in_uid(&uid).unwrap_or(uid),
false => uid,
};
if let Some(pending) = self.pending.lock().get(&uid).cloned() {
if let Some(pending) = self.writes.queued(&uid) {
let m = &pending.meta;
let file = File::open(&pending.path).map_err(|e| {
error!(%uid, path = %pending.path.display(), error = %e, "open staged blob failed");
@@ -1305,47 +1304,16 @@ impl Core {
}
}
/// The bytes `[offset, offset + size)` of a file open for writing: authored
/// ranges from its scratch `file`, the rest from its base through `base`,
/// and zeros past the base. `Ok(None)` when `base` says it cannot answer.
#[allow(clippy::too_many_arguments)]
fn assemble_open_read(
file: &File,
len: u64,
uid: &NodeUid,
base_size: u64,
written: &Intervals,
offset: u64,
size: u64,
mut base: impl FnMut(u64, u64) -> Result<Option<Vec<u8>>, Errno>,
) -> Result<Option<Vec<u8>>, Errno> {
if offset >= len || size == 0 {
return Ok(Some(Vec::new()));
}
let end = offset.saturating_add(size).min(len);
let mut out = Vec::with_capacity((end - offset) as usize);
for (s, e, authored) in written.segments(offset, end) {
if authored {
let mut buf = vec![0u8; (e - s) as usize];
file.read_exact_at(&mut buf, s).map_err(|err| {
warn!(%uid, error = %err, "scratch read failed");
Errno::EIO
})?;
out.extend_from_slice(&buf);
} else {
let bend = e.min(base_size);
if s < bend {
match base(s, bend - s)? {
Some(bytes) => out.extend_from_slice(&bytes),
None => return Ok(None),
}
}
// Anything past the base is a hole: zero-fill.
let zeros = e.saturating_sub(s.max(base_size));
out.resize(out.len() + zeros as usize, 0);
/// The errno for a read of an open file that failed: the base's own, or
/// `EIO` for the scratch file.
fn open_read_errno(uid: &NodeUid, failure: ReadFailure<Errno>) -> Errno {
match failure {
ReadFailure::Base(errno) => errno,
ReadFailure::Scratch(error) => {
warn!(%uid, %error, "scratch read failed");
Errno::EIO
}
}
Ok(Some(out))
}
#[cfg(test)]
@@ -1500,54 +1468,3 @@ mod prefetch_tests {
assert!(prefetch.streams.lock().len() <= MAX_PREFETCH_STREAMS + 1);
}
}
#[cfg(test)]
mod open_read_tests {
use super::*;
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
fn scratch(bytes: &[u8]) -> (File, PathBuf) {
let path = std::env::temp_dir().join(format!(
"pdfs-open-read-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let mut file = File::options()
.create_new(true)
.read(true)
.write(true)
.open(&path)
.unwrap();
file.write_all(bytes).unwrap();
(file, path)
}
/// The dispatch loop answers from what is on this machine and says so
/// when the base would have to be downloaded, for a worker to do it
/// (`docs/BUGS.md` B227).
#[test]
fn a_read_needing_the_base_says_so_instead_of_fetching() {
let uid = NodeUid::new(VolumeId::from("v"), LinkId::from("f"));
let (file, path) = scratch(b"ABCDEFGH");
let mut written = Intervals::default();
written.add(0, 4);
let authored = assemble_open_read(&file, 8, &uid, 8, &written, 0, 4, |_, _| {
panic!("an authored range never asks the base")
});
assert_eq!(authored.unwrap().as_deref(), Some(&b"ABCD"[..]));
let missing = assemble_open_read(&file, 8, &uid, 8, &written, 2, 6, |_, _| Ok(None));
assert_eq!(missing.unwrap(), None);
let base = assemble_open_read(&file, 10, &uid, 8, &written, 2, 8, |s, n| {
assert_eq!((s, n), (4, 4));
Ok(Some(b"efgh".to_vec()))
});
assert_eq!(base.unwrap().as_deref(), Some(&b"CDefgh\0\0"[..]));
let _ = std::fs::remove_file(path);
}
}
+176 -19
View File
@@ -2,6 +2,7 @@
//! recovering writes that were fsynced but not queued when the daemon stopped.
use super::*;
use pdfs_vfs::namespace::{ReplaceOutcome, settle_from_drive, settle_from_queue};
impl Core {
/// Rehydrate the in-memory `State` maps from the DB on mount, so a cold
@@ -28,17 +29,11 @@ impl Core {
// lying about the size reads as data loss. `hydrate_pending` ran before
// us, so the pending map is populated; snapshot it here rather than hold
// both locks at once.
let pending_sizes: HashMap<NodeUid, u64> = {
let pending = self.pending.lock();
pending
.iter()
.map(|(uid, pr)| (uid.clone(), pr.meta.len))
.collect()
};
let pending_sizes = self.writes.queued_sizes();
// `hydrate_pending` runs first and restores queued-trash tombstones.
// Their node rows remain persisted as drain-time access authority, but
// must not reappear in the mounted namespace after a restart.
let hidden = self.hidden.lock().clone();
let hidden = self.writes.hidden();
let mut st = self.state();
// Pass 1: give every uid its inode from its local id (the root is
@@ -102,11 +97,173 @@ impl Core {
st.hydrate_access();
// Pass 3: rebuild child listings for fully-enumerated folders.
let listings = listed_children(&st.entries, listed_dirs);
let listings = crate::state::listed_children(&st.entries, listed_dirs);
st.children.extend(listings);
info!(nodes = st.entries.len(), "hydrated metadata cache from db");
}
/// Startup recovery of the queue, with this daemon as its host.
pub(crate) fn recovery(&self) -> Recovery {
Recovery {
db: self.db.clone(),
cache: self.cache.clone(),
writes: self.writes.clone(),
host: Arc::new(self.clone()),
}
}
}
/// What recovery needs from the rest of the daemon.
pub(crate) trait RecoveryHost: Send + Sync {
/// Queue a write recovered from a blob fsynced before a stop, as if its
/// handle had just been released.
fn queue_recovered(&self, uid: &NodeUid, blob: &Path, meta: StagedWrite) -> Result<(), Errno>;
/// Drive's node `uid`: `None` when Drive cannot be asked now, and
/// `Some(None)` when it does not have the node.
fn remote_node(&self, uid: &NodeUid) -> Option<Option<Node>>;
/// Drop the queued trash of a replaced node whose rename was never
/// queued, so it stays where it is.
fn withdraw_victim_trash(&self, uid: &NodeUid) -> Result<(), Errno>;
/// Bring a replaced node back out of Drive's trash. Best effort; a failure
/// is logged and recorded in the activity log.
fn restore_victim(&self, uid: &NodeUid, parent: &NodeUid, name: &str);
}
impl RecoveryHost for Core {
fn queue_recovered(&self, uid: &NodeUid, blob: &Path, meta: StagedWrite) -> Result<(), Errno> {
self.enqueue_staged_write(uid, 0, blob, meta)
}
fn remote_node(&self, uid: &NodeUid) -> Option<Option<Node>> {
if !self.is_online() {
return None;
}
match self.block_on_bounded(self.drive.enumerate_nodes(std::slice::from_ref(uid))) {
Ok(nodes) => Some(nodes.into_iter().find(|node| node.uid == *uid)),
Err(error) if is_gone(&error) => Some(None),
Err(error) => {
self.lost_link(&error, "settle a replacing rename");
None
}
}
}
fn withdraw_victim_trash(&self, uid: &NodeUid) -> Result<(), Errno> {
self.discard_queued_ops(uid)?;
self.writes.unhide(uid);
Ok(())
}
fn restore_victim(&self, uid: &NodeUid, parent: &NodeUid, name: &str) {
self.restore_replaced(Some(&(0, uid.clone())), parent, name);
}
}
/// Rebuilds the queue from the database and the staging area after a
/// restart. Holds the database, the content cache and the write-back's state;
/// queueing a recovered write goes through [`RecoveryHost`].
pub(crate) struct Recovery {
db: Arc<Db>,
cache: Arc<ContentCache>,
writes: writes::WriteState,
host: Arc<dyn RecoveryHost>,
}
impl Recovery {
/// Settle the replacing renames an earlier run started and did not end
/// (`docs/BUGS.md` B302): forget the ones that reached their end state,
/// and put the victim back where the rename did not happen. One that needs
/// Drive while Drive cannot be asked stays for a later pass.
///
/// Runs at mount, after [`hydrate_pending`](Self::hydrate_pending), and on
/// the drain's idle passes. The journal holds only this run's own renames
/// apart from cut-off ones, and those are left alone, so the idle pass
/// never undoes a rename in progress.
pub(crate) fn settle_replaces(&self) {
let intents = match self.db.open_replaces() {
Ok(intents) if intents.is_empty() => return,
Ok(intents) => intents,
Err(error) => {
warn!(%error, "reading cut-off replacing renames failed");
return;
}
};
let ops = match self.db.pending_ops() {
Ok(ops) => ops,
Err(error) => {
warn!(%error, "reading the queue to settle replacing renames failed");
return;
}
};
for intent in intents {
let (Some(source), Some(victim), Some(parent)) = (
parse_node_uid(&intent.source_uid),
parse_node_uid(&intent.victim_uid),
parse_node_uid(&intent.new_parent_uid),
) else {
warn!(source = %intent.source_uid, "dropping a replace intent with an unparseable uid");
let _ = self.db.end_replace(&intent.source_uid);
continue;
};
// The source's end state is queued when one of its ops puts it at
// the new name: a rename, or the create a queued node's rename
// rewrote.
let rename_queued = ops.iter().any(|op| {
op.uid == intent.source_uid
&& [OP_RENAME, OP_CREATE, OP_MKDIR].contains(&op.kind.as_str())
&& op.parent_uid.as_deref() == Some(intent.new_parent_uid.as_str())
&& op.name.as_deref() == Some(intent.new_name.as_str())
});
let victim_trash_queued = ops
.iter()
.any(|op| op.uid == intent.victim_uid && op.kind == OP_TRASH);
let outcome = settle_from_queue(rename_queued, victim_trash_queued, is_local_uid(&victim))
.unwrap_or_else(|| {
if is_local_uid(&source) {
// A queued node whose create landed under the rename;
// Drive knows it by a uid this entry does not have.
warn!(%source, %victim, name = intent.new_name,
"cannot settle a replacing rename of a node created here; leaving the replaced node in the trash");
return ReplaceOutcome::Done;
}
let source_node = self.host.remote_node(&source);
let victim_node = match source_node {
Some(_) => self.host.remote_node(&victim),
None => None,
};
settle_from_drive(
&parent,
&intent.new_name,
source_node.as_ref().map(Option::as_ref),
victim_node.as_ref().map(Option::as_ref),
)
});
match outcome {
ReplaceOutcome::Wait => continue,
ReplaceOutcome::Done => {
info!(%source, name = intent.new_name, "a replacing rename cut off by a stop had finished");
}
ReplaceOutcome::WithdrawVictimTrash => {
if let Err(error) = self.host.withdraw_victim_trash(&victim) {
warn!(%victim, ?error, "withdrawing a replaced node's queued trash failed; trying again later");
continue;
}
info!(%victim, name = intent.new_name, "kept a node a cut-off rename was replacing");
}
ReplaceOutcome::RestoreVictim => {
self.host.restore_victim(&victim, &parent, &intent.new_name);
info!(%victim, name = intent.new_name, "restored a node a cut-off rename had replaced");
}
}
if let Err(error) = self.db.end_replace(&intent.source_uid) {
warn!(%source, %error, "ending a settled replace intent failed");
}
}
}
/// 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 —
@@ -115,7 +272,7 @@ impl Core {
///
/// 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) {
pub(crate) fn hydrate_pending(&self) {
let ops = match self.db.pending_ops() {
Ok(ops) => ops,
Err(e) => {
@@ -123,7 +280,7 @@ impl Core {
return;
}
};
let mut map = self.pending.lock();
let mut map = self.writes.pending.lock();
let mut restored = 0usize;
for op in ops {
let Some(uid) = parse_node_uid(&op.uid) else {
@@ -132,7 +289,7 @@ impl Core {
continue;
};
if op.kind == OP_TRASH {
self.hidden.lock().insert(uid.clone());
self.writes.hide(&uid);
}
restored += 1;
// Only a revision must have a blob. A create carries none until
@@ -188,7 +345,7 @@ impl Core {
/// `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) {
pub(crate) fn reconcile_staging(&self) {
let staged = self.cache.staged_writes();
if staged.is_empty() {
return;
@@ -225,7 +382,7 @@ impl Core {
example.get_or_insert_with(|| blob.clone());
continue;
};
if self.pending.lock().contains_key(&uid) {
if self.writes.is_queued(&uid) {
// A newer write for the same node is queued and carries its own
// blob. These bytes are older; keeping them is right, uploading
// them over the newer ones is not.
@@ -266,7 +423,7 @@ impl Core {
if let Some(old) = superseded {
self.cache.discard_staged(Path::new(&old));
}
self.pending.lock().insert(
self.writes.pending.lock().insert(
uid.clone(),
PendingRevision {
path: blob.clone(),
@@ -320,7 +477,7 @@ impl Core {
/// 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) {
pub(crate) fn recover_fsynced_writes(&self) {
let recovered = self.cache.recovered_writes();
if recovered.is_empty() {
return;
@@ -336,7 +493,7 @@ impl Core {
// now would use the wrong remote base. enqueue_staged_write would abandon it
// to staging; keep it in recovery instead so the drain loop can queue it
// once the queue clears.
if !meta.complete && self.pending.lock().contains_key(&uid) {
if !meta.complete && self.writes.is_queued(&uid) {
continue;
}
@@ -344,7 +501,7 @@ impl Core {
// 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) {
match self.host.queue_recovered(&uid, &blob, meta) {
Ok(()) => {
self.cache.discard_recovered(&blob);
queued += 1;
@@ -377,7 +534,7 @@ impl Core {
/// 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) {
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("?"),
+2 -6
View File
@@ -172,7 +172,7 @@ impl Core {
rel: dest_rel,
},
) = (&source, &dest)
&& Arc::ptr_eq(&core.root, &dest_core.root)
&& Arc::ptr_eq(&core.session.root, &dest_core.session.root)
{
return core.move_to(rel, dest_rel);
}
@@ -453,11 +453,7 @@ impl Core {
// longer has that uid, so the move went ahead under an open write.
let mut writing = false;
self.for_each_state(|st| {
writing = st
.active_writes
.keys()
.chain(&st.releasing)
.any(|&open| ino_is_under(st, open, ino));
writing = st.open.owed(false).any(|open| ino_is_under(st, open, ino));
});
Ok(writing)
}
+4 -7
View File
@@ -485,11 +485,8 @@ impl Core {
// 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())
.open
.owed(true)
.any(|open| relocate::ino_is_under(&st, open, ino));
(entry.node.name.clone(), entry.node.is_folder(), unsaved)
};
@@ -693,7 +690,7 @@ impl Core {
self.for_each_state(|st| {
st.forget_or_unlink(uid);
});
self.hidden.lock().insert(uid.clone());
self.writes.hide(uid);
if open_now {
if let Err(error) = self.withdraw_queued_ops(uid) {
error!(%uid, "remote replacement landed but queued-op cleanup failed");
@@ -763,7 +760,7 @@ impl Core {
.and_then(batch::into_unit)
{
Ok(()) => {
self.hidden.lock().remove(uid);
self.writes.unhide(uid);
self.for_each_mount(|st, notify| {
if let Some(&ino) = st.by_uid.get(parent) {
st.invalidate_listing(ino);
+1 -1
View File
@@ -133,7 +133,7 @@ impl Core {
// These paths walk the tree lazily, so a cold node needs the API.
// Offline that surfaces as EIO, which on its own would read to the
// user as a broken file rather than a missing network.
libc::EIO if !self.online.load(Ordering::Relaxed) => CoreError::offline(),
libc::EIO if !self.is_online() => CoreError::offline(),
libc::EINVAL => CoreError::invalid(format!("{what}: not a usable path")),
libc::ENOSPC => CoreError::new(ErrorKind::Quota, format!("{what}: out of space")),
libc::EEXIST => CoreError::conflict(format!("{what}: already exists")),
+98 -125
View File
@@ -16,7 +16,7 @@
//! file rather than trying to describe the new one. The next read repopulates
//! from whatever is live by then.
//! - **The active revision cannot be deleted**, and the server — not this code —
//! is what enforces that. [`Core::delete_revision_for_uid`] refuses locally
//! is what enforces that. [`Revisions::delete`] refuses locally
//! too, so the user gets a sentence instead of an API code.
use std::path::Path;
@@ -27,7 +27,12 @@ use proton_drive_rs::Revision;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use tracing::info;
use std::sync::Arc;
use proton_drive_rs::ProtonDriveClient;
use super::Core;
use crate::drive::DriveApi;
/// A [`Revision`] as the control protocol reports it.
fn revision_info(revision: Revision) -> RevisionInfo {
@@ -45,70 +50,37 @@ fn revision_info(revision: Revision) -> RevisionInfo {
}
}
impl Core {
/// The version history of the file at mountpoint-relative `rel`.
pub(crate) fn list_revisions(&self, rel: &Path) -> CoreResult<Vec<RevisionInfo>> {
let (_ino, uid) = self.resolve(rel)?;
self.list_revisions_for_uid(&uid)
}
/// A file's revisions on Drive. Every method takes a node already resolved to
/// its uid, and the name the activity feed shows for it.
///
/// It reaches the filesystem through [`RevisionsHost`]. [`Core::revisions`]
/// builds one on demand with the daemon as its host.
pub(crate) struct Revisions {
client: ProtonDriveClient,
drive: Arc<dyn DriveApi>,
rt: tokio::runtime::Handle,
host: Arc<dyn RevisionsHost>,
}
/// [`Core::list_revisions`] for a node addressed through any daemon location.
pub(crate) fn list_revisions_by_uid(&self, uid: &str) -> CoreResult<Vec<RevisionInfo>> {
let uid = self.resolve_anywhere(uid)?;
self.list_revisions_for_uid(&uid)
}
/// What [`Revisions`] needs from the filesystem.
pub(crate) trait RevisionsHost: Send + Sync {
/// Refuse unless this daemon may change the node's content. `what` names
/// the operation in the error.
fn require_writable(&self, uid: &NodeUid, what: &str) -> CoreResult<()>;
/// The node's active revision changed on the server: forget its cached
/// content and open readers, and fetch it again if it is kept offline.
fn content_replaced(&self, uid: &NodeUid);
/// Add an entry to the activity log.
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool);
}
fn list_revisions_for_uid(&self, uid: &NodeUid) -> CoreResult<Vec<RevisionInfo>> {
let revisions = self
.rt
.block_on(self.client.enumerate_revisions(uid))
.map_err(|e| CoreError::from_api(&e, "list revisions"))?;
Ok(revisions.into_iter().map(revision_info).collect())
}
/// Make `revision_id` the current content of the file at `rel`.
pub(crate) fn restore_revision(&self, rel: &Path, revision_id: &str) -> CoreResult<()> {
let (_ino, uid) = self.resolve(rel)?;
let name = rel
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| uid.to_string());
self.restore_revision_for_uid(&uid, revision_id, &name)?;
// The size and mtime a listing shows describe the revision that was
// active a moment ago.
self.invalidate_parent_listing(rel);
Ok(())
}
/// [`Core::restore_revision`] for a node addressed through any daemon
/// location.
pub(crate) fn restore_revision_by_uid(&self, uid: &str, revision_id: &str) -> CoreResult<()> {
let uid = self.resolve_anywhere(uid)?;
let name = uid.to_string();
self.restore_revision_for_uid(&uid, revision_id, &name)
}
fn restore_revision_for_uid(
&self,
uid: &NodeUid,
revision_id: &str,
name: &str,
) -> CoreResult<()> {
// Restoring rewrites the file's content: the same authority a write
// needs, not the one a read needs.
impl RevisionsHost for Core {
fn require_writable(&self, uid: &NodeUid, what: &str) -> CoreResult<()> {
self.require_uid_writable(uid)
.map_err(|error| self.errno_error(error, "restore revision"))?;
if let Err(e) = self
.rt
.block_on(self.client.restore_revision(uid, revision_id))
{
let error = CoreError::from_api(&e, "restore revision");
self.log_activity(ActivityKind::Restore, name, &error, false);
return Err(error);
}
// The active revision is changing behind our back — anything describing
// the old one (cached blocks, an open reader, the size in a listing) is
// stale from here on, and the server may not have applied the swap yet.
.map_err(|error| self.errno_error(error, what))
}
fn content_replaced(&self, uid: &NodeUid) {
self.cache.evict(uid);
self.evict_reader(uid);
// A file kept offline gets the restored content back on disk, and
@@ -116,9 +88,58 @@ impl Core {
if self.cache.is_pinned(uid) {
self.recheck_pinned(uid);
}
self.log_activity(
}
fn log_activity(&self, kind: ActivityKind, target: String, detail: String, ok: bool) {
Core::log_activity(self, kind, target, detail, ok);
}
}
impl Core {
/// The revisions service, with this daemon as its host.
pub(crate) fn revisions(&self) -> Revisions {
Revisions {
client: self.client.clone(),
drive: self.drive.clone(),
rt: self.rt.clone(),
host: Arc::new(self.clone()),
}
}
}
impl Revisions {
pub(crate) fn list(&self, uid: &NodeUid) -> CoreResult<Vec<RevisionInfo>> {
let revisions = self
.rt
.block_on(self.client.enumerate_revisions(uid))
.map_err(|e| CoreError::from_api(&e, "list revisions"))?;
Ok(revisions.into_iter().map(revision_info).collect())
}
pub(crate) fn restore(&self, uid: &NodeUid, revision_id: &str, name: &str) -> CoreResult<()> {
// Restoring rewrites the file's content: the same authority a write
// needs, not the one a read needs.
self.host.require_writable(uid, "restore revision")?;
if let Err(e) = self
.rt
.block_on(self.client.restore_revision(uid, revision_id))
{
let error = CoreError::from_api(&e, "restore revision");
self.host.log_activity(
ActivityKind::Restore,
name.to_string(),
error.to_string(),
false,
);
return Err(error);
}
// The active revision is changing behind our back — anything describing
// the old one (cached blocks, an open reader, the size in a listing) is
// stale from here on, and the server may not have applied the swap yet.
self.host.content_replaced(uid);
self.host.log_activity(
ActivityKind::Restore,
name,
name.to_string(),
format!("restored version {revision_id}"),
true,
);
@@ -126,32 +147,8 @@ impl Core {
Ok(())
}
/// Permanently delete `revision_id` from the history of the file at `rel`.
pub(crate) fn delete_revision(&self, rel: &Path, revision_id: &str) -> CoreResult<()> {
let (_ino, uid) = self.resolve(rel)?;
let name = rel
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| uid.to_string());
self.delete_revision_for_uid(&uid, revision_id, &name)
}
/// [`Core::delete_revision`] for a node addressed through any daemon
/// location.
pub(crate) fn delete_revision_by_uid(&self, uid: &str, revision_id: &str) -> CoreResult<()> {
let uid = self.resolve_anywhere(uid)?;
let name = uid.to_string();
self.delete_revision_for_uid(&uid, revision_id, &name)
}
fn delete_revision_for_uid(
&self,
uid: &NodeUid,
revision_id: &str,
name: &str,
) -> CoreResult<()> {
self.require_uid_writable(uid)
.map_err(|error| self.errno_error(error, "delete revision"))?;
pub(crate) fn delete(&self, uid: &NodeUid, revision_id: &str, name: &str) -> CoreResult<()> {
self.host.require_writable(uid, "delete revision")?;
// The server rejects deleting the active revision; saying so here is a
// sentence the user can act on instead of an API code, and it costs one
// listing the front-end already made to show the version list.
@@ -171,9 +168,9 @@ impl Core {
self.rt
.block_on(self.client.delete_revision(uid, revision_id))
.map_err(|e| CoreError::from_api(&e, "delete revision"))?;
self.log_activity(
self.host.log_activity(
ActivityKind::DeleteForever,
name,
name.to_string(),
format!("deleted version {revision_id}"),
true,
);
@@ -181,36 +178,7 @@ impl Core {
Ok(())
}
/// Write `revision_id` of the file at `rel` to the absolute local path
/// `dest`, leaving the file itself untouched.
pub(crate) fn save_revision_as(
&self,
rel: &Path,
revision_id: &str,
dest: &Path,
) -> CoreResult<u64> {
let (_ino, uid) = self.resolve(rel)?;
let name = rel
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| uid.to_string());
self.save_revision_for_uid(&uid, revision_id, &name, dest)
}
/// [`Core::save_revision_as`] for a node addressed through any daemon
/// location.
pub(crate) fn save_revision_as_by_uid(
&self,
uid: &str,
revision_id: &str,
dest: &Path,
) -> CoreResult<u64> {
let uid = self.resolve_anywhere(uid)?;
let name = uid.to_string();
self.save_revision_for_uid(&uid, revision_id, &name, dest)
}
fn save_revision_for_uid(
pub(crate) fn save_as(
&self,
uid: &NodeUid,
revision_id: &str,
@@ -253,13 +221,18 @@ impl Core {
// A half-written file looks like a successful export to every
// tool that opens it afterwards.
let _ = std::fs::remove_file(dest);
self.log_activity(ActivityKind::Download, name, &error, false);
self.host.log_activity(
ActivityKind::Download,
name.to_string(),
error.to_string(),
false,
);
return Err(error);
}
};
self.log_activity(
self.host.log_activity(
ActivityKind::Download,
name,
name.to_string(),
format!("saved version {revision_id} to {}", dest.display()),
true,
);
+45 -3
View File
@@ -2,7 +2,49 @@
use super::*;
/// Search over the database's node and home indexes. Holds the database, the
/// content cache (to say whether a hit is on this computer), the on-demand
/// mounts (to say which folders a hit can be opened through) and the home
/// indexer's busy flag.
pub(crate) struct Search {
db: Arc<Db>,
cache: Arc<ContentCache>,
mounts: Arc<Mutex<mount::SecondaryMountRegistry<SecondaryMount>>>,
indexing: Arc<AtomicBool>,
}
impl Core {
/// Search, over this daemon's indexes.
pub(crate) fn searcher(&self) -> Search {
Search {
db: self.db.clone(),
cache: self.cache.clone(),
mounts: self.mounts.clone(),
indexing: self.indexing.clone(),
}
}
/// See [`Search::roots`].
pub(super) fn search_roots(&self) -> SearchRoots {
self.searcher().roots()
}
}
impl Search {
/// Whether the home indexer is walking right now.
pub(crate) fn indexing(&self) -> bool {
self.indexing.load(Ordering::Relaxed)
}
/// The pinned uids, expanded through pinned folders, as one query.
fn pinned_set(&self) -> HashSet<String> {
self.db
.pinned_uids()
.unwrap_or_default()
.into_iter()
.collect()
}
/// The local locations a search result can be opened through, resolved once
/// per search rather than once per hit.
///
@@ -14,7 +56,7 @@ impl Core {
/// 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 {
pub(super) fn roots(&self) -> SearchRoots {
let live_mounts = self.mounts.lock();
let folders = self.db.sync_folder_list().unwrap_or_default();
SearchRoots {
@@ -43,7 +85,7 @@ impl Core {
.db
.search_in(query, limit, scope)
.map_err(|e| CoreError::from_api(&e, "search"))?;
let roots = self.search_roots();
let roots = self.roots();
let pinned = self.pinned_set();
Ok(hits
.into_iter()
@@ -105,7 +147,7 @@ impl Core {
// 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 roots = self.roots();
let pinned = self.pinned_set();
self.db
.search_candidates(query, candidate_limit)
+267
View File
@@ -0,0 +1,267 @@
//! The long-lived loops a mount runs, each as a [`Service`].
//!
//! Each type here names its thread, says how a stop reaches it and whether the
//! mount can do without it. `mount.rs` builds the list and starts it with
//! [`Services::start`](pdfs_core::lifecycle::Services::start); a stop wakes and
//! joins them in reverse order.
use std::os::unix::net::UnixListener;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use pdfs_core::lifecycle::{Service, Wake};
use pdfs_core::shutdown::Shutdown;
use pdfs_store::db::Db;
use super::Core;
use super::background::run_local_index;
use super::control::run_control_socket;
use super::events::{EventHub, run_event_sampler};
use super::sync;
use super::transfers::TransferRegistry;
/// One of the threads that send queued changes to Drive. The drain workers wait
/// on one condvar, which a stop has to notify; one notify wakes them all, so
/// only the first worker carries the wake.
pub(crate) struct DrainWorker {
pub(crate) core: Core,
pub(crate) index: usize,
}
impl Service for DrainWorker {
fn name(&self) -> String {
format!("pdfs-drain-{}", self.index)
}
fn wake(&self) -> Option<Wake> {
let core = self.core.clone();
(self.index == 0).then(|| Box::new(move || core.wake_drain()) as Wake)
}
fn run(self: Box<Self>) {
self.core.run_pending_drain(self.index == 0);
}
}
/// 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. It waits on its
/// channel, so a stop sends it `Stop`.
///
/// Optional: the mount still serves files without it.
pub(crate) struct SyncEngine {
pub(crate) syncer: sync::Syncer,
pub(crate) tx: std::sync::mpsc::Sender<sync::SyncMsg>,
pub(crate) rx: std::sync::mpsc::Receiver<sync::SyncMsg>,
}
impl Service for SyncEngine {
fn name(&self) -> String {
"pdfs-sync".to_owned()
}
fn required(&self) -> bool {
false
}
fn wake(&self) -> Option<Wake> {
let tx = self.tx.clone();
Some(Box::new(move || {
let _ = tx.send(sync::SyncMsg::Stop);
}))
}
fn run(self: Box<Self>) {
let Self { syncer, rx, .. } = *self;
sync::run(syncer, rx);
}
}
/// Reconciles leftover `(sync-conflict …)` copies: drops the ones that turned
/// out identical to the live file and surfaces the ones that differ. It
/// enumerates and trashes, so it must never block a FUSE call.
pub(crate) struct ConflictSweep(pub(crate) super::sweep::Sweeper);
impl Service for ConflictSweep {
fn name(&self) -> String {
"pdfs-conflict-sweep".to_owned()
}
fn run(self: Box<Self>) {
self.0.run();
}
}
/// Watches the link for the life of the mount: a mount from the cache waits
/// for the network to come back, and an online one can lose it at any moment.
pub(crate) struct OnlineProbe(pub(crate) super::link::OnlineProbe);
impl Service for OnlineProbe {
fn name(&self) -> String {
"pdfs-online-probe".to_owned()
}
fn run(self: Box<Self>) {
self.0.run();
}
}
/// Keeps pinned files on this computer through changes made elsewhere, and
/// fetches the ones a failed or missed download left out (`docs/BUGS.md`
/// B282). A check lists folders and downloads files.
pub(crate) struct PinKeeper(pub(crate) super::keeper::PinKeeper);
impl Service for PinKeeper {
fn name(&self) -> String {
"pdfs-pin-keeper".to_owned()
}
fn run(self: Box<Self>) {
self.0.run();
}
}
/// Keeps the launcher prompt's "This computer" index fresh. The walk is
/// I/O-heavy and must never sit in front of a FUSE callback.
pub(crate) struct LocalIndex {
pub(crate) db: Arc<Db>,
pub(crate) indexing: Arc<AtomicBool>,
pub(crate) transfers: Arc<TransferRegistry>,
pub(crate) mountpoint: PathBuf,
pub(crate) shutdown: Arc<Shutdown>,
}
impl Service for LocalIndex {
fn name(&self) -> String {
"pdfs-localindex".to_owned()
}
fn run(self: Box<Self>) {
let Self {
db,
indexing,
transfers,
mountpoint,
shutdown,
} = *self;
run_local_index(db, indexing, transfers, mountpoint, shutdown);
}
}
/// Answers the control socket, one job per connection.
///
/// The listener blocks in `accept`, which only returns when a connection
/// arrives, so a stop connects to it. It connects while the socket still
/// exists, which is the point of the poke, then unlinks 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. The
/// connections it handed off are jobs, which a stop joins; a subscription
/// among them waits on its mailbox, so the wake rings every mailbox too.
pub(crate) struct ControlListener {
pub(crate) core: Core,
pub(crate) username: String,
pub(crate) mountpoint: PathBuf,
pub(crate) listener: UnixListener,
pub(crate) socket: PathBuf,
}
impl Service for ControlListener {
fn name(&self) -> String {
"pdfs-control".to_owned()
}
fn wake(&self) -> Option<Wake> {
let socket = self.socket.clone();
let events: Arc<EventHub> = self.core.events.clone();
Some(Box::new(move || {
let _ = std::os::unix::net::UnixStream::connect(&socket);
let _ = std::fs::remove_file(&socket);
events.wake_all();
}))
}
fn run(self: Box<Self>) {
let Self {
core,
username,
mountpoint,
listener,
..
} = *self;
run_control_socket(core, username, mountpoint, listener);
}
}
/// Publishes what changes without one place to publish it from (status,
/// transfers, sync progress) to the front ends subscribed on the control
/// socket.
///
/// Optional: front ends still get every published change, only not the
/// sampled ones.
pub(crate) struct EventSampler {
pub(crate) core: Core,
pub(crate) username: String,
pub(crate) mountpoint: PathBuf,
}
impl Service for EventSampler {
fn name(&self) -> String {
"pdfs-events".to_owned()
}
fn required(&self) -> bool {
false
}
fn run(self: Box<Self>) {
run_event_sampler(self.core, self.username, self.mountpoint);
}
}
/// Watches the worker pool and answers the systemd watchdog. Its liveness
/// probe is a round trip over the control socket, so it starts after the
/// listener.
///
/// Optional: the mount works without it, only it is no longer diagnosable if
/// it wedges.
pub(crate) struct Supervisor {
pub(crate) core: Core,
pub(crate) socket: PathBuf,
}
impl Service for Supervisor {
fn name(&self) -> String {
"pdfs-supervisor".to_owned()
}
fn required(&self) -> bool {
false
}
fn run(self: Box<Self>) {
super::supervisor::run(self.core, self.socket);
}
}
/// Holds off a shutdown while changes exist only here (B66).
///
/// Optional: without it a shutdown is not delayed, and queued changes go out
/// on the next start.
pub(crate) struct Inhibitor {
pub(crate) db: Arc<Db>,
pub(crate) shutdown: Arc<Shutdown>,
}
impl Service for Inhibitor {
fn name(&self) -> String {
"pdfs-inhibit".to_owned()
}
fn required(&self) -> bool {
false
}
fn run(self: Box<Self>) {
super::inhibit::run(&self.db, &self.shutdown);
}
}
+52
View File
@@ -0,0 +1,52 @@
//! The cells that belong to one mount's FUSE session (`SessionCells`).
use super::*;
/// What belongs to one mount's FUSE session rather than to the daemon: whether
/// it is the primary My Files mount, the tree inode it is rooted at, its
/// kernel channel and whether the session is up.
///
/// Every other part of `Core` is shared between the primary mount and its
/// on-demand forks. A fork gets fresh cells from [`SessionCells::fork`].
#[derive(Clone)]
pub(crate) struct SessionCells {
/// False only for a forked on-demand device mount. The synthetic shared
/// directory belongs exclusively to the primary My Files mount.
pub(crate) primary: bool,
/// The tree inode this mount's session is rooted at, set when the session
/// is built ([`ProtonFs::new`]). Each fork has its own cell.
pub(crate) root: Arc<OnceLock<u64>>,
/// This mount's kernel notification channel, for telling the kernel to drop
/// metadata it has cached. Set once the session exists — which is *after*
/// the `Core` it is built from, hence the cell.
///
/// Per mount, not per daemon: each session calls its own root inode 1.
/// [`Core::fork_state`] gives each fork an empty cell of its own. Work that
/// changes the tree for every mount tells every session
/// ([`Core::for_each_mount`]).
pub(crate) notifier: Arc<OnceLock<KernelChannel>>,
/// True only after this mount's FUSE session spawned successfully.
/// Registration happens earlier for the primary drain, so registration
/// alone cannot answer whether the location is mounted.
pub(crate) session_live: Arc<AtomicBool>,
}
impl SessionCells {
pub(crate) fn new() -> Self {
Self {
primary: true,
root: Arc::new(OnceLock::new()),
notifier: Arc::new(OnceLock::new()),
session_live: Arc::new(AtomicBool::new(false)),
}
}
/// Fresh cells for an on-demand fork: not the primary mount, and no root,
/// channel or session until the fork's own session is built.
pub(crate) fn fork(&self) -> Self {
Self {
primary: false,
..Self::new()
}
}
}
+2 -2
View File
@@ -122,7 +122,7 @@ impl Core {
}
pub(super) fn ensure_shared_children(&self, ino: u64) -> Result<(), Errno> {
let online = self.online.load(Ordering::Relaxed);
let online = self.is_online();
let resident = self.state().children.contains_key(&ino);
match shared_listing_plan(
resident,
@@ -235,7 +235,7 @@ impl Core {
drop(st);
self.flush_access_changes();
self.mark_shared_refresh_success(SHARED_WITH_ME_SYNCED_MS);
if let Some(notifier) = self.notifier.get() {
if let Some(notifier) = self.session.notifier.get() {
let _ = notifier.inval_inode(ino);
}
Ok(())
+70 -267
View File
@@ -2,54 +2,62 @@
//! account has received, saved public-link bookmarks, and the reverse view of
//! everything this account shares out.
//!
//! All of it is remote-only state — nothing here touches the inode maps or the
//! content cache, so every method is a round-trip wrapped in the crate error
//! shape the control socket expects.
//! All of it is remote-only state: nothing here changes the tree or the
//! content cache's entries for this account's own files, so every method is a
//! round trip wrapped in the error shape the control socket expects.
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use parking_lot::Mutex;
use pdfs_core::control::{
BookmarkInfo, DirEntry, InvitationInfo, LinkChange, PublicLinkInfo, ShareEntry, ShareEntryKind,
SharedItem,
SharedItem, TransferDirection,
};
use pdfs_core::lockrank::Ranked;
use pdfs_core::{CoreError, CoreResult};
use tracing::debug;
use crate::QUOTA_TTL;
use pdfs_store::cache::ContentCache;
use proton_drive_rs::proton_sdk::crypto::VerificationStatus;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use proton_drive_rs::{MemberRole, NodeKind};
use proton_drive_rs::{MemberRole, Node, NodeKind, ProtonDriveClient};
use tracing::debug;
use proton_drive_rs::Node;
use super::drive::DriveApi;
use super::transfers::{CountingWriter, TransferRegistry};
use super::{State, node_size, parse_uid, public_link_info, role_from_str, role_to_str};
use super::{Core, node_size, parse_uid, public_link_info, role_from_str, role_to_str};
/// The last account quota answer, for `statfs(2)`, and whether a refresh
/// of it is running.
/// Sharing as a service of its own: what this account shares and with whom,
/// its public links, what others share with it, and its saved links.
///
/// Every method takes a node already resolved to its uid. Turning a path or a
/// wire-format uid into one, and the check that the node is this daemon's to
/// share, are the caller's (the control socket's), so this holds only the
/// handles it calls: the client, Drive, the content cache and the transfer
/// list for opening a shared file, and a read of the tree for paths.
#[derive(Clone)]
pub(crate) struct QuotaCache {
/// Last account quota answer and when it was learned, for `statfs(2)`.
///
/// `df` and the free-space preflight of every file manager and installer ask
/// for this, and the answer costs a round trip — so it is served from here
/// for [`QUOTA_TTL`] and refreshed on a worker afterwards. Total account
/// storage moves slowly enough that a minute-old number is a better answer
/// than either a stall or the zeroes the default implementation returns.
pub(crate) quota: Arc<Mutex<Option<(std::time::Instant, i64, i64)>>>,
/// Set while a `statfs` is refreshing [`Core::quota`], so the others serve
/// the last figures instead of each holding a worker on the same request.
pub(crate) quota_refreshing: Arc<AtomicBool>,
pub(crate) struct Sharing {
client: ProtonDriveClient,
drive: Arc<dyn DriveApi>,
rt: tokio::runtime::Handle,
cache: Arc<ContentCache>,
transfers: Arc<TransferRegistry>,
state: Arc<Ranked<State>>,
}
impl QuotaCache {
pub(crate) fn new() -> Self {
impl Sharing {
pub(crate) fn new(
client: ProtonDriveClient,
drive: Arc<dyn DriveApi>,
rt: tokio::runtime::Handle,
cache: Arc<ContentCache>,
transfers: Arc<TransferRegistry>,
state: Arc<Ranked<State>>,
) -> Self {
Self {
quota: Arc::new(Mutex::new(None)),
quota_refreshing: Arc::new(AtomicBool::new(false)),
client,
drive,
rt,
cache,
transfers,
state,
}
}
}
@@ -62,7 +70,7 @@ impl QuotaCache {
/// offer path-keyed actions on it. The local-state flags (`pinned`, `cached`)
/// stay false: they describe content this account owns a local copy policy for,
/// which a share on someone else's volume is not.
fn shared_entry_of(core: &Core, n: Node) -> DirEntry {
fn shared_entry_of(sharing: &Sharing, n: Node) -> DirEntry {
let is_dir = n.is_folder();
let size = match &n.kind {
NodeKind::File {
@@ -99,7 +107,7 @@ fn shared_entry_of(core: &Core, n: Node) -> DirEntry {
pinned: false,
pinned_by_folder: false,
cached: false,
path: core.rel_path_for_uid(&n.uid).unwrap_or_default(),
path: sharing.rel_path_for_uid(&n.uid).unwrap_or_default(),
uid: n.uid.to_string(),
role,
shared_by,
@@ -112,35 +120,12 @@ fn shared_entry_of(core: &Core, n: Node) -> DirEntry {
}
}
impl Core {
impl Sharing {
// ---- sharing a node ---------------------------------------------------
/// Invite Proton and/or external emails to the node at `rel` at `role`.
/// Invite Proton and/or external emails to the node `uid` at `role`.
/// Returns `(proton_invited, external_invited)`.
pub(crate) fn share_node(
&self,
rel: &Path,
emails: &[String],
role: &str,
message: Option<&str>,
) -> CoreResult<(usize, usize)> {
let (_ino, uid) = self.resolve(rel)?;
self.share_node_for_uid(&uid, emails, role, message)
}
/// [`Core::share_node`] for a node addressed through any daemon location.
pub(crate) fn share_node_by_uid(
&self,
uid: &str,
emails: &[String],
role: &str,
message: Option<&str>,
) -> CoreResult<(usize, usize)> {
let uid = self.resolve_shareable(uid)?;
self.share_node_for_uid(&uid, emails, role, message)
}
fn share_node_for_uid(
&self,
uid: &NodeUid,
emails: &[String],
@@ -155,25 +140,8 @@ impl Core {
.map_err(|e| CoreError::from_api(&e, "share"))
}
/// List the members, pending invitations and public link of the node at `rel`.
/// List the members, pending invitations and public link of the node `uid`.
pub(crate) fn list_share(
&self,
rel: &Path,
) -> CoreResult<(Vec<ShareEntry>, Option<PublicLinkInfo>)> {
let (_ino, uid) = self.resolve(rel)?;
self.list_share_for_uid(&uid)
}
/// [`Core::list_share`] for a node addressed through any daemon location.
pub(crate) fn list_share_by_uid(
&self,
uid: &str,
) -> CoreResult<(Vec<ShareEntry>, Option<PublicLinkInfo>)> {
let uid = self.resolve_shareable(uid)?;
self.list_share_for_uid(&uid)
}
fn list_share_for_uid(
&self,
uid: &NodeUid,
) -> CoreResult<(Vec<ShareEntry>, Option<PublicLinkInfo>)> {
@@ -225,32 +193,8 @@ impl Core {
}
/// Change the role of a member or pending Proton invitation on the node at
/// `rel`. External invitations have no role-update endpoint.
/// `uid`. External invitations have no role-update endpoint.
pub(crate) fn update_share_role(
&self,
rel: &Path,
id: &str,
kind: ShareEntryKind,
role: &str,
) -> CoreResult<()> {
let (_ino, uid) = self.resolve(rel)?;
self.update_share_role_for_uid(&uid, id, kind, role)
}
/// [`Core::update_share_role`] for a node addressed through any daemon
/// location.
pub(crate) fn update_share_role_by_uid(
&self,
uid: &str,
id: &str,
kind: ShareEntryKind,
role: &str,
) -> CoreResult<()> {
let uid = self.resolve_shareable(uid)?;
self.update_share_role_for_uid(&uid, id, kind, role)
}
fn update_share_role_for_uid(
&self,
uid: &NodeUid,
id: &str,
@@ -290,30 +234,8 @@ impl Core {
}
/// Remove a member, pending Proton invite, or external invite from the node
/// at `rel`.
/// at `uid`.
pub(crate) fn remove_share_entry(
&self,
rel: &Path,
id: &str,
kind: ShareEntryKind,
) -> CoreResult<()> {
let (_ino, uid) = self.resolve(rel)?;
self.remove_share_entry_for_uid(&uid, id, kind)
}
/// [`Core::remove_share_entry`] for a node addressed through any daemon
/// location.
pub(crate) fn remove_share_entry_by_uid(
&self,
uid: &str,
id: &str,
kind: ShareEntryKind,
) -> CoreResult<()> {
let uid = self.resolve_shareable(uid)?;
self.remove_share_entry_for_uid(&uid, id, kind)
}
fn remove_share_entry_for_uid(
&self,
uid: &NodeUid,
id: &str,
@@ -359,32 +281,8 @@ impl Core {
}
}
/// Create a public link on the node at `rel`, returning its info (with URL).
/// Create a public link on the node `uid`, returning its info (with URL).
pub(crate) fn create_public_link(
&self,
rel: &Path,
role: &str,
password: Option<&str>,
expires: Option<i64>,
) -> CoreResult<PublicLinkInfo> {
let (_ino, uid) = self.resolve(rel)?;
self.create_public_link_for_uid(&uid, role, password, expires)
}
/// [`Core::create_public_link`] for a node addressed through any daemon
/// location.
pub(crate) fn create_public_link_by_uid(
&self,
uid: &str,
role: &str,
password: Option<&str>,
expires: Option<i64>,
) -> CoreResult<PublicLinkInfo> {
let uid = self.resolve_shareable(uid)?;
self.create_public_link_for_uid(&uid, role, password, expires)
}
fn create_public_link_for_uid(
&self,
uid: &NodeUid,
role: &str,
@@ -399,36 +297,11 @@ impl Core {
Ok(public_link_info(link))
}
/// Change the public link `id` on the node at `rel`, keeping its URL.
pub(crate) fn update_public_link(
&self,
rel: &Path,
id: &str,
role: Option<&str>,
password: LinkChange<String>,
expires: LinkChange<i64>,
) -> CoreResult<PublicLinkInfo> {
let (_ino, uid) = self.resolve(rel)?;
self.update_public_link_for_uid(&uid, id, role, password, expires)
}
/// [`Core::update_public_link`] for a node addressed through any daemon
/// location.
pub(crate) fn update_public_link_by_uid(
&self,
uid: &str,
id: &str,
role: Option<&str>,
password: LinkChange<String>,
expires: LinkChange<i64>,
) -> CoreResult<PublicLinkInfo> {
let uid = self.resolve_shareable(uid)?;
self.update_public_link_for_uid(&uid, id, role, password, expires)
}
/// Change the public link `id` on the node `uid`, keeping its URL.
///
/// The SDK sets all three options on every update, so each `Keep` is
/// filled in from the link as it stands.
fn update_public_link_for_uid(
pub(crate) fn update_public_link(
&self,
uid: &NodeUid,
id: &str,
@@ -482,20 +355,8 @@ impl Core {
Ok(public_link_info(link))
}
/// Remove the public link `id` from the node at `rel`.
pub(crate) fn remove_public_link(&self, rel: &Path, id: &str) -> CoreResult<()> {
let (_ino, uid) = self.resolve(rel)?;
self.remove_public_link_for_uid(&uid, id)
}
/// [`Core::remove_public_link`] for a node addressed through any daemon
/// location.
pub(crate) fn remove_public_link_by_uid(&self, uid: &str, id: &str) -> CoreResult<()> {
let uid = self.resolve_shareable(uid)?;
self.remove_public_link_for_uid(&uid, id)
}
fn remove_public_link_for_uid(&self, uid: &NodeUid, id: &str) -> CoreResult<()> {
/// Remove the public link `id` from the node `uid`.
pub(crate) fn remove_public_link(&self, uid: &NodeUid, id: &str) -> CoreResult<()> {
let link = self
.rt
.block_on(self.client.get_public_link(uid))
@@ -507,25 +368,15 @@ impl Core {
.map_err(|e| CoreError::from_api(&e, "remove public link"))
}
/// Stop sharing the node at `rel`: remove its public link, then every
/// Stop sharing the node `uid`: remove its public link, then every
/// external invitation, Proton invitation and member. The SDK has no call
/// that deletes a share outright, so this composes the per-entry ones.
pub(crate) fn stop_sharing(&self, rel: &Path) -> CoreResult<StopSharingOutcome> {
let (_ino, uid) = self.resolve(rel)?;
self.stop_sharing_for_uid(&uid)
}
/// [`Core::stop_sharing`] for a node addressed through any daemon location.
pub(crate) fn stop_sharing_by_uid(&self, uid: &str) -> CoreResult<StopSharingOutcome> {
let uid = self.resolve_shareable(uid)?;
self.stop_sharing_for_uid(&uid)
}
///
/// Each step runs even when an earlier one failed, so a single stuck
/// member does not leave the public link up. The link goes first: it is the
/// widest exposure. Only a failure to list what is there fails the whole
/// request; a failed removal is counted in the outcome.
fn stop_sharing_for_uid(&self, uid: &NodeUid) -> CoreResult<StopSharingOutcome> {
pub(crate) fn stop_sharing(&self, uid: &NodeUid) -> CoreResult<StopSharingOutcome> {
let mut outcome = StopSharingOutcome::default();
let link = self
.rt
@@ -637,9 +488,17 @@ impl Core {
if let Some(p) = self.cache.cached_content_path(&uid, mtime, size) {
return Ok(p);
}
let bytes = self
.download_file_tracked(&uid, &node.name, size)
let guard = self.transfers.begin(
&node.name,
uid.to_string(),
TransferDirection::Download,
size,
);
let mut out = CountingWriter::new(Vec::with_capacity(size as usize), &guard);
self.rt
.block_on(self.drive.download_file_to(&uid, &mut out))
.map_err(|e| CoreError::from_api(&e, "download"))?;
let bytes = out.into_inner();
self.cache
.store(&uid, mtime, size, &bytes)
.map_err(|e| CoreError::internal(format!("cache store: {e}")))?;
@@ -721,62 +580,6 @@ impl Core {
.map_err(|e| CoreError::from_api(&e, "delete bookmark"))
}
// ---- account ----------------------------------------------------------
/// Total account storage usage `(max_space, used_space)` in bytes, across all
/// Proton products (not Drive-only). A remote round-trip; nothing here is
/// cached.
pub(crate) fn account_quota(&self) -> CoreResult<(i64, i64)> {
let q = self.block_on_bounded(self.drive.quota()).map_err(|e| {
self.lost_link(&e, "account quota");
CoreError::from_api(&e, "account quota")
})?;
*self.quota_cache.quota.lock() =
Some((std::time::Instant::now(), q.max_space, q.used_space));
Ok((q.max_space, q.used_space))
}
/// The account quota as `statfs(2)` needs it: cached for [`QUOTA_TTL`],
/// refetched after that, and `None` when there is no usable answer at all —
/// offline with nothing cached.
///
/// Never blocks on the network for a *fresh* value when a recent one exists,
/// because the callers are `df` and every "is there room?" preflight, and a
/// stale byte count is worth more to them than a stalled syscall. Offline,
/// the last known figures keep being served rather than degrading to zero.
pub(crate) fn account_quota_cached(&self) -> Option<(i64, i64)> {
if let Some((at, max_space, used_space)) = *self.quota_cache.quota.lock()
&& at.elapsed() < QUOTA_TTL
{
return Some((max_space, used_space));
}
let last = || {
self.quota_cache
.quota
.lock()
.map(|(_, max, used)| (max, used))
};
if !self.is_online()
|| self
.quota_cache
.quota_refreshing
.swap(true, std::sync::atomic::Ordering::AcqRel)
{
return last();
}
let refreshed = self.account_quota();
self.quota_cache
.quota_refreshing
.store(false, std::sync::atomic::Ordering::Release);
match refreshed {
Ok(q) => Some(q),
Err(error) => {
debug!(%error, "account quota refresh failed; serving the last known figures");
last()
}
}
}
// ---- shared by me -----------------------------------------------------
/// List the nodes I have shared with others, each with a summary of its share
@@ -846,15 +649,15 @@ impl Core {
/// tree, by walking parent inodes to the root. `None` when the node has never
/// been seen through the mount (e.g. shared but not browsed to this session) —
/// the caller then leaves the path empty.
pub(crate) fn rel_path_for_uid(&self, uid: &NodeUid) -> Option<String> {
fn rel_path_for_uid(&self, uid: &NodeUid) -> Option<String> {
// Relative to whichever root the node sits under: a node browsed
// through a sync folder is under that fork's root, not My Files
// (`docs/BUGS.md` B74).
walk_to_root(&self.state(), uid)
walk_to_root(&self.state.lock(), uid)
}
}
/// What [`Core::stop_sharing`] managed to remove.
/// What [`Sharing::stop_sharing`] managed to remove.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct StopSharingOutcome {
/// Entries removed (the link, invitations and members alike).
+130
View File
@@ -0,0 +1,130 @@
//! The mounted-files conformance scenarios (`pdfs_vfs::conformance`) run
//! through the FUSE adapter: a daemon mounted over the fake Drive, driven with
//! ordinary file system calls. The headless adapter runs the same scenarios
//! in `pdfs-vfs`, and both have to see the same outcomes.
use std::fs::{File, OpenOptions};
use std::os::unix::fs::FileExt;
use std::path::PathBuf;
use pdfs_vfs::conformance::Adapter;
use pdfs_vfs::headless::Failure;
/// A mount, addressed by paths relative to its root.
pub(crate) struct Mounted(pub(crate) PathBuf);
fn failure(error: std::io::Error) -> Failure {
error
.raw_os_error()
.map_or(Failure::Io, Failure::from_errno)
}
impl Adapter for Mounted {
type Fd = File;
fn create(&self, path: &str) -> Result<File, Failure> {
File::create(self.0.join(path)).map_err(failure)
}
fn open_write(&self, path: &str) -> Result<File, Failure> {
OpenOptions::new()
.write(true)
.open(self.0.join(path))
.map_err(failure)
}
fn write(&self, fd: &File, offset: u64, data: &[u8]) -> Result<(), Failure> {
fd.write_all_at(data, offset).map_err(failure)
}
fn set_len(&self, fd: &File, size: u64) -> Result<(), Failure> {
fd.set_len(size).map_err(failure)
}
fn fsync(&self, fd: &File) -> Result<(), Failure> {
fd.sync_all().map_err(failure)
}
fn close(&self, fd: File) -> Result<(), Failure> {
// `close(2)`'s own error is the flush's, which `File` drops; flush
// first so a failure is seen.
fd.sync_data().map_err(failure)?;
drop(fd);
Ok(())
}
fn read(&self, path: &str) -> Result<Vec<u8>, Failure> {
std::fs::read(self.0.join(path)).map_err(failure)
}
fn mkdir(&self, path: &str) -> Result<(), Failure> {
std::fs::create_dir(self.0.join(path)).map_err(failure)
}
fn unlink(&self, path: &str) -> Result<(), Failure> {
std::fs::remove_file(self.0.join(path)).map_err(failure)
}
fn rmdir(&self, path: &str) -> Result<(), Failure> {
std::fs::remove_dir(self.0.join(path)).map_err(failure)
}
fn rename(&self, from: &str, to: &str) -> Result<(), Failure> {
std::fs::rename(self.0.join(from), self.0.join(to)).map_err(failure)
}
fn list(&self, path: &str) -> Result<Vec<String>, Failure> {
let mut names = std::fs::read_dir(self.0.join(path))
.map_err(failure)?
.map(|entry| {
entry
.map(|entry| entry.file_name().to_string_lossy().into_owned())
.map_err(failure)
})
.collect::<Result<Vec<_>, _>>()?;
names.sort();
Ok(names)
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::*;
use crate::mount::MountOutcome;
use crate::sim::daemon::{Daemon, scratch, wait_until};
use crate::sim::fake_drive::{FakeDrive, Faults};
fn run_through_a_mount(label: &str, online: bool) {
let drive = FakeDrive::new();
let dir = scratch(label);
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
daemon.client.set_online(online);
let mount = Mounted(daemon.mountpoint.clone());
mount.mkdir("conformance").unwrap();
let failed = pdfs_vfs::conformance::run(&mount, "conformance");
daemon.client.set_online(true);
// Whatever the scenarios queued drains before the daemon stops, so the
// stop does not race an upload.
let drained = wait_until(Duration::from_secs(60), || {
daemon.pending().is_ok_and(|items| items.is_empty())
});
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let _ = std::fs::remove_dir_all(&dir);
assert!(failed.is_empty(), "{failed:#?}");
assert!(drained, "the queue did not drain");
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn the_mount_passes_every_conformance_scenario_online() {
run_through_a_mount("conformance-online", true);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn the_mount_passes_every_conformance_scenario_offline() {
run_through_a_mount("conformance-offline", false);
}
}
+121
View File
@@ -479,6 +479,7 @@ mod tests {
use super::*;
use crate::sim::fake_drive::{Entry, FakeDrive, Faults};
use pdfs_core::control::{RefreshScope, SyncIssue};
use proton_drive_rs::proton_sdk::ids::NodeUid;
use std::collections::BTreeMap;
#[test]
@@ -883,10 +884,16 @@ mod tests {
daemon.client.set_online(false);
std::fs::write(daemon.mountpoint.join("f.txt"), b"0123456789").unwrap();
// Usually the drain meets the outage first. Another caller (the event
// poll, a sync pass) can meet it first and take the mount offline,
// and then the drain claims nothing and the write has no failed
// attempt to wait out. Both must end with the write going out soon
// after the link returns.
assert!(wait_until(Duration::from_secs(30), || {
daemon
.pending()
.is_ok_and(|items| items.iter().any(|item| item.attempts > 0))
|| daemon.online().is_ok_and(|online| !online)
}));
// The drain records the failure just before it takes the mount
// offline. Left online, only the event poll would, much later.
@@ -4550,4 +4557,118 @@ mod tests {
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let _ = std::fs::remove_dir_all(&dir);
}
/// The state a stop leaves between the two steps of a replacing rename
/// sent to Drive inline: the replaced file in the trash, the source under
/// its old name, and the journal entry. The next start puts the replaced
/// file back (B302).
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_replace_cut_off_after_its_trash_brings_the_replaced_file_back() {
let drive = FakeDrive::new();
let dir = scratch("replace-cut-trash");
// Only this test's daemons in the log a failure prints.
take_logged();
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
std::fs::write(daemon.mountpoint.join("report.odt"), b"old").unwrap();
std::fs::write(daemon.mountpoint.join("report.odt.tmp"), b"new").unwrap();
assert!(wait_until(Duration::from_secs(30), || {
let tree = drive.tree();
tree.contains_key("report.odt") && tree.contains_key("report.odt.tmp")
}));
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let victim = drive.lookup("report.odt").unwrap();
let source = drive.lookup("report.odt.tmp").unwrap();
cut_off_replace(&dir, &source, &victim, &drive.root(), "report.odt");
drive.device().trash("report.odt");
// Without the listing lag: a lagging read shows the trash made just
// above as not done yet, and a restart quicker than the lag then left
// the file in the trash as never removed. A real stop comes long
// after its own trash.
let daemon = Daemon::start(&dir, drive.client(1, Faults::none())).unwrap();
assert!(
wait_until(Duration::from_secs(30), || {
drive.tree().get("report.odt") == Some(&Entry::File(Arc::new(b"old".to_vec())))
}),
"the replaced file came back: {:?}\n{}",
drive.tree(),
take_logged().join("\n")
);
assert!(drive.tree().contains_key("report.odt.tmp"));
assert!(wait_until(Duration::from_secs(30), || {
std::fs::read(daemon.mountpoint.join("report.odt")).is_ok_and(|b| b == b"old")
}));
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let db = Db::open(&dir.join("pdfs.db")).unwrap();
assert!(db.open_replaces().unwrap().is_empty());
drop(db);
let _ = std::fs::remove_dir_all(&dir);
}
/// The state a stop leaves between the two steps of a queued replacing
/// rename: the replaced file's trash queued, the rename not. The next
/// start drops the queued trash, so the file is never trashed (B302).
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_replace_cut_off_after_queueing_its_trash_keeps_the_replaced_file() {
let drive = FakeDrive::new();
let dir = scratch("replace-cut-queue");
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
std::fs::write(daemon.mountpoint.join("report.odt"), b"old").unwrap();
std::fs::write(daemon.mountpoint.join("report.odt.tmp"), b"new").unwrap();
assert!(wait_until(Duration::from_secs(30), || {
let tree = drive.tree();
tree.contains_key("report.odt") && tree.contains_key("report.odt.tmp")
}));
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let victim = drive.lookup("report.odt").unwrap();
let source = drive.lookup("report.odt.tmp").unwrap();
cut_off_replace(&dir, &source, &victim, &drive.root(), "report.odt");
let db = Db::open(&dir.join("pdfs.db")).unwrap();
db.replace_ops_with_trash(&victim.to_string(), "report.odt", 1)
.unwrap();
drop(db);
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
assert!(wait_until(Duration::from_secs(30), || {
std::fs::read(daemon.mountpoint.join("report.odt")).is_ok_and(|b| b == b"old")
}));
// Long enough for the drain to have sent a trash it still held.
std::thread::sleep(Duration::from_secs(3));
assert!(
drive.tree().contains_key("report.odt"),
"the replaced file stayed: {:?}",
drive.tree()
);
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let db = Db::open(&dir.join("pdfs.db")).unwrap();
assert!(db.open_replaces().unwrap().is_empty());
assert!(!db.has_pending_op(&victim.to_string(), "trash").unwrap());
drop(db);
let _ = std::fs::remove_dir_all(&dir);
}
/// Write the journal entry of a replacing rename, as an earlier run would
/// have before it removed the victim.
fn cut_off_replace(
dir: &Path,
source: &NodeUid,
victim: &NodeUid,
parent: &NodeUid,
name: &str,
) {
let db = Db::open(&dir.join("pdfs.db")).unwrap();
db.begin_replace(&pdfs_store::db::ReplaceIntent {
source_uid: source.to_string(),
victim_uid: victim.to_string(),
new_parent_uid: parent.to_string(),
new_name: name.to_owned(),
started_ms: 1,
run: 0,
})
.unwrap();
}
}
+1
View File
@@ -1,6 +1,7 @@
//! The simulation tests of `docs/TESTING.md`: a fake Drive with
//! the faults the real one has, and the tools to drive daemons against it.
pub(crate) mod conformance;
pub(crate) mod daemon;
pub(crate) use pdfs_drive::sim::fake_drive;
pub(crate) mod model;
+14
View File
@@ -140,6 +140,14 @@ pub(crate) fn run(seed: u64, profile: &'static Profile) -> Result<(), String> {
}
}
run.logged.extend(take_logged());
// Every stop, the restarts' included, ends all the services a mount
// started; one left running is a second generation beside the next mount's.
let outcome = outcome.and_then(
|()| match run.logged.iter().find(|line| left_running(line)) {
Some(line) => Err(format!("shutdown: a stop left services running: {line}")),
None => Ok(()),
},
);
match outcome {
Ok(()) => {
let _ = std::fs::remove_dir_all(&dir);
@@ -608,6 +616,12 @@ fn outcome(actual: &Result<Result<(), i32>, String>) -> String {
}
}
/// Whether `line` is the mount's report of services still running at its
/// stop deadline (`mount::halt_workers`).
fn left_running(line: &str) -> bool {
line.starts_with("background workers did not finish in time")
}
/// Run `profile` over the seeds the environment asks for: `PDFS_SIM_SEED`
/// alone, or `PDFS_SIM_SEEDS` of them (default `default_seeds`) from 1.
pub(crate) fn run_seeds(profile: &'static Profile, default_seeds: u64) {
+16 -5
View File
@@ -130,7 +130,13 @@ impl Core {
SizeUpgradeClaim::Start(slot, uids) => {
let core = self.clone();
let worker = slot.clone();
std::thread::spawn(move || core.run_size_upgrade(key, uids, worker));
if let Err(error) = self.services.spawn_job("pdfs-size-upgrade", move || {
core.run_size_upgrade(key, uids, worker)
}) {
// The waiters give up on the slot at their deadline and
// answer with the size they have.
warn!(%error, "could not start a size upgrade");
}
Some(slot)
}
}
@@ -159,9 +165,9 @@ impl Core {
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())
if let Err(error) = self
.services
.spawn_job("pdfs-size-waiters", move || queue.serve())
{
// Without a thread nothing would ever answer these. A provisional
// size is wrong; a `stat` that never returns wedges the caller.
@@ -184,6 +190,11 @@ impl Core {
let (mut key, mut uids, mut slot) = (key, uids, slot);
loop {
for chunk in uids.chunks(SIZE_UPGRADE_CHUNK) {
// A stop joins this job; the rest of the folder can wait for
// the next mount, which lists it afresh.
if self.shutdown.is_stopping() {
break;
}
let result =
self.block_on_within(BATCH_CALL_TIMEOUT, self.drive.enumerate_nodes(chunk));
self.apply_size_upgrade(key, result);
@@ -321,7 +332,7 @@ impl Core {
};
changed.push(ino);
// An open write handle is ahead of the server too (B109).
if st.active_writes.contains_key(&ino) {
if st.open.is_writing(ino) {
continue;
}
let NodeKind::File { claimed_size, .. } = &node.kind else {
+117 -43
View File
@@ -30,6 +30,10 @@ use pdfs_core::control::ActivityKind;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use tracing::{debug, info, warn};
use pdfs_core::shutdown::Shutdown;
use pdfs_drive::DriveApi;
use pdfs_store::db::Db;
use super::{Core, node_content_sha1, node_revision_id, node_size};
/// What the conflict sweep may do, and the copies it already checked this
@@ -44,7 +48,7 @@ pub(crate) struct SweepState {
/// 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.
/// [`Sweeper::run`] and `docs/BUGS.md` B99.
pub(crate) conflict_notified: Arc<Mutex<HashSet<NodeUid>>>,
}
@@ -107,17 +111,113 @@ pub(crate) fn conflict_base_name(name: &str) -> Option<String> {
Some(base)
}
/// What the conflict sweep needs from the rest of the daemon: the tree of
/// every mount and the activity feed.
pub(crate) trait SweepHost: Send + Sync {
/// Whether `uid` is on this account's own volume, or a virtual node.
fn is_own_or_virtual(&self, uid: &NodeUid) -> bool;
/// Whether the mount believes Drive is reachable.
fn is_online(&self) -> bool;
/// Whether a node is being written or held open in any mount.
fn is_busy(&self, uid: &NodeUid) -> bool;
/// For one pass: whether the conflict listing can show a copy.
fn conflict_locator(&self) -> Box<dyn Fn(&NodeUid) -> bool + '_>;
/// Unhook a node Drive no longer has from every mount, and drop its
/// cached content and open readers.
fn forget(&self, uid: &NodeUid);
fn log_activity(&self, kind: ActivityKind, target: &str, detail: String, ok: bool);
}
impl SweepHost for Core {
fn is_own_or_virtual(&self, uid: &NodeUid) -> bool {
Core::is_own_or_virtual(self, uid)
}
fn is_online(&self) -> bool {
Core::is_online(self)
}
fn is_busy(&self, uid: &NodeUid) -> bool {
Core::is_busy(self, uid)
}
fn conflict_locator(&self) -> Box<dyn Fn(&NodeUid) -> bool + '_> {
let roots = Core::search_roots(self);
Box::new(move |uid| self.conflict_path(&roots, uid).is_some())
}
fn forget(&self, uid: &NodeUid) {
// Leaving a conflict copy hooked up in the tree keeps a node we have
// just trashed remotely visible and readable in whichever mount shows
// it (`docs/BUGS.md` B74).
self.for_each_state(|st| {
st.forget_or_unlink(uid);
});
self.cache.evict(uid);
self.evict_reader(uid);
}
fn log_activity(&self, kind: ActivityKind, target: &str, detail: String, ok: bool) {
Core::log_activity(self, kind, target, detail, ok);
}
}
impl Core {
/// The conflict sweep, with this daemon as its host.
pub(crate) fn sweeper(&self) -> Sweeper {
Sweeper {
drive: self.drive.clone(),
rt: self.rt.clone(),
db: self.db.clone(),
shutdown: self.shutdown.clone(),
state: self.sweep.clone(),
host: Arc::new(self.clone()),
}
}
/// Whether a node has a write in flight or a file handle open against it.
/// Read-only opens use fh 0 and are not tracked, so this is specifically the
/// writer/holder check.
/// Asked across **every** mount. The sweep runs on the primary Core but
/// trashes nodes anywhere in the tree, and a file open inside a sync folder
/// is tracked in that fork's `State` — so consulting `self.state` alone
/// answered "idle" for every such file and let the sweep delete one with a
/// writer attached (`docs/BUGS.md` B74). Busy anywhere means busy.
pub(crate) fn is_busy(&self, uid: &NodeUid) -> bool {
let mut busy = false;
self.for_each_state(|st| {
let Some(&ino) = st.by_uid.get(uid) else {
return;
};
busy |= st.open.is_busy(ino);
});
busy
}
}
/// Reconciles leftover conflict copies (the module documentation says how).
/// Holds Drive, the runtime, the database, the stop signal and its own state;
/// it reaches the mounts through [`SweepHost`].
pub(crate) struct Sweeper {
drive: Arc<dyn DriveApi>,
rt: tokio::runtime::Handle,
db: Arc<Db>,
shutdown: Arc<Shutdown>,
state: SweepState,
host: Arc<dyn SweepHost>,
}
impl Sweeper {
/// Sweep for stale conflict copies forever, on its own thread. See the module
/// docs for the identical/divergent policy.
pub(crate) fn run_conflict_sweep_loop(&self) {
pub(crate) fn run(&self) {
// Both waits are interruptible, so teardown does not have to sit out a
// five-minute interval to join this thread (`docs/BUGS.md` B44).
if !self.shutdown.sleep(CONFLICT_SWEEP_WARMUP) {
return;
}
loop {
self.sweep_conflicts_once();
self.sweep_once();
if !self.shutdown.sleep(CONFLICT_SWEEP_INTERVAL) {
return;
}
@@ -125,7 +225,7 @@ impl Core {
}
/// One sweep pass over every node the daemon currently knows.
fn sweep_conflicts_once(&self) {
fn sweep_once(&self) {
let stored = match self.db.load_all() {
Ok(s) => s,
Err(e) => {
@@ -136,7 +236,7 @@ impl Core {
let nodes: Vec<_> = stored
.into_iter()
.map(|stored| stored.node)
.filter(|node| self.is_own_or_virtual(&node.uid))
.filter(|node| self.host.is_own_or_virtual(&node.uid))
.collect();
// Index live (non-trashed) files by (parent, name) for sibling lookup.
@@ -153,8 +253,8 @@ impl Core {
by_parent_name.insert((parent, node.name.as_str()), node);
}
let roots = self.search_roots();
let online = self.online.load(std::sync::atomic::Ordering::Relaxed);
let listed = self.host.conflict_locator();
let online = self.host.is_online();
for node in &nodes {
if node.trashed || node.is_folder() {
continue;
@@ -169,7 +269,7 @@ impl Core {
.unwrap_or_default();
let sibling = by_parent_name.get(&(parent, base.as_str())).copied();
match decide(node, sibling, &base, self.sweep.sweep_mode) {
match decide(node, sibling, &base, self.state.sweep_mode) {
SweepAction::Remove => {
// Only while online — the remote trash is the point. Offline,
// it waits for a later pass.
@@ -181,7 +281,7 @@ impl Core {
// would sit in the feed as "resolved" with no way to act on
// it (`docs/BUGS.md` B99).
SweepAction::Flag(detail) => {
if self.conflict_path(&roots, &node.uid).is_some() {
if listed(&node.uid) {
self.flag_conflict(&node.uid, &node.name, detail);
} else {
debug!(uid = %node.uid, name = %node.name, "conflict sweep: copy is outside every location; not flagged");
@@ -219,12 +319,7 @@ impl Core {
return;
}
}
// Leaving a conflict copy hooked up in the tree keeps a node we have
// just trashed remotely visible and readable in whichever mount shows
// it (`docs/BUGS.md` B74).
self.for_each_state(|st| {
st.forget_or_unlink(uid);
});
self.host.forget(uid);
// Deliberately *not* `discard_queued_ops`: `duplicate_still_removable`
// proved the queue empty before the trash above, but that proof is stale
// the moment `trash_nodes` goes to the network. A `close(2)` landing in
@@ -232,14 +327,12 @@ impl Core {
// blob holding the only copy of them. Leaving the op queued is the
// non-destructive outcome: the drain re-reads the node, sees it trashed,
// and `revision_conflict` routes it to `keep_as_conflict_copy`.
self.cache.evict(uid);
self.evict_reader(uid);
if let Err(e) = self.db.delete_node(uid) {
warn!(%uid, error = ?e, "conflict sweep: db delete after trash failed");
}
self.invalidate_trash();
self.sweep.conflict_notified.lock().remove(uid);
self.log_activity(
super::trash::invalidate_trash(&self.db);
self.state.conflict_notified.lock().remove(uid);
self.host.log_activity(
ActivityKind::Trash,
name,
format!("auto-removed duplicate of {base}"),
@@ -273,7 +366,7 @@ impl Core {
// Someone is writing to it, or holds it open. Trashing now would pull the
// node out from under a live handle.
if self.is_busy(uid) {
if self.host.is_busy(uid) {
debug!(%uid, name, "conflict sweep: skipping duplicate that is open or being written");
return false;
}
@@ -306,32 +399,12 @@ impl Core {
}
}
/// Whether a node has a write in flight or a file handle open against it.
/// Read-only opens use fh 0 and are not tracked, so this is specifically the
/// writer/holder check.
/// Asked across **every** mount. The sweep runs on the primary Core but
/// trashes nodes anywhere in the tree, and a file open inside a sync folder
/// is tracked in that fork's `State` — so consulting `self.state` alone
/// answered "idle" for every such file and let the sweep delete one with a
/// writer attached (`docs/BUGS.md` B74). Busy anywhere means busy.
pub(crate) fn is_busy(&self, uid: &NodeUid) -> bool {
let mut busy = false;
self.for_each_state(|st| {
let Some(&ino) = st.by_uid.get(uid) else {
return;
};
busy |=
st.active_writes.contains_key(&ino) || st.handles.values().any(|&held| held == ino);
});
busy
}
/// Surface a conflict copy that needs the user's attention, once. The
/// in-memory set spares the database each pass; the activity log itself is
/// 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.sweep.conflict_notified.lock().insert(uid.clone()) {
if !self.state.conflict_notified.lock().insert(uid.clone()) {
return;
}
match self.db.activity_has(ActivityKind::Conflict, name) {
@@ -342,7 +415,8 @@ impl Core {
Err(e) => warn!(%uid, name, error = ?e, "conflict sweep: activity check failed"),
}
debug!(%uid, name, detail, "conflict sweep: flagged divergent conflict copy");
self.log_activity(ActivityKind::Conflict, name, detail, false);
self.host
.log_activity(ActivityKind::Conflict, name, detail, false);
}
}
+1 -1
View File
@@ -38,7 +38,7 @@ impl SyncHost for Core {
}
fn upload_thumbnails(&self, path: &Path, name: &str) -> Vec<Thumbnail> {
Core::upload_thumbnails(self, path, name)
self.photos().upload_thumbnails(path, name)
}
}
+114 -44
View File
@@ -2,6 +2,7 @@
//! listing in the background, restoring from it, deleting from it for good.
use super::*;
use crate::listing::listing_stale;
/// Whether a trash refresh is running, and the wake-up for requests waiting
/// on its progress.
@@ -13,7 +14,7 @@ pub(crate) struct TrashState {
/// Fires whenever a trash refresh persists a batch or finishes, so a
/// `ListTrash` request waiting on a first-ever refresh wakes on progress
/// instead of polling or blocking for the whole run. See
/// [`Core::await_trash_refresh`].
/// [`Trash::await_trash_refresh`].
pub(crate) trash_progress: Arc<tokio::sync::Notify>,
}
@@ -26,7 +27,75 @@ impl TrashState {
}
}
/// The Drive trash as a service: listing it, refreshing that listing, and
/// restoring or deleting from it.
///
/// It holds only the handles it calls, and reaches the mounted trees through
/// [`TrashHost`]. [`Core::trash`] builds one on demand with the daemon as its
/// host. A clone shares everything, which is how a refresh moves onto a
/// background task.
#[derive(Clone)]
pub(crate) struct Trash {
drive: Arc<dyn DriveApi>,
rt: tokio::runtime::Handle,
db: Arc<Db>,
events: Arc<events::EventHub>,
services: pdfs_core::lifecycle::ServiceBoard,
writes: writes::WriteState,
jobs: TrashState,
host: Arc<dyn TrashHost>,
}
/// What the trash needs from the mounted trees.
pub(crate) trait TrashHost: Send + Sync {
/// Re-enumerate these folders on next access, in every mount, because a
/// restored node reappears under one of them.
fn invalidate_listings_of(&self, parents: &[NodeUid]);
/// Forget nodes the server no longer has, in every mount, with any cached
/// content they own.
fn drop_local(&self, uids: &[NodeUid]);
}
impl TrashHost for Core {
fn invalidate_listings_of(&self, parents: &[NodeUid]) {
// Keyed by uid, so it applies to every mount: a restored node reappears
// in whichever mounts show its parent, not only the primary one.
self.for_each_state(|st| {
for parent in parents {
if let Some(&ino) = st.by_uid.get(parent) {
st.invalidate_listing(ino);
}
}
});
}
fn drop_local(&self, uids: &[NodeUid]) {
Core::drop_local(self, uids);
}
}
impl Core {
/// [`Trash::invalidate_trash`], without building the service.
pub(super) fn invalidate_trash(&self) {
invalidate_trash(&self.db);
}
/// The trash service, with this daemon as its host.
pub(crate) fn trash(&self) -> Trash {
Trash {
drive: self.drive.clone(),
rt: self.rt.clone(),
db: self.db.clone(),
events: self.events.clone(),
services: self.services.clone(),
writes: self.writes.clone(),
jobs: self.trash_jobs.clone(),
host: Arc::new(self.clone()),
}
}
}
impl Trash {
/// List the account's trash, from the DB. Trashed nodes are outside the
/// mounted tree — the FUSE side forgot them when they were trashed — so the
/// listing is persisted in its own table rather than derived from `State`, and
@@ -36,7 +105,7 @@ impl Core {
/// Stale-while-revalidate, like the photos timeline: a persisted listing comes
/// back at DB speed and is refreshed in the background past [`TRASH_TTL`].
/// Our own trash mutations invalidate it outright (see
/// [`Core::invalidate_trash`]), so the TTL only covers changes made elsewhere.
/// [`Trash::invalidate_trash`]), so the TTL only covers changes made elsewhere.
///
/// The refresh always runs *off* the request: a never-fetched trash waits for
/// it, but only for [`TRASH_FIRST_WAIT`], and then answers with the batches
@@ -44,9 +113,9 @@ impl Core {
/// made a large trash unlistable — the refresh outran the front-end's read
/// timeout, the user asked again, and each attempt left another full refresh
/// grinding in the daemon (`docs/BUGS.md` B72).
pub(super) fn list_trash(&self) -> CoreResult<Vec<DirEntry>> {
pub(crate) fn list_trash(&self) -> CoreResult<Vec<DirEntry>> {
let never_fetched = self.db.state_i64(TRASH_SYNCED_MS).ok().flatten().is_none();
if never_fetched || self.listing_stale(TRASH_SYNCED_MS, TRASH_TTL) {
if never_fetched || listing_stale(&self.db, TRASH_SYNCED_MS, TRASH_TTL) {
self.spawn_trash_refresh();
}
if never_fetched {
@@ -99,7 +168,7 @@ impl Core {
/// What a trashed folder holds: its children on the server, and the
/// stored trash entries trashed inside it before it went.
pub(super) fn list_trashed_folder(&self, uid: &str) -> CoreResult<Vec<DirEntry>> {
pub(crate) fn list_trashed_folder(&self, uid: &str) -> CoreResult<Vec<DirEntry>> {
let folder =
parse_uid(uid).ok_or_else(|| CoreError::invalid(format!("invalid uid: {uid}")))?;
let children = self
@@ -177,7 +246,7 @@ impl Core {
/// [`TRASH_MATERIALIZE_CHUNK`] is stored as it lands, so a large trash
/// fills the page while it loads. Rows the server no longer lists go once
/// the whole listing is in, never earlier.
pub(super) async fn refresh_trash(&self) -> CoreResult<()> {
pub(crate) async fn refresh_trash(&self) -> CoreResult<()> {
let started = Instant::now();
let uids = within_trash_call("enumerate trash", self.drive.enumerate_trash_node_uids())
.await?
@@ -200,7 +269,7 @@ impl Core {
let listed: HashSet<String> = uids.iter().map(ToString::to_string).collect();
let removed = self.db.trash_retain(&listed).map_err(CoreError::from)?;
if removed > 0 {
self.trash.trash_progress.notify_waiters();
self.jobs.trash_progress.notify_waiters();
}
let missing: Vec<NodeUid> = uids
.into_iter()
@@ -235,7 +304,7 @@ impl Core {
.collect();
materialized += items.len();
self.db.trash_upsert(&items).map_err(CoreError::from)?;
self.trash.trash_progress.notify_waiters();
self.jobs.trash_progress.notify_waiters();
self.events.publish(&[Topic::Trash]);
debug!(
materialized,
@@ -258,43 +327,44 @@ impl Core {
}
/// Refresh the trash off the request path. At most one refresh at a time —
/// including the one a first-ever [`Core::list_trash`] waits on, so a burst
/// including the one a first-ever [`Trash::list_trash`] waits on, so a burst
/// of requests against an unfetched trash joins one refresh instead of
/// starting one apiece.
pub(super) fn spawn_trash_refresh(&self) {
if self.trash.trash_refreshing.swap(true, Ordering::SeqCst) {
pub(crate) fn spawn_trash_refresh(&self) {
if self.jobs.trash_refreshing.swap(true, Ordering::SeqCst) {
return;
}
let core = self.clone();
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();
});
let this = self.clone();
self.services
.spawn_task_job(&self.rt, "pdfs-trash-refresh", async move {
let refreshed = this.refresh_trash().await;
this.jobs.trash_refreshing.store(false, Ordering::SeqCst);
match refreshed {
Ok(_) => this.events.publish(&[Topic::Trash]),
Err(e) => warn!(error = %e, "background trash refresh failed"),
}
// After the flag, so a waiter that wakes on this sees it cleared.
this.jobs.trash_progress.notify_waiters();
});
}
/// Wait for the in-flight trash refresh to make progress, for at most
/// `budget`. Returns early when it finishes; never cancels it — the refresh
/// is a detached task, so giving up here costs the work nothing.
pub(super) fn await_trash_refresh(&self, budget: Duration) {
pub(crate) fn await_trash_refresh(&self, budget: Duration) {
let deadline = Instant::now() + budget;
self.rt.block_on(async {
while self.trash.trash_refreshing.load(Ordering::SeqCst) {
while self.jobs.trash_refreshing.load(Ordering::SeqCst) {
let Some(left) = deadline.checked_duration_since(Instant::now()) else {
break;
};
let notified = self.trash.trash_progress.notified();
let notified = self.jobs.trash_progress.notified();
tokio::pin!(notified);
// Register before re-checking the flag: a refresh that finishes
// in between must not leave us waiting for a notify that has
// already fired.
notified.as_mut().enable();
if !self.trash.trash_refreshing.load(Ordering::SeqCst) {
if !self.jobs.trash_refreshing.load(Ordering::SeqCst) {
break;
}
if tokio::time::timeout(left, notified).await.is_err() {
@@ -312,8 +382,8 @@ impl Core {
/// trash ourselves. The next Trash page then *waits* for a fresh listing
/// rather than painting one from before the mutation — the user just made the
/// change and is about to look straight at it.
pub(super) fn invalidate_trash(&self) {
let _ = self.db.clear_state(TRASH_SYNCED_MS);
pub(crate) fn invalidate_trash(&self) {
invalidate_trash(&self.db);
}
/// Restore trashed nodes to the folders they were trashed from, together
@@ -334,8 +404,8 @@ impl Core {
/// The destination parents are read *before* the restore — a restored node
/// reappears in a listing the daemon may already have cached, so each one is
/// invalidated and re-enumerated on next access.
pub(super) fn restore(&self, uids: &[String]) -> CoreResult<usize> {
let requested = Self::parse_uids(uids)?;
pub(crate) fn restore(&self, uids: &[String]) -> CoreResult<usize> {
let requested = Core::parse_uids(uids)?;
// A listing we could not read is not a reason to refuse the restore: it
// only costs the expansion, and the requested nodes still go back.
let relations = self.db.trash_parents().unwrap_or_default();
@@ -378,7 +448,7 @@ impl Core {
let (uid, outcome) = item?;
match outcome {
Ok(()) => {
self.hidden.lock().remove(&uid);
self.writes.unhide(&uid);
restored.push(uid);
}
Err(e) => {
@@ -398,13 +468,7 @@ impl Core {
}
// Keyed by uid, so it applies to every mount: a restored node reappears
// in whichever mounts show its parent, not only the primary one.
self.for_each_state(|st| {
for parent in &parents {
if let Some(&ino) = st.by_uid.get(parent) {
st.invalidate_listing(ino);
}
}
});
self.host.invalidate_listings_of(&parents);
let back: Vec<String> = restored.iter().map(ToString::to_string).collect();
let _ = self.db.trash_remove(&back);
self.invalidate_trash();
@@ -413,8 +477,8 @@ impl Core {
/// Permanently delete trashed nodes. Irreversible on the server; locally it
/// drops any metadata and cached content the node still owns.
pub(super) fn delete_forever(&self, uids: &[String]) -> CoreResult<usize> {
let parsed = Self::parse_uids(uids)?;
pub(crate) fn delete_forever(&self, uids: &[String]) -> CoreResult<usize> {
let parsed = Core::parse_uids(uids)?;
// Streamed, and each node's local state is dropped as its batch lands.
// A permanent delete is irreversible, so the useful property is that a
// daemon interrupted mid-batch has already forgotten exactly the nodes
@@ -429,7 +493,7 @@ impl Core {
let (uid, outcome) = item?;
match outcome {
Ok(()) => {
self.drop_local(std::slice::from_ref(&uid));
self.host.drop_local(std::slice::from_ref(&uid));
gone.push(uid.to_string());
deleted += 1;
}
@@ -460,7 +524,7 @@ impl Core {
/// is what kept the delete from ever being sent (`docs/BUGS.md` B293).
/// The stored listing is cleared at once, and the server is asked again
/// after [`TRASH_TTL`], so anything it still holds then shows up again.
pub(super) fn empty_trash(&self) -> CoreResult<usize> {
pub(crate) fn empty_trash(&self) -> CoreResult<usize> {
let uids: Vec<String> = self
.db
.trash_seen()
@@ -471,7 +535,7 @@ impl Core {
.block_on(within_trash_call("empty trash", self.drive.empty_trash()))?
.map_err(|e| CoreError::from_api(&e, "empty trash"))?;
let parsed: Vec<NodeUid> = uids.iter().filter_map(|uid| parse_uid(uid)).collect();
self.drop_local(&parsed);
self.host.drop_local(&parsed);
let _ = self.db.trash_replace(&[]);
let _ = self.db.set_state_i64(TRASH_SYNCED_MS, now_ms());
self.events.publish(&[Topic::Trash]);
@@ -479,7 +543,7 @@ impl Core {
}
}
/// An entry inside a trashed folder, for [`Core::list_trashed_folder`].
/// An entry inside a trashed folder, for [`Trash::list_trashed_folder`].
pub(super) fn trashed_entry(
uid: String,
name: String,
@@ -618,3 +682,9 @@ pub(super) fn expand_restore(
waves.retain(|wave| !wave.is_empty());
waves
}
/// Mark the stored trash listing stale, so the next listing waits for a
/// fresh one.
pub(crate) fn invalidate_trash(db: &Db) {
let _ = db.clear_state(TRASH_SYNCED_MS);
}
+1
View File
@@ -70,6 +70,7 @@ async fn run_uploads(
));
}
let thumbnails = core
.photos()
.upload_thumbnails_async(t.path.clone(), t.name.clone())
.await;
match core
+1 -5
View File
@@ -6,7 +6,7 @@ use std::time::{Duration, Instant};
use proton_drive_rs::proton_sdk::ids::{LinkId, NodeUid, VolumeId};
use proton_drive_rs::{Node, NodeKind};
pub(crate) const VIRTUAL_VOLUME: &str = "virtual";
pub(crate) use pdfs_vfs::ids::{VIRTUAL_VOLUME, is_virtual_uid};
pub(crate) const SHARED_WITH_ME_LINK: &str = "sharedwithme";
pub(crate) const SHARED_WITH_ME_BASE: &str = "Shared with me";
const MAX_COMPONENT_BYTES: usize = 255;
@@ -18,10 +18,6 @@ pub(crate) fn shared_with_me_uid() -> NodeUid {
)
}
pub(crate) fn is_virtual_uid(uid: &NodeUid) -> bool {
uid.volume_id.as_str() == VIRTUAL_VOLUME
}
pub(crate) fn is_own_or_virtual_uid(uid: &NodeUid, own_volume: &VolumeId) -> bool {
uid.volume_id == *own_volume || is_virtual_uid(uid)
}
+28
View File
@@ -44,6 +44,7 @@ mod nodes;
mod ops;
mod photos;
mod pins;
mod replace;
mod share_access;
mod state;
mod sync;
@@ -63,6 +64,7 @@ pub use ops::{
};
pub use photos::{StoredPhoto, StoredPlace, THUMB_HAVE, THUMB_NONE, THUMB_UNKNOWN, TimelineRow};
pub use pins::PinRow;
pub use replace::ReplaceIntent;
pub use sync::{SavedWalk, SavedWalkDir, SavedWalkItem, StoredSyncEntry, StoredSyncFolder};
pub use trash::StoredTrash;
@@ -108,6 +110,10 @@ pub struct Db {
/// to be owned here rather than by `open`'s stack frame. `None` for
/// in-memory databases, which nothing else can reach.
_single_writer: Option<File>,
/// Tells this opening of the database from earlier ones, so that journal
/// entries a previous run left behind can be told from this run's own
/// (see `replace`).
run: u64,
}
/// Idle read-only connections, opened on demand and kept for reuse.
@@ -294,6 +300,7 @@ impl Db {
idle: Mutex::new(Vec::new()),
}),
_single_writer: single_writer,
run: next_run(),
};
// A drain claim names a worker thread in the process that took it, and
// the single-writer lock above says that process is not running. Any
@@ -384,6 +391,7 @@ impl Db {
conn: Ranked::new(Rank::DbWriter, conn),
readers: None,
_single_writer: None,
run: next_run(),
};
db.migrate()?;
Ok(db.into_conn())
@@ -408,6 +416,7 @@ impl Db {
conn: Ranked::new(Rank::DbWriter, conn),
readers: None,
_single_writer: None,
run: next_run(),
};
db.migrate()?;
Ok(db)
@@ -429,6 +438,25 @@ fn is_in_memory(path: &Path) -> bool {
p == ":memory:" || p.is_empty()
}
/// A value no other opening of a database has used: the time in nanoseconds,
/// made unique within this process by a counter.
fn next_run() -> u64 {
use std::sync::atomic::{AtomicU64, Ordering};
static LAST: AtomicU64 = AtomicU64::new(0);
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0);
let mut last = LAST.load(Ordering::Relaxed);
loop {
let next = now.max(last + 1);
match LAST.compare_exchange_weak(last, next, Ordering::Relaxed, Ordering::Relaxed) {
Ok(_) => return next,
Err(seen) => last = seen,
}
}
}
/// Take the single-instance write lock for the database at `path`.
///
/// The daemon is the only writer by design — the front-ends go through the
+105
View File
@@ -0,0 +1,105 @@
//! The journal of replacing renames.
//!
//! Drive has no rename that replaces its destination, so a `rename(2)` over an
//! existing name removes the node there first and renames the source second.
//! A stop between the two leaves the destination in Drive's trash and the
//! source under its old name: neither the old state nor the new one. An entry
//! here is written before the first step and removed after the last, so the
//! next start finds every replace that was cut off and settles it
//! (`docs/BUGS.md` B302).
//!
//! Kept in `sync_state` under [`REPLACE_PREFIX`], so the schema does not
//! change.
use rusqlite::params;
use serde::{Deserialize, Serialize};
use super::Db;
use pdfs_core::Result;
/// The `sync_state` key prefix of a journal entry. The rest of the key is the
/// source's uid.
const REPLACE_PREFIX: &str = "replace:";
/// A replacing rename that has started: `source` is to be renamed to
/// `new_name` in `new_parent`, over `victim`. Uids are in their `Display`
/// form.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReplaceIntent {
pub source_uid: String,
pub victim_uid: String,
pub new_parent_uid: String,
pub new_name: String,
/// When the rename started, in milliseconds since the epoch.
pub started_ms: i64,
/// The opening of the database the rename started under. Set by
/// [`Db::begin_replace`].
#[serde(default)]
pub run: u64,
}
impl ReplaceIntent {
fn run_is(&self, run: u64) -> bool {
self.run == run
}
}
impl Db {
/// Record that a replacing rename is about to remove its victim. Committed
/// with a synced WAL before it returns, as the queue's own rows are: the
/// removal that follows may reach Drive at once.
pub fn begin_replace(&self, intent: &ReplaceIntent) -> Result<()> {
let intent = ReplaceIntent {
run: self.run,
..intent.clone()
};
let value = serde_json::to_string(&intent)?;
let conn = self.durable()?;
conn.execute(
"INSERT INTO sync_state (key, value) VALUES (?1, ?2)
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
params![format!("{REPLACE_PREFIX}{}", intent.source_uid), value],
)?;
Ok(())
}
/// Forget the replacing rename of `source_uid`: it finished, failed and
/// was undone, or was settled after a restart.
pub fn end_replace(&self, source_uid: &str) -> Result<()> {
self.conn.lock().execute(
"DELETE FROM sync_state WHERE key = ?1",
params![format!("{REPLACE_PREFIX}{source_uid}")],
)?;
Ok(())
}
/// Every replacing rename an earlier run started and did not end. This
/// run's own are in progress, and are not returned. An entry that cannot
/// be read is dropped, with a warning: it cannot be settled.
pub fn open_replaces(&self) -> Result<Vec<ReplaceIntent>> {
let rows: Vec<(String, String)> = {
let conn = self.read()?;
let mut stmt = conn.prepare(
"SELECT key, value FROM sync_state WHERE key >= ?1 AND key < ?2 ORDER BY key",
)?;
stmt.query_map(params![REPLACE_PREFIX, "replace;"], |row| {
Ok((row.get(0)?, row.get(1)?))
})?
.collect::<rusqlite::Result<_>>()?
};
let mut out = Vec::with_capacity(rows.len());
for (key, value) in rows {
match serde_json::from_str::<ReplaceIntent>(&value) {
Ok(intent) if intent.run_is(self.run) => {}
Ok(intent) => out.push(intent),
Err(error) => {
tracing::warn!(key, %error, "dropping an unreadable replace intent");
self.conn
.lock()
.execute("DELETE FROM sync_state WHERE key = ?1", params![key])?;
}
}
}
Ok(out)
}
}
+39
View File
@@ -8381,3 +8381,42 @@ fn a_read_without_a_reader_connection_fails_instead_of_waiting_on_the_writer() {
"the read must fail, not queue behind the writer"
);
}
/// A replacing rename's journal entry outlives the run that wrote it, and is
/// gone once ended; other `sync_state` keys are not taken for entries.
#[test]
fn a_replace_intent_is_kept_until_it_ends() {
let db = Db::open_in_memory().unwrap();
let intent = ReplaceIntent {
source_uid: "vol~src".into(),
victim_uid: "vol~victim".into(),
new_parent_uid: "vol~dir".into(),
new_name: "report.odt".into(),
started_ms: 7,
run: 0,
};
db.begin_replace(&intent).unwrap();
db.with_conn(|conn| {
conn.execute(
"INSERT INTO sync_state (key, value) VALUES ('replacement', 'x'), ('replace;', 'y')",
[],
)?;
Ok(())
})
.unwrap();
// This run's own replace is in progress, not cut off.
assert!(db.open_replaces().unwrap().is_empty());
db.with_conn(|conn| {
conn.execute(
"UPDATE sync_state SET value = json_set(value, '$.run', 1) WHERE key = 'replace:vol~src'",
[],
)?;
Ok(())
})
.unwrap();
let open = db.open_replaces().unwrap();
assert_eq!(open.len(), 1);
assert_eq!(open[0].victim_uid, intent.victim_uid);
db.end_replace("vol~src").unwrap();
assert!(db.open_replaces().unwrap().is_empty());
}
File diff suppressed because it is too large. Load diff
+578
View File
@@ -0,0 +1,578 @@
//! Applying a pass's plan: uploads, downloads and the other effects, in
//! batches, and the baseline each one leaves behind.
use super::*;
impl Syncer {
/// Store the revision id of each file in one listing whose baseline row has
/// none, when the size the walk just read shows that file unchanged.
///
/// The classification step does the same, but only a pass that gets all the
/// way through the walk reaches it. A large folder whose walk is cut short
/// every time (a restart, a logout) then reads the size of every such file
/// again, one key unlock each, on every pass, and never finishes (B294).
pub(super) fn record_revisions(
&self,
folder_id: i64,
prefix: &str,
nodes: &[Node],
sized: &HashMap<String, (i64, Option<String>)>,
baseline: &HashMap<String, StoredSyncEntry>,
) {
let rows = revisions_to_record(prefix, nodes, sized, baseline);
if rows.is_empty() {
return;
}
match self.store.sync_entries_set_revision(folder_id, &rows) {
Ok(n) => self.trace_count(Count::Revisions, n),
Err(e) => debug!(folder = prefix, error = ?e, "sync: cannot record revision ids"),
}
}
/// Record a folder's baseline row (folders carry no content signature).
pub(super) fn baseline_dir(
&self,
folder_id: i64,
rel: &str,
uid: &NodeUid,
) -> Result<(), String> {
self.store
.sync_entry_upsert(folder_id, &dir_row(rel, uid))
.map_err(|e| format!("baseline dir {rel}: {e:?}"))
}
/// Run a batch of queued [`Pending`] ops concurrently (bounded by
/// [`SYNC_CONCURRENCY`]) and fold their results back into the reconcile's
/// shared state on the engine thread: created folders are registered in
/// `remote_dirs` (so deeper paths resolve their parent), and what each op did
/// is tallied into `outcome`. Driven by `block_on` from the (non-runtime) sync
/// engine thread, spawning the tasks onto the shared runtime.
///
/// Fails with [`PassAbort::Stopped`] once the daemon is stopping, after the
/// ops already sending have finished.
pub(super) fn flush_batch(
&self,
folder_id: i64,
local_root: &Path,
remote_dirs: &mut HashMap<String, NodeUid>,
batch: Vec<Pending>,
outcome: &mut Outcome,
) -> Result<(), PassAbort> {
if batch.is_empty() {
return Ok(());
}
self.progress_queued(folder_id, batch.len());
self.trace_count(Count::Queued, batch.len());
let applying = Instant::now();
let core = self.clone();
let root = local_root.to_path_buf();
let results = self.rt.block_on(async move {
let sem = Arc::new(tokio::sync::Semaphore::new(SYNC_CONCURRENCY));
let mut set = tokio::task::JoinSet::new();
for op in batch {
let core = core.clone();
let sem = sem.clone();
let root = root.clone();
set.spawn(async move {
let _permit = sem.acquire_owned().await.expect("semaphore not closed");
// An op still waiting for its turn when the stop comes is
// not started; the ones already sending finish.
if core.shutdown.is_stopping() {
return None;
}
Some(core.apply_pending(folder_id, &root, op).await)
});
}
let mut out = Vec::new();
let mut join_errors = 0usize;
while let Some(joined) = set.join_next().await {
match joined {
Ok(Some(result)) => out.push(result),
Ok(None) => {}
// The runtime ends with the daemon and cancels what is left.
Err(e) if e.is_cancelled() => {}
Err(e) => {
join_errors += 1;
warn!(error = %e, "sync: task panicked");
}
}
}
(out, join_errors)
});
self.trace_phase(Phase::Apply, applying.elapsed());
let (results, join_errors) = results;
outcome.errors += join_errors;
for result in results {
match result {
Ok(applied) => {
outcome.record(&applied);
if let Applied::Dir(rel, uid) = applied {
remote_dirs.insert(rel, uid);
}
}
Err(e) => {
warn!(error = %e, "sync: step failed; continuing");
outcome.failed(&e);
}
}
}
// The pass goes no further: the next depth's paths may need a folder
// this batch did not get to make, and went on to fail one by one
// (`docs/BUGS.md` B169).
if self.shutdown.is_stopping() {
return Err(PassAbort::Stopped);
}
if self.pass_abandoned(folder_id) {
return Err(PassAbort::Abandoned);
}
Ok(())
}
/// Whether a removal of `folder_id` is waiting for its running pass.
pub(super) fn pass_abandoned(&self, folder_id: i64) -> bool {
self.abandon.lock().contains(&folder_id)
}
/// Apply one [`Pending`] op (async, so it can run concurrently in a batch),
/// reporting it to the folder's live progress and to the activity feed. Each
/// item logs its own line — the feed is meant to answer "what is it doing",
/// which a pass-level summary alone cannot.
pub(super) async fn apply_pending(
&self,
folder_id: i64,
local_root: &Path,
op: Pending,
) -> Result<Applied, String> {
self.progress_started(folder_id, base_name(op.rel()));
let step = Instant::now();
let result = self.apply_one(folder_id, local_root, &op).await;
self.trace_call(op.call(), step.elapsed());
self.progress_finished(folder_id);
let name = base_name(op.rel());
match &result {
Ok(Applied::Adopted) => {}
Ok(_) => self.log_activity(op.kind(), name, op.detail(), true),
Err(e) => self.log_activity(op.kind(), name, e.clone(), false),
}
result
}
/// The body of one [`Pending`] op, without the progress/activity bookkeeping.
pub(super) async fn apply_one(
&self,
folder_id: i64,
local_root: &Path,
op: &Pending,
) -> Result<Applied, String> {
match op {
Pending::CreateDir { rel, parent } => {
let uid = self
.drive
.create_folder(parent, base_name(rel), Some(now_secs()))
.await
.map_err(|e| format!("create remote folder {rel}: {e}"))?;
// The parent has gained a child that no cached listing of it
// knows about (B86).
self.invalidate_children_of(parent);
self.baseline_dir(folder_id, rel, &uid)?;
Ok(Applied::Dir(rel.clone(), uid))
}
Pending::UploadNew { rel, parent } => {
self.upload_new(folder_id, local_root, rel, parent).await
}
Pending::UploadRevision { rel, uid, seen } => {
self.upload_revision(folder_id, local_root, rel, uid, seen)
.await
}
Pending::Download {
rel,
uid,
seen,
local,
} => {
self.download_file(folder_id, local_root, rel, uid, seen, *local)
.await?;
Ok(Applied::Downloaded)
}
Pending::Adopt {
rel,
uid,
seen: remote,
sha1,
local,
} => {
let path = local_root.join(rel_to_path(rel));
let hashed = tokio::task::spawn_blocking(move || local_sha1(&path))
.await
.map_err(|e| format!("hash {rel}: {e}"))?
.map_err(|e| format!("hash {rel}: {e}"))?;
let Some((seen, digest)) = hashed else {
return Ok(Applied::Vanished);
};
// Edited since the scan: the next pass plans it again.
if !seen.same_content(local) {
return Ok(Applied::Vanished);
}
if !digest.eq_ignore_ascii_case(sha1) {
info!(
rel,
"sync: same size as on Drive but different content; keeping a conflict copy"
);
return self
.take_remote_keeping_local(folder_id, local_root, rel, uid, remote)
.await;
}
self.store
.sync_entry_upsert(
folder_id,
&StoredSyncEntry {
rel_path: rel.clone(),
remote_uid: Some(uid.to_string()),
local_mtime: seen.mtime,
local_mtime_ns: seen.mtime_ns,
local_size: seen.size,
remote_rev: Some(remote.mtime.to_string()),
remote_hash: Some(remote.size.to_string()),
remote_revision_id: remote.revision.clone(),
},
)
.map_err(|e| format!("adopt baseline {rel}: {e:?}"))?;
Ok(Applied::Adopted)
}
Pending::Conflict { rel, uid, seen } => {
self.take_remote_keeping_local(folder_id, local_root, rel, uid, seen)
.await
}
Pending::PushConflict { rel, parent } => {
// The ordinary conflict resolution — rename the local copy aside and
// let the next pass upload it — loses the file here: the folder is
// going on-demand, so "next pass" comes after the local tree has been
// evicted. Push the conflict copy now, while it still exists, and
// leave the remote file holding the original path.
let path = local_root.join(rel_to_path(rel));
let conflict = preserve_conflict_copy(&path, now_secs())
.map_err(|e| format!("set aside conflict copy for {rel}: {e}"))?;
let name = conflict
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.ok_or_else(|| format!("conflict copy for {rel} has no name"))?;
let conflict_rel = join_rel(parent_rel(rel), &name);
self.upload_new(folder_id, local_root, &conflict_rel, parent)
.await?;
info!(rel, "sync: uploaded local changes as a conflict copy");
Ok(Applied::Conflict)
}
}
}
/// Set the local copy aside (it re-uploads as a new file next pass), then
/// take the remote version as the shared truth.
pub(super) async fn take_remote_keeping_local(
&self,
folder_id: i64,
local_root: &Path,
rel: &str,
uid: &NodeUid,
seen: &RemoteSeen,
) -> Result<Applied, String> {
let path = local_root.join(rel_to_path(rel));
if path.exists() {
preserve_conflict_copy(&path, now_secs())
.map_err(|e| format!("set aside conflict copy for {rel}: {e}"))?;
info!(rel, "sync: kept local changes as a conflict copy");
}
// The local copy has just been moved aside, so the state this
// download expects to find at the path is "nothing" — anything
// that appears while it runs is a *new* racing write, and gets
// its own conflict copy rather than being overwritten (B39).
self.download_file(folder_id, local_root, rel, uid, seen, None)
.await?;
Ok(Applied::Conflict)
}
/// Upload a brand-new local file to its remote parent, then record baseline.
pub(super) async fn upload_new(
&self,
folder_id: i64,
local_root: &Path,
rel: &str,
parent: &NodeUid,
) -> Result<Applied, String> {
let path = local_root.join(rel_to_path(rel));
let name = base_name(rel);
let Some(file) = open_to_upload(&path, rel)? else {
return Ok(Applied::Vanished);
};
let meta = file.metadata().map_err(|e| format!("stat {rel}: {e}"))?;
let mtime = system_mtime(&meta);
// Taken from the descriptor being streamed, so it names the content that
// actually goes up rather than whatever is at the path when we finish.
let streamed = LocalSig::from(&meta);
let thumbnails = self
.thumbnails_for_upload(path.clone(), name.to_string())
.await;
// Count the bytes as they are read, so this upload shows up in
// `GetQueueStatus` next to a manual one. The uid isn't known until the
// draft is sealed, so the transfer registers without one.
let (reader, sent) = Sha1Tap::new(OwnedCountingReader::new(
file,
self.transfers
.begin(name, "", TransferDirection::Upload, meta.len()),
));
let uid = self
.drive
// Mirror push: the local file is authoritative. If a prior attempt was
// interrupted mid-upload it left an unsealed draft of this name; recover
// it even across a daemon restart (which rotates our client uid), so the
// folder can reach idle instead of `AlreadyExists`-looping forever.
.upload_file_replacing_draft_from(
parent,
name,
pdfs_drive::media_type_for(name),
reader,
meta.len() as i64,
thumbnails,
Some(mtime),
false,
)
.await
.map_err(|e| format!("upload {rel}: {e}"))?;
// The parent has gained a child that no cached listing of it knows
// about. Without this, a folder later switched to on-demand serves a
// snapshot that predates this upload (B86).
self.invalidate_children_of(parent);
warn_if_torn(rel, &path, streamed);
let remote = self
.landed_as_sent(rel, &uid, &sent.digest(), streamed)
.await?;
self.record_file_baseline(folder_id, rel, Some(streamed), &uid, &remote)?;
Ok(Applied::Uploaded)
}
/// Upload a changed local file as a new revision of an existing remote node.
///
/// The revision supersedes whatever is current on Drive, and the plan comes
/// from a walk that may be minutes old. Another computer syncing the same
/// folder may have committed a revision since, and uploading over it would
/// leave that edit only in the revision history. So Drive is asked first,
/// and a file that moved on is left for the next pass, which keeps the
/// local edit as a conflict copy (B249). A revision committed between this
/// check and the upload's own draft is not caught here; the read-back after
/// the upload catches one committed after it.
pub(super) async fn upload_revision(
&self,
folder_id: i64,
local_root: &Path,
rel: &str,
uid: &NodeUid,
seen: &RemoteSeen,
) -> Result<Applied, String> {
let path = local_root.join(rel_to_path(rel));
let Some(file) = open_to_upload(&path, rel)? else {
return Ok(Applied::Vanished);
};
let current = self
.drive
.enumerate_nodes(std::slice::from_ref(uid))
.await
.map_err(|e| format!("check {rel} on Drive: {e}"))?;
match current.first() {
Some(node) if !node.trashed && seen.still_current(node) => {}
Some(node) if !node.trashed => {
return Err(format!(
"{rel} changed on Drive since this pass looked; it is compared again on the next pass"
));
}
_ => {
return Err(format!(
"{rel} is no longer on Drive where this pass saw it; it is compared again on the next pass"
));
}
}
let meta = file.metadata().map_err(|e| format!("stat {rel}: {e}"))?;
let mtime = system_mtime(&meta);
let streamed = LocalSig::from(&meta);
let thumbnails = self
.thumbnails_for_upload(path.clone(), base_name(rel).to_string())
.await;
let (reader, sent) = Sha1Tap::new(OwnedCountingReader::new(
file,
self.transfers.begin(
base_name(rel),
uid.to_string(),
TransferDirection::Upload,
meta.len(),
),
));
self.drive
.upload_new_revision_from(uid, reader, meta.len() as i64, thumbnails, Some(mtime))
.await
.map_err(|e| format!("upload revision {rel}: {e}"))?;
warn_if_torn(rel, &path, streamed);
let remote = self
.landed_as_sent(rel, uid, &sent.digest(), streamed)
.await?;
self.record_file_baseline(folder_id, rel, Some(streamed), uid, &remote)?;
Ok(Applied::Uploaded)
}
/// Download a remote file to its local path (atomically via a temp file),
/// stamp the local mtime to match the remote, then record baseline.
///
/// `expected_local` is the identity planning saw at the destination. The
/// rename below is the destructive step, and the download in between can run
/// for minutes, so the destination is re-examined right before it: a local
/// file that no longer matches the plan is set aside as a conflict copy
/// instead of being replaced (`docs/BUGS.md` B39).
///
/// The baseline records `seen`, the revision the pass planned to download,
/// and not a read of the node afterwards. Another computer may commit a
/// revision while the download runs, and a read-back would record that
/// revision as synced while the disk holds the older one, so its edit would
/// never arrive (B250). If the download did fetch the newer revision, the
/// next pass fetches it once more, which costs a transfer and loses nothing.
pub(super) async fn download_file(
&self,
folder_id: i64,
local_root: &Path,
rel: &str,
uid: &NodeUid,
seen: &RemoteSeen,
expected_local: Option<LocalSig>,
) -> Result<(), String> {
let (mtime, size) = (seen.mtime, seen.size);
let path = local_root.join(rel_to_path(rel));
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| format!("mkdir for {rel}: {e}"))?;
}
let tmp = staging_path(&path);
// A file an on-demand mount already read, say one just moved here from
// it, is in the content cache under the same revision key.
let seeded = size > 0 && self.cache.copy_cached_to(uid, mtime, size as u64, &tmp);
if seeded {
std::fs::File::open(&tmp)
.and_then(|f| f.sync_all())
.map_err(|e| {
let _ = std::fs::remove_file(&tmp);
format!("sync tmp {rel}: {e}")
})?;
debug!(
rel,
"sync: placed from the content cache instead of downloading"
);
} else {
let out = std::fs::File::create(&tmp).map_err(|e| format!("create tmp {rel}: {e}"))?;
// Count the bytes as they land, so the download reports progress like
// an on-demand hydration does.
let guard = self.transfers.begin(
base_name(rel),
uid.to_string(),
TransferDirection::Download,
size.max(0) as u64,
);
let mut out = CountingWriter::new(out, &guard);
self.drive
.download_file_to(uid, &mut out)
.await
.map_err(|e| {
let _ = std::fs::remove_file(&tmp);
format!("download {rel}: {e}")
})?;
let mut out = out.into_inner();
out.flush().map_err(|e| format!("flush tmp {rel}: {e}"))?;
out.sync_all().map_err(|e| format!("sync tmp {rel}: {e}"))?;
}
place_download(&tmp, &path, expected_local, mtime, rel)?;
// Here the file on disk *is* the transferred content: it was published
// by a rename and stamped just above, so its stat is the identity.
self.record_file_baseline(folder_id, rel, local_sig(&path), uid, seen)
}
/// What Drive holds for `uid` after this daemon uploaded content with SHA-1
/// `sent` and identity `streamed` to it, as the baseline should record it.
///
/// Read back so the stored signature is exactly what a walk reports next
/// time. A digest on Drive that is not `sent` means another computer
/// committed a revision right after this upload. Recording that revision
/// as synced would hide it, and the edit here would be lost to it on the
/// next download. So the baseline is left as it was, and the next pass sees
/// both sides changed and keeps a conflict copy (B250).
pub(super) async fn landed_as_sent(
&self,
rel: &str,
uid: &NodeUid,
sent: &str,
streamed: LocalSig,
) -> Result<RemoteSeen, String> {
let node = match self.drive.enumerate_nodes(std::slice::from_ref(uid)).await {
Ok(nodes) => nodes.into_iter().next(),
Err(e) => {
warn!(rel, error = %e, "sync: baseline refetch failed; using local mtime");
None
}
};
let Some(node) = node else {
// Drive does not list a node it has just made at once. The upload
// stamped it with the local modification time, so that and the
// size sent are what a walk reports.
return Ok(RemoteSeen {
mtime: streamed.mtime,
size: streamed.size,
revision: None,
});
};
if let Some(digest) = pdfs_drive::node_content_sha1(&node)
&& !digest.eq_ignore_ascii_case(sent)
{
return Err(format!(
"{rel} was changed on Drive by another client right after this upload; it is compared again on the next pass"
));
}
let (mtime, size) = remote_file_sig(&node);
Ok(RemoteSeen {
mtime,
size,
revision: pdfs_drive::node_revision_id(&node),
})
}
/// Record a file's baseline: the local identity these bytes came from and
/// the remote revision they were synced with. Called after every
/// upload/download so the very next reconcile sees the path as unchanged.
///
/// `local` is the identity the *transferred content* corresponds to, which
/// is not always the file's current stat. An upload streams the live file,
/// so it passes the identity it read the first byte at: if a writer changed
/// the file mid-stream, the remote now holds a torn revision, and recording
/// the pre-upload identity is what makes the next pass see the path as
/// locally changed and upload a whole, clean revision over it. Recording the
/// post-upload stat instead declared the torn revision synchronized and left
/// it as the file's content on Drive (`docs/BUGS.md` B40).
pub(super) fn record_file_baseline(
&self,
folder_id: i64,
rel: &str,
local: Option<LocalSig>,
uid: &NodeUid,
remote: &RemoteSeen,
) -> Result<(), String> {
let Some(local) = local else {
return Err(format!("stat {rel}: no local identity to baseline"));
};
self.store
.sync_entry_upsert(
folder_id,
&StoredSyncEntry {
rel_path: rel.to_string(),
remote_uid: Some(uid.to_string()),
local_mtime: local.mtime,
local_mtime_ns: local.mtime_ns,
local_size: local.size,
remote_rev: Some(remote.mtime.to_string()),
remote_hash: Some(remote.size.to_string()),
remote_revision_id: remote.revision.clone(),
},
)
.map_err(|e| format!("baseline {rel}: {e:?}"))
}
}
+350
View File
@@ -0,0 +1,350 @@
//! The push pass: sending local changes to Drive between full passes.
use super::*;
impl Syncer {
/// Get every local change up to Drive, and nothing else — the pass run for a
/// folder waiting to go on-demand, whose local copy is about to be evicted.
///
/// This exists because a full [`do_reconcile`](Self::do_reconcile) is both too
/// slow and too wasteful to stand between the user and the switch they asked
/// for. It walks the whole remote tree (the minutes-long part of a pass over a
/// large folder) to answer a question the switch makes irrelevant — what the
/// remote side has that we don't — and then downloads those files onto a disk
/// we are about to clear. A push pass answers only "is anything here not on
/// Drive yet?", which the local tree and the baseline already know, so it needs
/// no remote walk at all and finishes in the time the local walk takes.
///
/// The remote is consulted for exactly one thing: the files whose local copy
/// changed. Those, and only those, could be a two-sided edit, so their nodes are
/// fetched (cheaply, in one batch) to check whether the remote moved too. If it
/// did, the local copy goes up under a conflict name rather than overwriting the
/// other side. Everything else — remote edits, remote deletions, remote-only
/// files — is left for the FUSE mount to show live once the switch lands.
///
/// Per-path failures are counted, never fatal, exactly as in `do_reconcile`; a
/// non-zero [`Outcome::errors`] leaves the folder out of `idle`, which keeps the
/// queued switch waiting rather than evicting a file that never made it up.
pub(super) fn push_pass(
&self,
folder_id: i64,
local_root: &Path,
remote_root: &NodeUid,
rules: &IgnoreRules,
) -> Result<Outcome, PassAbort> {
// This pass uploads without walking Drive, so a walk saved by an
// earlier pass would not know what it sent; see `do_reconcile`.
self.store
.sync_walk_clear(folder_id)
.map_err(|e| format!("drop the saved walk: {e:?}"))?;
let step = Instant::now();
let baseline = self
.store
.sync_entries(folder_id)
.map_err(|e| format!("load baseline: {e:?}"))?;
self.trace_phase(Phase::Baseline, step.elapsed());
// Only the local side is walked here, so each baseline path is checked once.
self.progress_scan_total(folder_id, baseline.len());
let mut local: HashMap<String, LocalItem> = HashMap::new();
let mut unscanned = Unscanned::default();
let step = Instant::now();
let writing = open_for_write_set(local_root);
self.walk_local(
folder_id,
local_root,
rules,
&writing,
&mut local,
&mut unscanned,
)?;
self.trace_phase(Phase::LocalWalk, step.elapsed());
self.trace_count(Count::LocalEntries, local.len());
// The guard compares against the paths this pass could still see: an
// ignored or unreadable path is absent from `local` by rule or by
// failure, not by loss, and counting those as missing would trip the
// guard on every pass — wedging the folder's sync permanently — the
// moment a rule covers the whole tree.
let tracked = tracked_baseline(&baseline, rules, &unscanned);
// A local copy that is gone in its entirety is not trashed on Drive,
// for the reason `guard_local_wipe` gives. A full pass stops there, but
// this one exists for a switch to on-demand, which needs nothing local
// and leaves Drive as it is: refusing the pass would only keep the
// folder out of `idle`, wedging the switch for good (#46). So the pass
// forgets those paths instead of trashing them, and the mount then
// shows everything Drive still has.
let local_gone = match guard_local_wipe(&tracked, &local) {
Ok(()) => false,
Err(reason) => {
warn!(id = folder_id, %reason, "sync: going on-demand without trashing anything on Drive");
true
}
};
// The remote folder uids come from the baseline instead of a walk: every
// directory this device has synced recorded its uid there when it was
// created or first matched up.
let mut remote_dirs: HashMap<String, NodeUid> = HashMap::new();
remote_dirs.insert(String::new(), remote_root.clone());
for (rel, item) in &local {
if !item.is_dir {
continue;
}
if let Some(uid) = baseline
.get(rel)
.and_then(|e| e.remote_uid.as_deref())
.and_then(parse_uid)
{
remote_dirs.insert(rel.clone(), uid);
}
}
// A local directory the baseline has no uid for is either brand new or one
// whose first pass never finished — and those look identical from here.
// Creating it blindly would duplicate a remote folder we simply haven't
// looked at, so when any exist, the remote folder tree is walked for real.
// It costs one light listing per folder and no file keys, and a folder whose
// baseline is complete — the case this pass is written for — skips it
// entirely and touches the network only for the files it uploads.
if local
.iter()
.any(|(rel, item)| item.is_dir && !remote_dirs.contains_key(rel))
{
self.walk_remote_dirs(folder_id, remote_root, "", &mut remote_dirs)?;
}
// Files whose local copy has moved since the baseline: the only ones with
// anything to push, and the only ones that could be a two-sided edit.
let changed: Vec<&String> = local
.iter()
.filter(|(_, item)| !item.is_dir && !item.open_for_write)
.filter(|(rel, item)| {
baseline
.get(*rel)
.is_none_or(|b| b.local_mtime != item.mtime || b.local_size != item.size)
})
.map(|(rel, _)| rel)
.collect();
// One light batch tells us which of those also changed remotely. A light
// node carries the modification time and the revision id without
// unlocking the node key, and those are what the baseline compares
// against.
let check: Vec<NodeUid> = changed
.iter()
.filter_map(|rel| baseline.get(*rel))
.filter_map(|e| e.remote_uid.as_deref())
.filter_map(parse_uid)
.collect();
let remote_now: HashMap<String, (i64, Option<String>)> = if check.is_empty() {
HashMap::new()
} else {
self.rt
.block_on(self.drive.enumerate_nodes_light(&check))
.map_err(|e| format!("resolve changed nodes: {e}"))?
.into_iter()
.filter(|n| !n.trashed)
.map(|n| {
let revision = pdfs_drive::node_revision_id(&n);
(n.uid.to_string(), (n.modification_time, revision))
})
.collect()
};
let changed: HashSet<&String> = changed.into_iter().collect();
let mut outcome = Outcome {
deferred: local.values().filter(|item| item.open_for_write).count(),
unscanned: unscanned.report(),
..Default::default()
};
let mut order: Vec<&String> = local.keys().collect();
order.sort_by_key(|p| p.matches('/').count());
// Same depth-ascending batching as `do_reconcile`: a folder is created
// remotely before the paths inside it are classified, so their parent uid is
// in `remote_dirs` by the time they need it.
let mut batch: Vec<Pending> = Vec::new();
let mut batch_depth = 0usize;
for rel in order {
let depth = rel.matches('/').count();
if depth > batch_depth {
self.flush_batch(
folder_id,
local_root,
&mut remote_dirs,
std::mem::take(&mut batch),
&mut outcome,
)?;
batch_depth = depth;
}
let item = &local[rel];
if item.is_dir {
// The folder is already on Drive, so only its children carry work —
// but if the walk above is what found it, record the uid now so the
// next pass over this folder needs no walk at all.
if let Some(uid) = remote_dirs.get(rel) {
if baseline
.get(rel)
.and_then(|e| e.remote_uid.as_deref())
.is_none()
&& let Err(e) = self.baseline_dir(folder_id, rel, uid)
{
warn!(rel, error = %e, "sync: folder step failed; continuing");
outcome.failed(&format!("{rel}: {e}"));
}
continue;
}
match remote_dirs.get(parent_rel(rel)) {
Some(parent) => batch.push(Pending::CreateDir {
rel: rel.clone(),
parent: parent.clone(),
}),
None => {
warn!(rel, "sync: no remote parent for folder; continuing");
outcome.failed(&format!("{rel}: no remote parent for folder"));
}
}
continue;
}
if !changed.contains(rel) {
// Local copy matches the baseline, so it is already on Drive.
continue;
}
let base = baseline.get(rel);
let uid = base
.and_then(|e| e.remote_uid.as_deref())
.and_then(parse_uid);
match uid {
// Never uploaded (or the remote node is gone): it goes up as a new file.
None => match remote_dirs.get(parent_rel(rel)) {
Some(parent) => batch.push(Pending::UploadNew {
rel: rel.clone(),
parent: parent.clone(),
}),
None => {
warn!(rel, "sync: no remote parent for file; continuing");
outcome.failed(&format!("{rel}: no remote parent for file"));
}
},
Some(uid) => {
let (remote_moved, seen) = match remote_now.get(&uid.to_string()) {
Some((mtime, revision)) => {
let recorded = base.and_then(remote_sig);
let moved = recorded.is_none_or(|(m, _)| m != *mtime)
|| revision_moved(base, revision.as_deref());
let seen = RemoteSeen {
mtime: *mtime,
size: recorded.map_or(0, |(_, size)| size),
revision: revision.clone(),
};
(moved, seen)
}
// Trashed or unreadable remotely — treat as gone and re-upload
// the local copy as a new file rather than losing it.
None => {
match remote_dirs.get(parent_rel(rel)) {
Some(parent) => batch.push(Pending::UploadNew {
rel: rel.clone(),
parent: parent.clone(),
}),
None => {
warn!(rel, "sync: no remote parent for file; continuing");
outcome.failed(&format!("{rel}: no remote parent for file"));
}
}
continue;
}
};
if remote_moved {
match remote_dirs.get(parent_rel(rel)) {
Some(parent) => batch.push(Pending::PushConflict {
rel: rel.clone(),
parent: parent.clone(),
}),
None => {
warn!(rel, "sync: no remote parent for file; continuing");
outcome.failed(&format!("{rel}: no remote parent for file"));
}
}
} else {
batch.push(Pending::UploadRevision {
rel: rel.clone(),
uid,
seen,
});
}
}
}
}
self.flush_batch(
folder_id,
local_root,
&mut remote_dirs,
std::mem::take(&mut batch),
&mut outcome,
)?;
// Paths the baseline knows that are no longer on disk: the user deleted them
// locally, and the deletion has to reach Drive before the mount starts
// showing the folder's remote contents — otherwise everything they deleted
// comes back the moment the switch lands. Shallowest first, skipping anything
// under a folder already trashed (its children went with it).
let deletions = local_deletions(&tracked, &local);
if local_gone {
// Forgotten instead of trashed. A row left behind would read to
// the switch as a deletion not on Drive yet and withdraw it, and
// to a later full pass as a reason to stop again. Forgotten, a full
// pass downloads the paths again.
let mut forgotten: HashSet<&str> = HashSet::new();
for rel in &deletions {
let mut parent = parent_rel(rel);
while !parent.is_empty() && !forgotten.contains(parent) {
parent = parent_rel(parent);
}
if parent.is_empty() {
let _ = self.store.sync_entries_remove_subtree(folder_id, rel);
forgotten.insert(rel);
}
}
return Ok(outcome);
}
let mut trashed: Vec<String> = Vec::new();
for rel in &deletions {
if trashed
.iter()
.any(|dir| rel.starts_with(&format!("{dir}/")))
{
let _ = self.store.sync_entry_remove(folder_id, rel);
continue;
}
let Some(uid) = baseline[rel].remote_uid.as_deref().and_then(parse_uid) else {
let _ = self.store.sync_entry_remove(folder_id, rel);
continue;
};
if let Err(e) = self
.rt
.block_on(self.drive.trash_nodes(&[uid]))
.and_then(batch::into_unit)
{
warn!(rel, error = %e, "sync: trash remote failed");
self.log_activity(ActivityKind::Trash, base_name(rel), e.to_string(), false);
outcome.failed(&format!("{rel}: {e}"));
continue;
}
trashed.push(rel.clone());
if let Some(parent) = parent_uid_of(rel, &remote_dirs, &baseline) {
self.invalidate_children_of(&parent);
}
let _ = self.store.sync_entry_remove(folder_id, rel);
self.log_activity(
ActivityKind::Trash,
base_name(rel),
"removed on Drive",
true,
);
outcome.deleted += 1;
}
Ok(outcome)
}
}
+553
View File
@@ -0,0 +1,553 @@
//! The walks of a pass: the local tree, Drive's folders (resumable, and only
//! the changed ones when the event feed can be trusted), and listing one.
use super::*;
impl Syncer {
/// Recursively walk a local tree into `out`, keyed by `/`-joined relative
/// path. Symlinks and other special files are skipped, and paths that cannot
/// be read go to `unscanned`. Reports each entry to the pass's scan progress.
pub(super) fn walk_local(
&self,
folder_id: i64,
root: &Path,
rules: &IgnoreRules,
writing: &HashSet<PathBuf>,
out: &mut HashMap<String, LocalItem>,
unscanned: &mut Unscanned,
) -> Result<(), String> {
walk_local_tree(root, rules, writing, out, unscanned, &mut |rel| {
self.progress_scanned(folder_id, base_name(rel))
})
}
/// Map every remote folder under `folder` to its uid by rel path, ignoring
/// files. The cheap half of [`walk_remote`](Self::walk_remote): folders carry no
/// content signature, so a light listing answers this without unlocking a single
/// node key. Used by [`push_pass`](Self::push_pass) to tell a folder it must
/// create from one it just hasn't recorded yet.
pub(super) fn walk_remote_dirs(
&self,
folder_id: i64,
folder: &NodeUid,
prefix: &str,
dirs: &mut HashMap<String, NodeUid>,
) -> Result<(), String> {
let uids = self
.rt
.block_on(self.drive.enumerate_folder_children_node_uids(folder))
.map_err(|e| format!("enumerate {folder}: {e}"))?;
if uids.is_empty() {
return Ok(());
}
let nodes = self
.rt
.block_on(self.drive.enumerate_nodes_light(&uids))
.map_err(|e| format!("resolve nodes: {e}"))?;
for node in nodes {
if node.trashed || !node.is_folder() || !pdfs_drive::remote_name_is_safe(&node.name) {
continue;
}
let rel = join_rel(prefix, &node.name);
self.progress_scanned(folder_id, base_name(&rel));
dirs.insert(rel.clone(), node.uid.clone());
self.walk_remote_dirs(folder_id, &node.uid, &rel, dirs)?;
}
Ok(())
}
/// Walk the remote tree of a mirror folder into `walk`, folder by folder,
/// recording every descendant's relative path, and mapping each subfolder's
/// rel path to its uid in `walk.dirs`.
///
/// A file's size comes from its extended attributes, which only its own node
/// key can decrypt — and unlocking that key costs an S2K derivation (tens of
/// milliseconds) *per file*, which is the bulk of a pass over a large folder.
/// So the walk enumerates cheaply ([`enumerate_nodes_light`]) and only pays
/// for the files whose modification time has moved away from `baseline`: an
/// unchanged mtime means the recorded size still stands.
///
/// [`enumerate_nodes_light`]: proton_drive_rs::ProtonDriveClient::enumerate_nodes_light
///
/// What the walk could not read goes to `walk.gaps`, never silently out of
/// the map: a missing path reads as deleted on Drive.
///
/// Each folder's listing is saved as it comes in. A walk cut short by a
/// stop resumes from what was saved and lists only the folders it had not
/// reached, where it used to start over and, on a folder large enough,
/// never finish (B294). The database drops a saved walk whenever the
/// folder's baseline changes, so a resumed walk never meets a baseline
/// newer than its listings; it is as old as a long walk's first listings
/// would be, and the apply step checks each file again before it acts.
pub(super) fn walk_remote(
&self,
folder_id: i64,
root: &NodeUid,
walk: &mut RemoteWalk<'_>,
baseline: &HashMap<String, StoredSyncEntry>,
) -> Result<(), PassAbort> {
let WalkStart {
mut todo,
mut children,
dirty_upto,
} = self.start_walk(folder_id, root, walk);
// Folders to list again next pass: their listing failed or came back
// short this time.
let mut again: Vec<String> = Vec::new();
let mut listed: HashSet<String> = HashSet::new();
while let Some(next) = todo.pop_front() {
// Checked per folder, not per pass: this walk is the long pole on a
// large tree, and a user who asks for on-demand three minutes into
// it should not wait out the rest of a survey of files they want
// deleted. Bailing out here is safe precisely because the walk has
// applied nothing — a *partial* remote map, on the other hand,
// would be read as "the remote deleted everything we haven't
// reached yet", so it must never reach the diff.
if self.shutdown.is_stopping() {
return Err(PassAbort::Stopped);
}
if self.pass_abandoned(folder_id) {
return Err(PassAbort::Abandoned);
}
if self.ondemand_queued(folder_id) {
return Err(PassAbort::Interrupted);
}
// Gone with a folder listed again before it, or listed already.
if walk.dirs.get(&next.prefix) != Some(&next.uid) || !listed.insert(next.prefix.clone())
{
continue;
}
let prefix = next.prefix;
// What an earlier listing could not read is read again now.
walk.gaps.forget(&prefix);
let Some(listing) = self.list_remote(folder_id, &next.uid, &prefix, walk, baseline)?
else {
// What the saved walk holds of it is older than the change
// that marked it: its files are left out of this pass, as a
// folder a full walk could not list is.
if let Some(children) = &children {
for rel in children.of(&prefix) {
if !walk.dirs.contains_key(rel) {
walk.out.remove(rel);
}
}
}
again.push(prefix);
continue;
};
if listing.short || !listing.unread.is_empty() {
again.push(prefix.clone());
}
let mut removed = Vec::new();
let mut kept: HashSet<String> = HashSet::new();
if let Some(children) = &mut children {
// Listed again: what it held before and no longer holds goes,
// with all under it. A folder still there under the same uid
// keeps what was saved under it.
let fresh: HashMap<&str, &RemoteItem> = listing
.items
.iter()
.map(|(rel, item)| (rel.as_str(), item))
.collect();
for old in children.take(&prefix) {
let same_folder = walk.dirs.get(&old).is_some_and(|uid| {
fresh
.get(old.as_str())
.is_some_and(|item| item.is_dir && &item.uid == uid)
});
if same_folder {
kept.insert(old);
} else {
children.remove_subtree(&old, walk, &mut removed);
}
}
children.add(
&prefix,
listing
.items
.iter()
.map(|(rel, _)| rel)
.chain(&listing.unread),
);
}
let mut saved = Vec::with_capacity(listing.items.len() + listing.unread.len());
for (rel, item) in listing.items {
self.progress_scanned(folder_id, base_name(&rel));
saved.push(SavedWalkItem {
rel_path: rel.clone(),
uid: Some(item.uid.to_string()),
is_dir: item.is_dir,
mtime: item.mtime,
size: item.size,
revision: item.revision.clone(),
sha1: item.sha1.clone(),
});
if item.is_dir {
walk.dirs.insert(rel.clone(), item.uid.clone());
if !kept.contains(&rel) {
todo.push_back(WalkNext {
prefix: rel.clone(),
uid: item.uid.clone(),
});
}
}
walk.out.insert(rel, item);
}
for rel in listing.unread {
self.progress_scanned(folder_id, base_name(&rel));
saved.push(SavedWalkItem {
rel_path: rel.clone(),
uid: None,
is_dir: false,
mtime: 0,
size: 0,
revision: None,
sha1: None,
});
walk.gaps.unread(rel);
}
// A walk that cannot be saved still runs; it just starts over if
// it is cut short.
if let Err(e) =
self.store
.sync_walk_record(folder_id, &prefix, listing.short, &saved, &removed)
{
debug!(folder = prefix, error = ?e, "sync: cannot save the walk's progress");
}
}
// A stop that came during the last listing still ends the pass here,
// and the next one resumes a walk with nothing left to list.
if self.shutdown.is_stopping() {
return Err(PassAbort::Stopped);
}
self.finish_walk(folder_id, dirty_upto, &again)
.map_err(|e| PassAbort::from(format!("save the walk of Drive: {e:?}")))
}
/// Keep a walk that reached its end as the next pass's picture of Drive.
/// A walk that listed every folder drops the dirty marks it read past; a
/// walk of the dirty folders only drops the marks it read, up to
/// `dirty_upto`. Either way, the folders in `again` stay dirty, so the
/// next pass lists them again.
pub(super) fn finish_walk(
&self,
folder_id: i64,
dirty_upto: Option<i64>,
again: &[String],
) -> pdfs_core::Result<()> {
if !again.is_empty() {
self.store.sync_remote_mark(folder_id, again)?;
}
match dirty_upto {
Some(seq) => self.store.sync_remote_dirty_consume(folder_id, seq),
None => {
if !self.store.sync_walk_complete(folder_id)? {
debug!(
id = folder_id,
"sync: the walk of Drive was dropped before its end"
);
}
Ok(())
}
}
}
/// Where a walk of Drive starts.
///
/// - A complete walk, kept up to date by the event stream, is loaded into
/// `walk`, and only the folders marked dirty since are listed again.
/// - A walk an earlier pass did not finish is loaded and continues, when
/// it is recent enough.
/// - Otherwise a new walk starts at the root.
pub(super) fn start_walk(
&self,
folder_id: i64,
root: &NodeUid,
walk: &mut RemoteWalk<'_>,
) -> WalkStart {
let root_uid = root.to_string();
let saved = match self.store.sync_walk_load(folder_id) {
Ok(saved) => saved,
Err(e) => {
warn!(id = folder_id, error = ?e, "sync: cannot read the saved walk; starting over");
None
}
};
if let Some(saved) = saved
&& saved.root_uid == root_uid
{
let age = now_secs().saturating_sub(saved.started);
if saved.complete
&& age < AUDIT_INTERVAL.as_secs() as i64
&& self.events_trusted(root)
&& let Some(start) = self.walk_dirty(folder_id, &saved, walk)
{
return start;
}
if !saved.complete
&& age < WALK_MAX_AGE.as_secs() as i64
&& let Some(restored) = restore_walk(&saved, walk)
{
self.progress_scanned_many(folder_id, restored.items);
self.trace_count(Count::Resumed, restored.items);
info!(
id = folder_id,
restored = restored.items,
folders_left = restored.todo.len(),
age_s = age,
"sync: resuming the walk of Drive"
);
return WalkStart {
todo: restored.todo,
children: None,
dirty_upto: None,
};
}
// Loaded into `walk`, and of no use: start from nothing.
walk.out.clear();
walk.dirs.retain(|rel, _| rel.is_empty());
*walk.gaps = RemoteGaps::default();
}
if let Err(e) = self.store.sync_walk_begin(folder_id, &root_uid, now_secs()) {
debug!(id = folder_id, error = ?e, "sync: cannot save the walk's progress");
}
WalkStart {
todo: VecDeque::from([WalkNext {
prefix: String::new(),
uid: root.clone(),
}]),
children: None,
dirty_upto: None,
}
}
/// Start from a complete walk: load it into `walk`, and list again the
/// folders marked dirty since, plus any found since and not listed yet.
/// `None` when it cannot be read back.
pub(super) fn walk_dirty(
&self,
folder_id: i64,
saved: &SavedWalk,
walk: &mut RemoteWalk<'_>,
) -> Option<WalkStart> {
let dirty = match self.store.sync_remote_dirty(folder_id) {
Ok(dirty) => dirty,
Err(e) => {
warn!(id = folder_id, error = ?e, "sync: cannot read what changed on Drive");
return None;
}
};
let restored = restore_walk(saved, walk)?;
let mut todo = restored.todo;
let mut dirs: Vec<&str> = dirty.iter().map(|(_, dir)| dir.as_str()).collect();
dirs.sort_by_key(|dir| (dir.matches('/').count(), *dir));
dirs.dedup();
// Shallowest first: a folder listed again may turn out new or gone,
// and is then listed whole or dropped with what is under it.
for dir in &dirs {
match walk.dirs.get(*dir) {
Some(uid) => todo.push_back(WalkNext {
prefix: dir.to_string(),
uid: uid.clone(),
}),
// Gone from Drive, or new and not listed yet: listing its
// parent, marked too, settles it.
None => debug!(id = folder_id, dir, "sync: a dirty folder is not on Drive"),
}
}
self.progress_scanned_many(folder_id, restored.items);
self.trace_count(Count::Reused, restored.items);
self.trace_count(Count::Dirty, dirs.len());
info!(
id = folder_id,
known = restored.items,
dirty = dirs.len(),
to_list = todo.len(),
"sync: listing only the folders changed on Drive"
);
Some(WalkStart {
todo,
children: Some(restored.children),
dirty_upto: Some(dirty.iter().map(|(seq, _)| *seq).max().unwrap_or(0)),
})
}
/// Whether Drive's event stream for `root` is being followed, so a
/// change on Drive is marked dirty by the time a pass looks. The stream
/// covers the account's own volume only, and must have been read lately.
///
/// Right after a start, the stream has not been read yet: wait a little
/// for it rather than walk all of Drive again.
pub(super) fn events_trusted(&self, root: &NodeUid) -> bool {
if root.volume_id != self.primary_root_uid.volume_id {
return false;
}
let started = Instant::now();
while self.events_read_at.load(Ordering::Relaxed) == 0
&& started.elapsed() < EVENTS_FRESH
&& self.shutdown.sleep(Duration::from_millis(250))
{}
let read_at = self.events_read_at.load(Ordering::Relaxed);
read_at > 0 && now_secs().saturating_sub(read_at) < EVENTS_FRESH.as_secs() as i64
}
/// List one folder on Drive. `None` when the listing failed: that is
/// noted in `walk.gaps`, and the folder is not saved as listed, so a
/// resumed walk asks again. A failure at the root fails the pass.
pub(super) fn list_remote(
&self,
folder_id: i64,
folder: &NodeUid,
prefix: &str,
walk: &mut RemoteWalk<'_>,
baseline: &HashMap<String, StoredSyncEntry>,
) -> Result<Option<Listing>, PassAbort> {
let listing = Instant::now();
let step = Instant::now();
let uids = self
.rt
.block_on(self.drive.enumerate_folder_children_node_uids(folder))
.map_err(|e| format!("enumerate {folder}: {e}"));
self.trace_call(Call::ListChildren, step.elapsed());
self.trace_count(Count::RemoteFolders, 1);
let Some(uids) = unlisted_gap(walk, prefix, uids)? else {
return Ok(None);
};
let mut out = Listing::default();
if uids.is_empty() {
return Ok(Some(out));
}
let step = Instant::now();
let nodes = self
.rt
.block_on(self.drive.enumerate_nodes_light(&uids))
.map_err(|e| format!("resolve nodes: {e}"));
self.trace_call(Call::ReadNodes, step.elapsed());
let Some(nodes) = unlisted_gap(walk, prefix, nodes)? else {
return Ok(None);
};
// The SDK leaves out a node it cannot decrypt, and says so only in its
// log. Its name went with it, so all this can record is the folder.
if nodes.len() < uids.len() {
warn!(
folder = prefix,
listed = uids.len(),
read = nodes.len(),
"sync: some nodes on Drive cannot be read; leaving them out"
);
walk.gaps.short_listing(prefix);
out.short = true;
}
let nodes: Vec<Node> = nodes
.into_iter()
.filter(|node| {
let safe = pdfs_drive::remote_name_is_safe(&node.name);
if !safe {
warn!(folder = prefix, uid = %node.uid, "sync: a name on Drive cannot be a local file name; leaving it out");
}
safe
})
.collect();
// Files whose recorded mtime no longer matches: their size has to be
// read for real, so these are the only node keys worth unlocking.
let stale: Vec<NodeUid> = nodes
.iter()
.filter(|n| !n.trashed && !n.is_folder())
.filter(|n| {
unchanged_remote_size(
baseline,
&join_rel(prefix, &n.name),
n.modification_time,
pdfs_drive::node_revision_id(n).as_deref(),
)
.is_none()
})
.map(|n| n.uid.clone())
.collect();
// The full enumeration also decrypts the content digest, which the
// first sync of a path compares against the local file (B248).
let sized: HashMap<String, (i64, Option<String>)> = if stale.is_empty() {
HashMap::new()
} else {
let step = Instant::now();
let full = self
.rt
.block_on(self.drive.enumerate_nodes(&stale))
.map_err(|e| format!("resolve nodes: {e}"));
self.trace_call(Call::ReadNodesFull, step.elapsed());
self.trace_count(Count::NodesFull, stale.len());
let Some(full) = unlisted_gap(walk, prefix, full)? else {
return Ok(None);
};
full.iter()
.map(|n| {
(
n.uid.to_string(),
(remote_file_sig(n).1, pdfs_drive::node_content_sha1(n)),
)
})
.collect()
};
let stale: HashSet<String> = stale.iter().map(|u| u.to_string()).collect();
self.record_revisions(folder_id, prefix, &nodes, &sized, baseline);
self.trace_count(Count::Nodes, nodes.len());
self.engine.trace(|t| t.listing(prefix, listing.elapsed()));
for node in nodes {
if node.trashed {
continue;
}
let rel = join_rel(prefix, &node.name);
if node.is_folder() {
out.items.push((
rel,
RemoteItem {
uid: node.uid,
is_dir: true,
mtime: 0,
size: 0,
revision: None,
sha1: None,
},
));
continue;
}
let (size, sha1) = if stale.contains(&node.uid.to_string()) {
match sized.get(&node.uid.to_string()) {
Some(sized) => sized.clone(),
// Its size was needed but could not be read (the full
// enumeration skipped it as undecryptable). Leave it out
// rather than record a stale size, and say so: missing,
// it would read as deleted on Drive.
None => {
out.unread.push(rel);
continue;
}
}
} else {
match unchanged_remote_size(
baseline,
&rel,
node.modification_time,
pdfs_drive::node_revision_id(&node).as_deref(),
) {
Some(size) => (size, None),
None => continue,
}
};
out.items.push((
rel,
RemoteItem {
revision: pdfs_drive::node_revision_id(&node),
uid: node.uid,
is_dir: false,
mtime: node.modification_time,
size,
sha1,
},
));
}
Ok(Some(out))
}
}
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "pdfs-vfs"
version.workspace = true
edition.workspace = true
license.workspace = true
authors.workspace = true
rust-version.workspace = true
repository.workspace = true
homepage.workspace = true
description = "The mounted-files service of the Proton Drive Linux client, without a kernel adapter"
[features]
# Helpers that let other crates' tests build and inspect a tree.
test-support = []
[dependencies]
pdfs-core.workspace = true
pdfs-drive.workspace = true
pdfs-store.workspace = true
proton-drive-rs.workspace = true
libc.workspace = true
parking_lot.workspace = true
tracing.workspace = true
+330
View File
@@ -0,0 +1,330 @@
//! Scenarios every adapter of the mounted-files service has to pass the same
//! way: what a file holds after it is written, resized, synced, closed and
//! opened again, and what create, mkdir, unlink, rmdir and rename do with
//! names.
//!
//! [`run`] takes an [`Adapter`] and a folder to work in. The headless adapter
//! runs them in this crate's tests; `pdfs-fuse` runs them through a mount. A
//! scenario reports what it saw instead of panicking, so one run lists every
//! difference.
use crate::headless::{Failure, Fd, Headless};
/// File and folder operations by path, relative to the adapter's root.
pub trait Adapter {
/// A file open for writing.
type Fd;
/// Create the file, or empty it when it exists, and open it for writing.
fn create(&self, path: &str) -> Result<Self::Fd, Failure>;
fn open_write(&self, path: &str) -> Result<Self::Fd, Failure>;
fn write(&self, fd: &Self::Fd, offset: u64, data: &[u8]) -> Result<(), Failure>;
fn set_len(&self, fd: &Self::Fd, size: u64) -> Result<(), Failure>;
fn fsync(&self, fd: &Self::Fd) -> Result<(), Failure>;
fn close(&self, fd: Self::Fd) -> Result<(), Failure>;
/// The whole content of the file.
fn read(&self, path: &str) -> Result<Vec<u8>, Failure>;
fn mkdir(&self, path: &str) -> Result<(), Failure>;
fn unlink(&self, path: &str) -> Result<(), Failure>;
fn rmdir(&self, path: &str) -> Result<(), Failure>;
fn rename(&self, from: &str, to: &str) -> Result<(), Failure>;
/// The names in the folder, sorted.
fn list(&self, path: &str) -> Result<Vec<String>, Failure>;
}
impl Adapter for Headless {
type Fd = Fd;
fn create(&self, path: &str) -> Result<Fd, Failure> {
Headless::create(self, path)
}
fn open_write(&self, path: &str) -> Result<Fd, Failure> {
Headless::open_write(self, path)
}
fn write(&self, fd: &Fd, offset: u64, data: &[u8]) -> Result<(), Failure> {
Headless::write(self, fd, offset, data)
}
fn set_len(&self, fd: &Fd, size: u64) -> Result<(), Failure> {
Headless::set_len(self, fd, size)
}
fn fsync(&self, fd: &Fd) -> Result<(), Failure> {
Headless::fsync(self, fd)
}
fn close(&self, fd: Fd) -> Result<(), Failure> {
Headless::close(self, fd)
}
fn read(&self, path: &str) -> Result<Vec<u8>, Failure> {
Headless::read(self, path)
}
fn mkdir(&self, path: &str) -> Result<(), Failure> {
Headless::mkdir(self, path)
}
fn unlink(&self, path: &str) -> Result<(), Failure> {
Headless::unlink(self, path)
}
fn rmdir(&self, path: &str) -> Result<(), Failure> {
Headless::rmdir(self, path)
}
fn rename(&self, from: &str, to: &str) -> Result<(), Failure> {
Headless::rename(self, from, to)
}
fn list(&self, path: &str) -> Result<Vec<String>, Failure> {
Headless::list(self, path)
}
}
/// What a scenario saw that it should not have.
pub type Outcome = Result<(), String>;
/// A scenario, run in a folder of its own.
pub type Scenario<A> = fn(&A, &Dir) -> Outcome;
/// The folder a scenario works in.
pub struct Dir(String);
impl Dir {
/// The path of `name` in this folder.
pub fn at(&self, name: &str) -> String {
format!("{}/{name}", self.0)
}
pub fn path(&self) -> &str {
&self.0
}
}
/// Every scenario, by name.
pub fn scenarios<A: Adapter>() -> Vec<(&'static str, Scenario<A>)> {
vec![
("a_reopened_file_has_what_was_written", reopened_file::<A>),
("a_partial_overwrite_keeps_the_rest", partial_overwrite::<A>),
("a_read_while_open_sees_the_writes", read_while_open::<A>),
(
"a_hole_past_a_grow_reads_as_zeros",
hole_reads_as_zeros::<A>,
),
("a_create_over_a_file_empties_it", create_empties::<A>),
("folders_list_their_children", folders_list::<A>),
("a_rename_moves_and_replaces", rename_replaces::<A>),
("a_rename_refuses_what_posix_refuses", rename_refusals::<A>),
("removing_follows_posix", remove_rules::<A>),
(
"an_unlinked_open_file_does_not_come_back",
unlinked_open::<A>,
),
]
}
/// Run every scenario in its own folder under `base`, which must exist. The
/// result names each scenario that failed and why.
pub fn run<A: Adapter>(adapter: &A, base: &str) -> Vec<(&'static str, String)> {
let mut failed = Vec::new();
for (name, scenario) in scenarios::<A>() {
let dir = Dir(format!("{base}/{name}"));
let outcome = adapter
.mkdir(dir.path())
.map_err(|e| format!("mkdir {}: {e:?}", dir.path()))
.and_then(|()| scenario(adapter, &dir));
if let Err(why) = outcome {
failed.push((name, why));
}
}
failed
}
/// `Err` naming `what` unless `got` is `want`.
fn expect<T: PartialEq + std::fmt::Debug>(what: &str, got: T, want: T) -> Outcome {
if got == want {
Ok(())
} else {
Err(format!("{what}: got {got:?}, want {want:?}"))
}
}
/// The `Ok` of `result`, or `Err` naming `what`.
fn ok<T>(what: &str, result: Result<T, Failure>) -> Result<T, String> {
result.map_err(|e| format!("{what}: {e:?}"))
}
fn write_file<A: Adapter>(a: &A, path: &str, bytes: &[u8]) -> Outcome {
let fd = ok(&format!("create {path}"), a.create(path))?;
ok(&format!("write {path}"), a.write(&fd, 0, bytes))?;
ok(&format!("close {path}"), a.close(fd))
}
/// Written, resized, synced, closed and opened again: the bytes are what the
/// handle left, and a second handle adds to them.
fn reopened_file<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let f = d.at("f.txt");
let fd = ok("create", a.create(&f))?;
ok("write", a.write(&fd, 0, b"hello world"))?;
ok("set_len", a.set_len(&fd, 5))?;
ok("fsync", a.fsync(&fd))?;
ok("close", a.close(fd))?;
expect("after close", a.read(&f), Ok(b"hello".to_vec()))?;
let fd = ok("reopen", a.open_write(&f))?;
ok("append", a.write(&fd, 5, b" again"))?;
ok("close again", a.close(fd))?;
expect("after reopen", a.read(&f), Ok(b"hello again".to_vec()))
}
fn partial_overwrite<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let f = d.at("f.txt");
write_file(a, &f, b"abcdef")?;
let fd = ok("reopen", a.open_write(&f))?;
ok("overwrite", a.write(&fd, 2, b"XY"))?;
ok("close", a.close(fd))?;
expect("content", a.read(&f), Ok(b"abXYef".to_vec()))
}
fn read_while_open<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let f = d.at("f.txt");
let fd = ok("create", a.create(&f))?;
ok("write", a.write(&fd, 0, b"draft"))?;
let seen = a.read(&f);
ok("close", a.close(fd))?;
expect("while open", seen, Ok(b"draft".to_vec()))
}
fn hole_reads_as_zeros<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let f = d.at("f.bin");
let fd = ok("create", a.create(&f))?;
ok("write", a.write(&fd, 0, b"ab"))?;
ok("grow", a.set_len(&fd, 4))?;
ok("write past the end", a.write(&fd, 6, b"z"))?;
ok("close", a.close(fd))?;
expect("content", a.read(&f), Ok(b"ab\0\0\0\0z".to_vec()))
}
fn create_empties<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let f = d.at("f.txt");
write_file(a, &f, b"old content")?;
write_file(a, &f, b"new")?;
expect("content", a.read(&f), Ok(b"new".to_vec()))
}
fn folders_list<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let sub = d.at("sub");
ok("mkdir", a.mkdir(&sub))?;
expect("mkdir again", a.mkdir(&sub), Err(Failure::Exists))?;
write_file(a, &format!("{sub}/b.txt"), b"b")?;
write_file(a, &format!("{sub}/a.txt"), b"a")?;
expect(
"listing",
a.list(&sub),
Ok(vec!["a.txt".to_owned(), "b.txt".to_owned()]),
)?;
expect(
"parent listing",
a.list(d.path()),
Ok(vec!["sub".to_owned()]),
)?;
expect(
"mkdir under a file",
a.mkdir(&format!("{sub}/a.txt/x")),
Err(Failure::NotDirectory),
)
}
fn rename_replaces<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let (from, to) = (d.at("a.txt"), d.at("b.txt"));
write_file(a, &from, b"A")?;
write_file(a, &to, b"B")?;
ok("rename over", a.rename(&from, &to))?;
expect("destination", a.read(&to), Ok(b"A".to_vec()))?;
expect("source", a.read(&from), Err(Failure::NotFound))?;
ok("mkdir", a.mkdir(&d.at("sub")))?;
ok("move", a.rename(&to, &d.at("sub/c.txt")))?;
expect("moved", a.read(&d.at("sub/c.txt")), Ok(b"A".to_vec()))?;
expect("listing", a.list(d.path()), Ok(vec!["sub".to_owned()]))
}
fn rename_refusals<A: Adapter>(a: &A, d: &Dir) -> Outcome {
ok("mkdir", a.mkdir(&d.at("dir")))?;
ok("mkdir inner", a.mkdir(&d.at("dir/inner")))?;
ok("mkdir full", a.mkdir(&d.at("full")))?;
write_file(a, &d.at("full/x"), b"x")?;
write_file(a, &d.at("f.txt"), b"f")?;
expect(
"folder into itself",
a.rename(&d.at("dir"), &d.at("dir/inner/dir")),
Err(Failure::InvalidArgument),
)?;
expect(
"file over folder",
a.rename(&d.at("f.txt"), &d.at("dir")),
Err(Failure::IsDirectory),
)?;
expect(
"folder over file",
a.rename(&d.at("dir"), &d.at("f.txt")),
Err(Failure::NotDirectory),
)?;
expect(
"folder over a full folder",
a.rename(&d.at("dir"), &d.at("full")),
Err(Failure::NotEmpty),
)?;
expect(
"missing source",
a.rename(&d.at("nothing"), &d.at("g.txt")),
Err(Failure::NotFound),
)?;
expect("file kept", a.read(&d.at("f.txt")), Ok(b"f".to_vec()))?;
expect("full kept", a.list(&d.at("full")), Ok(vec!["x".to_owned()]))
}
fn remove_rules<A: Adapter>(a: &A, d: &Dir) -> Outcome {
ok("mkdir", a.mkdir(&d.at("dir")))?;
write_file(a, &d.at("dir/f"), b"f")?;
expect(
"unlink a folder",
a.unlink(&d.at("dir")),
Err(Failure::IsDirectory),
)?;
expect(
"rmdir a file",
a.rmdir(&d.at("dir/f")),
Err(Failure::NotDirectory),
)?;
expect(
"rmdir a full folder",
a.rmdir(&d.at("dir")),
Err(Failure::NotEmpty),
)?;
expect(
"unlink nothing",
a.unlink(&d.at("nothing")),
Err(Failure::NotFound),
)?;
ok("unlink", a.unlink(&d.at("dir/f")))?;
ok("rmdir", a.rmdir(&d.at("dir")))?;
expect("listing", a.list(d.path()), Ok(Vec::new()))
}
fn unlinked_open<A: Adapter>(a: &A, d: &Dir) -> Outcome {
let f = d.at("f.txt");
let fd = ok("create", a.create(&f))?;
ok("write", a.write(&fd, 0, b"doomed"))?;
ok("unlink", a.unlink(&f))?;
ok("write after unlink", a.write(&fd, 6, b" still"))?;
ok("close", a.close(fd))?;
expect("read", a.read(&f), Err(Failure::NotFound))?;
expect("listing", a.list(d.path()), Ok(Vec::new()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_headless_adapter_passes_every_scenario() {
let dir = std::env::temp_dir().join(format!("pdfs-headless-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let headless = Headless::open(&dir).unwrap();
headless.mkdir("conformance").unwrap();
let failed = run(&headless, "conformance");
let _ = std::fs::remove_dir_all(&dir);
assert!(failed.is_empty(), "{failed:#?}");
}
}
File diff suppressed because it is too large. Load diff
+629
View File
@@ -0,0 +1,629 @@
//! A second adapter over the mounted-files service, with no kernel: files and
//! folders addressed by path, served by [`Files`] and [`Namespace`].
//!
//! It exists to show what the service needs from an adapter, and that nothing
//! of FUSE is left in it. The Linux FUSE adapter in `pdfs-fuse` answers the
//! kernel with what the services return; this one answers a caller with
//! [`Failure`]. The conformance scenarios (`conformance`, with the
//! `test-support` feature) run through both and expect the same outcomes.
//!
//! [`Headless`] has no Drive. Its host queues every create in the real store
//! as the daemon does offline, and nothing drains the queue. The bytes a
//! closed file committed are kept in memory, as the content of its next
//! revision would be.
//!
//! What the kernel does before it calls the FUSE adapter, this adapter does
//! itself: it resolves a path one name at a time, refuses to make a name that
//! is taken, and opens an existing file when asked to create it. The services
//! leave those checks to the adapter.
use std::collections::HashMap;
use std::fs::File;
use std::path::Path;
use std::sync::Arc;
use parking_lot::Mutex;
use pdfs_core::lockrank::{Rank, Ranked};
use pdfs_store::cache::ContentCache;
use pdfs_store::db::{Db, LOCAL_VOLUME, OP_CREATE, OP_MKDIR, PARK_UNTIL, PendingOp};
use proton_drive_rs::Node;
use proton_drive_rs::proton_sdk::ids::{LinkId, NodeUid, VolumeId};
use crate::files::{FileError, Files, FilesHost};
use crate::ids::is_local_uid;
use crate::namespace::{Namespace, NamespaceError, NamespaceHost, RenameFlags};
use crate::nodes::local_node;
use crate::open::{Intervals, ReadFailure, WriteHandle, assemble_open_read};
use crate::tree::{NodeError, State, StateGuard};
use crate::writes::WriteState;
/// Why the headless adapter refused or failed an operation. The FUSE adapter
/// answers each with the errno named here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Failure {
/// `ENOENT`: no such file or folder.
NotFound,
/// `EEXIST`: the name is taken.
Exists,
/// `EISDIR`: a folder where a file was needed.
IsDirectory,
/// `ENOTDIR`: a file where a folder was needed.
NotDirectory,
/// `ENOTEMPTY`: the folder has children.
NotEmpty,
/// `EINVAL`: an operation that cannot be done, such as moving a folder
/// into itself.
InvalidArgument,
/// `EACCES`: the node may not be changed.
Denied,
/// `EBUSY`: try again.
Busy,
/// `EBADF`: no file is open under this handle.
BadHandle,
/// `ENOSPC`: the local disk is full.
NoSpace,
/// `EOPNOTSUPP`: the operation is not supported.
Unsupported,
/// `EIO`: something failed underneath.
Io,
}
impl Failure {
/// The failure an OS error stands for, as the FUSE adapter answers it.
pub fn from_errno(errno: i32) -> Self {
match errno {
libc::ENOENT => Failure::NotFound,
libc::EEXIST => Failure::Exists,
libc::EISDIR => Failure::IsDirectory,
libc::ENOTDIR => Failure::NotDirectory,
libc::ENOTEMPTY => Failure::NotEmpty,
libc::EINVAL => Failure::InvalidArgument,
libc::EACCES | libc::EPERM => Failure::Denied,
libc::EBUSY => Failure::Busy,
libc::EBADF => Failure::BadHandle,
libc::ENOSPC | libc::EDQUOT => Failure::NoSpace,
libc::EOPNOTSUPP => Failure::Unsupported,
_ => Failure::Io,
}
}
}
/// What the headless host fails with.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostError {
NotFound,
Denied,
Io,
}
impl From<HostError> for Failure {
fn from(error: HostError) -> Self {
match error {
HostError::NotFound => Failure::NotFound,
HostError::Denied => Failure::Denied,
HostError::Io => Failure::Io,
}
}
}
impl From<FileError<HostError>> for Failure {
fn from(error: FileError<HostError>) -> Self {
match error {
FileError::NotFound => Failure::NotFound,
FileError::IsDirectory => Failure::IsDirectory,
FileError::Denied => Failure::Denied,
FileError::BadHandle => Failure::BadHandle,
FileError::NoSpace | FileError::QuotaExceeded => Failure::NoSpace,
FileError::Unsupported => Failure::Unsupported,
FileError::Io | FileError::Storage(_) => Failure::Io,
FileError::Host(error) => error.into(),
}
}
}
impl From<NamespaceError<HostError>> for Failure {
fn from(error: NamespaceError<HostError>) -> Self {
match error {
NamespaceError::NotFound => Failure::NotFound,
NamespaceError::IsDirectory => Failure::IsDirectory,
NamespaceError::NotDirectory => Failure::NotDirectory,
NamespaceError::NotEmpty => Failure::NotEmpty,
NamespaceError::InvalidArgument => Failure::InvalidArgument,
NamespaceError::Exists => Failure::Exists,
NamespaceError::Busy => Failure::Busy,
NamespaceError::Io => Failure::Io,
NamespaceError::Host(error) => error.into(),
}
}
}
fn node_failure(error: NodeError) -> HostError {
match error {
NodeError::NotFound => HostError::NotFound,
NodeError::NotWritable => HostError::Denied,
}
}
/// A file open for writing through the headless adapter.
#[derive(Debug)]
pub struct Fd {
ino: u64,
fh: u64,
}
struct Inner {
state: Arc<Ranked<State>>,
db: Arc<Db>,
cache: Arc<ContentCache>,
/// What each file's last close committed: the content its next revision
/// would upload.
content: Mutex<HashMap<NodeUid, Vec<u8>>>,
}
/// The host of the headless adapter: offline, with the real store.
#[derive(Clone)]
struct LocalHost(Arc<Inner>);
impl LocalHost {
fn state(&self) -> StateGuard<'_> {
StateGuard::new(self.0.state.lock(), &self.0.db)
}
fn base(&self, uid: &NodeUid) -> Vec<u8> {
self.0.content.lock().get(uid).cloned().unwrap_or_default()
}
fn drop_ops(&self, uid: &NodeUid) -> Result<(), HostError> {
self.0
.db
.delete_ops_for_uid(&uid.to_string())
.map(drop)
.map_err(|_| HostError::Io)
}
}
/// The bytes `[0, len)` of a file open for writing: what it wrote from
/// `file`, the rest from `base`.
fn assemble(file: &File, len: u64, written: &Intervals, base: &[u8]) -> Result<Vec<u8>, HostError> {
let base_len = base.len() as u64;
let read = assemble_open_read::<()>(file, len, base_len, written, 0, len, |offset, n| {
Ok(Some(base[offset as usize..(offset + n) as usize].to_vec()))
});
match read {
Ok(Some(bytes)) => Ok(bytes),
Ok(None) | Err(ReadFailure::Base(())) | Err(ReadFailure::Scratch(_)) => Err(HostError::Io),
}
}
impl FilesHost for LocalHost {
type Error = HostError;
fn settle_size(&self, _ino: u64, _uid: &NodeUid) -> Option<u64> {
None
}
fn fill_gaps(
&self,
uid: &NodeUid,
file: &File,
len: u64,
_base_mtime: i64,
_base_size: u64,
written: &Intervals,
) -> Result<(), HostError> {
use std::os::unix::fs::FileExt;
let base = self.base(uid);
file.set_len(len).map_err(|_| HostError::Io)?;
for (start, end, authored) in written.segments(0, len) {
let end = end.min(base.len() as u64);
if !authored && start < end {
file.write_all_at(&base[start as usize..end as usize], start)
.map_err(|_| HostError::Io)?;
}
}
Ok(())
}
fn landed(&self, _uid: &NodeUid) -> Option<Node> {
None
}
fn commit(&self, handle: &mut WriteHandle) -> Result<(), HostError> {
let committed = if handle.dirty {
let base = self.base(&handle.uid);
Some(assemble(&handle.file, handle.len, &handle.written, &base)?)
} else {
None
};
self.0.cache.clear_scratch_durable(&handle.path);
let _ = std::fs::remove_file(&handle.path);
if let Some(bytes) = committed {
self.0.content.lock().insert(handle.uid.clone(), bytes);
}
Ok(())
}
fn discard_unlinked(&self, uid: &NodeUid) {
self.0.content.lock().remove(uid);
let _ = self.drop_ops(uid);
}
}
impl NamespaceHost for LocalHost {
type Error = HostError;
fn require_writable(&self, ino: u64) -> Result<(), HostError> {
self.0
.state
.lock()
.require_writable(ino)
.map_err(node_failure)
}
fn require_uid_writable(&self, uid: &NodeUid) -> Result<(), HostError> {
let st = self.0.state.lock();
match st.by_uid.get(uid) {
Some(&ino) => st.require_writable(ino).map_err(node_failure),
None => Err(HostError::Denied),
}
}
fn ensure_children(&self, _ino: u64) -> Result<(), HostError> {
// Every folder is made here and listed from the start.
Ok(())
}
fn lookup_child(&self, parent: u64, name: &str) -> Result<Option<(u64, NodeUid)>, HostError> {
let st = self.0.state.lock();
Ok(st
.children
.get(&parent)
.into_iter()
.flatten()
.filter_map(|ino| st.entries.get(ino).map(|entry| (*ino, entry)))
.find(|(_, entry)| entry.node.name == name)
.map(|(ino, entry)| (ino, entry.uid.clone())))
}
fn sends_inline(&self) -> bool {
false
}
fn mint(
&self,
_parent: &NodeUid,
_name: &str,
_folder: bool,
) -> Result<Option<Node>, HostError> {
Ok(None)
}
fn queue_create(
&self,
parent_uid: &NodeUid,
name: &str,
folder: bool,
parked: bool,
) -> Result<Node, HostError> {
let now = now_secs();
let lid = self
.0
.db
.add_local_row(&parent_uid.to_string(), name, folder, now)
.map_err(|_| HostError::Io)?;
let uid = NodeUid::new(VolumeId::from(LOCAL_VOLUME), LinkId::from(lid.to_string()));
let op = PendingOp {
id: 0,
kind: if folder { OP_MKDIR } else { OP_CREATE }.to_string(),
uid: uid.to_string(),
parent_uid: Some(parent_uid.to_string()),
name: Some(name.to_owned()),
blob_path: None,
meta_json: None,
created_at: now * 1000,
attempts: 0,
last_error: None,
next_attempt_at: if parked { PARK_UNTIL } else { 0 },
};
self.0.db.enqueue_op(&op).map_err(|_| HostError::Io)?;
Ok(local_node(uid, parent_uid.clone(), name.to_owned(), folder))
}
fn access_changed(&self) {}
fn drop_queued(&self, uid: &NodeUid, _keep_staged: bool) -> Result<(), HostError> {
self.drop_ops(uid)
}
fn landed_uid(&self, _ino: u64) -> Option<NodeUid> {
None
}
fn has_pending_moves_out_of(&self, _uid: &NodeUid) -> Result<bool, HostError> {
Ok(false)
}
fn queue_trash(&self, uid: &NodeUid, _name: &str, open: bool) -> Result<(), HostError> {
// Only the root is not made here, and it cannot be removed.
self.state().forget_or_unlink(uid);
if !open {
self.0.content.lock().remove(uid);
}
Ok(())
}
fn trash_remote(&self, _uid: &NodeUid, _name: &str) -> Result<bool, HostError> {
Ok(false)
}
fn remove_replaced(&self, _ino: u64, uid: &NodeUid, _name: &str) -> Result<(), HostError> {
let open = {
let st = self.0.state.lock();
st.by_uid
.get(uid)
.and_then(|ino| st.entries.get(ino))
.is_some_and(|entry| entry.open_count > 0)
};
if is_local_uid(uid) {
self.drop_ops(uid)?;
}
self.state().forget_or_unlink(uid);
if !open {
self.0.content.lock().remove(uid);
}
Ok(())
}
fn restore_replaced(&self, _victim: Option<&(u64, NodeUid)>, _parent: &NodeUid, _name: &str) {}
fn queue_rename(
&self,
ino: u64,
_uid: &NodeUid,
_old_parent_uid: &NodeUid,
new_parent_ino: u64,
new_parent_uid: &NodeUid,
new_name: &str,
_authorized: bool,
) -> Result<(), HostError> {
self.state()
.rename_in_place(ino, new_parent_ino, new_parent_uid, new_name);
Ok(())
}
fn rename_remote(
&self,
_uid: &NodeUid,
_new_parent: Option<&NodeUid>,
_new_name: Option<&str>,
) -> Result<bool, HostError> {
Ok(false)
}
fn wake_drain(&self) {}
fn trashed(&self, _uid: &NodeUid, _name: &str, _open: bool) {}
}
fn now_secs() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs() as i64)
}
/// The mounted-files service of one root, served by path.
pub struct Headless {
host: LocalHost,
files: Files<LocalHost>,
namespace: Namespace<LocalHost>,
root: u64,
}
impl Headless {
/// A new, empty root, with its store and cache in `dir`.
pub fn open(dir: &Path) -> std::io::Result<Self> {
let other = |e: &dyn std::fmt::Display| std::io::Error::other(e.to_string());
std::fs::create_dir_all(dir)?;
let db = Arc::new(Db::open(&dir.join("cache.db")).map_err(|e| other(&e))?);
let cache = Arc::new(
ContentCache::open(dir.join("content"), dir.join("pins"), 0, db.clone())
.map_err(|e| other(&e))?,
);
let state = Arc::new(Ranked::new(
Rank::State,
State::new(db.clone(), HashMap::new()),
));
let root_uid = NodeUid::new(VolumeId::from("headless"), LinkId::from("root"));
let root = {
let mut st = StateGuard::new(state.lock(), &db);
let ino = st.install_root(local_node(root_uid.clone(), root_uid, String::new(), true));
st.children.insert(ino, Vec::new());
ino
};
let host = LocalHost(Arc::new(Inner {
state: state.clone(),
db: db.clone(),
cache: cache.clone(),
content: Mutex::default(),
}));
let writes = WriteState::default();
Ok(Headless {
files: Files::new(
state.clone(),
db.clone(),
cache.clone(),
writes.clone(),
host.clone(),
),
namespace: Namespace::new(state, db, cache, writes, host.clone()),
host,
root,
})
}
/// The inode at `path`, resolved one name at a time from the root.
fn resolve(&self, path: &str) -> Result<u64, Failure> {
let mut ino = self.root;
for name in components(path) {
if !self.is_folder(ino)? {
return Err(Failure::NotDirectory);
}
ino = self
.host
.lookup_child(ino, name)?
.ok_or(Failure::NotFound)?
.0;
}
Ok(ino)
}
/// The folder `path` names a child of, and the child's name.
fn split<'p>(&self, path: &'p str) -> Result<(u64, &'p str), Failure> {
let mut names: Vec<&str> = components(path).collect();
let name = names.pop().ok_or(Failure::InvalidArgument)?;
let parent = self.resolve(&names.join("/"))?;
if !self.is_folder(parent)? {
return Err(Failure::NotDirectory);
}
Ok((parent, name))
}
fn is_folder(&self, ino: u64) -> Result<bool, Failure> {
self.host
.0
.state
.lock()
.entries
.get(&ino)
.map(|entry| entry.node.is_folder())
.ok_or(Failure::NotFound)
}
fn child(&self, parent: u64, name: &str) -> Result<Option<u64>, Failure> {
Ok(self.host.lookup_child(parent, name)?.map(|(ino, _)| ino))
}
/// Create the file at `path`, or empty it when it exists, and open it for
/// writing, as `open(O_CREAT | O_TRUNC)` does.
pub fn create(&self, path: &str) -> Result<Fd, Failure> {
let (parent, name) = self.split(path)?;
if let Some(ino) = self.child(parent, name)? {
let fd = self.open_ino(ino)?;
self.set_len(&fd, 0)?;
return Ok(fd);
}
let made = self.namespace.create(parent, name)?;
Ok(Fd {
ino: made.ino,
fh: made.fh,
})
}
/// Open the file at `path` for writing.
pub fn open_write(&self, path: &str) -> Result<Fd, Failure> {
let ino = self.resolve(path)?;
self.open_ino(ino)
}
fn open_ino(&self, ino: u64) -> Result<Fd, Failure> {
let fh = self.files.open(ino, true)?;
Ok(Fd { ino, fh })
}
pub fn write(&self, fd: &Fd, offset: u64, data: &[u8]) -> Result<(), Failure> {
Ok(self.files.write(fd.ino, fd.fh, offset, data)?)
}
pub fn set_len(&self, fd: &Fd, size: u64) -> Result<(), Failure> {
match self.files.resize(fd.ino, size)? {
true => Ok(()),
false => Err(Failure::BadHandle),
}
}
pub fn fsync(&self, fd: &Fd) -> Result<(), Failure> {
Ok(self.files.fsync(fd.fh)?)
}
pub fn close(&self, fd: Fd) -> Result<(), Failure> {
Ok(self.files.release(fd.ino, fd.fh)?)
}
/// The whole content of the file at `path`: what a handle open on it
/// holds, or else what its last close committed.
pub fn read(&self, path: &str) -> Result<Vec<u8>, Failure> {
let ino = self.resolve(path)?;
let (uid, size, view) = {
let st = self.host.0.state.lock();
let entry = st.entries.get(&ino).ok_or(Failure::NotFound)?;
if entry.node.is_folder() {
return Err(Failure::IsDirectory);
}
(
entry.uid.clone(),
pdfs_drive::node_size(&entry.node),
st.open.writer(ino).map(WriteHandle::read_view),
)
};
let base = self.host.base(&uid);
match view {
Some(view) => Ok(assemble(&view.file, view.len, &view.written, &base)?),
None => {
let mut bytes = base;
bytes.resize(size as usize, 0);
Ok(bytes)
}
}
}
pub fn mkdir(&self, path: &str) -> Result<(), Failure> {
let (parent, name) = self.split(path)?;
if self.child(parent, name)?.is_some() {
return Err(Failure::Exists);
}
self.namespace.mkdir(parent, name)?;
Ok(())
}
pub fn unlink(&self, path: &str) -> Result<(), Failure> {
let (parent, name) = self.split(path)?;
Ok(self.namespace.unlink(parent, name)?)
}
pub fn rmdir(&self, path: &str) -> Result<(), Failure> {
let (parent, name) = self.split(path)?;
Ok(self.namespace.rmdir(parent, name)?)
}
pub fn rename(&self, from: &str, to: &str) -> Result<(), Failure> {
let (parent, name) = self.split(from)?;
let (new_parent, new_name) = self.split(to)?;
self.child(parent, name)?.ok_or(Failure::NotFound)?;
self.namespace
.rename(parent, name, new_parent, new_name, RenameFlags::default())?;
Ok(())
}
/// The names in the folder at `path`, sorted.
pub fn list(&self, path: &str) -> Result<Vec<String>, Failure> {
let ino = self.resolve(path)?;
if !self.is_folder(ino)? {
return Err(Failure::NotDirectory);
}
let st = self.host.0.state.lock();
let mut names: Vec<String> = st
.children
.get(&ino)
.into_iter()
.flatten()
.filter_map(|kid| st.entries.get(kid).map(|entry| entry.node.name.clone()))
.collect();
names.sort();
Ok(names)
}
}
fn components(path: &str) -> impl Iterator<Item = &str> {
path.split('/')
.filter(|name| !name.is_empty() && *name != ".")
}
+27
View File
@@ -0,0 +1,27 @@
//! Inode numbers the tree reserves, and the volume of nodes that only exist
//! here.
use proton_drive_rs::proton_sdk::ids::NodeUid;
/// The root inode of every session. Each session calls its own root 1.
pub const ROOT_INO: u64 = 1;
/// Parent inode for a persisted node whose parent row is missing from the
/// database. No folder carries this inode, so such a node is listed by nobody
/// and stays inert until a live enumeration re-parents it.
pub const ORPHAN_INO: u64 = 0;
/// The volume id of the folders this client makes up, such as "Shared with
/// me". No such volume exists on Drive.
pub const VIRTUAL_VOLUME: &str = "virtual";
/// Whether `uid` names a folder this client made up rather than a Drive node.
pub fn is_virtual_uid(uid: &NodeUid) -> bool {
uid.volume_id.as_str() == VIRTUAL_VOLUME
}
/// Whether this node exists only on this machine, so far. Such a uid is
/// meaningless to the API and must never be sent to it.
pub fn is_local_uid(uid: &NodeUid) -> bool {
uid.volume_id.as_str() == pdfs_store::db::LOCAL_VOLUME
}
+34
View File
@@ -0,0 +1,34 @@
//! The mounted-files service: what a file open through a mount is, and what
//! happens to its bytes between `open` and `close`.
//!
//! Step 5 of the 4.0 plan in `docs/ARCHITECTURE.md` moves the mount's
//! state here, slice by slice, so that it can be built and tested without a
//! kernel. Nothing in this crate knows about `fuser` or errno: the FUSE
//! adapter in `pdfs-fuse` maps the typed errors at the boundary.
//!
//! So far it holds the tree ([`tree`]): the nodes a mount shows, their
//! stable inode numbers, and the per-mount roots; and the open files
//! ([`open`]): the scratch file a handle writes into, which bytes of it are
//! authored, the released write that waits for its upload, and directory
//! handles; what the mount accepted but has not sent to Drive yet
//! ([`writes`]); the POSIX rules on names and on what a rename may replace
//! ([`names`]); which nodes a folder lists ([`nodes`]); and two services
//! behind host ports: the open files from open to close ([`files`]), and
//! create, mkdir, unlink, rmdir and rename ([`namespace`]).
//!
//! A second adapter, [`headless`], serves the same services by path with no
//! kernel and no Drive. The scenarios in `conformance` (with the
//! `test-support` feature) run through it here and through a FUSE mount in
//! `pdfs-fuse`, and both have to see the same outcomes.
#[cfg(any(test, feature = "test-support"))]
pub mod conformance;
pub mod files;
pub mod headless;
pub mod ids;
pub mod names;
pub mod namespace;
pub mod nodes;
pub mod open;
pub mod tree;
pub mod writes;
+110
View File
@@ -0,0 +1,110 @@
//! The POSIX rules on names and on what a rename may replace.
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
/// Why a pathname component cannot name a node.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NameError {
/// Longer than `NAME_MAX` (255 bytes).
TooLong,
/// Empty, `.` or `..`.
Reserved,
/// Not UTF-8, which Drive requires.
NotUtf8,
}
/// Why a rename may not replace its destination.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReplaceError {
/// A file would replace a directory.
IsDirectory,
/// A directory would replace a file.
NotDirectory,
/// The directory to replace is not empty.
NotEmpty,
}
/// Convert one kernel pathname component into the UTF-8 name accepted by Drive.
/// Linux filesystems conventionally cap a component at `NAME_MAX` (255 bytes),
/// but the FUSE kernel path can pass a longer component through to userspace.
pub fn component(name: &OsStr) -> Result<String, NameError> {
let bytes = name.as_bytes();
if bytes.len() > 255 {
return Err(NameError::TooLong);
}
if bytes.is_empty() || bytes == b"." || bytes == b".." {
return Err(NameError::Reserved);
}
name.to_str().map(str::to_owned).ok_or(NameError::NotUtf8)
}
/// Whether a `rename` may replace an existing destination, per POSIX.
///
/// Split out from the handler because it is the part that is pure and the part
/// that is dangerous: every `Err` here is a refusal that happens *before*
/// anything is trashed, and getting one wrong turns a refusal into the
/// destruction of the destination (`docs/BUGS.md` B13).
///
/// `dst_empty` is only meaningful when `dst_dir`; pass `true` otherwise.
pub fn check_replaceable(
src_dir: bool,
dst_dir: bool,
dst_empty: bool,
) -> Result<(), ReplaceError> {
match (src_dir, dst_dir) {
// A non-directory may not replace a directory, or vice versa.
(false, true) => Err(ReplaceError::IsDirectory),
(true, false) => Err(ReplaceError::NotDirectory),
// Proton trashes a folder with its whole subtree, so replacing a
// non-empty one would silently take its contents with it. POSIX says
// ENOTEMPTY, which is also the safe answer.
(true, true) if !dst_empty => Err(ReplaceError::NotEmpty),
_ => Ok(()),
}
}
#[cfg(test)]
mod replace_tests {
use super::{ReplaceError, check_replaceable};
/// The case that motivated all of this: rsync renaming its temp file over
/// the real one. Two plain files, and it has to be allowed — refusing is
/// what made every rsync transfer fail at the last step (`docs/BUGS.md` B13).
#[test]
fn a_file_may_replace_a_file() {
assert!(check_replaceable(false, false, true).is_ok());
}
#[test]
fn an_empty_directory_may_be_replaced_by_a_directory() {
assert!(check_replaceable(true, true, true).is_ok());
}
/// Proton trashes a folder with its whole subtree, so allowing this would
/// discard every file under the destination without ever naming them.
#[test]
fn a_non_empty_directory_is_never_replaced() {
let e = check_replaceable(true, true, false).expect_err("must refuse");
assert_eq!(e, ReplaceError::NotEmpty);
}
#[test]
fn the_two_ends_must_agree_on_being_a_directory() {
assert_eq!(
check_replaceable(false, true, true).expect_err("a file may not replace a directory"),
ReplaceError::IsDirectory
);
assert_eq!(
check_replaceable(true, false, true).expect_err("a directory may not replace a file"),
ReplaceError::NotDirectory
);
}
/// `dst_empty` describes a directory; it must not leak into the file case,
/// where callers pass `true` by convention.
#[test]
fn emptiness_is_ignored_when_the_destination_is_a_file() {
assert!(check_replaceable(false, false, false).is_ok());
}
}
File diff suppressed because it is too large. Load diff
+193
View File
@@ -0,0 +1,193 @@
//! Rules about the nodes a mount lists that need neither the kernel nor Drive:
//! which of them a folder shows, how queued changes lie over a listing, and
//! what a node made here looks like before Drive has seen it.
use std::collections::{HashMap, HashSet};
use pdfs_core::timestamp::now_secs;
use pdfs_drive::{media_type_for, remote_name_is_safe};
use proton_drive_rs::proton_sdk::ids::NodeUid;
use proton_drive_rs::{Node, NodeKind};
use tracing::warn;
/// Fabricate the node the server would have returned, for a `create`/`mkdir`
/// that could not reach it. Everything the kernel asks about a fresh node —
/// name, kind, size, times — is knowable locally; the uid is the only invention,
/// and the drain replaces it with the real one.
pub fn local_node(uid: NodeUid, parent_uid: NodeUid, name: String, is_dir: bool) -> Node {
let now = now_secs();
Node {
uid,
parent_uid: Some(parent_uid),
kind: if is_dir {
NodeKind::Folder
} else {
NodeKind::File {
media_type: media_type_for(&name).to_string(),
total_size_on_storage: 0,
// No revision has been sealed: nothing has been uploaded yet.
active_revision_state: None,
active_revision_id: None,
content_sha1: None,
claimed_size: Some(0),
claimed_modification_time: None,
}
},
name,
creation_time: now,
modification_time: now,
trashed: false,
is_shared: false,
is_shared_publicly: false,
signature_email: None,
membership: None,
// A locally fabricated node is on the main volume, never a photo/album.
photo: None,
album: None,
// Nothing signed it: it has never been near the crypto layer.
verification: Default::default(),
direct_role: None,
share_id: None,
}
}
/// Whether `node` is a file Drive lists without an active revision, as it does
/// one whose create has not been committed.
pub fn is_unrevised(node: &Node) -> bool {
matches!(
node.kind,
NodeKind::File {
active_revision_id: None,
..
}
)
}
/// The plaintext size, in bytes, that a node reports.
/// Overwrite each file node's `claimed_size` with the optimistic size of its
/// queued write, where it has one. Folders and nodes with nothing queued are
/// left alone. See [`Core::stamp_pending_sizes`] for why this exists.
pub fn apply_pending_sizes(nodes: &mut [Node], sizes: &HashMap<NodeUid, u64>) {
for node in nodes {
if let Some(&len) = sizes.get(&node.uid)
&& let NodeKind::File { claimed_size, .. } = &mut node.kind
{
*claimed_size = Some(len as i64);
}
}
}
pub fn node_visible(node: &Node, folder_uid: &NodeUid, hidden: &HashSet<NodeUid>) -> bool {
if !remote_name_is_safe(&node.name) {
warn!(uid = %node.uid, "a remote name cannot be a local file name; leaving it out");
return false;
}
!node.trashed && node.uid != *folder_uid && !hidden.contains(&node.uid)
}
/// Lay what is queued for a folder over Drive's listing of it, from
/// `Db::queued_children`: a node a queued rename moved away is dropped, and a
/// node a queued create, mkdir or rename put there is listed as the DB has it.
///
/// That node holds its name here: a create Drive already has but whose answer
/// is still on its way, or which the drain is still reading back, is listed by
/// Drive under its new uid and by the queue under its stand-in. Both were
/// listed, and a 128-file folder listed 129 (`docs/BUGS.md` B164).
pub fn overlay_queued(nodes: &mut Vec<Node>, queued: Vec<Node>, gone: &HashSet<String>) {
let here: HashSet<String> = queued.iter().map(|node| node.uid.to_string()).collect();
let names: HashSet<&str> = queued.iter().map(|node| node.name.as_str()).collect();
nodes.retain(|node| {
let uid = node.uid.to_string();
!gone.contains(&uid) && !here.contains(&uid) && !names.contains(node.name.as_str())
});
nodes.extend(queued);
}
#[cfg(test)]
mod pending_size_tests {
use super::{Node, NodeKind, NodeUid, apply_pending_sizes};
use pdfs_drive::node_size;
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
use std::collections::HashMap;
fn uid(link: &str) -> NodeUid {
NodeUid::new(VolumeId::from("vol"), LinkId::from(link))
}
fn file(link: &str, claimed: i64) -> Node {
Node {
uid: uid(link),
parent_uid: Some(uid("parent")),
kind: NodeKind::File {
media_type: "text/plain".into(),
total_size_on_storage: 0,
active_revision_state: None,
active_revision_id: None,
content_sha1: None,
claimed_size: Some(claimed),
claimed_modification_time: None,
},
name: link.into(),
creation_time: 100,
modification_time: 100,
trashed: false,
is_shared: false,
is_shared_publicly: false,
signature_email: None,
membership: None,
photo: None,
album: None,
verification: Default::default(),
direct_role: None,
share_id: None,
}
}
fn folder(link: &str) -> Node {
Node {
kind: NodeKind::Folder,
..file(link, 0)
}
}
/// B11: a re-enumeration mid-write must not revert the size to the
/// server's. A file that stats as 0 gets no `read` from the kernel at all,
/// so the staged blob is never served and the file reads as empty.
#[test]
fn a_queued_write_keeps_its_optimistic_size_through_a_re_enumeration() {
let mut nodes = vec![file("queued", 0), file("settled", 4096)];
let sizes = HashMap::from([(uid("queued"), 3)]);
apply_pending_sizes(&mut nodes, &sizes);
assert_eq!(
node_size(&nodes[0]),
3,
"the remote's pre-write size must not win over the queued write's"
);
assert_eq!(
node_size(&nodes[1]),
4096,
"a file with nothing queued keeps the size the server reported"
);
}
/// The map is keyed by uid and says nothing about kind; a folder that
/// somehow collides must not grow a `claimed_size`.
#[test]
fn folders_are_left_alone() {
let mut nodes = vec![folder("dir")];
apply_pending_sizes(&mut nodes, &HashMap::from([(uid("dir"), 999)]));
assert!(matches!(nodes[0].kind, NodeKind::Folder));
assert_eq!(node_size(&nodes[0]), 0);
}
/// The common case: nothing queued, nothing touched.
#[test]
fn an_empty_pending_map_changes_nothing() {
let mut nodes = vec![file("a", 10), file("b", 20)];
apply_pending_sizes(&mut nodes, &HashMap::new());
assert_eq!(node_size(&nodes[0]), 10);
assert_eq!(node_size(&nodes[1]), 20);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+268
View File
@@ -0,0 +1,268 @@
//! What the mount accepted and has not yet sent to Drive (`WriteState`).
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use parking_lot::Mutex;
use proton_drive_rs::proton_sdk::ids::NodeUid;
use pdfs_store::cache::Baseline;
use crate::ids::is_local_uid;
use crate::open::PendingRevision;
/// The write-back's state: writes accepted from the kernel and not yet sent,
/// nodes removed here that a stale listing may still return, and the changes
/// this daemon made that Drive's event feed will echo back.
///
/// The drain, the queue and recovery own it. Everything else, the read path,
/// listings, the pin keeper and the event feed, asks through the methods
/// below instead of taking its locks.
#[derive(Clone, Default)]
pub struct WriteState {
/// Writes accepted from the kernel but not yet uploaded, keyed by node.
/// The in-memory face of the `pending_op` table, from
/// which it is rebuilt on mount.
///
/// Two things read it: [`Core::read_range`], because until the op drains the
/// staged blob *is* the file's content and the remote still holds the old
/// revision; and the drain worker, which performs the uploads.
pub pending: Arc<Mutex<HashMap<NodeUid, PendingRevision>>>,
/// Nodes removed through this daemon which a briefly stale remote listing
/// may still return. Uids are not reused; an explicit restore clears one.
hidden: Arc<Mutex<HashSet<NodeUid>>>,
/// Nodes this daemon changed on the remote itself, and how many echoes of
/// those changes the event feed still owes us.
///
/// The feed replays our own writes back at us seconds later, and a
/// `NodeUpdated` carries no revision id — nothing in it distinguishes "another
/// device changed this file" from "you changed this file". Treating the echo
/// as foreign is not free: it evicts the content blob we just uploaded, so the
/// next read re-downloads a revision the API may not be serving yet. That is
/// how a SQLite database written on the mount came back `malformed`, and how a
/// mount doing bulk uploads spent its time re-fetching its own bytes.
///
/// So the first event for a node we changed ourselves, within
/// [`SELF_CHANGE_TTL_MS`], is consumed rather than applied: the tree already
/// holds what that event describes, because [`Core::refresh_after_upload`] put
/// it there. Anything beyond that applies normally, which bounds the staleness
/// a genuine remote change can suffer to one event.
///
/// Shared across forks like `pending`: the drain that records the change and
/// the event task that consumes the echo are both per-daemon.
self_changes: Arc<Mutex<HashMap<NodeUid, SelfChange>>>,
}
impl WriteState {
pub fn new() -> Self {
Self {
pending: Arc::new(Mutex::new(HashMap::new())),
hidden: Arc::new(Mutex::new(HashSet::new())),
self_changes: Arc::new(Mutex::new(HashMap::new())),
}
}
/// The write queued for `uid`, if any: its staged blob is the file's
/// content until the drain sends it.
pub fn queued(&self, uid: &NodeUid) -> Option<PendingRevision> {
self.pending.lock().get(uid).cloned()
}
/// The remote revision a write to `uid` was made against, for the
/// conflict check: the queued write's own base while one is queued, and
/// otherwise the base the handle started from. `None` for a node that has
/// never existed remotely: there is no revision to conflict with until its
/// create drains.
pub fn 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,
}),
}
}
/// Whether a write for `uid` is queued and not yet sent. A remote change
/// to such a node is not applied over it.
pub fn is_queued(&self, uid: &NodeUid) -> bool {
self.pending.lock().contains_key(uid)
}
/// The size the queued write for `uid` gives the file, if one is queued.
pub fn queued_len(&self, uid: &NodeUid) -> Option<u64> {
self.pending.lock().get(uid).map(|queued| queued.meta.len)
}
/// The size each queued write gives its file. Empty when nothing is
/// queued.
pub fn queued_sizes(&self) -> HashMap<NodeUid, u64> {
self.pending
.lock()
.iter()
.map(|(uid, queued)| (uid.clone(), queued.meta.len))
.collect()
}
/// The nodes removed here that a listing must leave out, even if Drive
/// still returns them.
pub fn hidden(&self) -> HashSet<NodeUid> {
self.hidden.lock().clone()
}
/// Leave `uid` out of listings from now on: it was removed here.
pub fn hide(&self, uid: &NodeUid) {
self.hidden.lock().insert(uid.clone());
}
/// List `uid` again: it was restored or put back.
pub fn unhide(&self, uid: &NodeUid) {
self.hidden.lock().remove(uid);
}
/// Record that this daemon just changed `uid` on Drive, so the event
/// feed's echo of the change is recognised (see [`echoes`]).
pub fn note_echo(&self, uid: &NodeUid, now_ms: i64) {
note_self_change(&mut self.self_changes.lock(), uid, now_ms);
}
/// Claim one outstanding echo for `uid`: whether the event being applied
/// is one this daemon caused.
pub fn take_echo(&self, uid: &NodeUid, now_ms: i64) -> bool {
take_self_change(&mut self.self_changes.lock(), uid, now_ms)
}
}
/// 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 [`writes::WriteState`].
pub(crate) const SELF_CHANGE_TTL_MS: i64 = 120_000;
/// A remote change this daemon made, awaiting its echo from the event feed.
pub(crate) 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(crate) 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(crate) 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
}
#[cfg(test)]
mod tests {
use super::*;
use proton_drive_rs::proton_sdk::ids::{LinkId, VolumeId};
/// An event feed carries no revision id, so the only thing that tells a
/// remote change apart from the echo of one this daemon just made is this
/// bookkeeping. Getting it wrong is expensive in both directions: too eager
/// and we evict the bytes we uploaded and re-download them from an API that
/// may still be serving the previous revision (a SQLite file on the mount
/// read back `malformed`); too generous and a real change from another device
/// is ignored.
#[test]
fn a_self_change_is_claimed_once_and_expires() {
let mut changes = HashMap::new();
let uid = NodeUid::new(VolumeId::from("vol"), LinkId::from("link"));
let other = NodeUid::new(VolumeId::from("vol"), LinkId::from("other"));
let t0 = 1_000_000;
assert!(
!take_self_change(&mut changes, &uid, t0),
"a node we never touched is never ours"
);
note_self_change(&mut changes, &uid, t0);
assert!(
take_self_change(&mut changes, &uid, t0 + 5_000),
"the echo of our own change is claimed"
);
assert!(
!take_self_change(&mut changes, &uid, t0 + 6_000),
"and only once, so a later foreign change still applies"
);
// A create followed by a revision upload is two changes to one node, and
// the feed reports both.
note_self_change(&mut changes, &uid, t0);
note_self_change(&mut changes, &uid, t0);
assert!(take_self_change(&mut changes, &uid, t0 + 1));
assert!(take_self_change(&mut changes, &uid, t0 + 2));
assert!(!take_self_change(&mut changes, &uid, t0 + 3));
// Past the window the attribution is a guess, and a wrong guess leaves
// the user looking at a stale file.
note_self_change(&mut changes, &uid, t0);
assert!(!take_self_change(
&mut changes,
&uid,
t0 + SELF_CHANGE_TTL_MS
));
assert!(
!changes.contains_key(&uid),
"an expired change is dropped, not left to be re-tested"
);
// An echo that never arrives must not accumulate for the life of the
// daemon; the next recorded change prunes it.
note_self_change(&mut changes, &uid, t0);
note_self_change(&mut changes, &other, t0 + SELF_CHANGE_TTL_MS);
assert_eq!(
changes.len(),
1,
"recording a change prunes the ones whose echo never came"
);
}
}
+150 -13
View File
@@ -50,8 +50,9 @@ graph TD
| [`pdfs-core`](../crates/pdfs-core) | Authentication and keyring (`auth`), configuration and directories (`config`), the control protocol (`control`), search scoring, ignore rules, Google Takeout parsing, the machine profile, the transfer registry (`transfers`) and the shutdown signal (`shutdown`) |
| [`pdfs-store`](../crates/pdfs-store) | The SQLite schema and queries (`db/`), the content cache (`cache`) |
| [`pdfs-drive`](../crates/pdfs-drive) | The `DriveApi` seam over the SDK, the call counter (`counted`), and `FakeDrive` for the simulations |
| [`pdfs-sync`](../crates/pdfs-sync) | The mirror engine: its passes and engine thread (`mirror`), with its reads and writes of the local disk in one module (`mirror::local`), and the parts with no I/O: planner, pass model and pass trace. It owns its state (`SyncParts`), reads and writes its tables only through `SyncStore`, and reaches the daemon only through `SyncHost` |
| [`pdfs-fuse`](../crates/pdfs-fuse) | The daemon: FUSE handlers (`filesystem`), the tree (`state`), finding nodes (`resolve`), folder listings and file sizes (`listing`, `sizes`), reads (`reads`), queueing and the drain (`enqueue`, `queue`, `drain`, `upload`), calls sent straight to Drive (`remote`), requests by path (`requests`), startup recovery (`recovery`), pins, search, trash, the shared tree (`shared`), the link state (`link`), remote events (`background`), the daemon's side of the sync engine (`sync`, which implements `SyncHost`), moves between locations (`relocate`), control handlers (`control`), push events (`events`), photos, sharing, devices, the supervisor, and the simulation tests (`sim/`) |
| [`pdfs-sync`](../crates/pdfs-sync) | The mirror engine: its passes (`mirror`), split into the walks (`mirror::walk`), applying a plan (`mirror::apply`) and the push pass (`mirror::push`), its engine thread (`mirror::engine`), its reads and writes of the local disk in one module (`mirror::local`), and the parts with no I/O: planner, pass model and pass trace. It owns its state (`SyncParts`), reads and writes its tables only through `SyncStore`, and reaches the daemon only through `SyncHost` |
| [`pdfs-vfs`](../crates/pdfs-vfs) | The mounted-files service, with no kernel adapter: the tree (`tree`: nodes, stable inodes, per-mount roots), the reserved inodes (`ids`), the open files (`open`: write handles and their authored ranges, released writes waiting for upload, directory handles, `fallocate` rules), the open-file service (`files`: open, write, resize, fsync and close, behind the `FilesHost` port), the namespace service (`namespace`: create, mkdir, unlink, rmdir and rename behind the `NamespaceHost` port, and the settling of a cut-off replacing rename), a headless adapter that serves both by path (`headless`) and the scenarios every adapter has to pass (`conformance`), and what the mount accepted but has not sent yet (`writes`: queued revisions, nodes removed here, echoes of our own changes). Errors are typed; the FUSE adapter maps them to errno |
| [`pdfs-fuse`](../crates/pdfs-fuse) | The daemon: FUSE handlers (`filesystem`), finding nodes (`resolve`), folder listings and file sizes (`listing`, `sizes`), reads (`reads`), queueing and the drain (`enqueue`, `queue`, `drain`, `upload`), calls sent straight to Drive (`remote`), requests by path (`requests`), startup recovery (`recovery`), pins, search, trash, the shared tree (`shared`), the link state (`link`), remote events (`background`), the daemon's side of the sync engine (`sync`, which implements `SyncHost`), moves between locations (`relocate`), control handlers (`control`), push events (`events`), photos, sharing, devices, the supervisor, and the simulation tests (`sim/`) |
| [`pdfs-daemon`](../crates/pdfs-daemon) | The daemon's composition root: waits for a session, opens the database and the content cache, resumes the session and mounts, then remounts or retries with a backoff and records each failure |
| [`pdfs-cli`](../crates/pdfs-cli) | The `pdfs` binary. `pdfs daemon` runs `pdfs_daemon::run` in-process; every other command is a control-socket client |
| [`pdfs-gui`](../crates/pdfs-gui) | `pdfs-app`, `pdfs-tray` and `pdfs-prompt`. Pages in `src/app/pages/`, widgets in `src/app/widgets/`, CSS and icons in `resources/` |
@@ -469,7 +470,9 @@ both with `pdfs_core::search::relevance_score`, so the prompt can merge them int
| `pdfs-control` | Accepts control connections; at most 64 handlers |
| `pdfs-events` | Publishes status, transfer and topic changes to subscribers |
| `pdfs-sync`, `pdfs-sync-poll` | Mirror passes and the remote poll (§7) |
| Tokio runtime | Remote calls, and the Drive and photos event streams (§6) |
| `pdfs-event-sync`, `pdfs-photo-events` | Async tasks on the Tokio runtime that follow the Drive and photos event streams (§6) |
| `pdfs-gallery` | Async task. Refreshes the gallery's visibility every minute and on request |
| Tokio runtime | Remote calls |
| `pdfs-online-probe` | Probes Drive while offline |
| `pdfs-pin-keeper` | Checks pins once a second for work: every pin at startup, when the link returns and after the event feed loses continuity, and the pins a batch of remote events changed. Downloads files kept offline that are missing or stale; failures retry with a backoff of 30 s to 30 min (`docs/BUGS.md` B282) |
| `pdfs-supervisor` | Logs workers that hold one job for minutes, a queue that stops draining, and control requests that never return; samples memory; pings the systemd watchdog only after a round trip over the control socket succeeds (`WatchdogSec=120`) |
@@ -477,14 +480,32 @@ both with `pdfs_core::search::relevance_score`, so the prompt can merge them int
| Smaller helpers | `pdfs-localindex` (home index for search), `pdfs-pause` (ends a timed pause), `pdfs-similar` (similar photos, on request), `pdfs-diagnostics` |
Long-running loops wait on one shared `Shutdown` signal instead of sleeping, so a stop joins them
instead of leaving them behind (`docs/BUGS.md` B44). The mount starts its long-lived threads
through `pdfs_core::lifecycle::Services`. Each one is started with its name and, if it blocks where
the signal does not reach, the call that wakes it: the drain's condvar, the sync engine's `Stop`
message, a connection to the control socket. A stop signals, wakes and joins them in reverse start
order, up to one 10-second deadline, and names any that are still running at the end.
instead of leaving them behind (`docs/BUGS.md` B44). Each long-lived thread is a
`pdfs_core::lifecycle::Service`, defined in `pdfs-fuse/src/services.rs`. A service says what its
thread is called, whether the mount can run without it, and, if it blocks where the signal does
not reach, the call that wakes it: the drain's condvar, the sync engine's `Stop` message, a
connection to the control socket. The mount builds the list and starts it through
`Services::start`. A required service that cannot start fails the mount attempt, which is retried;
an optional one (the sync engine, the event sampler, the supervisor, the inhibitor) is logged and
skipped. A stop signals, wakes and joins them in reverse start
order, up to one 10-second deadline, and names any that are still running at the end. A
service can also be an async task on the runtime (`Services::spawn_task`): the event streams and
the gallery refresh. A stop aborts such a task at its next `.await` and waits for it to end. These
tasks used to run until the runtime went away, which on a stop is when the process exits.
The sims fail a run whose stops leave a service running.
`pdfs diagnostics` reports what each worker is doing and which services are still running. The
supervisor warns once about a service that ended while the mount runs.
Work a request starts and does not wait for (a cache check, `VACUUM`, an import, a folder pin, a
re-date, a profile backup, a size upgrade) runs as a one-shot job:
`ServiceBoard::spawn_job` starts it on a named thread and lists it until it ends. `pdfs
diagnostics` shows the jobs running and how long each has run. Async work of the same kind (the
trash, timeline and album refreshes a listing starts) goes through `ServiceBoard::spawn_task_job`
and is listed the same way. Each control connection is a job too. A stop closes the board to new
jobs, aborts the async ones and joins the thread jobs before the services, up to the same
deadline. A long job checks the `Shutdown` signal between steps. Jobs used to be left running, and
one still waiting on Drive when the runtime went away panicked on its next timer.
---
## 10. Threat model: what this client writes to disk in plaintext
@@ -733,14 +754,130 @@ The work goes in steps. Each ships the same behaviour with the simulation tests
| 5 | `pdfs-vfs`: open files, then directories and renames, behind the FUSE adapter |
| 6 | One admission policy for mirrors, reads and writeback |
Step 3 so far: the daemon's long-lived threads start and stop through one `Services` set (§9).
Step 3 so far: the daemon's long-lived threads and async loops start and stop through one
`Services` set (§9).
`Core`'s fields are grouped by owner, each group a struct in the module that owns it:
`photos::PhotoJobs`, `drain::DrainState`, `reads::ReadState`, `sizes::SizeState`,
`trash::TrashState`, `shared::SharedState`, `sharing::QuotaCache` and `sweep::SweepState`.
`trash::TrashState`, `shared::SharedState`, `quota::QuotaCache`, `pause::SyncPause` and
`sweep::SweepState`.
`Core`'s methods are split by area out of `lib.rs` into their own modules. The daemon's run loop
moved out of `pdfs-cli` into `pdfs-daemon`, which is where the services will be built. What is left in `Core`
is shared by several owners (the tree, the database, the queue's `pending` map) and needs ports
before it can move.
moved out of `pdfs-cli` into `pdfs-daemon`, which is where the services will be built.
State that several owners share sits behind a narrow interface of its own:
- `writes::WriteState` holds the write-back's queued writes, the nodes removed here and the echoes
the event feed owes. The queue, the drain and recovery own it. The read path, listings, the pin
keeper and the event feed ask it whether a node has a queued write, what size it gives the file,
and which nodes to leave out. They do not take its locks.
- `session::SessionCells` holds what belongs to one mount's FUSE session: whether it is the
primary mount, its root inode, its kernel channel and whether it is up. An on-demand fork gets
fresh cells from `SessionCells::fork`, and shares the rest of `Core`.
- `link::Link` holds whether Drive answers, next to when the link went down, and is the only
code that changes it: it flips the flag, logs the outage and wakes whoever waits. Code reads it
through `Core::is_online`.
Some areas are services of their own rather than methods on `Core`. `sharing::Sharing` holds
only the handles it calls (the client, Drive, the content cache, the transfer list and a read of
the tree), and every one of its methods takes a node already resolved to its uid. Like the sync
engine's `Syncer`, it can be built and tested without the rest of the daemon.
`photos::Photos` is the timeline, albums, thumbnails, the Google Photos import and the redate
job. It holds the handles it calls and the `PhotoJobs` state, and reaches the filesystem through a
`PhotosHost` port with three methods: list a folder, for the recursive thumbnail build; note a
change made here, so its echo in the event feed is not taken for a remote edit; and add an entry
to the activity log. `Core::photos` builds one on demand with the daemon as its
host, as `Core::syncer` does for the sync engine. Trashing photos stays on `Core`, because it
checks write authority against the tree and drops open readers.
`trash::Trash` lists the Drive trash, refreshes that listing, and restores or deletes from it. Its
`TrashHost` port has two methods, both of which reach every mount: re-enumerate the folders a
restored node comes back into, and forget nodes the server no longer has. `Core::trash` builds it
on demand.
`revisions::Revisions` lists, restores, deletes and saves a file's earlier revisions. Like
`Sharing`, it only takes a node already resolved to its uid. Its `RevisionsHost` port checks that
the node may be written, drops what describes the old content (cached blocks and open readers)
and fetches it again if it is kept offline, and adds an activity entry.
`devices::Devices` holds the account's devices on Drive: listing, renaming, deleting, adopting
and migrating them, and registering this computer. Its `DevicesHost` port moves a folder, runs a
sync pass and re-enumerates a folder, which is what migrating a device's folders needs. Synced
folders and on-demand mounts are still methods on `Core`.
`profile::ProfileBackup` writes this machine's profile to its device and reads the profiles other
machines wrote, to offer their folders for restore. It needs nothing from the filesystem, so it
has no host. Turning the offered folders into synced folders stays on `Core`.
`maintenance::Maintenance` runs `VACUUM` and the deep integrity check as jobs, one at a time, and
keeps the last check's findings.
`search::Search` answers searches over the node and home indexes. It holds the database, the
content cache, the on-demand mounts and the home indexer's busy flag.
`recovery::Recovery` rebuilds the queue after a restart: the pending map, the staging area and
writes fsynced before the stop. Its `RecoveryHost` port queues a recovered write. Rebuilding the
tree stays on `Core`.
The mount's background loops are services of their own too, each started from the list in
`services.rs`:
- `link::OnlineProbe` probes the link back while it is down. Its `LinkHost` port stores the root
Drive answered with, lets what waited on the link go (relisting, retrying backed-off ops,
waking the drain, rechecking pins), reports a refused session and repairs the root's share id.
- `sweep::Sweeper` is the conflict sweep. Its `SweepHost` port asks whether a node is the
account's own, whether the mount is online, whether a node is busy in any mount and whether
the conflict listing can show a copy; it unhooks a trashed copy from every mount and adds
activity entries.
- `keeper::PinKeeper` keeps pinned files current. Its `KeeperHost` port finds a node in the tree,
lists kept folders, describes a file as a pin keeps it and downloads it.
- The inhibitor takes only the database and the stop signal.
The drain workers, the control listener, the event sampler and the supervisor still take a whole
`Core`. The drain is the write-back, which is part of the mounted-files service (step 5); the
other three answer front ends with reports drawn from every area.
The control socket answers each area's requests in a module of its own under `control/`:
sharing, Photos, synced folders and devices, revisions, and the trash and cache. Each module
exports a pattern macro naming its requests, and the main match hands them over in one arm, so
the compiler still checks that every request has an answer. A module turns a path or a uid into a
node once, then asks the service.
What is left in `Core` is the mounted-files side: the tree and its per-mount state, reads,
queued writes and the drain, listings and sizes, path requests, and the registry of on-demand
mounts. Step 5 turns that into the `pdfs-vfs` service. `Core` also implements the services'
host ports and builds each service on demand, which moves to `pdfs-daemon` once the services no
longer need the tree.
Step 5 has started. `pdfs-vfs` holds the tree (`tree::State`: every node a mount shows, its
stable inode, the roots of each session) and the open files (`open::OpenFiles`: write handles by
inode and by handle number, the inodes being released, and directory handles with their frozen
listings). A write goes through `stage_write`, which reports a full disk as a typed error; the
tree refuses a write to a read-only node with `NodeError`; the FUSE adapter maps both to errno.
The crate depends on no kernel or GUI crate; `cargo tree -p pdfs-vfs` shows neither.
The open-file service, `files::Files`, serves a file from open to close: the write open and its
base, writes, resizes and `fallocate`, flush, the fsync barrier and the release. Each write
handle counts its changes in a generation, and an fsync holds the handle's barrier from reading
it to writing its sidecar, so overlapping fsyncs record in order (B301). What the service needs
from Drive and the upload queue goes through `files::FilesHost`, which `Core` implements; the
FUSE callbacks keep the inode translation, the choice of thread and the reply.
The namespace service, `namespace::Namespace`, serves create, mkdir, unlink, rmdir and rename: whether a
new node is made on Drive at once or queued, the parked create of a transient name, the POSIX
checks on what `unlink`, `rmdir` and a replacing rename may remove, the order of a trash (Drive
first, then the tree), and the replace journal written before a rename removes its destination. Drive calls, the queue and the access rules go through `namespace::NamespaceHost`, which
`Core` implements. The module also holds the rules that settle a replacing rename a stop cut off
(B302). What still sits in `pdfs-fuse` around the tree is the code that fills it (listings,
sizes, the drain) and the read path.
A second adapter, `headless::Headless`, serves both services by path, with no kernel and no
Drive: its host queues every create in the store as the daemon does offline. It does itself what
the kernel does before it calls the FUSE adapter: it resolves a path one name at a time, refuses
a name that is taken, and opens a file it is asked to create when one exists. The scenarios in
`pdfs_vfs::conformance` (written, resized, synced, closed and reopened files; folders; renames
and removals with their POSIX refusals; an unlinked open file) run through it in `pdfs-vfs` and
through a FUSE mount, online and offline, in `pdfs-fuse`'s simulations, and both see the same
outcomes. `cargo tree -p pdfs-vfs` still shows no kernel or GUI crate.
Steps 0 to 3 are 4.0.0. Steps 4 to 6 follow in 4.x, one service at a time. Out of scope for
now: an encrypted local vault (full-disk encryption covers a copied disk today), Windows and
+108 -1
View File
@@ -108,6 +108,9 @@ a live account since.
| Entry | Title |
|---|---|
| [B302](#b302--a-stop-during-a-replacing-rename-leaves-the-replaced-file-in-the-trash) | A stop during a replacing rename leaves the replaced file in the trash |
| [B301](#b301--two-overlapping-fsyncs-can-leave-the-older-ones-record-on-disk) | Two overlapping fsyncs can leave the older one's record on disk |
| [B300](#b300--a-read-during-a-release-can-be-served-the-revision-the-write-replaced) | A read during a release can be served the revision the write replaced |
| [B299](#b299--a-synced-folder-in-the-trash-blocks-attaching-any-other-folder) | A synced folder in the trash blocks attaching any other folder |
| [B298](#b298--a-synced-folder-edit-whose-upload-lost-its-answer-is-kept-as-a-conflict-copy-of-itself) | A synced-folder edit whose upload lost its answer is kept as a conflict copy of itself |
| [B297](#b297--the-simulations-fail-and-hang-when-run-in-parallel-and-nothing-stops-that) | The simulations fail and hang when run in parallel, and nothing stops that |
@@ -402,6 +405,104 @@ a live account since.
Newest first.
### B302 — A stop during a replacing rename leaves the replaced file in the trash
**Status:** Fixed (unverified)
**Found:** 2026-11-27, from the review of the mounted filesystem in `FUSE.md`, while moving the
namespace operations toward `pdfs-vfs` (step 5 of `docs/ARCHITECTURE.md`). It was not seen in a
run.
**Where:** `serve_rename` and `ReplaceJournal` in `crates/pdfs-fuse/src/filesystem.rs`;
`Recovery::settle_replaces` in `crates/pdfs-fuse/src/recovery.rs`; `Db::begin_replace` in
`crates/pdfs-store/src/db/replace.rs`; the settle rules in `crates/pdfs-vfs/src/namespace.rs`
**Repro:** Save a file with an editor that writes a temporary file and renames it over the
original. Stop the daemon (a crash, a power loss or a `kill -9`) after the original has gone to the
trash and before the rename. Online, the original is in Drive's trash and the new content is under
the temporary name. With local-first or offline, the queue holds the original's trash and no rename,
so the next start sends the trash. Either way, the file is gone from its name.
**Cause.** Drive has no rename that replaces its destination, so `rename(2)` over an existing name
removes the destination first and renames the source second (B13). A failure between the two steps
puts the destination back (`restore_replaced`), but a stop between them left nothing to say that a
rename was half done.
**Fix.** A replacing rename writes a journal entry before it removes the destination, with a synced
commit, and removes the entry when it returns, whichever way it returns. The entry lives in
`sync_state`, so the schema does not change. On the next start, and on the drain's idle passes
while Drive could not be asked, each entry from an earlier run is settled:
- the source's rename, or the create it rewrote, is queued: the rename stands;
- the destination's trash is queued and the rename is not: the queued trash is dropped;
- otherwise Drive is asked. If the source has its new name, the rename stands. If the destination is
in the trash, it is restored. If the destination never got there, nothing is undone.
Entries are tagged with the opening of the database that wrote them, so a rename in progress is
never settled under it. A source created here whose create landed under the rename is known to Drive
by a uid the entry does not have; it is logged and left as it is.
**Verified:** `a_replace_cut_off_after_its_trash_brings_the_replaced_file_back` and
`a_replace_cut_off_after_queueing_its_trash_keeps_the_replaced_file` start a daemon on the state a
stop leaves, and fail without the settle. They write that state directly; no test stops a daemon in
the middle of a rename.
---
### B301 — Two overlapping fsyncs can leave the older one's record on disk
**Status:** Fixed (unverified)
**Found:** 2026-11-27, from the review of the mounted filesystem in `FUSE.md`, while moving the
fsync into `pdfs-vfs` (step 5 of `docs/ARCHITECTURE.md`). It was not seen in a run.
**Where:** `Files::fsync` in `crates/pdfs-vfs/src/files.rs`; `WriteHandle::generation` and
`WriteHandle::barrier` in `crates/pdfs-vfs/src/open.rs`
**Repro:** Write a file and call `fsync` from two threads on the same open file, with a write in
between. Each fsync runs on a worker. If the first one finishes after the second, its record of the
file goes to disk last. Kill the daemon before the file is closed. The restart recovers the file
as the first fsync saw it and loses the bytes the second one had made durable.
**Cause.** An fsync copied what the handle held (length, written ranges, base), synced the scratch
file and then wrote that copy as the sidecar a restart recovers from. Nothing ordered two of these
on the same file, so the copy that was written last was not always the newest.
**Fix.** Each write handle counts its changes in `generation` and carries a `barrier` lock. An
fsync takes the barrier before it reads the handle and holds it until the sidecar is written, so a
later fsync records at least what an earlier one did. The barrier also keeps the generation last
made durable, and an fsync with nothing new since then skips the sidecar.
**Verified:** `an_fsync_records_what_the_file_holds_when_its_turn_comes` holds the barrier, writes
while an fsync waits for it, and checks that a restart recovers the later bytes. No test drives
this through a mount.
---
### B300 — A read during a release can be served the revision the write replaced
**Status:** Fixed (unverified)
**Found:** 2026-11-27, by reading the code while moving the open files into `pdfs-vfs` (step 5 of
`docs/ARCHITECTURE.md`). It was not seen in a run.
**Where:** `OpenFiles::release` and `OpenFiles::reader` in `crates/pdfs-vfs/src/open.rs`;
`Core::read_local` in `crates/pdfs-fuse/src/reads.rs` and the `read` callback in
`crates/pdfs-fuse/src/filesystem.rs`
**Repro:** Keep one read-only handle open on a file, and read through it from a second thread.
Write the file through another handle and close it. A read that lands after the release took the
write state out of the open files, but before the release queued the new revision, finds neither
of them, and is answered with the revision on Drive from before the write.
**Cause.** The release removed the writer first and queued the revision second. Each read looks for
an open writer, then for a queued revision, then goes to the cache or Drive. The release runs on the
dispatch loop, so an `open` and `read` issued after `close(2)` are served after it. A read already
running on a worker, through a handle opened earlier, is not ordered that way.
**Fix.** A release now keeps a read view of the writer (its scratch file, length, base and written
ranges) until the revision is queued. `OpenFiles::reader` answers from the open writer, or from that
view, and both read paths ask it first. The view was already kept in one form, as the set of inodes
being released, which only the check for unsaved changes looked at.
**Verified:** `the_last_release_hands_back_the_write_and_marks_it_releasing` checks that a read finds
the write until `finish_release`. No test drives the race through a mount.
---
### B299 — A synced folder in the trash blocks attaching any other folder
**Status:** Fixed (unverified)
@@ -4801,6 +4902,12 @@ which survives the landing, and queues the write against the real uid when the n
**Test:** the unit tests `a_landed_placeholder_keeps_its_lid` and
`an_inode_gives_back_the_lid_it_was_made_from`. Seed 1 of three-clients passes.
**Seen again:** 2026-11-26, once in a full local sim run, in
`a_move_blocked_by_trash_can_be_retried_after_restore`. Its first write, of a new file in a new
folder, logged "access changed before the write could be queued" for `local~14`, and the file
read back empty. The next five runs of that test passed, and so did five on main. The race left
is somewhere other than the lookup by local id that the fix added.
---
### B138 — A file created where another is leaving lands as a conflict copy
@@ -5998,7 +6105,7 @@ since Sep 20, 13:13 · Resolved`. `find` showed all six copies still on disk, in
journal showed the daemon mounting at 17:29:33, and the entries were stamped 17:30. That is the
sweep's 30-second warmup.
**Where:** `crates/pdfs-fuse/src/sweep.rs` (`flag_conflict`, `sweep_conflicts_once`),
**Where:** `crates/pdfs-fuse/src/sweep.rs` (`flag_conflict`, `Sweeper::sweep_once`),
`crates/pdfs-fuse/src/conflicts.rs` (`list_conflicts`), `crates/pdfs-fuse/src/control.rs`
(`ResolveConflict`).
+7 -1
View File
@@ -17,7 +17,9 @@ kept, with a list of the folders that changed on Proton Drive since (49).
### Added
- **`pdfs diagnostics` says which of the daemon's background services are running.** If one
ends while the drive is mounted, for example the sync engine after a crash, the journal says
so once, by name, instead of saying nothing until a restart.
so once, by name, instead of saying nothing until a restart. It also lists the jobs running
in the background, such as a cache check, an import, a folder being pinned or a refresh of
the trash or the photo timeline, and how long each has run.
- **`PDFS_INSTANCE` runs a second client next to your own.** With a name set, the client keeps
its own directories, keyring entry, kernel keys and mountpoint, so a test account can run
alongside the account you use. `scripts/live-bench.py` uses it to time one edit, from the
@@ -57,6 +59,10 @@ kept, with a list of the folders that changed on Proton Drive since (49).
first pass, and whenever the change feed lost track (#53).
### Fixed
- **A stop ends the loops that follow Proton Drive's change feed before the daemon exits.**
The loops that read the Drive and photos event streams, and the gallery refresh, kept
running after every other service had stopped, and could still write to the database while
the process exited.
- **A synced folder whose folder on Drive is in the trash no longer blocks attaching another.**
Until it was removed, every `pdfs sync attach` failed with "remote sync folder is in the trash",
whatever folder it named (B299).