Compare commits

...
Author SHA1 Message Date
nvrl 153e8e9f13 Merge pull request #219 from narrrl/feat/tray-icons
feat(gui,packaging): the tray's own icons, drawn from the app's folder
2026-11-28 16:02:33 +01:00
nvrl 060219b008 Merge pull request #220 from narrrl/fix/create-landing-keeps-rename
fix(fuse): keep a rename made while a landed create is read back
2026-11-28 16:02:22 +01:00
nvrl 7956f5a23b docs(bugs): B310, the seed-5 conflict copy from CI on main 2026-11-28 15:58:36 +01:00
nvrl 18a59908ba fix(fuse): keep a rename made while a landed create is read back
Adoption keeps the tree's name while a rename is queued, and asks before
the read-back (B161) and under the tree lock (B152). A rename queued
after the first look and landed before the second left no op for
either, and the read-back still had the old name, so the tree took it
back. A later rename over the new name then had no victim to trash, and
waited on its own move away from that name until it ran out of tries.

Adoption now notes the node's placement before the read-back. Queueing
a rename moves the tree entry, so a placement that changed meanwhile
is kept like a queued rename.

B309.
2026-11-28 15:56:59 +01:00
nvrl c44e2694f2 feat(gui,packaging): the tray's own icons, drawn from the app's folder
The tray showed stock theme icons (folder-remote, view-refresh,
dialog-warning and so on), which looked like a prototype next to the
app icon. It now shows the app's folder as a one-colour symbolic
icon: solid when up to date, with a badge in a bite out of the corner
for syncing, paused, a failing change or an expired sign-in, and
hollow when offline or stopped.

Each icon is a single filled even-odd path, because several panels
recolour symbolic icons by forcing the fill of every shape.
scripts/render-tray-icons.py generates them.

The packages install them into hicolor/scalable/status. The tray also
writes them to its cache directory at start and sets that as the
item's IconThemePath, so a build from source finds them too.
2026-11-28 15:17:05 +01:00
nvrl d79c26f732 Merge pull request #218 from narrrl/fix/write-open-queued-length
fix(vfs,fuse): a write open over a queued edit starts at the edit's length
2026-11-28 15:06:14 +01:00
nvrl 2882f17ade docs(bugs): B308 likely explains the conflict copy in run 59 too 2026-11-28 14:33:52 +01:00
nvrl 1ab759ebcc fix(vfs,fuse): a write open over a queued edit starts at the edit's length
When an upload landed just as the next edit was queued, `place_landed`
put the landed node's size back over the size the edit had stamped. A
write opened next started at that older size, not the queued blob's.
A larger size left the gap past a later write unauthored, and the commit
filled it from the older revision. A smaller one cut the file.

The write handle now starts at the queued edit's length, because the
blob is the whole file. `place_landed` also applies queued sizes to the
node it read back before interning it, as listings do. That narrows the
stale-size window, but no site holds `pending` and `state` together, so
it can't close it.

B308.
2026-11-28 14:31:40 +01:00
nvrl 9667b7daca Merge pull request #217 from narrrl/fix/stale-pin-and-unbrowsed-share
fix(fuse,store): unpin a deleted file and manage shares of unloaded files
2026-11-28 14:06:01 +01:00
nvrl e2e8d3ad75 docs(changelog): list the pin and share fixes under 4.0.0 2026-11-28 14:05:28 +01:00
nvrl d5bcba5aa7 fix(fuse,store): unpin a deleted file and manage shares of unloaded files
A pin outlived its node: delete_node and complete_trash_op dropped the
node row but not the pin, and unpin resolves the pin's path first, so a
pin of a deleted file could never be removed. Both now delete the pin in
the same transaction, and Unpin falls back to dropping a pin by the path
it is recorded under when that path no longer resolves. The Storage page
also stops polling that file's thumbnail.

By-uid sharing requests proved ownership only through the live tree, the
mirror index or the Photos timeline, so a share of a file in a folder not
loaded this session could not be stopped from Shared by me. Drive's
shared-by-me list now counts as that proof when the others find nothing.
2026-11-28 14:04:51 +01:00
nvrl 4913178532 Merge pull request #216 from narrrl/feat/effect-intents-complete
Feat/effect intents complete
2026-11-28 13:09:48 +01:00
nvrl 1bd3d1577a Merge pull request #215 from narrrl/chore/release-4.0.0
chore(release): 4.0.0
2026-11-28 13:09:13 +01:00
nvrl cf09850c17 Merge pull request #214 from narrrl/feat/effect-intents-complete
feat(sync,cli): record deletions as effects and list unsettled effects in diagnostics
2026-11-28 13:09:00 +01:00
nvrl 8ee457cbcf docs(bugs): B307, a write in the echoes simulation waits out the interactive timeout 2026-11-28 13:08:40 +01:00
nvrl d03c96e0c8 chore(release): 4.0.0 2026-11-28 13:08:40 +01:00
nvrl a0c51d87fb feat(sync,cli): record deletions as effects and list unsettled effects in diagnostics
A mirror pass now writes an intent before it trashes a file or folder on
Drive (trash) or removes one from disk (delete-local), and settles it by
the result, as it already did for uploads, downloads and folders.

pdfs diagnostics lists the effects not settled yet, oldest first, at most
20 with the total count, read in the same bounded database probe as the
pending-op count. The JSON report has them as effects.
2026-11-28 13:04:36 +01:00
nvrl cf2632a1b5 Merge pull request #213 from narrrl/fix/sign-out-outcome
Fix/sign out outcome
2026-11-28 12:34:50 +01:00
nvrl af033f33a4 Merge pull request #211 from narrrl/fix/drop-preview
feat(gui): say what a drop onto a Files folder will do
2026-11-28 12:33:42 +01:00
nvrl 99f76ba95f feat(gui): say what a drop onto a Files folder will do
Rows dragged within the app move, and the same files dragged from a file
manager browsing the mount are copied, but the drop highlight looked the
same either way. The drop targets now preload the dragged file list and
show a hint over the view built from the same plan the drop runs: Move,
Copy or Upload n items to the folder, and how many are left out.
2026-11-28 12:33:16 +01:00
nvrl bb13097604 fix(gui): show recent Drive files only to the account that opened them
The search window listed the last files opened from any account signed
in on this computer, before a single key was typed. Each Drive visit now
records its account, and only the signed-in account's visits are listed
or ranked. Visits from before accounts were recorded stay hidden.
Preferences > Apps adds Remember recent files (prompt.remember_recent)
and Clear recent files. The window reloads its history each time it
opens, so a clear made in the app takes effect at once.
2026-11-28 12:33:16 +01:00
nvrl 58bbac76aa fix(gui): count the files a photo cleanup moves to Trash
In Find Similar Photos, unticking a shot stored as RAW and JPEG moves
both files, but the footer counted photos only. The footer now names the
files when they differ ("Move 1 photo (2 files) to Trash"), a card shows
what its shot is stored as, each card says whether it stays or moves to
Trash, and each set's heading counts what stays, so a set wider than the
window still says what happens to it.
2026-11-28 12:33:15 +01:00
nvrl 1e041150f3 fix(gui): keep a public link's address hidden until asked for
The Share dialog titled an existing link's row with its full URL, so
anyone watching the screen could copy it, and an expired link still
offered Copy. The row is now titled by policy ("Public viewer link")
with how the link works below. A reveal button shows the address, and
every repaint hides it again. An expired link offers Edit Expiry, which
opens its settings, instead of Copy. Shared by me's menu leads with Edit
Link Expiry for an expired link.
2026-11-28 12:33:15 +01:00
nvrl 61dcdf3493 Merge pull request #207 from narrrl/fix/link-settings-staged
fix(gui): save a public link's settings together
2026-11-28 12:33:12 +01:00
nvrl e3f371eb5d Merge pull request #206 from narrrl/fix/sign-out-outcome
Land #203 and #204 on main
2026-11-28 12:32:52 +01:00
nvrl bbd4784ccf fix(gui): save a public link's settings together
Choosing Editor on an existing link updated it at once, so viewer-link
holders could edit before the password the owner was adding was set,
and removing the password also applied at once. The role, password and
expiry are now staged and sent in one update by Save Link Settings,
under a line that says how the link will work once saved. Closing the
dialog sends nothing. While creating a link, Enter in the password field
moves on to Expires instead of creating the link.
2026-11-28 12:04:31 +01:00
nvrl d025e53933 Merge pull request #205 from narrrl/fix/access-snapshot
fix(store): read a node's access from one snapshot
2026-11-28 10:51:54 +01:00
nvrl 65d17fd3a7 Merge pull request #202 from narrrl/fix/trash-targets
fix(gui): make Trash actions act on the selection, not a hidden parent
2026-11-28 10:50:45 +01:00
nvrl c747802240 fix(gui): say which part of a sign-out did not finish
Sign-out took a failed status request for an empty queue, so the
confirmation dropped its unsent-changes warning exactly when the
service could not say. It now says the count is unknown.

After confirmation, the app ignored what auth::logout reported: a
keyring that refused to delete the stored session was only logged, and
the sign-in page appeared while the next start would sign in again. That
case now stays on screen with Try Again. When Proton did not confirm the
end of the session, a toast says where in the account it can be ended.
2026-11-28 10:49:38 +01:00
nvrl d0efbcddeb fix(gui): report each item of a bulk stop-sharing or leave
run_requests sent the requests in turn and stopped at the first failure
with one generic toast. When the second of three items failed, the first
had already lost its links and invitations, the third was never tried,
and the owner had to work out which was which.

Each item is now tried even when an earlier one is refused, since the
items do not depend on each other. Once the service stops answering,
the rest are left unsent. When any item did not go through, the page is
reloaded so a lost reply shows its real state, and a dialog names each
such item as refused (with the reason), unanswered or not tried, with
Try Again for just those. A batch of one still reports with a toast.
2026-11-28 10:49:38 +01:00
nvrl e5f37d8359 fix(store): read a node's access from one snapshot
effective_node_access resolved a stand-in's row by local id, checked the
row existed, and walked its ancestors in three separate reads. A create
that landed between the first two left the stand-in with no row, so the
mount answered EACCES for a node both authorities call writable. Run the
statements in one read transaction (docs/BUGS.md B306).
2026-11-28 10:49:37 +01:00
nvrl 79d4013b8c fix(gui): make Trash actions act on the selection, not a hidden parent
Inside a trashed folder, the items went to the trash with it and are
not in the trash on their own. Restore on one of them restored the
folder, and Delete Permanently, from the bar or the Delete key,
resolved to the folder as well. Only the confirmation named the folder,
after the user had chosen the destructive action.

Restore keeps resolving to the folder, but the bar and the menu now
say "Restore Folder “name”", under "Deleted with its folder". Delete
Permanently acts only on items in the trash on their own: for items
inside a trashed folder the bar's button is off with an explanation,
and the Delete key explains that only the whole folder can be deleted,
from the top of the trash. Restore on a location row says how many
items it restores.

resolve_targets separates the two cases and has unit tests.
2026-11-28 10:49:37 +01:00
nvrl 3a02c56440 Merge pull request #201 from narrrl/fix/discard-scope
fix(gui,fuse): list every change a queue discard undoes
2026-11-28 10:45:25 +01:00
nvrl 40484bbbae test(fuse): match a discard's ops by node, not by the path a rename may not show yet 2026-11-28 10:34:04 +01:00
nvrl 6803571802 fix(gui,fuse): list every change a queue discard undoes
Discarding one queued change drops every change queued on the same
node: a file on Drive goes back to how Drive has it, and a node made
here is removed. The dialog was titled "Discard Change?" and named one
change, so discarding a failed rename could also undo a later edit.

The queue listing now carries each op's node and whether Drive ever had
it (PendingOpInfo::node, ::local_only, both serde-defaulted). The dialog
lists every change the discard drops, says which of the two outcomes
applies, counts them in the heading and the button, and offers "Export
My Version…" for the newest content among them.

The discard sim now also checks that an edit and a rename of one file
share a node, and that only a file made here is local_only.
2026-11-28 10:34:04 +01:00
nvrl 861af49d22 Merge pull request #200 from narrrl/fix/stop-sync-delete
fix(gui,fuse): name the deletion when stopping a sync deletes the Drive folder
2026-11-28 10:30:50 +01:00
nvrl c5f40f63b2 Merge pull request #199 from narrrl/feat/upload-paths
feat(diagnostics): count uploads by the path the SDK took
2026-11-28 10:30:12 +01:00
nvrl 7e12c747a0 fix(gui,fuse): name the deletion when stopping a sync deletes the Drive folder
With "Also delete from Proton Drive" on, the stop-sync dialog kept its
routine heading, button and toast, although the action also moves the
folder in Proton Drive to the trash, and for an online-only folder that
is the only copy. The heading and button now change with the switch, and
the toast names the deletion.

The daemon dropped the folder from the sync set first and then only
logged a failed trash, so a removal while offline answered "removed
synced folder" and the copy in Proton Drive stayed without a word. It
now answers with an error that says the folder stopped syncing but its
Drive folder was not moved to the trash.

New sim: stopping_sync_says_so_when_its_drive_folder_could_not_be_deleted.
The catalogs are regenerated with po/update.sh, which also marks one
string that main no longer uses as obsolete.
2026-11-28 03:25:59 +01:00
nvrl 8881c79f15 feat(diagnostics): count uploads by the path the SDK took
The SDK sends a small file in one request and any other in blocks, and
picks the path inside each upload call. It reports the choice only as the
backend attribute of its upload timers. pdfs-core now wraps the tracing
telemetry sink with one that counts those events, and pdfs diagnostics
shows the counts, failures and times for small and block uploads since
start (upload_paths in the JSON report).

If small files stop taking the one-request path, because small_uploads is
off or Proton Drive refuses it, this is where it shows.

The live bench records the split per phase.
2026-11-28 03:03:28 +01:00
nvrl f975d9cf17 Merge pull request #198 from narrrl/perf/revision-over
perf(sync): check an edit's base revision through the upload's own read
2026-11-28 02:11:30 +01:00
nvrl deb15a3327 Merge pull request #197 from narrrl/feat/sdk-0.12.7
build(deps): proton-sdk and proton-drive-rs 0.12.7
2026-11-28 01:23:57 +01:00
nvrl 8c7a0a8a17 perf(sync): check an edit's base revision through the upload's own read
A mirror edit read the file's node before each upload to make sure no
other client had committed a revision since the pass looked (B249). The
SDK then read the same link again for the content key and the revision
id. proton-drive-rs 0.12.8 adds upload_new_revision_over, which makes
that check with its own read and creates the revision over the expected
one. The mirror now uses it whenever it knows the revision it saw, and
keeps the separate read only for rows without one.

0.12.8 also caches a folder's hash key, so a second upload into the same
folder reads none of its keys again.

The fake drive answers upload_new_revision_over with Moved, Trashed or
Sealed, and honors hold_next_read, so the B249 sim still covers the race.
2026-11-28 01:21:56 +01:00
nvrl 9533ebcdfc build(deps): proton-sdk and proton-drive-rs 0.12.7
The new SDK sends a file whose encrypted size is under 128 KiB, and a new
revision of one, in a single request instead of a draft, its block and a
commit. Synced folders and the drive mount both stream their uploads, so both
take the one-request path. The small_uploads switch turns it off.
2026-11-28 00:33:48 +01:00
nvrl ccc679eef5 Merge pull request #196 from narrrl/feat/small-uploads
fix(sync): take an unanswered upload's file on Drive as our own, not a conflict
2026-11-28 00:30:10 +01:00
nvrl 20603205d9 fix(sync): take an unanswered upload's file on Drive as our own, not a conflict
When a mirror upload's answer was lost and the file was edited again before
the next pass, the plan saw a path new on both sides with different bytes and
kept the newer local edit as a sync-conflict copy of this computer's own
upload (B305).

An upload or new revision that hears no success back now notes the SHA-1 of
the bytes it sent in its effect intent (schema 52, sync_intent.sent_sha1s).
Before keeping a conflict copy, the plan checks whether Drive's file holds
exactly bytes an unsettled upload of that path sent. If so, the local bytes go
up as a revision of it. A first-sync adopt of a same-size file with other
bytes does the same. Every other case is unchanged.
2026-11-28 00:21:47 +01:00
nvrl d1421a84b1 Merge pull request #195 from narrrl/feat/small-upload-switch
feat(config): switch for the one-request small upload
2026-11-28 00:16:50 +01:00
nvrl 670ec7db31 Merge pull request #194 from narrrl/fix/ci-apt-microsoft
ci: drop the runner's Microsoft apt source before the update
2026-11-28 00:16:36 +01:00
nvrl 30b20fc444 Merge pull request #193 from narrrl/feat/bench-small-files
test(bench): time many small files and count the requests they take
2026-11-28 00:16:23 +01:00
nvrl 5c6360e6e7 feat(config): switch for the one-request small upload
small_uploads in config.json, on when absent, decides whether the daemon's Drive client sends a small file in one request. It lets the path be turned off without a new build while it is new.
2026-11-28 00:09:40 +01:00
nvrl 42926b71a9 ci: drop the runner's Microsoft apt source before the update
packages.microsoft.com answered 403 on a main run, and apt-get update failed the release-cache job. Nothing here installs from it.
2026-11-27 23:32:42 +01:00
nvrl 21e7c03460 test(bench): time many small files and count the requests they take
live-bench.py gets a small scenario: a tree of small random files and a few images with thumbnails, a first sync, then a batch of edits. Each phase reports wall time, files per second, the daemon's CPU time and the requests it sent, counted from the SDK's telemetry. This is the baseline for the one-request small upload.
2026-11-27 23:26:07 +01:00
nvrl 9b541899ef Merge pull request #192 from narrrl/feat/sync-effect-intents
feat(sync): record an intent for each effect a mirror pass sends
2026-11-27 22:57:29 +01:00
nvrl 8a5f3f9ae0 Merge pull request #191 from narrrl/fix/rewatch-pass
fix(sync): watch a sync root again when it is replaced
2026-11-27 22:57:13 +01:00
nvrl d0697b7fcc feat(sync): record an intent for each effect a mirror pass sends
Each effect is written to sync_intent (schema 51) before it is sent and settled once its result is in. At a start, intents still issued become unsure; a pass that looked at every path settles older ones it did not send again. Shadow mode: nothing reads the intents to decide what to send.
2026-11-27 22:52:46 +01:00
nvrl f32e1b2765 fix(sync): watch a sync root again when it is replaced
A watch follows the folder it was set on. When a root was moved away and
made again before the engine dropped the old watch, or between two
passes, the path still existed, so the old watch on the moved folder
stayed and the new root was never watched. Files written in it waited
for the two-minute poll, which made a_root_made_again_is_watched_again
fail on main.

Each watch now keeps the root's device and inode. A pass that finds the
root replaced stops trusting the folder's claims and asks for the
watches again, and setting them up replaces any watch whose root is gone
or another folder. Each folder watched anew then gets a pass, since a
file written before its watch was in place has no event.
2026-11-27 22:34:06 +01:00
nvrl b43f46e582 Merge pull request #189 from narrrl/feat/sync-act-on-root-state
feat(sync): walk in full only the side the root state owes
2026-11-27 21:21:39 +01:00
nvrl d3b70f1ee6 Merge pull request #186 from narrrl/docs/where-4.0-stands
docs: record where the 4.0 steps stand
2026-11-27 21:21:11 +01:00
nvrl 30b6d27c74 feat(sync): walk in full only the side the root state owes
The root reducer now keeps the first unanswered doubt for the disk and
for Drive apart. A restart, a watcher error or an overflow owes the
disk; a gap in the event stream or a switch to on-demand called off
owes Drive. A pass asks what is owed before it walks, walks that side
in full, and reports which sides it walked in full, and only those
answer a doubt. The older checks still apply on top, so a pass never
walks less than before.

A sync root found missing loses its watch, and a folder made in its
place is not watched by it. The engine now drops the watch and stops
trusting the folder's claims when the root is missing, and sets the
watch up again once a pass finds the root back.
2026-11-27 21:11:06 +01:00
nvrl d10b28b14f feat(sync): skip the full local walk while the watcher is trusted
A mirror pass now claims the local dirty marks before it reads the disk.
When the claim is trusted, the ignore rules are unchanged and the last
full walk is under an hour old, the pass takes the walk it kept from the
pass before and reads again only the marked folders, the paths marked in
full and the files that were open for writing. A walk is kept only after
a pass that changed nothing on disk, failed nothing and could read every
path. A full walk still runs hourly and after anything that breaks trust,
and only full walks check the dirty set for misses.

The watcher now marks the folder holding a name that is not UTF-8 instead
of dropping the event. A new trace count, local reused, shows the paths a
pass took over from the kept walk.
2026-11-27 20:17:27 +01:00
nvrl c25e17fa9f test(fuse): drain the shared log before the local dirty set sim
The sim capture is one log for every test in the process. Lines that
earlier tests left in it reached the_local_dirty_set_covers_what_the_walk_finds,
whose check expects exactly one root state change, so it failed in the
full CI run while passing on its own.
2026-11-27 20:16:33 +01:00
nvrl 6c21a58acf docs: record where the 4.0 steps stand
Step 4 has five parts on main now (typed absence, the delete window,
enforced evidence, the local dirty set, the root reducer), and the
architecture document described none of them. Step 3 stops with Core
holding only the handles of the parts that own state; the document now
says so, and why the SDK's id and node types are still seen by the
inner crates.
2026-11-27 19:36:16 +01:00
nvrl ea29a260b0 Merge pull request #180 from narrrl/fix/echo-false-conflict
fix(fuse): read a write based on a landed create's placeholder as the create's revision
2026-11-27 19:31:10 +01:00
nvrl 8e9816919d Merge pull request #184 from narrrl/feat/sync-root-reducer
feat(sync): run a root reducer per mirror folder alongside the engine
2026-11-27 19:30:48 +01:00
nvrl 90e9c0de26 Merge branch 'feat/sync-local-dirty' into feat/sync-root-reducer
# Conflicts:
#	crates/pdfs-fuse/src/mount.rs
#	crates/pdfs-sync/src/mirror/host.rs
2026-11-27 19:27:09 +01:00
nvrl 61e0eefe3a Merge branch 'feat/sync-enforce-evidence' into feat/sync-local-dirty
# Conflicts:
#	crates/pdfs-fuse/src/mount.rs
#	crates/pdfs-sync/src/mirror/host.rs
2026-11-27 19:26:48 +01:00
nvrl 7862fc9195 Merge branch 'feat/sync-delete-window' into feat/sync-enforce-evidence 2026-11-27 19:26:18 +01:00
nvrl 413be9d961 feat(sync): run a root reducer per mirror folder alongside the engine
One pure state machine per mirror folder says how far the engine can
trust what it has seen: discovering, following, auditing after a doubt
(a watcher error, an overflowed queue, a gap in Drive's event stream, a
restart or a suspension), suspended, draining for on-demand, or handed
off. The passes, the watcher, the event stream and pause feed it inputs;
step() takes no time and does no I/O, so an input sequence replays
exactly.

Nothing acts on the state yet. The engine logs each transition as
'sync: root state', so it can be compared with what the engine did
before a pass relies on it.
2026-11-27 19:20:35 +01:00
nvrl 0fd8dda0d5 feat(sync): keep a local dirty set from the watcher, checked against the walk
The filesystem watcher now marks each path an event names, per mirror
folder (LocalDirty, in memory). A pass claims the marks before it plans
and retires them once it applied everything it found; marks made while
it ran stay for the next pass. A claim is trusted when the folder's
watch was live since the last pass claimed: a watcher error, an
overflowed queue or a restart breaks that.

For now the set is only checked. Each pass still walks the whole
folder, and counts in its trace the claimed marks, whether the claim
was trusted, and the changes it found on disk that a trusted claim did
not cover. Once that stays at zero, a trusted claim can stand in for
the local walk.
2026-11-27 19:14:35 +01:00
nvrl 4f542ae4d6 feat(sync): do not make a deletion the evidence does not back
The shadow check from the typed absence change counted deletions not
backed by proof of absence and acted on nothing. A deletion it flags is
now left out of the pass: it is logged, counted in the trace and failed
as a step, and the baseline row stays, so the next pass plans it again.
A regression in the filters then keeps a file on both sides instead of
deleting it, and a simulation that expects the deletion sees the file
still there.
2026-11-27 19:03:57 +01:00
nvrl ef5f832b0f fix(fuse): read a write based on a landed create's placeholder as the create's revision
A write released while its file's create landed could keep the
placeholder's base, a local mtime and no revision id: the release takes
its handle out of the tree before it queues, so neither the rebase of
open handles nor the rebase of queued writes reached it. The drain then
compared mtimes, Drive had stamped the create a second later, and the
write went up as a conflict copy of the file's own create (B304).

Landing a create now remembers the placeholder's stamp with the revision
the create sealed, and the drain reads a revision-less base with that
stamp as that revision.
2026-11-27 18:56:13 +01:00
109 changed files with 16937 additions and 7294 deletions

No files matched your search

+9
View File
@@ -17,6 +17,9 @@ jobs:
- name: Install native dependencies
run: |
# The runner image lists Microsoft's apt repository, which nothing here
# needs and which at times answers 403 and fails the update.
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
sudo apt-get update
sudo apt-get install -y \
pkg-config \
@@ -80,6 +83,9 @@ jobs:
- name: Install native dependencies
run: |
# The runner image lists Microsoft's apt repository, which nothing here
# needs and which at times answers 403 and fails the update.
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
sudo apt-get update
sudo apt-get install -y \
pkg-config \
@@ -129,6 +135,9 @@ jobs:
- name: Install native dependencies
run: |
# The runner image lists Microsoft's apt repository, which nothing here
# needs and which at times answers 403 and fails the update.
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
sudo apt-get update
sudo apt-get install -y \
pkg-config \
+7
View File
@@ -20,6 +20,9 @@ jobs:
- name: Install system dependencies
run: |
# The runner image lists Microsoft's apt repository, which nothing here
# needs and which at times answers 403 and fails the update.
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
sudo apt-get update
sudo apt-get install -y \
pkg-config \
@@ -75,6 +78,9 @@ jobs:
- name: Install system dependencies
run: |
# The runner image lists Microsoft's apt repository, which nothing here
# needs and which at times answers 403 and fails the update.
grep -rl packages.microsoft.com /etc/apt/sources.list.d/ | xargs -r sudo rm -f || true
sudo apt-get update
sudo apt-get install -y \
pkg-config \
@@ -156,6 +162,7 @@ jobs:
cp packaging/io.narl.proton-drive-linux.desktop deb/usr/share/applications/
cp packaging/io.narl.proton-drive-linux-tray.desktop deb/etc/xdg/autostart/
cp packaging/io.narl.proton-drive-linux.svg deb/usr/share/icons/hicolor/scalable/apps/
install -Dm644 -t deb/usr/share/icons/hicolor/scalable/status crates/pdfs-gui/resources/icons/tray/*.svg
install -Dm644 packaging/io.narl.proton-drive-linux.policy deb/usr/share/polkit-1/actions/io.narl.proton-drive-linux.policy
cp packaging/proton-drive.service deb/usr/lib/systemd/user/
cp LICENSE deb/usr/share/licenses/proton-drive-linux/
Generated
+14 -14
View File
@@ -3634,7 +3634,7 @@ checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
[[package]]
name = "pdfs-cli"
version = "3.10.0"
version = "4.0.0"
dependencies = [
"anyhow",
"clap",
@@ -3653,7 +3653,7 @@ dependencies = [
[[package]]
name = "pdfs-core"
version = "3.10.0"
version = "4.0.0"
dependencies = [
"async-trait",
"base64 0.23.1",
@@ -3683,7 +3683,7 @@ dependencies = [
[[package]]
name = "pdfs-daemon"
version = "3.10.0"
version = "4.0.0"
dependencies = [
"anyhow",
"pdfs-core",
@@ -3695,7 +3695,7 @@ dependencies = [
[[package]]
name = "pdfs-drive"
version = "3.10.0"
version = "4.0.0"
dependencies = [
"async-trait",
"futures",
@@ -3710,7 +3710,7 @@ dependencies = [
[[package]]
name = "pdfs-fuse"
version = "3.10.0"
version = "4.0.0"
dependencies = [
"async-trait",
"base64 0.23.1",
@@ -3748,7 +3748,7 @@ dependencies = [
[[package]]
name = "pdfs-gui"
version = "3.10.0"
version = "4.0.0"
dependencies = [
"anyhow",
"async-channel",
@@ -3773,7 +3773,7 @@ dependencies = [
[[package]]
name = "pdfs-sched"
version = "3.10.0"
version = "4.0.0"
dependencies = [
"parking_lot 0.13.0",
"tokio",
@@ -3781,7 +3781,7 @@ dependencies = [
[[package]]
name = "pdfs-store"
version = "3.10.0"
version = "4.0.0"
dependencies = [
"libc",
"parking_lot 0.13.0",
@@ -3797,7 +3797,7 @@ dependencies = [
[[package]]
name = "pdfs-sync"
version = "3.10.0"
version = "4.0.0"
dependencies = [
"notify",
"parking_lot 0.13.0",
@@ -3813,7 +3813,7 @@ dependencies = [
[[package]]
name = "pdfs-vfs"
version = "3.10.0"
version = "4.0.0"
dependencies = [
"libc",
"parking_lot 0.13.0",
@@ -4071,9 +4071,9 @@ dependencies = [
[[package]]
name = "proton-drive-rs"
version = "0.12.6"
version = "0.12.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b1a71d0e737a9bd6cff07105218e7bef3bddcfd9d6651646d7302cdbba71961"
checksum = "11c09c245784d7253072b751e43b1919140fdbc8641c5328a7e2801889c86041"
dependencies = [
"async-trait",
"base64 0.23.1",
@@ -4191,9 +4191,9 @@ dependencies = [
[[package]]
name = "proton-sdk"
version = "0.12.6"
version = "0.12.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81edef2b4b174e936a3537793ee901b92dd7c0484eb7fed09ad69432f407f86b"
checksum = "7a6ed261fbcabf35abe67ebf8c8aff85b01fc43aef5b298380a6e6f7d3dd31d3"
dependencies = [
"aes-gcm 0.11.1",
"async-trait",
+3 -3
View File
@@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/pdfs-core", "crates/pdfs-store", "crates/pdfs-drive", "crates/pdfs-sync", "crates/pdfs-sched", "crates/pdfs-vfs", "crates/pdfs-fuse", "crates/pdfs-daemon", "crates/pdfs-cli", "crates/pdfs-gui"]
[workspace.package]
version = "3.10.0"
version = "4.0.0"
edition = "2024"
license = "MIT"
authors = ["Nils Pukropp <contact@narl.io>"]
@@ -15,8 +15,8 @@ keywords = ["proton", "drive", "fuse", "sync", "linux"]
categories = ["filesystem", "command-line-utilities"]
[workspace.dependencies]
proton-sdk = { version = "0.12.6" }
proton-drive-rs = { version = "0.12.6" }
proton-sdk = { version = "0.12.8" }
proton-drive-rs = { version = "0.12.8" }
proton-gallery-app-rs = "0.1.0"
proton-gallery-rs = "0.1.5"
proton-map-rs = "0.1.0"
+74 -2
View File
@@ -289,6 +289,29 @@ pub(super) fn admission_line(load: &pdfs_core::control::AdmissionLoad) -> String
line
}
/// One mirror effect not settled yet in `pdfs diagnostics`:
/// `folder 3 upload docs/a.txt: retry, sent 2 times, 5m0s ago (timed out)`.
pub(super) fn effect_line(intent: &pdfs_core::control::EffectIntent) -> String {
let times = if intent.attempts == 1 {
"time"
} else {
"times"
};
let mut line = format!(
"folder {} {} {}: {}, sent {} {times}, {} ago",
intent.folder_id,
intent.kind,
intent.rel_path,
intent.state,
intent.attempts,
human_secs(intent.age_secs),
);
if let Some(error) = &intent.last_error {
line.push_str(&format!(" ({error})"));
}
line
}
/// A wait, in ms below a second, where most admission waits fall.
fn wait_ms(ms: u64) -> String {
if ms < 1000 {
@@ -389,6 +412,28 @@ pub(super) fn cmd_diagnostics() -> Result<()> {
);
}
}
if d.upload_paths.iter().any(|stat| stat.count > 0) {
println!("uploads since start, by path:");
for stat in &d.upload_paths {
println!(
" {:<38} {:>7} files {:>5} failed {:>9} ms total {:>7} ms longest",
stat.path, stat.count, stat.errors, stat.total_ms, stat.longest_ms,
);
}
}
match &d.effects {
None => {}
Some(effects) if effects.count == 0 => println!("sync effects not settled: none"),
Some(effects) => {
println!("sync effects not settled: {} (oldest first)", effects.count);
for intent in &effects.oldest {
println!(" {}", effect_line(intent));
}
if effects.count > effects.oldest.len() {
println!(" and {} more", effects.count - effects.oldest.len());
}
}
}
if d.inflight.is_empty() {
println!("in-flight requests: none");
} else {
@@ -517,9 +562,36 @@ pub(super) fn cmd_cache_inspect(deep: bool) -> Result<()> {
#[cfg(test)]
mod tests {
use pdfs_core::control::AdmissionLoad;
use pdfs_core::control::{AdmissionLoad, EffectIntent};
use super::admission_line;
use super::{admission_line, effect_line};
#[test]
fn an_effect_line_says_what_waits_and_why() {
let intent = EffectIntent {
folder_id: 3,
rel_path: "docs/a.txt".into(),
kind: "upload".into(),
state: "retry".into(),
attempts: 2,
age_secs: 300,
last_error: Some("timed out".into()),
};
assert_eq!(
effect_line(&intent),
"folder 3 upload docs/a.txt: retry, sent 2 times, 5m0s ago (timed out)"
);
let sent = EffectIntent {
state: "issued".into(),
attempts: 1,
last_error: None,
..intent
};
assert_eq!(
effect_line(&sent),
"folder 3 upload docs/a.txt: issued, sent 1 time, 5m0s ago"
);
}
#[test]
fn an_admission_line_says_who_waits_and_for_how_long() {
+1 -2
View File
@@ -38,7 +38,6 @@ use proton_sdk::error::ProtonError;
use proton_sdk::http::Tokens;
use proton_sdk::login::{self, LoginError, Step};
use proton_sdk::session::{PasswordMode, ProtonApiSession, ResumeParameters};
use proton_sdk::telemetry::TracingTelemetry;
use serde::{Deserialize, Serialize};
use zeroize::Zeroizing;
@@ -771,7 +770,7 @@ async fn migrate_legacy(
/// default.
fn tune(client: ProtonDriveClient, passphrases: &KeyPassphrases) -> ProtonDriveClient {
let client = client
.with_telemetry(TracingTelemetry::shared())
.with_telemetry(crate::uploads::telemetry())
.with_small_file_upload(true);
match AppDirs::new().and_then(|dirs| crate::sdkcache::SdkCache::shared(&dirs)) {
Ok(cache) => {
+8
View File
@@ -278,6 +278,12 @@ pub struct AppConfig {
/// the field.
#[serde(default)]
pub local_first: Option<bool>,
/// Send a file small enough, with its thumbnails, to fit 128 KiB in one
/// request instead of three or more. `None` means on. `false` uploads
/// every file in blocks, the way all files went before. Defaulted for
/// configs predating the field.
#[serde(default)]
pub small_uploads: Option<bool>,
/// Ask GitHub once a day whether a newer release is out, and say so in the
/// desktop app. Off by default: GitHub then sees the address and version
/// asking. Never used where a package manager installs updates (see
@@ -1077,6 +1083,7 @@ mod tests {
language: Some("de".to_string()),
online_map: true,
local_first: Some(false),
small_uploads: Some(false),
update_check: true,
update_last_checked: Some(1_760_000_000),
update_latest: Some("3.6.0".to_string()),
@@ -1096,6 +1103,7 @@ mod tests {
assert_eq!(decoded.update_latest.as_deref(), Some("3.6.0"));
assert_eq!(decoded.language.as_deref(), Some("de"));
assert_eq!(decoded.upload_limit, Some(500_000));
assert_eq!(decoded.small_uploads, Some(false));
assert_eq!(decoded.download_limit, None);
assert_eq!(decoded.files_view, config.files_view);
assert_eq!(decoded.photos_view, config.photos_view);
+60
View File
@@ -1171,6 +1171,15 @@ pub struct PendingOpInfo {
/// Carries file content that [`Request::ExportPendingOp`] can save.
#[serde(default)]
pub exportable: bool,
/// The node the op changes. A discard drops every op queued on the same
/// node (see [`Request::DiscardPendingOp`]), so this tells which rows go
/// together. Empty from a daemon that predates the field.
#[serde(default)]
pub node: String,
/// The node was made on this computer and Drive has never had it. A
/// discard removes it here, rather than putting back what Drive has.
#[serde(default)]
pub local_only: bool,
}
/// Why Drive refused a queued change (in [`PendingOpInfo`]). The change stays
@@ -2374,6 +2383,11 @@ pub struct Diagnostics {
/// field.
#[serde(default)]
pub drive_calls: Vec<DriveCallStat>,
/// Uploads since start, by how the SDK sent their content: `small` in one
/// request, `blocks` as a draft, its blocks and a commit. Empty from a
/// daemon that predates the field.
#[serde(default)]
pub upload_paths: Vec<UploadPathStat>,
/// The daemon's long-lived threads, in start order, and whether each is
/// still running. Empty from a daemon that predates the field.
#[serde(default)]
@@ -2386,6 +2400,41 @@ pub struct Diagnostics {
/// Empty from a daemon that predates the field.
#[serde(default)]
pub admission: Vec<AdmissionLoad>,
/// The mirror effects not settled yet: sent and waiting for an answer,
/// left unsure by a stop, or failed. `None` when the database did not
/// answer in time, or from a daemon that predates the field.
#[serde(default)]
pub effects: Option<EffectReport>,
}
/// The mirror effects not settled yet, in [`Diagnostics::effects`].
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct EffectReport {
/// How many there are.
pub count: usize,
/// The oldest of them, at most [`EffectReport::SHOWN`].
pub oldest: Vec<EffectIntent>,
}
impl EffectReport {
/// How many effects a report lists.
pub const SHOWN: usize = 20;
}
/// One mirror effect not settled yet, in [`EffectReport::oldest`].
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct EffectIntent {
pub folder_id: i64,
pub rel_path: String,
/// What it does, such as `upload`, `download` or `trash`.
pub kind: String,
/// `issued`, `unsure`, `retry` or `blocked`.
pub state: String,
/// How many times it was sent.
pub attempts: u32,
/// How long ago it was last sent.
pub age_secs: u64,
pub last_error: Option<String>,
}
/// One class of background step in the daemon's admission, in
@@ -2433,6 +2482,17 @@ pub struct DriveCallStat {
pub longest_ms: u64,
}
/// Uploads that took one path, in [`Diagnostics::upload_paths`].
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct UploadPathStat {
/// `small` or `blocks`.
pub path: String,
pub count: u64,
pub errors: u64,
pub total_ms: u64,
pub longest_ms: u64,
}
/// What the folder-sync engine is doing, for [`Diagnostics`].
///
/// The engine is one thread that runs every synced folder's passes in turn.
+1
View File
@@ -30,6 +30,7 @@ pub mod timestamp;
pub mod transfers;
pub mod tray;
pub mod update;
pub mod uploads;
// Photo logic shared with Proton Gallery through the proton-rs crates.
pub use proton_gallery_rs::{exiftime, places, similar, takeout};
+14
View File
@@ -139,6 +139,11 @@ pub struct PromptConfig {
/// false for a launcher that advertises support but is themed without them.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub menu_icons: Option<bool>,
/// Remember what the search window opens, to list it before a search and
/// rank it higher in one. Defaults to true. Off, the history is cleared
/// the next time the window opens and nothing more is kept.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub remember_recent: Option<bool>,
}
/// Which front end the prompt presents.
@@ -158,6 +163,11 @@ pub enum PromptMode {
/// than the GTK prompt's cap because filtering happens launcher-side.
pub const DEFAULT_MENU_LIMIT: usize = 50;
/// The search window's history of what it opened, in the state directory.
/// The app deletes it to clear the list; the window reads it again each time
/// it opens.
pub const PROMPT_HISTORY_FILE: &str = "prompt-history.json";
impl PromptConfig {
pub fn resolved_mode(&self) -> PromptMode {
self.mode.unwrap_or_default()
@@ -170,6 +180,10 @@ impl PromptConfig {
pub fn resolved_menu_icons(&self) -> bool {
self.menu_icons.unwrap_or(true)
}
pub fn resolved_remember_recent(&self) -> bool {
self.remember_recent.unwrap_or(true)
}
}
/// One line offered to the launcher.
+41 -3
View File
@@ -363,6 +363,19 @@ pub enum Verdict {
/// Compiled ignore rules for one synced folder.
pub struct IgnoreRules {
matcher: Option<Gitignore>,
/// A hash of the patterns the rules were built from, so a caller can tell
/// whether they changed.
source: u64,
}
/// A hash of `globals` and the folder's ignore file, `file` (its name and
/// text), in the order [`IgnoreRules::load`] reads them.
fn rules_source(globals: &[String], file: Option<(&str, &[u8])>) -> u64 {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
globals.hash(&mut hasher);
file.hash(&mut hasher);
hasher.finish()
}
impl IgnoreRules {
@@ -382,6 +395,7 @@ impl IgnoreRules {
}
}
let mut file = None;
for name in IGNORE_FILE_NAMES {
let path = root.join(name);
if !path.is_file() {
@@ -390,15 +404,24 @@ impl IgnoreRules {
// `add` returns the first parse error but still takes the lines it
// could read, so a bad line costs that line and nothing more.
let _ = builder.add(&path);
file = Some((*name, std::fs::read(&path).unwrap_or_default()));
any = true;
break;
}
let source = rules_source(
globals,
file.as_ref().map(|(name, text)| (*name, text.as_slice())),
);
if !any {
return Self { matcher: None };
return Self {
matcher: None,
source,
};
}
Self {
matcher: builder.build().ok(),
source,
}
}
@@ -415,17 +438,32 @@ impl IgnoreRules {
for line in text.lines() {
any |= builder.add_line(Some(file.clone()), line).is_ok();
}
let source = rules_source(globals, Some((IGNORE_FILE_NAMES[0], text.as_bytes())));
if !any {
return Self { matcher: None };
return Self {
matcher: None,
source,
};
}
Self {
matcher: builder.build().ok(),
source,
}
}
/// Rules matching nothing, for callers with no folder context.
pub fn empty() -> Self {
Self { matcher: None }
Self {
matcher: None,
source: rules_source(&[], None),
}
}
/// Identifies the patterns these rules were built from: rules loaded
/// again from the same globals and the same ignore file give the same
/// value. Only for comparing within one run of the daemon.
pub fn source(&self) -> u64 {
self.source
}
/// Whether any rule is loaded. When false, [`is_ignored`](Self::is_ignored)
+191
View File
@@ -0,0 +1,191 @@
//! How the SDK sent each upload's content, counted from its telemetry.
//!
//! A file whose encrypted size is under 128 KiB goes up in one request
//! (`small`). Any other file goes up as a draft, its blocks and a commit
//! (`blocks`). The SDK picks the path inside each upload call and reports it
//! only as the `backend` attribute of the `upload_file` and
//! `upload_new_revision` timers, so this module counts those events. If the
//! share of small uploads drops to zero for small files, the one-request path
//! is off or the server refuses it, and `pdfs diagnostics` shows that.
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use proton_sdk::telemetry::{Outcome, Telemetry, TelemetryEvent, TracingTelemetry};
/// The counts of every upload of this process, by path.
pub static UPLOAD_PATHS: UploadPaths = UploadPaths::new();
/// Upload counts for each path.
#[derive(Debug)]
pub struct UploadPaths {
small: PathStat,
blocks: PathStat,
}
#[derive(Debug)]
struct PathStat {
count: AtomicU64,
errors: AtomicU64,
total_ms: AtomicU64,
longest_ms: AtomicU64,
}
/// One path's counts at one moment.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UploadPathStat {
/// `small` or `blocks`.
pub path: &'static str,
pub count: u64,
pub errors: u64,
pub total_ms: u64,
pub longest_ms: u64,
}
impl PathStat {
const fn new() -> Self {
Self {
count: AtomicU64::new(0),
errors: AtomicU64::new(0),
total_ms: AtomicU64::new(0),
longest_ms: AtomicU64::new(0),
}
}
fn add(&self, failed: bool, took: Duration) {
let ms = u64::try_from(took.as_millis()).unwrap_or(u64::MAX);
self.count.fetch_add(1, Ordering::Relaxed);
if failed {
self.errors.fetch_add(1, Ordering::Relaxed);
}
self.total_ms.fetch_add(ms, Ordering::Relaxed);
self.longest_ms.fetch_max(ms, Ordering::Relaxed);
}
fn snapshot(&self, path: &'static str) -> UploadPathStat {
UploadPathStat {
path,
count: self.count.load(Ordering::Relaxed),
errors: self.errors.load(Ordering::Relaxed),
total_ms: self.total_ms.load(Ordering::Relaxed),
longest_ms: self.longest_ms.load(Ordering::Relaxed),
}
}
}
impl Default for UploadPaths {
fn default() -> Self {
Self::new()
}
}
impl UploadPaths {
pub const fn new() -> Self {
Self {
small: PathStat::new(),
blocks: PathStat::new(),
}
}
/// Count `event` if it is the end of an upload.
pub fn record(&self, event: &TelemetryEvent) {
if !matches!(event.operation, "upload_file" | "upload_new_revision") {
return;
}
let backend = event
.attributes
.iter()
.find_map(|(key, value)| (*key == "backend").then_some(value.as_str()));
let stat = match backend {
Some("small") => &self.small,
Some("blocks") => &self.blocks,
_ => return,
};
stat.add(event.outcome == Outcome::Failure, event.duration);
}
/// The counts so far, small first.
pub fn snapshot(&self) -> [UploadPathStat; 2] {
[self.small.snapshot("small"), self.blocks.snapshot("blocks")]
}
}
/// The SDK's telemetry sink for this process: every event goes to `tracing`
/// as before, and uploads are also counted in [`UPLOAD_PATHS`].
pub fn telemetry() -> Arc<dyn Telemetry> {
Arc::new(Counting {
inner: TracingTelemetry::shared(),
})
}
struct Counting {
inner: Arc<dyn Telemetry>,
}
impl Telemetry for Counting {
fn record(&self, event: &TelemetryEvent) {
UPLOAD_PATHS.record(event);
self.inner.record(event);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn event(operation: &'static str, backend: &str, outcome: Outcome, ms: u64) -> TelemetryEvent {
TelemetryEvent {
operation,
outcome,
duration: Duration::from_millis(ms),
attributes: vec![
("backend", backend.to_owned()),
("aead", "false".to_owned()),
],
}
}
#[test]
fn uploads_are_counted_by_the_path_the_sdk_took() {
let paths = UploadPaths::new();
paths.record(&event("upload_file", "small", Outcome::Success, 300));
paths.record(&event(
"upload_new_revision",
"small",
Outcome::Failure,
500,
));
paths.record(&event("upload_file", "blocks", Outcome::Success, 2_000));
let [small, blocks] = paths.snapshot();
assert_eq!(
small,
UploadPathStat {
path: "small",
count: 2,
errors: 1,
total_ms: 800,
longest_ms: 500,
}
);
assert_eq!(
(blocks.count, blocks.errors, blocks.longest_ms),
(1, 0, 2_000)
);
}
#[test]
fn other_operations_and_events_without_a_backend_are_not_counted() {
let paths = UploadPaths::new();
paths.record(&event("http_request", "small", Outcome::Success, 10));
paths.record(&TelemetryEvent {
operation: "upload_file",
outcome: Outcome::Success,
duration: Duration::from_millis(10),
attributes: Vec::new(),
});
assert!(paths.snapshot().iter().all(|stat| stat.count == 0));
}
}
+7
View File
@@ -241,6 +241,13 @@ pub fn mount_once(mountpoint: Option<PathBuf>) -> Result<pdfs_fuse::MountOutcome
let (client, session) = rt
.block_on(auth::resume_client())
.context("resume session (run `pdfs login` first)")?;
// On unless the config turns it off: the one-request upload for small
// files is new, and this lets it be switched off without a new build.
let small_uploads = config.small_uploads.unwrap_or(true);
if !small_uploads {
tracing::info!("small files are uploaded in blocks: small_uploads is off in the config");
}
let client = client.with_small_file_upload(small_uploads);
// Token updates are persisted automatically in real-time. The SDK session has
// a token refresh callback registered during `resume_client` that writes updated
+25 -1
View File
@@ -23,7 +23,7 @@ use proton_drive_rs::{
Thumbnail, ThumbnailType, TrashedNode,
};
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead, RevisionUpload};
/// Every kind of call [`DriveApi`] makes, one per method.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -393,6 +393,30 @@ impl DriveApi for Counted {
.await
}
async fn upload_new_revision_over_dyn(
&self,
file_uid: &NodeUid,
expected: &str,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
) -> Result<RevisionUpload> {
// Counted with the other revision uploads: it is one, with its check.
self.timed(
DriveCall::UploadNewRevision,
self.inner.upload_new_revision_over_dyn(
file_uid,
expected,
reader,
intended_size,
thumbnails,
last_modification_time,
),
)
.await
}
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
self.timed(DriveCall::OpenRevision, self.inner.open_revision(uid))
.await
+55
View File
@@ -33,6 +33,8 @@ use proton_drive_rs::{
NodeMoveItem, ProtonDriveClient, RevisionReader, Thumbnail, ThumbnailType, TrashedNode,
};
pub use proton_drive_rs::{RevisionUpload, SealedUpload};
pub mod counted;
pub mod digest;
@@ -120,6 +122,18 @@ pub trait DriveApi: Send + Sync {
last_modification_time: Option<i64>,
) -> Result<()>;
/// A new revision of `file_uid`, only over the revision `expected`. See
/// [`ProtonDriveClient::upload_new_revision_over`].
async fn upload_new_revision_over_dyn(
&self,
file_uid: &NodeUid,
expected: &str,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
) -> Result<RevisionUpload>;
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>>;
/// The file's thumbnail of `thumbnail_type`, or `None` when its revision
@@ -287,6 +301,26 @@ impl dyn DriveApi {
.await
}
pub async fn upload_new_revision_over<R: Read + Send>(
&self,
file_uid: &NodeUid,
expected: &str,
mut reader: R,
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
) -> Result<RevisionUpload> {
self.upload_new_revision_over_dyn(
file_uid,
expected,
&mut reader,
intended_size,
thumbnails,
last_modification_time,
)
.await
}
pub async fn download_file_to<W: Write + Send>(
&self,
uid: &NodeUid,
@@ -468,6 +502,27 @@ impl DriveApi for ProtonDriveClient {
.await
}
async fn upload_new_revision_over_dyn(
&self,
file_uid: &NodeUid,
expected: &str,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
) -> Result<RevisionUpload> {
ProtonDriveClient::upload_new_revision_over(
self,
file_uid,
expected,
reader,
intended_size,
thumbnails,
last_modification_time.and_then(pdfs_core::timestamp::modification_time),
)
.await
}
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
let reader = ProtonDriveClient::open_revision(self, uid).await?;
Ok(Arc::new(reader))
+52 -1
View File
@@ -67,7 +67,7 @@ use proton_drive_rs::{
use sha1::{Digest as _, Sha1};
use super::rng::Rng;
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead};
use crate::{DriveApi, NodeOutcomes, OutcomeStream, RevisionRead, RevisionUpload, SealedUpload};
/// The volume every fake node lives on.
pub const VOLUME: &str = "simvol";
@@ -1531,6 +1531,57 @@ impl DriveApi for FakeClient {
Ok(())
}
async fn upload_new_revision_over_dyn(
&self,
file_uid: &NodeUid,
expected: &str,
reader: &mut (dyn Read + Send),
intended_size: i64,
thumbnails: Vec<Thumbnail>,
last_modification_time: Option<i64>,
) -> Result<RevisionUpload> {
// The SDK reads the file's link for its keys and checks the revision
// on that read, so it is held, lags and counts like any other read.
self.wait_if_held(&self.0.hold, std::slice::from_ref(file_uid))
.await;
let lag = self.lag();
let seen = self
.request(false, |server| {
Ok(server
.visible(file_uid, lag, Instant::now())
.map(|remote| (remote.trashed, remote.file.map(|file| file.revision))))
})
.await?;
match seen {
None => return Err(api(ResponseCode::DoesNotExist, "file not found")),
Some((true, _)) => return Ok(RevisionUpload::Trashed),
Some((false, revision)) if revision.as_deref() != Some(expected) => {
return Ok(RevisionUpload::Moved);
}
Some(_) => {}
}
self.upload_new_revision_from_dyn(
file_uid,
reader,
intended_size,
thumbnails,
last_modification_time,
)
.await?;
let revision_id = self
.0
.drive
.server
.lock()
.current(file_uid)
.and_then(|remote| remote.file.as_ref().map(|file| file.revision.clone()))
.unwrap_or_default();
Ok(RevisionUpload::Sealed(SealedUpload {
node_uid: file_uid.clone(),
revision_id,
}))
}
async fn open_revision(&self, uid: &NodeUid) -> Result<Arc<dyn RevisionRead>> {
let file = self
.request(false, |server| {
+7 -1
View File
@@ -3,6 +3,7 @@
use super::*;
use crate::shutdown::Shutdown;
use pdfs_core::error::session_revoked;
use pdfs_sync::root::{Doubt, RootInput};
/// Drop `uid` from one mount's tree and tell that mount's kernel session the
/// entry is gone. Shared by the trash and delete paths, which differ only in
@@ -148,7 +149,12 @@ fn apply_event(core: &Core, event: &DriveEvent, dirty: &mut DirtyParents) -> pdf
core.db.sync_remote_changed(&node_uid.to_string(), None)
}
// What changed went by unseen: every pass walks Drive whole again.
DriveEvent::ContinuityLost { .. } => core.db.sync_walks_clear_all().map(|()| Vec::new()),
DriveEvent::ContinuityLost { .. } => {
core.sync
.roots
.input_all(RootInput::Doubted(Doubt::EventGap));
core.db.sync_walks_clear_all().map(|()| Vec::new())
}
_ => Ok(Vec::new()),
};
match marked {
+20 -5
View File
@@ -16,6 +16,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use pdfs_core::config::AppDirs;
use pdfs_core::control::ErrorKind;
use pdfs_core::control::{
ActivityKind, Event, HEARTBEAT, PhotoMonth, RefreshScope, Request as CtlRequest,
Response as CtlResponse, Topic, TransferDirection, TrashFailure,
@@ -647,8 +648,23 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
},
Err(e) => CtlResponse::error(e),
},
Ok(CtlRequest::Unpin { path }) => match route_keep(core, mountpoint, &path) {
Ok((routed, rel)) => match routed.unpin(&rel) {
Ok(CtlRequest::Unpin { path }) => {
let unpinned = route_keep(core, mountpoint, &path)
.and_then(|(routed, rel)| routed.unpin(&rel))
.or_else(|e| match e.kind {
// The node is gone, and its pin with it unless the pin
// was left behind; drop that one by the path it is listed
// under.
ErrorKind::NotFound => match core.unpin_stale(&path) {
Ok(true) => Ok(Path::new(&path)
.file_name()
.map_or_else(|| path.clone(), |n| n.to_string_lossy().into_owned())),
Ok(false) => Err(e),
Err(stale) => Err(stale),
},
_ => Err(e),
});
match unpinned {
Ok(name) => {
core.profile().touch_profile();
CtlResponse::Ok {
@@ -656,9 +672,8 @@ fn handle_control_conn(core: &Core, username: &str, mountpoint: &Path, stream: U
}
}
Err(e) => CtlResponse::error(e),
},
Err(e) => CtlResponse::error(e),
},
}
}
Ok(CtlRequest::ListPins) => CtlResponse::Pins {
pins: core.list_pins(),
},
+17 -7
View File
@@ -9,12 +9,13 @@
use std::path::Path;
use pdfs_core::CoreResult;
use pdfs_core::control::ErrorKind;
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;
use crate::{Core, parse_uid};
/// 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
@@ -73,13 +74,22 @@ impl Target {
})
}
/// A node named by its uid, which one of this daemon's locations, or the
/// Photos timeline, must show to be this account's.
/// A node named by its uid, which one of this daemon's locations, the
/// Photos timeline, or Drive's list of what this account shared must show
/// to be this account's. The last covers a node shared from elsewhere and
/// never browsed to here: Shared by me lists it, and without it the share
/// could not be managed, nor stopped, from this computer.
fn uid(core: &Core, uid: String) -> Self {
Self {
node: core.resolve_shareable(&uid),
label: uid,
}
let node = core.resolve_shareable(&uid).or_else(|e| {
if e.kind != ErrorKind::NotFound {
return Err(e);
}
match parse_uid(&uid) {
Some(node) if core.sharing.shared_by_me(&node)? => Ok(node),
_ => Err(e),
}
});
Self { node, label: uid }
}
}
+16 -2
View File
@@ -130,12 +130,26 @@ pub(super) fn answer(ask: &Ask<'_>, request: CtlRequest) -> CtlResponse {
},
CtlRequest::RemoveSyncFolder { id, delete_remote } => {
match core.remove_sync_folder(id, delete_remote) {
Ok(()) => {
Ok(None) => {
core.profile().touch_profile();
CtlResponse::Ok {
message: "removed synced folder".to_string(),
message: if delete_remote {
"removed synced folder and moved its folder in Proton Drive to the trash"
} else {
"removed synced folder"
}
.to_string(),
}
}
// The folder no longer syncs, but its copy in Proton Drive is
// still there. That is not what was asked, so it is an error,
// and the message says which half happened.
Ok(Some(trash_error)) => {
core.profile().touch_profile();
CtlResponse::error(CoreError::remote(format!(
"stopped syncing the folder, but its folder in Proton Drive was not moved to the trash: {trash_error}"
)))
}
Err(e) => CtlResponse::error(e),
}
}
+28 -11
View File
@@ -765,9 +765,18 @@ impl Core {
jobs
}
/// Remove a synced folder from the sync set. `delete_remote` also deletes its
/// folder under the device root; otherwise the cloud copy is left in place.
pub(crate) fn remove_sync_folder(&self, id: i64, delete_remote: bool) -> CoreResult<()> {
/// Remove a synced folder from the sync set. `delete_remote` also moves its
/// folder under the device root to the trash; otherwise the cloud copy is
/// left in place.
///
/// The folder is out of the sync set before the trash is asked, so a trash
/// that fails does not fail the removal. It comes back as `Some(error)`,
/// for the caller to say that the cloud copy is still there.
pub(crate) fn remove_sync_folder(
&self,
id: i64,
delete_remote: bool,
) -> CoreResult<Option<String>> {
let lock = self.sync.lock(id);
// A pass holds the lock for as long as it runs, hours on a large
// folder. Ask it to stop at its next checkpoint rather than wait it
@@ -823,16 +832,24 @@ impl Core {
self.clear_sync_folder_paused(id);
// Stop watching the folder we just dropped.
let _ = self.sync.tx.send(sync::SyncMsg::Rewatch);
if delete_remote
&& let Some(uid) = parse_uid(&folder.remote_uid)
&& let Err(e) = self
.rt
.block_on(self.drive.trash_nodes(&[uid]))
.and_then(batch::into_unit)
if !delete_remote {
return Ok(None);
}
let Some(uid) = parse_uid(&folder.remote_uid) else {
warn!(id, remote = %folder.remote_uid, "delete remote device folder: bad uid");
return Ok(Some(format!("bad folder id {}", folder.remote_uid)));
};
match self
.rt
.block_on(self.drive.trash_nodes(&[uid]))
.and_then(batch::into_unit)
{
warn!(id, error = %e, "delete remote device folder failed");
Ok(()) => Ok(None),
Err(e) => {
warn!(id, error = %e, "delete remote device folder failed");
Ok(Some(e.to_string()))
}
}
Ok(())
}
/// Trigger a reconcile: one folder by id, or every folder when `id` is `None`.
+85 -8
View File
@@ -19,10 +19,13 @@ use std::time::{Duration, Instant};
use parking_lot::Mutex;
use pdfs_core::control::{
AdmissionLoad, Diagnostics, DriveCallStat, InflightRequest, ServiceState, WorkerState,
AdmissionLoad, Diagnostics, DriveCallStat, EffectIntent, EffectReport, InflightRequest,
ServiceState, UploadPathStat, WorkerState,
};
use pdfs_core::lifecycle::ServiceBoard;
use pdfs_core::timestamp::now_secs;
use pdfs_store::db::StoredIntent;
use super::Core;
@@ -145,6 +148,7 @@ impl Core {
})
.unwrap_or_default();
inflight.sort_by_key(|request| std::cmp::Reverse(request.age_secs));
let (pending_ops, effects) = self.database_quickly().unzip();
Diagnostics {
uptime_secs: STARTED.elapsed().as_secs(),
@@ -166,7 +170,8 @@ impl Core {
inflight,
control_handlers: super::control::active_handlers(),
control_handler_limit: super::control::handler_limit(),
pending_ops: self.pending_ops_quickly(),
pending_ops,
effects,
sync: Some(self.sync.engine.report()),
services: self
.services
@@ -200,6 +205,17 @@ impl Core {
longest_ms: u64::try_from(stat.longest.as_millis()).unwrap_or(u64::MAX),
})
.collect(),
upload_paths: pdfs_core::uploads::UPLOAD_PATHS
.snapshot()
.into_iter()
.map(|stat| UploadPathStat {
path: stat.path.to_owned(),
count: stat.count,
errors: stat.errors,
total_ms: stat.total_ms,
longest_ms: stat.longest_ms,
})
.collect(),
admission: self
.sync
.admission
@@ -218,26 +234,50 @@ impl Core {
}
}
/// Queued mutations, or `None` when the database did not answer within
/// [`PENDING_COUNT_DEADLINE`] or an earlier probe is still waiting on it.
/// Queued mutations and the mirror effects not settled yet, or `None`
/// when the database did not answer within [`DATABASE_DEADLINE`] or an
/// earlier probe is still waiting on it.
///
/// The supervisor asks for a report every tick. One thread per report
/// would pile up behind a database that never answers, so a second probe
/// is not started until the first one has returned.
fn pending_ops_quickly(&self) -> Option<u64> {
fn database_quickly(&self) -> Option<(u64, EffectReport)> {
let db = self.db.clone();
probe_once(
&self.services,
&self.pending_probe,
PENDING_COUNT_DEADLINE,
DATABASE_DEADLINE,
move || {
let counts = db.pending_op_counts().ok()?;
Some(counts.uploads.max(0) as u64 + counts.changes.max(0) as u64)
let pending = counts.uploads.max(0) as u64 + counts.changes.max(0) as u64;
let intents = db.sync_intents(None).ok()?;
Some((pending, effect_report(intents, now_secs())))
},
)
}
}
/// The report of the unsettled `intents`, oldest first, at `now`.
fn effect_report(mut intents: Vec<StoredIntent>, now: i64) -> EffectReport {
intents.sort_by_key(|intent| (intent.issued_at, intent.id));
EffectReport {
count: intents.len(),
oldest: intents
.into_iter()
.take(EffectReport::SHOWN)
.map(|intent| EffectIntent {
folder_id: intent.folder_id,
rel_path: intent.rel_path,
kind: intent.kind,
state: intent.state,
attempts: intent.attempts,
age_secs: u64::try_from(now - intent.issued_at).unwrap_or(0),
last_error: intent.last_error,
})
.collect(),
}
}
fn millis(took: Duration) -> u64 {
u64::try_from(took.as_millis()).unwrap_or(u64::MAX)
}
@@ -270,12 +310,49 @@ fn probe_once<T: Send + 'static>(
}
/// How long the report waits for the database before reporting without it.
const PENDING_COUNT_DEADLINE: Duration = Duration::from_millis(500);
const DATABASE_DEADLINE: Duration = Duration::from_millis(500);
#[cfg(test)]
mod tests {
use super::*;
/// The report counts every unsettled effect but lists only the oldest,
/// so a folder with thousands of failed uploads stays readable.
#[test]
fn the_effect_report_lists_the_oldest_and_counts_them_all() {
let intent = |id: i64, issued_at: i64| StoredIntent {
id,
folder_id: 1,
rel_path: format!("f{id}"),
kind: "trash".into(),
state: "retry".into(),
attempts: 2,
issued_at,
last_error: Some("offline".into()),
sent_sha1s: Vec::new(),
};
let total = EffectReport::SHOWN as i64 + 5;
let intents = (0..total).map(|id| intent(id, 1_000 - id)).collect();
let report = effect_report(intents, 1_100);
assert_eq!(report.count, total as usize);
assert_eq!(report.oldest.len(), EffectReport::SHOWN);
let first = &report.oldest[0];
assert_eq!(first.rel_path, format!("f{}", total - 1));
assert_eq!(first.age_secs, 100 + total as u64 - 1);
assert_eq!(first.last_error.as_deref(), Some("offline"));
assert!(
report
.oldest
.windows(2)
.all(|pair| pair[0].age_secs >= pair[1].age_secs)
);
// A clock that went back reads as just sent, not as a wrap.
assert_eq!(
effect_report(vec![intent(1, 2_000)], 1_000).oldest[0].age_secs,
0
);
}
/// The request name is read off the wire format, so it must match both
/// shapes serde produces.
#[test]
+52
View File
@@ -80,6 +80,13 @@ pub(crate) struct DrainState {
/// The node an upload has just put on Drive, from when the drain lets go
/// of its blob until the tree has the node (`docs/BUGS.md` B170).
pub(crate) landed: Arc<Mutex<HashMap<NodeUid, Node>>>,
/// A landed create's placeholder stamp, by the uid Drive gave it, with the
/// revision the create sealed. A write released while the create landed
/// can be based on the placeholder: a local mtime and no revision id. Its
/// bytes are the ones the create sent, so the drain reads that base as the
/// sealed revision ([`placeholder_base`]). Dropped once a later upload of
/// the file lands.
pub(crate) placeholders: Arc<Mutex<HashMap<NodeUid, Baseline>>>,
/// How long this node's last upload actually took, in milliseconds, with
/// the time it was measured for eviction. Feeds
/// [`Core::revision_debounce`]: a file that takes 30 seconds to send needs
@@ -110,6 +117,7 @@ impl DrainState {
unadopted: Arc::new(Mutex::new(HashMap::new())),
sealed_unread: Arc::new(Mutex::new(HashMap::new())),
landed: Arc::new(Mutex::new(HashMap::new())),
placeholders: Arc::new(Mutex::new(HashMap::new())),
upload_times: Arc::new(Mutex::new(HashMap::new())),
upload_cancel: Arc::new(Mutex::new(HashMap::new())),
landing_uploads: Arc::new(AtomicU64::new(0)),
@@ -874,6 +882,29 @@ fn revision_changed(base: &Baseline, node: &Node) -> Option<String> {
})
}
/// `base` as the revision it was made against, for [`revision_changed`].
///
/// A base with no revision id whose stamp is a landed create's placeholder
/// (`placeholder`) was taken from that placeholder by a write released while
/// the create landed: the release had taken its handle out of the tree, so the
/// rebase onto the landed node missed it, and it queued after the queued writes
/// were rebased. The placeholder's bytes are the ones the create sent, so the
/// base is the revision the create sealed. Compared by its local mtime instead,
/// the write was a conflict copy of the file's own create whenever the server
/// stamped the create a second later than the placeholder.
fn placeholder_base(base: &Baseline, placeholder: Option<&Baseline>) -> Baseline {
match placeholder {
Some(created)
if base.revision_id.is_none()
&& created.mtime == base.mtime
&& created.size == base.size =>
{
created.clone()
}
_ => base.clone(),
}
}
/// Whether a queued write that found the remote moved on ([`revision_changed`]
/// fired) is nonetheless a single-writer self-supersede rather than a foreign
/// conflict — the remote sits at a revision this daemon sealed itself, so
@@ -1808,6 +1839,27 @@ mod tests {
assert!(revision_changed(&base, &remote).is_some());
}
/// A write released while its file's create landed keeps the
/// placeholder's base: the local mtime, a second before the server's
/// stamp, and no revision id.
#[test]
fn a_write_based_on_a_landed_create_placeholder_is_not_a_conflict() {
let placeholder = baseline(1_795_799_834, 28, None);
let created = baseline(1_795_799_834, 28, Some("rev-create"));
let landed = file_node(1_795_799_835, 28, Some("rev-create"));
assert!(revision_changed(&placeholder, &landed).is_some());
let base = placeholder_base(&placeholder, Some(&created));
assert_eq!(revision_changed(&base, &landed), None);
// Another device writing over the create is still a conflict.
let edited = file_node(1_795_799_835, 28, Some("theirs"));
assert!(revision_changed(&base, &edited).is_some());
// A base with a revision of its own, or another stamp, is left alone.
let other = baseline(1_795_799_830, 28, None);
assert_eq!(placeholder_base(&other, Some(&created)), other);
let revised = baseline(1_795_799_834, 28, Some("older"));
assert_eq!(placeholder_base(&revised, Some(&created)), revised);
}
/// The reported shape (docs/BUGS.md B113): a downloader creates a file
/// through the mount, and the file is moved before its write drains. The
/// move re-stamps the node's mtime on the server (1790955809 -> 1790956593),
+40 -2
View File
@@ -637,6 +637,16 @@ impl Core {
// answer may still have the old name (`docs/BUGS.md` B161).
let real_key = real.to_string();
let renaming = self.db.has_pending_op(&real_key, OP_RENAME)?;
// Where the tree has the node before the read-back. A rename queued
// after the check above and landed before the one under the lock
// below leaves no op for either to see, while the read-back can still
// have the old name. The tree moved the entry when the rename was
// queued, so a placement that changed meanwhile is the user's
// (docs/BUGS.md B309).
let before = {
let st = self.state();
placed_in(&st, real).or_else(|| placed_in(&st, local))
};
// Drive answers a create before it lists the new node.
let mut node = self
.read_back(real)
@@ -651,6 +661,9 @@ impl Core {
// B123).
let remote = node.clone();
self.stamp_pending_sizes(std::slice::from_mut(&mut node));
// The placeholder as the tree has it, before the landed node replaces
// it: the base of a write that opened over it (`placeholder_base`).
let mut placeholder = None;
// The rows and queued ops already follow the node: `retire_create`
// moved its row to the real uid, and ops find it by local id.
@@ -666,13 +679,19 @@ impl Core {
// before it renames the entry under this lock. Asked only before,
// a rename made since was overwritten with the name the create was
// sent with, here and in the node row (`docs/BUGS.md` B152).
let renaming =
renaming || matches!(self.db.has_pending_op(&real_key, OP_RENAME), Ok(true));
let renaming = renaming
|| placed_in(st, real) != before
|| matches!(self.db.has_pending_op(&real_key, OP_RENAME), Ok(true));
if renaming && let Some(e) = st.entries.get(&ino) {
node.name = e.node.name.clone();
node.parent_uid = e.node.parent_uid.clone();
}
st.write_through(node.clone());
if let Some(e) = st.entries.get(&ino)
&& node_revision_id(&e.node).is_none()
{
placeholder.get_or_insert((e.node.modification_time, node_size(&e.node)));
}
let mut landed = node.clone();
st.keep_open_write_size(ino, &mut landed);
if let Some(e) = st.entries.get_mut(&ino) {
@@ -719,6 +738,25 @@ impl Core {
{
warn!(%real, error = %e, "persisting our sealed revision failed");
}
// A release that took its handle out of the tree before the rebase
// below and queues after `rebaseline_pending` is caught by neither,
// and an incomplete write does not chain onto our own revision. Its
// base is the placeholder, whose bytes the create sent.
if let Some((mtime, size)) = placeholder
&& mtime != remote.modification_time
&& size == node_size(&remote)
&& let Some(rev) = node_revision_id(&remote)
{
self.drain.placeholders.lock().insert(
real.clone(),
Baseline {
mtime,
size,
hash: None,
revision_id: Some(rev),
},
);
}
self.rebase_open_writes(real, &remote);
// A write carried over from the create was made against no revision at
// all; the one just created is what it now replaces.
+10
View File
@@ -116,6 +116,8 @@ impl Core {
if node.trashed {
return Ok(Some("the file was trashed remotely".into()));
}
let placeholder = self.drain.placeholders.lock().get(uid).cloned();
let base = &placeholder_base(base, placeholder.as_ref());
let Some(reason) = revision_changed(base, &node) else {
return Ok(None);
};
@@ -511,6 +513,8 @@ impl Core {
if fetched.is_ok() {
self.drain.sealed_unread.lock().remove(uid);
}
// This upload went after any write based on the create's placeholder.
self.drain.placeholders.lock().remove(uid);
let node = match fetched {
Ok(Some(node)) => node,
// Trashed or deleted under us: the tree will hear it from the event
@@ -623,6 +627,12 @@ impl Core {
.db
.has_pending_op(&uid.to_string(), OP_RENAME)
.unwrap_or(false);
// A write queued since the check above has stamped its size on the
// tree already, and the node read back must not put the landed size
// back over it. Listings do the same (B308).
let mut landed = [node.clone()];
self.stamp_pending_sizes(&mut landed);
let [node] = landed;
self.for_each_state(|st| {
let moved = placed_in(st, uid) != before;
let Some(entry) = st.by_uid.get(uid).and_then(|ino| st.entries.get(ino)) else {
+1
View File
@@ -61,6 +61,7 @@ impl Core {
if let Err(e) = self.db.clear_own_sealed_rev(&uid.to_string()) {
debug!(%uid, error = %e, "clearing the sealed-revision record failed");
}
self.drain.placeholders.lock().remove(&uid);
self.invalidate_trash();
self.log_activity(ActivityKind::Trash, &name, "trashed", true);
info!(%uid, name, "pending trash landed");
+2
View File
@@ -520,6 +520,8 @@ pub(crate) fn mount_with(
unscanned: Arc::default(),
abandon: Arc::default(),
events_read_at: Arc::new(AtomicI64::new(0)),
local_dirty: Arc::default(),
roots: Arc::default(),
admission: Arc::new(pdfs_sched::Classes::new(|class| match class {
pdfs_sched::Class::Mirror => sync::SYNC_CONCURRENCY,
pdfs_sched::Class::Listing => super::listing::COLD_LISTINGS,
+16
View File
@@ -194,6 +194,22 @@ impl Core {
Ok(name)
}
/// Drop the pins recorded under `path`, the path a front end lists a pin
/// by, when their node is gone. A deleted node leaves no path to resolve,
/// so [`unpin`](Self::unpin) cannot find it, and the pin would stay listed
/// as kept offline for good. Returns whether any pin was dropped.
pub(super) fn unpin_stale(&self, path: &str) -> CoreResult<bool> {
let uids = self
.cache
.remove_pins_at(path)
.map_err(|e| CoreError::from_api(&e, "unpin"))?;
for uid in uids.iter().filter_map(|s| parse_uid(s)) {
self.cache.evict(&uid);
self.evict_reader(&uid);
}
Ok(!uids.is_empty())
}
/// Whether the node at `ino` is kept offline because a folder above it is
/// pinned, whether or not it is also pinned on its own.
pub(super) fn pinned_by_folder(&self, ino: u64) -> bool {
+3
View File
@@ -37,6 +37,7 @@ impl Core {
.filter(|path| !path.is_empty())
.or_else(|| op.name.clone())
.unwrap_or_else(|| op.uid.clone());
let local_only = parse_node_uid(&op.uid).is_some_and(|uid| is_local_uid(&uid));
PendingOpInfo {
id: op.id,
kind: op.kind,
@@ -49,6 +50,8 @@ impl Core {
failing: op.attempts >= FAILING_ATTEMPTS || issues.contains_key(&op.id),
issue: issues.get(&op.id).map(|issue| SyncIssue::parse(issue)),
exportable,
node: op.uid,
local_only,
}
})
.collect())
+11
View File
@@ -645,6 +645,17 @@ impl Sharing {
Ok(items)
}
/// Whether Drive lists `uid` among the nodes this account shared. That list
/// is the account's own word that the node is its share, so it stands in
/// for the residency proof a node never browsed to cannot give.
pub(crate) fn shared_by_me(&self, uid: &NodeUid) -> CoreResult<bool> {
let uids = self
.rt
.block_on(self.client.enumerate_shared_by_me_node_uids())
.map_err(|e| CoreError::from_api(&e, "enumerate shared-by-me"))?;
Ok(uids.contains(uid))
}
/// Best-effort mountpoint-relative path for a node already interned in the live
/// 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) —
+524
View File
@@ -1332,6 +1332,33 @@ mod tests {
std::fs::remove_file(mnt.join("gone.txt")).unwrap();
std::fs::write(mnt.join("new.txt"), b"new").unwrap();
std::fs::create_dir(mnt.join("dir")).unwrap();
std::fs::rename(mnt.join("edit.txt"), mnt.join("edited.txt")).unwrap();
// The queue says which changes share a node, so the app can name
// every change a discard drops, and which nodes Drive never had.
let queued = daemon.pending().unwrap();
let on = |name: &str| -> Vec<&PendingOpInfo> {
queued.iter().filter(|op| op.path.ends_with(name)).collect()
};
// By node, not by path: the path an op shows may still be the old
// name for a moment after the rename.
let edit = queued
.iter()
.find(|op| op.kind == "revision")
.expect("the edit is queued");
let same: Vec<&str> = queued
.iter()
.filter(|op| op.node == edit.node)
.map(|op| op.kind.as_str())
.collect();
assert!(!edit.node.is_empty());
assert_eq!(same, ["revision", "rename"], "{queued:?}");
assert!(!edit.local_only);
assert!(on("new.txt").iter().all(|op| op.local_only), "{queued:?}");
assert!(
on("moved.txt").iter().all(|op| !op.local_only),
"{queued:?}"
);
// Discarding one change drops the others queued on its node.
for _ in 0..10 {
@@ -1520,6 +1547,86 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_file_renamed_while_its_create_is_read_back_keeps_its_new_name() {
// The create had landed and the drain was reading the node back. The
// rename came after the drain's first look for a queued rename, and
// landed before its second, so neither saw it. The answer still had
// the old name, which the tree took back. A rename over the new name
// then found nothing to replace and waited on its own name (B309).
let drive = FakeDrive::new();
let dir = scratch("renamed-while-read-back");
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
let mnt = daemon.mountpoint.clone().join("x");
std::fs::create_dir(&mnt).unwrap();
assert!(wait_until(Duration::from_secs(30), || {
daemon.pending().is_ok_and(|items| items.is_empty()) && drive.lookup("x").is_some()
}));
let create = daemon.client.hold_reply_to_next_create();
daemon.write_new(&mnt.join("d"), b"abc").unwrap();
assert!(wait_until(Duration::from_secs(30), || create.reached()));
let uid = drive.lookup("x/d").unwrap();
// Answer read-backs in turn until the create is retired; hold the
// first one after that, which is the adoption's.
let mut held = create;
let adopting = loop {
let next = daemon.client.hold_answer_to_next_read(&uid);
drop(held);
assert!(wait_until(Duration::from_secs(30), || next.reached()));
if daemon
.pending()
.is_ok_and(|items| items.iter().all(|op| op.kind != "create"))
{
break next;
}
held = next;
};
std::fs::rename(mnt.join("d"), mnt.join("b.txt")).unwrap();
assert!(
wait_until(Duration::from_secs(10), || drive
.lookup("x/b.txt")
.is_some()),
"{:?} {:?}",
daemon.pending(),
drive.tree()
);
drop(adopting);
// Before any listing or event could put it right.
std::thread::sleep(Duration::from_millis(100));
assert!(mnt.join("b.txt").exists() && !mnt.join("d").exists());
assert!(
wait_until(Duration::from_secs(30), || {
daemon.pending().is_ok_and(|items| items.is_empty())
}),
"{:?}",
daemon.pending()
);
let names: Vec<_> = std::fs::read_dir(&mnt)
.unwrap()
.map(|e| e.unwrap().file_name().into_string().unwrap())
.collect();
assert_eq!(names, ["b.txt"]);
// And a rename over it replaces it, as it does on any file.
daemon.write_new(&mnt.join("e.md"), b"new").unwrap();
std::fs::rename(mnt.join("e.md"), mnt.join("b.txt")).unwrap();
let file = Some(Entry::File(Arc::new(b"new".to_vec())));
assert!(
wait_until(Duration::from_secs(10), || {
daemon.pending().is_ok_and(|items| items.is_empty())
&& drive.tree().get("x/b.txt").cloned() == file
}),
"{:?} {:?}",
daemon.pending(),
drive.tree()
);
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_file_read_back_before_drive_committed_it_keeps_its_bytes() {
@@ -1963,6 +2070,308 @@ mod tests {
.map_or(0, |c| c.value)
}
/// Once the watch has been live for a pass, a pass reads again only what
/// the watcher reported, and that is enough to find every change: an
/// edit, a new folder with a file in it, a deletion, and a folder moved in
/// from outside with a folder and a file in it (`local_dirty`).
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_trusted_local_dirty_set_stands_in_for_the_walk() {
// The log is shared by every test in the process: drop what earlier
// tests left in it, so only this daemon's lines are counted.
take_logged();
let drive = FakeDrive::new();
let dir = scratch("local-dirty");
let (daemon, folder, _client) =
start_mirror(&drive, &dir, &[("a.txt", b"one"), ("b.txt", b"two")]);
// From the pass after this one, the watch has been live since the
// last claim.
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
let settled = quiet_pass(&daemon, folder).expect("a quiet pass is traced");
assert_eq!(counted(&settled, "local dirty untrusted"), 0, "{settled}");
assert!(counted(&settled, "local reused") > 0, "{settled}");
let local = dir.join("local");
let outside = dir.join("outside");
std::fs::create_dir_all(outside.join("deep")).unwrap();
std::fs::write(outside.join("deep").join("x.txt"), b"moved in").unwrap();
std::fs::write(local.join("a.txt"), b"edited").unwrap();
std::fs::create_dir(local.join("new")).unwrap();
std::fs::write(local.join("new").join("c.txt"), b"three").unwrap();
std::fs::remove_file(local.join("b.txt")).unwrap();
std::fs::rename(&outside, local.join("moved")).unwrap();
assert!(wait_until(Duration::from_secs(60), || {
drive.lookup("mirrored/new/c.txt").is_some()
&& drive.lookup("mirrored/moved/deep/x.txt").is_some()
&& drive.lookup("mirrored/b.txt").is_none()
}));
let after = quiet_pass(&daemon, folder).expect("a quiet pass is traced");
assert_eq!(counted(&after, "local dirty untrusted"), 0, "{after}");
// Still taken from the last pass's walk: none of the passes since
// changed anything on disk, so each kept its walk for the next.
assert!(counted(&after, "local reused") > 0, "{after}");
let logged = take_logged();
let missed: Vec<&String> = logged
.iter()
.filter(|line| line.contains("local dirty set missed"))
.collect();
assert!(missed.is_empty(), "{missed:?}");
// The first pass took the folder from discovery to following, and
// nothing since put it in doubt (`root`).
let roots: Vec<&String> = logged
.iter()
.filter(|line| line.contains("sync: root state"))
.collect();
assert!(
roots.len() == 1 && roots[0].contains("to=following"),
"{roots:?}"
);
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let _ = std::fs::remove_dir_all(&dir);
}
/// A sync root moved away and made again in its place is a new folder
/// on disk, which the old watch does not see. The engine watches it again
/// once it is back, and walks it once more after, so a file written in
/// it as the watch was set up still reaches Drive without waiting for the
/// poll (`root`).
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_root_made_again_is_watched_again() {
take_logged();
let drive = FakeDrive::new();
let dir = scratch("root-again");
let (daemon, folder, _client) =
start_mirror(&drive, &dir, &[("a.txt", b"one"), ("b.txt", b"two")]);
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
let local = dir.join("local");
let away = dir.join("away");
std::fs::rename(&local, &away).unwrap();
let _ = daemon.request(&Request::SyncNow { id: Some(folder) });
assert!(wait_until(Duration::from_secs(30), || {
take_logged()
.iter()
.any(|line| line.contains("to=suspended (RootMissing)"))
}));
// A new folder in the old one's place, with the same files.
std::fs::create_dir(&local).unwrap();
for name in ["a.txt", "b.txt"] {
std::fs::copy(away.join(name), local.join(name)).unwrap();
}
let _ = daemon.request(&Request::SyncNow { id: Some(folder) });
// The pass that finds it back walks it in full, and the watches are
// set up again after it.
assert!(wait_until(Duration::from_secs(30), || {
take_logged().iter().any(|line| {
line.contains("from=suspended (RootMissing)") && line.contains("to=following")
})
}));
// Written as that pass ends, which may be before the watch is set up
// again: the event is then lost, and only the pass the new watch
// brings about finds the file. Nothing else asks for one, and the
// poll is two minutes off.
std::fs::write(local.join("c.txt"), b"three").unwrap();
assert!(
wait_until(Duration::from_secs(60), || drive
.lookup("mirrored/c.txt")
.is_some()),
"a file written in the root made again reaches Drive"
);
assert!(drive.lookup("mirrored/a.txt").is_some());
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let _ = std::fs::remove_dir_all(&dir);
}
/// A sync root replaced between two passes is never seen missing, and
/// the watch stays on the folder moved away. The pass sees the root is
/// another folder, and the engine watches the new one (`root`).
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_root_replaced_between_passes_is_watched_again() {
take_logged();
let drive = FakeDrive::new();
let dir = scratch("root-replaced");
let (daemon, folder, _client) =
start_mirror(&drive, &dir, &[("a.txt", b"one"), ("b.txt", b"two")]);
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
let local = dir.join("local");
let away = dir.join("away");
std::fs::rename(&local, &away).unwrap();
std::fs::create_dir(&local).unwrap();
for name in ["a.txt", "b.txt"] {
std::fs::copy(away.join(name), local.join(name)).unwrap();
}
take_logged();
let _ = daemon.request(&Request::SyncNow { id: Some(folder) });
assert!(wait_until(Duration::from_secs(30), || {
take_logged()
.iter()
.any(|line| line.contains("the folder's root was replaced"))
}));
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
std::fs::write(local.join("c.txt"), b"three").unwrap();
// Only the watch can bring this pass about: the poll is two minutes
// off.
assert!(
wait_until(Duration::from_secs(60), || drive
.lookup("mirrored/c.txt")
.is_some()),
"a file written in the root put in place reaches Drive"
);
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let _ = std::fs::remove_dir_all(&dir);
}
/// An effect a daemon sent and never heard back from is `unsure` at the
/// next start. One the folder still needs is sent again, and settles; one
/// it no longer needs is settled by the first pass that looks (`effect`).
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn an_effect_left_unsure_by_a_stop_is_sent_again_or_settled() {
take_logged();
let drive = FakeDrive::new();
let dir = scratch("unsure-effect");
let (daemon, folder, client) = start_mirror(&drive, &dir, &[("a.txt", b"one")]);
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
// What a daemon killed while it sent two uploads leaves: one landed
// (a.txt is on Drive), the other never went out.
let sent = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64
- 10;
let db = reopen(&dir);
db.sync_intent_issue(folder, "a.txt", "upload", sent)
.unwrap();
db.sync_intent_issue(folder, "new.txt", "upload", sent)
.unwrap();
drop(db);
std::fs::write(dir.join("local").join("new.txt"), b"new").unwrap();
take_logged();
let daemon = Daemon::start(&dir, client).unwrap();
assert!(wait_until(Duration::from_secs(60), || drive
.lookup("mirrored/new.txt")
.is_some()));
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
let logged = take_logged();
let has = |text: &str| logged.iter().any(|line| line.contains(text));
assert!(
has("effects=2") && has("did not hear back from"),
"{logged:#?}"
);
assert!(
has("sending again an effect a stopped daemon may have made"),
"{logged:#?}"
);
assert!(
has("an effect a stopped daemon may have made is no longer needed"),
"{logged:#?}"
);
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
assert!(
reopen(&dir).sync_intents(Some(folder)).unwrap().is_empty(),
"every intent settled"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// The mirror effects not settled yet, from `pdfs diagnostics`.
fn effects(daemon: &Daemon) -> Vec<control::EffectIntent> {
let Ok(Response::Diagnostics { diagnostics }) = daemon.request(&Request::Diagnostics)
else {
panic!("no diagnostics");
};
diagnostics.effects.map(|e| e.oldest).unwrap_or_default()
}
/// A deletion a mirror pass sends is recorded like any other effect, and
/// `pdfs diagnostics` lists it until it lands: a trash on Drive while its
/// answer is outstanding, and a removal from disk.
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_deletion_is_an_effect_until_it_lands() {
let drive = FakeDrive::new();
let dir = scratch("deletion-effect");
let (daemon, folder, _client) = start_mirror(
&drive,
&dir,
&[
("a.txt", b"one"),
("b.txt", b"two"),
("c.txt", b"three"),
("d.txt", b"four"),
],
);
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
let uid = drive.lookup("mirrored/a.txt").unwrap();
let held = daemon.client.hold_next_trash(&uid);
std::fs::remove_file(dir.join("local").join("a.txt")).unwrap();
assert!(wait_until(Duration::from_secs(60), || held.reached()));
let listed = effects(&daemon);
assert!(
listed.iter().any(|e| e.folder_id == folder
&& e.rel_path == "a.txt"
&& e.kind == "trash"
&& e.state == "issued"),
"{listed:#?}"
);
drop(held);
assert!(wait_until(Duration::from_secs(60), || {
drive.lookup("mirrored/a.txt").is_none() && effects(&daemon).is_empty()
}));
drive.device().trash("mirrored/b.txt");
assert!(wait_until(Duration::from_secs(60), || {
!dir.join("local").join("b.txt").exists()
}));
assert!(
wait_until(Duration::from_secs(30), || effects(&daemon).is_empty()),
"{:#?}",
effects(&daemon)
);
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let _ = std::fs::remove_dir_all(&dir);
}
/// A restart owes the disk a walk in full, since nothing watched it
/// meanwhile, and owes Drive nothing: its event stream resumes from the
/// cursor (`root`).
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_restart_walks_the_disk_in_full_and_not_drive() {
take_logged();
let drive = FakeDrive::new();
let dir = scratch("restart-owes");
let (daemon, folder, _client) =
start_mirror(&drive, &dir, &[("a.txt", b"one"), ("b.txt", b"two")]);
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
take_logged();
let daemon = daemon.restart().unwrap();
let quiet = quiet_pass(&daemon, folder).expect("a quiet pass is traced");
let logged = take_logged();
let roots: Vec<&String> = logged
.iter()
.filter(|line| line.contains("sync: root state"))
.collect();
assert!(
roots.len() == 1
&& roots[0].contains("from=auditing (local: Restart)")
&& roots[0].contains("to=following")
&& roots[0].contains("Covered { local: true, remote: false }"),
"{roots:?}"
);
assert!(
!logged
.iter()
.any(|line| line.contains("the root state asks for a walk of all of Drive")),
"a restart owes Drive nothing"
);
assert!(counted(&quiet, "reused") > 0, "{quiet}");
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_mirror_pass_reports_where_its_time_went() {
@@ -2246,6 +2655,70 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_mirror_create_whose_reply_was_lost_is_adopted_after_a_restart_and_its_edit_lands() {
// Drive made the file, but the answer never came back, and the daemon
// stopped before it tried again. While it was stopped the file was
// written again. A one-request small upload makes this the common way
// a create goes unanswered: it leaves a whole file, never a draft. The
// start must find that file, take it as this one, and put the newer
// bytes on it: one file, no conflict copy.
take_logged();
let drive = FakeDrive::new();
let dir = scratch("mirror-lost-create-restart");
let (daemon, folder, client) = start_mirror(&drive, &dir, &[("a.txt", b"one")]);
let local = dir.join("local");
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
client.lose_reply_to_next_create();
std::fs::write(local.join("new.txt"), b"first").unwrap();
assert!(wait_until(Duration::from_secs(30), || {
on_drive(&drive, "mirrored/new.txt").is_some_and(|bytes| bytes == b"first")
}));
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
std::fs::write(local.join("new.txt"), b"second, written while stopped").unwrap();
let daemon = Daemon::start(&dir, client).unwrap();
let landed = wait_until(Duration::from_secs(60), || {
on_drive(&drive, "mirrored/new.txt")
.is_some_and(|bytes| bytes == b"second, written while stopped")
});
let logged = take_logged();
assert!(
landed,
"{:#?}\n{:#?}",
drive.tree(),
logged
.iter()
.filter(|l| l.contains("sync") || l.contains("new"))
.collect::<Vec<_>>()
);
quiet_pass(&daemon, folder).expect("a quiet pass is traced");
assert!(conflict_copies(&local, "new").is_empty());
let tree = drive.tree();
assert!(
!tree.keys().any(|k| k.contains("sync-conflict")),
"{tree:?}"
);
assert_eq!(
tree.keys().filter(|k| k.contains("new")).count(),
1,
"{tree:?}"
);
assert_eq!(
std::fs::read(local.join("new.txt")).unwrap(),
b"second, written while stopped"
);
assert!(matches!(daemon.stop(), Ok(MountOutcome::Shutdown)));
assert!(
reopen(&dir).sync_intents(Some(folder)).unwrap().is_empty(),
"every intent settled"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_revision_made_during_a_mirror_download_still_arrives() {
@@ -4177,6 +4650,57 @@ mod tests {
id
}
/// Stop syncing with "Also delete from Proton Drive" on, while Drive cannot
/// be reached. The folder stops syncing, but its copy in Proton Drive
/// stays. The reply was a plain success, so the app said "Stopped syncing
/// folder" and nothing told the user the cloud copy was still there.
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn stopping_sync_says_so_when_its_drive_folder_could_not_be_deleted() {
let drive = FakeDrive::new();
let dir = scratch("stop-sync-delete-offline");
let daemon = Daemon::start(&dir, drive.client(1, Faults::lan())).unwrap();
let local = dir.join("docs");
let id = sync_folder(&daemon, &local, "mirror");
std::fs::write(local.join("keep.txt"), b"keep").unwrap();
daemon.request(&Request::SyncNow { id: Some(id) }).unwrap();
let on_drive = || {
drive.tree().iter().any(|(path, entry)| {
path.ends_with("docs/keep.txt") && *entry == Entry::File(Arc::new(b"keep".to_vec()))
})
};
assert!(
wait_until(Duration::from_secs(30), || on_drive()
&& listed_folder(&daemon, id).is_some_and(|f| f.state == "idle")),
"the folder synced: {:?}",
listed_folder(&daemon, id)
);
daemon.client.set_online(false);
let error = daemon
.request(&Request::RemoveSyncFolder {
id,
delete_remote: true,
})
.unwrap_err()
.to_string();
daemon.client.set_online(true);
assert!(
error.contains("stopped syncing the folder")
&& error.contains("was not moved to the trash"),
"{error}"
);
assert!(
listed_folder(&daemon, id).is_none(),
"the folder still syncs"
);
assert!(on_drive(), "the copy in Proton Drive is gone after all");
assert_eq!(std::fs::read(local.join("keep.txt")).unwrap(), b"keep");
daemon.stop().unwrap();
let _ = std::fs::remove_dir_all(dir);
}
#[test]
#[ignore = "mounts FUSE: run with `cargo test -p pdfs-fuse sim:: -- --ignored`"]
fn a_move_out_of_an_on_demand_folder_refuses_a_file_still_open_for_writing() {
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Generated by scripts/render-tray-icons.py; edit that, not this. -->
<style>.ColorScheme-Text{color:#2e3436}</style>
<path class="ColorScheme-Text" fill="currentColor" fill-rule="evenodd" d="M1 3.5Q1 2.5 2 2.5H5.6Q6.1 2.5 6.45 2.85L7.4 3.8Q7.6 4 7.9 4H14Q15 4 15 5V6.75H7.05L5.8 5.5H1ZM1 7.25Q1 6.25 2 6.25H5.2Q5.6 6.25 5.9 6.55L6.6 7.25Q6.85 7.5 7.2 7.5H14Q15 7.5 15 8.5V8.646A4.5 4.5 0 0 0 7.757 13.5H2Q1 13.5 1 12.5ZM8.5 12A3.5 3.5 0 1 0 15.5 12A3.5 3.5 0 1 0 8.5 12ZM11.8 9.5H12.2Q12.7 9.5 12.7 10V12.1Q12.7 12.6 12.2 12.6H11.8Q11.3 12.6 11.3 12.1V10Q11.3 9.5 11.8 9.5ZM11.25 14.05A0.75 0.75 0 1 0 12.75 14.05A0.75 0.75 0 1 0 11.25 14.05Z"/>
</svg>

After

Width:  |  Height:  |  Size: 741 B

@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Generated by scripts/render-tray-icons.py; edit that, not this. -->
<style>.ColorScheme-Text{color:#2e3436}</style>
<path class="ColorScheme-Text" fill="currentColor" fill-rule="evenodd" d="M1 3.5Q1 2.5 2 2.5H5.6Q6.1 2.5 6.45 2.85L7.4 3.8Q7.6 4 7.9 4H14Q15 4 15 5V6.75H7.05L5.8 5.5H1ZM1 7.25Q1 6.25 2 6.25H5.2Q5.6 6.25 5.9 6.55L6.6 7.25Q6.85 7.5 7.2 7.5H14Q15 7.5 15 8.5V8.646A4.5 4.5 0 0 0 7.757 13.5H2Q1 13.5 1 12.5ZM2.25 8.75H8.888A4.5 4.5 0 0 0 7.507 12.25H2.25ZM12 11.081L13.379 9.702L14.298 10.621L12.919 12L14.298 13.379L13.379 14.298L12 12.919L10.621 14.298L9.702 13.379L11.081 12L9.702 10.621L10.621 9.702Z"/>
</svg>

After

Width:  |  Height:  |  Size: 715 B

@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Generated by scripts/render-tray-icons.py; edit that, not this. -->
<style>.ColorScheme-Text{color:#2e3436}</style>
<path class="ColorScheme-Text" fill="currentColor" fill-rule="evenodd" d="M1 3.5Q1 2.5 2 2.5H5.6Q6.1 2.5 6.45 2.85L7.4 3.8Q7.6 4 7.9 4H14Q15 4 15 5V6.75H7.05L5.8 5.5H1ZM1 7.25Q1 6.25 2 6.25H5.2Q5.6 6.25 5.9 6.55L6.6 7.25Q6.85 7.5 7.2 7.5H14Q15 7.5 15 8.5V12.5Q15 13.5 14 13.5H2Q1 13.5 1 12.5ZM2.25 8.75H13.75V12.25H2.25Z"/>
</svg>

After

Width:  |  Height:  |  Size: 536 B

@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Generated by scripts/render-tray-icons.py; edit that, not this. -->
<style>.ColorScheme-Text{color:#2e3436}</style>
<path class="ColorScheme-Text" fill="currentColor" fill-rule="evenodd" d="M1 3.5Q1 2.5 2 2.5H5.6Q6.1 2.5 6.45 2.85L7.4 3.8Q7.6 4 7.9 4H14Q15 4 15 5V6.75H7.05L5.8 5.5H1ZM1 7.25Q1 6.25 2 6.25H5.2Q5.6 6.25 5.9 6.55L6.6 7.25Q6.85 7.5 7.2 7.5H14Q15 7.5 15 8.5V8.646A4.5 4.5 0 0 0 7.757 13.5H2Q1 13.5 1 12.5ZM10.1 9.25H10.8Q11.2 9.25 11.2 9.65V14.35Q11.2 14.75 10.8 14.75H10.1Q9.7 14.75 9.7 14.35V9.65Q9.7 9.25 10.1 9.25ZM13.2 9.25H13.9Q14.3 9.25 14.3 9.65V14.35Q14.3 14.75 13.9 14.75H13.2Q12.8 14.75 12.8 14.35V9.65Q12.8 9.25 13.2 9.25Z"/>
</svg>

After

Width:  |  Height:  |  Size: 747 B

@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Generated by scripts/render-tray-icons.py; edit that, not this. -->
<style>.ColorScheme-Text{color:#2e3436}</style>
<path class="ColorScheme-Text" fill="currentColor" fill-rule="evenodd" d="M1 3.5Q1 2.5 2 2.5H5.6Q6.1 2.5 6.45 2.85L7.4 3.8Q7.6 4 7.9 4H14Q15 4 15 5V6.75H7.05L5.8 5.5H1ZM1 7.25Q1 6.25 2 6.25H5.2Q5.6 6.25 5.9 6.55L6.6 7.25Q6.85 7.5 7.2 7.5H14Q15 7.5 15 8.5V8.646A4.5 4.5 0 0 0 7.757 13.5H2Q1 13.5 1 12.5ZM10.1 11.6V11.5A1.9 1.9 0 0 1 13.9 11.5V11.6H13.05V11.5A1.05 1.05 0 0 0 10.95 11.5V11.6ZM10.1 11.6H13.9Q14.5 11.6 14.5 12.2V14.2Q14.5 14.8 13.9 14.8H10.1Q9.5 14.8 9.5 14.2V12.2Q9.5 11.6 10.1 11.6Z"/>
</svg>

After

Width:  |  Height:  |  Size: 714 B

@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Generated by scripts/render-tray-icons.py; edit that, not this. -->
<style>.ColorScheme-Text{color:#2e3436}</style>
<path class="ColorScheme-Text" fill="currentColor" fill-rule="evenodd" d="M1 3.5Q1 2.5 2 2.5H5.6Q6.1 2.5 6.45 2.85L7.4 3.8Q7.6 4 7.9 4H14Q15 4 15 5V6.75H7.05L5.8 5.5H1ZM1 7.25Q1 6.25 2 6.25H5.2Q5.6 6.25 5.9 6.55L6.6 7.25Q6.85 7.5 7.2 7.5H14Q15 7.5 15 8.5V12.5Q15 13.5 14 13.5H2Q1 13.5 1 12.5Z"/>
</svg>

After

Width:  |  Height:  |  Size: 508 B

@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<!-- Generated by scripts/render-tray-icons.py; edit that, not this. -->
<style>.ColorScheme-Text{color:#2e3436}</style>
<path class="ColorScheme-Text" fill="currentColor" fill-rule="evenodd" d="M1 3.5Q1 2.5 2 2.5H5.6Q6.1 2.5 6.45 2.85L7.4 3.8Q7.6 4 7.9 4H14Q15 4 15 5V6.75H7.05L5.8 5.5H1ZM1 7.25Q1 6.25 2 6.25H5.2Q5.6 6.25 5.9 6.55L6.6 7.25Q6.85 7.5 7.2 7.5H14Q15 7.5 15 8.5V8.646A4.5 4.5 0 0 0 7.757 13.5H2Q1 13.5 1 12.5ZM9.087 10.94L9.461 10.222L10.007 9.625L10.69 9.19L11.462 8.947L12.27 8.912L13.06 9.087L13.778 9.461L14.375 10.007L15.026 9.461L14.498 12.087L12.804 11.325L13.455 10.779L13.09 10.444L12.65 10.215L12.166 10.107L11.67 10.129L11.197 10.278L10.779 10.545L10.444 10.91L10.215 11.35ZM14.913 13.06L14.539 13.778L13.993 14.375L13.31 14.81L12.538 15.053L11.73 15.088L10.94 14.913L10.222 14.539L9.625 13.993L8.974 14.539L9.502 11.913L11.196 12.675L10.545 13.221L10.91 13.556L11.35 13.785L11.834 13.893L12.33 13.871L12.803 13.722L13.221 13.455L13.556 13.09L13.785 12.65Z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

+1
View File
@@ -59,6 +59,7 @@ scale.browser-status-meter trough { min-width: 140px; min-height: 6px; }
.dropzone-active { border-color: var(--accent-bg-color); background: color-mix(in srgb, var(--accent-bg-color) 10%, transparent); }
.files-drop-active { outline: 2px dashed var(--accent-bg-color); outline-offset: -4px; border-radius: 12px; background: color-mix(in srgb, var(--accent-bg-color) 6%, transparent); }
.files-drop-folder { border-radius: 8px; background: color-mix(in srgb, var(--accent-bg-color) 22%, transparent); box-shadow: inset 0 0 0 2px var(--accent-bg-color); }
.files-drop-hint { padding: 8px 16px; border-radius: 9999px; background: var(--accent-bg-color); color: var(--accent-fg-color); font-weight: bold; box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2); }
.file-pending { opacity: 0.45; }
/* Photo viewer: always light-on-dark, whatever the system style */
+3
View File
@@ -500,6 +500,7 @@ fn build_window(app: &adw::Application) {
restore: RefCell::new(None),
crumb: browser_widgets.crumb.clone(),
content: browser_widgets.content.clone(),
drop_hint: browser_widgets.drop_hint.clone(),
status: browser_widgets.status.clone(),
retry: browser_widgets.retry.clone(),
split: browser_widgets.split.clone(),
@@ -548,6 +549,8 @@ fn build_window(app: &adw::Application) {
subtitle: trash_widgets.subtitle.clone(),
selection_bar: trash_widgets.selection_bar.clone(),
selection_label: trash_widgets.selection_label.clone(),
restore_selected: trash_widgets.restore_selected.clone(),
delete_selected: trash_widgets.delete_selected.clone(),
loader: Loader::new(&trash_widgets.content),
back: trash_widgets.back.clone(),
crumb: trash_widgets.crumb.clone(),
+195 -9
View File
@@ -31,6 +31,9 @@ pub(crate) struct BrowserState {
/// Swaps the Files content area between the grid/list views and the status
/// page below; see [`browser_status`].
pub(crate) content: gtk4::Stack,
/// Floats over the views while something is dragged over them, saying
/// what a drop there does; see [`show_drop_preview`].
pub(crate) drop_hint: gtk4::Label,
/// The Files empty/loading/error surface, shown in place of the views.
pub(crate) status: adw::StatusPage,
/// Sits in [`Self::status`]; shown when a load failed because the mount
@@ -135,6 +138,7 @@ pub(crate) struct BrowserWidgets {
pub(crate) crumb: gtk4::Box,
/// Swaps the content area between the grid/list views and the status page.
pub(crate) content: gtk4::Stack,
pub(crate) drop_hint: gtk4::Label,
/// The empty/loading/error surface shown in place of the views.
pub(crate) status: adw::StatusPage,
/// Sits in the status page; shown only when the mount service is down.
@@ -344,6 +348,19 @@ pub(crate) fn build_browser_page() -> (gtk4::Widget, BrowserWidgets) {
content.set_transition_type(gtk4::StackTransitionType::Crossfade);
content.add_named(&view_stack, Some("views"));
content.add_named(&status, Some("status"));
// What a drop does, over the views while a drag is over them.
let drop_hint = gtk4::Label::builder()
.halign(gtk4::Align::Center)
.valign(gtk4::Align::End)
.margin_bottom(18)
.justify(gtk4::Justification::Center)
.wrap(true)
.visible(false)
.can_target(false)
.build();
drop_hint.add_css_class("files-drop-hint");
let content_overlay = gtk4::Overlay::builder().child(&content).build();
content_overlay.add_overlay(&drop_hint);
// The details pane slides in from the right while its header toggle is on.
let (details_pane, details) = build_details_pane();
@@ -356,7 +373,7 @@ pub(crate) fn build_browser_page() -> (gtk4::Widget, BrowserWidgets) {
// itself; the header toggle alone decides.
.pin_sidebar(true)
.max_sidebar_width(300.0)
.content(&content)
.content(&content_overlay)
.sidebar(&details_pane)
.build();
@@ -492,6 +509,7 @@ pub(crate) fn build_browser_page() -> (gtk4::Widget, BrowserWidgets) {
files,
crumb,
content,
drop_hint,
status,
retry,
search,
@@ -1401,11 +1419,16 @@ pub(crate) fn wire_browser_actions(ui: &Rc<Ui>, build_thumbnails: &gtk4::Button)
gtk4::gdk::FileList::static_type(),
gtk4::gdk::DragAction::COPY | gtk4::gdk::DragAction::MOVE,
);
// Loaded on enter, so the hint can say what the drop does before it lands.
drop.set_preload(true);
let ui_enter = ui.clone();
drop.connect_enter(move |_, _, _| {
drop.connect_enter(move |target, _, _| {
ui_enter.browser.content.add_css_class("files-drop-active");
page_drop_preview(&ui_enter, target);
browser_drop_action()
});
let ui_value = ui.clone();
drop.connect_value_notify(move |target| page_drop_preview(&ui_value, target));
drop.connect_motion(|_, _, _| browser_drop_action());
let ui_leave = ui.clone();
drop.connect_leave(move |_| {
@@ -1413,6 +1436,7 @@ pub(crate) fn wire_browser_actions(ui: &Rc<Ui>, build_thumbnails: &gtk4::Button)
.browser
.content
.remove_css_class("files-drop-active");
ui_leave.browser.drop_hint.set_visible(false);
});
let ui_drop = ui.clone();
drop.connect_drop(move |target, value, _, _| {
@@ -1420,6 +1444,7 @@ pub(crate) fn wire_browser_actions(ui: &Rc<Ui>, build_thumbnails: &gtk4::Button)
.browser
.content
.remove_css_class("files-drop-active");
ui_drop.browser.drop_hint.set_visible(false);
let Ok(files) = value.get::<gtk4::gdk::FileList>() else {
return false;
};
@@ -3024,19 +3049,29 @@ pub(crate) fn attach_drop(ui: &Rc<Ui>, item: &gtk4::ListItem, anchor: &gtk4::Box
.formats()
.contains_type(gtk4::gdk::FileList::static_type())
});
let anchor_enter = anchor.clone();
target.connect_enter(move |_, _, _| {
target.set_preload(true);
let (anchor_enter, ui_enter, item_enter) = (anchor.clone(), ui.clone(), item.clone());
target.connect_enter(move |target, _, _| {
anchor_enter.add_css_class("files-drop-folder");
folder_drop_preview(&ui_enter, target, &item_enter);
browser_drop_action()
});
let (ui_value, item_value) = (ui.clone(), item.clone());
target.connect_value_notify(move |target| folder_drop_preview(&ui_value, target, &item_value));
target.connect_motion(|_, _, _| browser_drop_action());
let anchor_leave = anchor.clone();
target.connect_leave(move |_| anchor_leave.remove_css_class("files-drop-folder"));
let (anchor_leave, ui_leave) = (anchor.clone(), ui.clone());
target.connect_leave(move |_| {
anchor_leave.remove_css_class("files-drop-folder");
// The page's own target takes over under the pointer; it repaints the
// hint for the folder on screen as it is entered.
ui_leave.browser.drop_hint.set_visible(false);
});
let ui = ui.clone();
let item = item.clone();
let anchor_drop = anchor.clone();
target.connect_drop(move |target, value, _, _| {
anchor_drop.remove_css_class("files-drop-folder");
ui.browser.drop_hint.set_visible(false);
let Some(obj) = item.item().and_downcast::<BoxedAnyObject>() else {
return false;
};
@@ -3055,6 +3090,123 @@ pub(crate) fn attach_drop(ui: &Rc<Ui>, item: &gtk4::ListItem, anchor: &gtk4::Box
anchor.add_controller(target);
}
/// The page's drop hint, for the folder on screen.
fn page_drop_preview(ui: &Rc<Ui>, target: &gtk4::DropTarget) {
if !ui.browser.search.text().trim().is_empty() {
// Search results have no one folder to drop into.
ui.browser.drop_hint.set_visible(false);
return;
}
let dest = ui.browser.path.borrow().clone();
let name = match dest.rsplit('/').next().filter(|name| !name.is_empty()) {
Some(name) => name.to_string(),
None => gettext("My files"),
};
show_drop_preview(ui, target, &dest, &name);
}
/// A folder cell's drop hint, for that folder.
fn folder_drop_preview(ui: &Rc<Ui>, target: &gtk4::DropTarget, item: &gtk4::ListItem) {
let Some(obj) = item.item().and_downcast::<BoxedAnyObject>() else {
return;
};
let (dest, name) = {
let entry = obj.borrow::<DirEntry>();
(entry_rel(ui, &entry), entry.name.clone())
};
show_drop_preview(ui, target, &dest, &name);
}
/// Say what dropping what `target` holds into `dest` would do, the way
/// [`drop_files`] will do it. Nothing is shown until the files have loaded.
fn show_drop_preview(ui: &Rc<Ui>, target: &gtk4::DropTarget, dest: &str, name: &str) {
let hint = &ui.browser.drop_hint;
let Some(files) = target
.value()
.and_then(|value| value.get::<gtk4::gdk::FileList>().ok())
else {
hint.set_visible(false);
return;
};
let mountpoint = ui.dirs.resolved_mountpoint(&ui.dirs.load_config());
let (in_drive, uploads) =
split_dropped(&mountpoint, files.files().iter().filter_map(|f| f.path()));
let moving = from_this_app(target);
let dropped = in_drive.len();
let going = drop_targets(in_drive, dest, moving).len();
hint.set_label(&drop_preview(
DropPlan {
going,
skipped: dropped - going,
uploads: uploads.len(),
moving,
},
name,
));
hint.set_visible(true);
}
/// What a drop would do, counted: see [`drop_files`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct DropPlan {
/// Items already in Proton Drive that go to the folder.
pub(crate) going: usize,
/// Items already in Proton Drive that cannot go there: the folder itself,
/// one of its parents, or, for a move, what is in it already.
pub(crate) skipped: usize,
/// Files from outside Proton Drive, uploaded into the folder.
pub(crate) uploads: usize,
/// The items in Proton Drive move rather than copy.
pub(crate) moving: bool,
}
/// The drop hint for `plan` into the folder called `folder`. Each line is one
/// sentence, so no translation is put together from pieces.
pub(crate) fn drop_preview(plan: DropPlan, folder: &str) -> String {
if plan.going == 0 && plan.uploads == 0 {
return gettext("Nothing here can go into this folder");
}
let mut lines = Vec::new();
if plan.going > 0 {
let n = plan.going as u64;
lines.push(if plan.moving {
// Translators: shown while dragging; {folder} is the folder the items would go to.
ngettext_f(
"Move {n} item to “{folder}”",
"Move {n} items to “{folder}”",
n,
&[("folder", folder)],
)
} else {
// Translators: shown while dragging; {folder} is the folder the items would go to.
ngettext_f(
"Copy {n} item to “{folder}”",
"Copy {n} items to “{folder}”",
n,
&[("folder", folder)],
)
});
}
if plan.uploads > 0 {
// Translators: shown while dragging; {folder} is the folder the files would go to.
lines.push(ngettext_f(
"Upload {n} item to “{folder}”",
"Upload {n} items to “{folder}”",
plan.uploads as u64,
&[("folder", folder)],
));
}
if plan.skipped > 0 {
lines.push(ngettext_f(
"{n} item can't go there and is left out",
"{n} items can't go there and are left out",
plan.skipped as u64,
&[],
));
}
lines.join("\n")
}
/// The action to answer a drag over the browser with: always a copy. Rows
/// dragged from this app offer nothing else (see [`attach_drag`]), and an
/// outside drag is never answered with a move, which would have the source
@@ -3564,9 +3716,9 @@ fn listing_summary(files: usize, folders: usize, file_bytes: u64) -> String {
#[cfg(test)]
mod tests {
use super::{
MoveTarget, badge_for, copy_target_allowed, drop_targets, hit_location, icon_base_for,
listing_summary, move_target_allowed, show_thumbnail_build_progress, sort_entries,
split_dropped,
DropPlan, MoveTarget, badge_for, copy_target_allowed, drop_preview, drop_targets,
hit_location, icon_base_for, listing_summary, move_target_allowed,
show_thumbnail_build_progress, sort_entries, split_dropped,
};
use std::path::{Path, PathBuf};
@@ -3645,6 +3797,40 @@ mod tests {
["Docs/a.pdf", "Photos/b.jpg"]
);
}
/// The hint says the same thing the drop will do: a move for rows from
/// this app, a copy for files from a file manager browsing the mount, and
/// how many are left out.
#[test]
fn the_drop_hint_names_the_action_and_what_is_left_out() {
let plan = |going, skipped, uploads, moving| DropPlan {
going,
skipped,
uploads,
moving,
};
assert_eq!(
drop_preview(plan(3, 0, 0, true), "Receipts"),
"Move 3 items to “Receipts”"
);
assert_eq!(
drop_preview(plan(1, 0, 0, false), "Receipts"),
"Copy 1 item to “Receipts”"
);
assert_eq!(
drop_preview(plan(0, 0, 2, false), "Receipts"),
"Upload 2 items to “Receipts”"
);
// A selection that holds the folder itself: the rest still moves.
assert_eq!(
drop_preview(plan(2, 1, 0, true), "Receipts"),
"Move 2 items to “Receipts”\n1 item can't go there and is left out"
);
assert_eq!(
drop_preview(plan(0, 2, 0, true), "Receipts"),
"Nothing here can go into this folder"
);
}
use pdfs_core::config::{FileSort, FilesView};
use pdfs_core::control::{DirEntry, SyncIssue, ThumbnailBuildStatus};
+44 -10
View File
@@ -1007,20 +1007,54 @@ pub(crate) fn prompt_remove_sync_folder(
dialog.set_response_appearance("remove", adw::ResponseAppearance::Destructive);
dialog.set_default_response(Some("cancel"));
dialog.set_close_response("cancel");
let ui = ui.clone();
dialog.connect_response(None, move |_, resp| {
if resp == "remove" {
run_devices_mutation(
&ui,
Request::RemoveSyncFolder {
id,
delete_remote: !attached && delete_remote.is_active(),
// With the switch on, the button does more than stop syncing, so it says
// so: the heading, the button and the outcome all name the deletion.
delete_remote.connect_active_notify({
let dialog = dialog.clone();
move |row| {
let deleting = row.is_active();
dialog.set_heading(Some(&if deleting {
gettext("Stop Syncing and Delete Folder?")
} else {
gettext("Stop Syncing Folder?")
}));
dialog.set_response_label(
"remove",
&if deleting {
gettext("Stop Syncing and Delete")
} else {
gettext("Stop Syncing")
},
&gettext("Stopped syncing folder"),
&gettext("Couldn't stop syncing the folder"),
);
}
});
let ui = ui.clone();
dialog.connect_response(None, move |_, resp| {
if resp != "remove" {
return;
}
let deleting = !attached && delete_remote.is_active();
let (done, failed) = if deleting {
(
gettext("Stopped syncing and moved the folder in Proton Drive to the trash"),
gettext("Couldn't stop syncing and delete the folder"),
)
} else {
(
gettext("Stopped syncing folder"),
gettext("Couldn't stop syncing the folder"),
)
};
run_devices_mutation(
&ui,
Request::RemoveSyncFolder {
id,
delete_remote: deleting,
},
&done,
&failed,
);
});
dialog.present(win.as_ref());
}
+192 -19
View File
@@ -310,6 +310,7 @@ fn duplicate_review(
// Every copy's toggle, by set, so the button can count what goes.
let toggles: Rc<RefCell<SetToggles>> = Rc::new(RefCell::new(Vec::new()));
let mut kept_labels: Vec<gtk4::Label> = Vec::new();
for set in sets {
let Some(first) = set.first() else {
continue;
@@ -333,20 +334,29 @@ fn duplicate_review(
};
let heading = gtk4::Label::builder().label(title).xalign(0.0).build();
heading.add_css_class("heading");
// How many of the set stay, in the heading's line: a set wider than
// the window hides some of its cards, and this still says what goes.
let kept = gtk4::Label::builder().xalign(1.0).hexpand(true).build();
kept.add_css_class("dim-label");
let header = gtk4::Box::new(gtk4::Orientation::Horizontal, 12);
header.append(&heading);
header.append(&kept);
let row = gtk4::Box::new(gtk4::Orientation::Horizontal, 12);
let mut set_toggles = Vec::new();
for (index, photo) in set.into_iter().enumerate() {
let (card, keep) = copy_card(ui, &photo, index == 0 || finder == Finder::Similar);
let (card, keep) =
copy_card(ui, &photo, index == 0 || finder == Finder::Similar, finder);
row.append(&card);
set_toggles.push((photo, keep));
}
kept_labels.push(kept);
let row_scroll = gtk4::ScrolledWindow::builder()
.vscrollbar_policy(gtk4::PolicyType::Never)
.propagate_natural_height(true)
.child(&row)
.build();
let section = gtk4::Box::new(gtk4::Orientation::Vertical, 6);
section.append(&heading);
section.append(&header);
section.append(&row_scroll);
content.append(&section);
toggles.borrow_mut().push(set_toggles);
@@ -356,22 +366,14 @@ fn duplicate_review(
let toggles = toggles.clone();
let trash = trash.clone();
move || {
let n = doomed(&toggles.borrow()).len();
trash.set_label(&match finder {
Finder::Exact => ngettext_f(
"Move {n} copy to Trash",
"Move {n} copies to Trash",
n as u64,
&[],
),
Finder::Similar => ngettext_f(
"Move {n} photo to Trash",
"Move {n} photos to Trash",
n as u64,
&[],
),
});
let toggles = toggles.borrow();
let (n, files) = doomed_counts(&toggles, finder);
trash.set_label(&trash_label(finder, n, files));
trash.set_sensitive(n > 0);
for (set, label) in toggles.iter().zip(&kept_labels) {
let keep = set.iter().filter(|(_, t)| t.is_active()).count();
label.set_label(&kept_label(keep, set.len()));
}
}
};
sync();
@@ -421,6 +423,94 @@ fn duplicate_review(
(scroll.upcast(), handler)
}
/// How many photos go to Trash, and how many files that is. An exact copy is
/// one file. A similar photo takes its whole shot, a RAW and its JPEG
/// together.
fn doomed_counts(toggles: &SetToggles, finder: Finder) -> (usize, usize) {
let doomed: Vec<&PhotoItem> = toggles
.iter()
.flatten()
.filter(|(_, keep)| !keep.is_active())
.map(|(photo, _)| photo)
.collect();
(doomed.len(), files_of(doomed.into_iter(), finder))
}
/// How many files trashing `photos` moves.
fn files_of<'a>(photos: impl Iterator<Item = &'a PhotoItem>, finder: Finder) -> usize {
photos
.map(|photo| match finder {
Finder::Exact => 1,
Finder::Similar => photo.group_size.max(1) as usize,
})
.sum()
}
/// The footer button: what it moves, in photos and, when that differs, files.
fn trash_label(finder: Finder, photos: usize, files: usize) -> String {
match finder {
Finder::Exact => ngettext_f(
"Move {n} copy to Trash",
"Move {n} copies to Trash",
photos as u64,
&[],
),
Finder::Similar if files > photos => ngettext_f(
// Translators: {n} is a number of photos, {files} how many files they are stored as (always more than {n}).
"Move {n} photo ({files} files) to Trash",
"Move {n} photos ({files} files) to Trash",
photos as u64,
&[("files", &files.to_string())],
),
Finder::Similar => ngettext_f(
"Move {n} photo to Trash",
"Move {n} photos to Trash",
photos as u64,
&[],
),
}
}
/// How many of a set stay.
fn kept_label(kept: usize, of: usize) -> String {
ngettext_f(
// Translators: {n} photos of a set of {total} stay; the rest go to Trash.
"Keeping {n} of {total}",
"Keeping {n} of {total}",
kept as u64,
&[("total", &of.to_string())],
)
}
/// What a card's photo is stored as, when that is more than one file.
fn stored_as(photo: &PhotoItem) -> Option<String> {
let n = photo.group_size;
(n > 1).then(|| {
if photo.has_raw {
ngettext_f(
// Translators: a shot stored as a camera RAW file and others, such as its JPEG.
"RAW + {n} more file",
"RAW + {n} more files",
u64::from(n - 1),
&[],
)
} else {
ngettext_f("{n} file", "{n} files", u64::from(n), &[])
}
})
}
/// What happens to a card's photo, under its toggle.
fn outcome_label(keep: bool) -> String {
if keep {
// Translators: a photo in the duplicates review that stays.
pgettext("duplicates", "Kept")
} else {
// Translators: a photo in the duplicates review that goes to Trash.
pgettext("duplicates", "Moves to Trash")
}
}
/// The uids of every copy not kept.
fn doomed(toggles: &SetToggles) -> Vec<String> {
toggles
@@ -431,8 +521,14 @@ fn doomed(toggles: &SetToggles) -> Vec<String> {
.collect()
}
/// One copy: its thumbnail, its file name, and whether to keep it.
fn copy_card(ui: &Rc<Ui>, photo: &PhotoItem, keep: bool) -> (gtk4::Box, gtk4::ToggleButton) {
/// One copy: its thumbnail, its file name, and whether to keep it. A similar
/// shot stored as several files says so, since all of them go with it.
fn copy_card(
ui: &Rc<Ui>,
photo: &PhotoItem,
keep: bool,
finder: Finder,
) -> (gtk4::Box, gtk4::ToggleButton) {
let picture = gtk4::Picture::builder()
.content_fit(gtk4::ContentFit::Cover)
.can_shrink(true)
@@ -464,11 +560,88 @@ fn copy_card(ui: &Rc<Ui>, photo: &PhotoItem, keep: bool) -> (gtk4::Box, gtk4::To
.active(keep)
.build();
toggle.add_css_class("pill");
let outcome = gtk4::Label::builder().label(outcome_label(keep)).build();
outcome.add_css_class("caption");
if !keep {
outcome.add_css_class("error");
}
let outcome_t = outcome.clone();
toggle.connect_toggled(move |toggle| {
outcome_t.set_label(&outcome_label(toggle.is_active()));
if toggle.is_active() {
outcome_t.remove_css_class("error");
} else {
outcome_t.add_css_class("error");
}
});
let card = gtk4::Box::new(gtk4::Orientation::Vertical, 6);
card.set_size_request(COPY_SIZE, -1);
card.append(&overlay);
card.append(&label);
if finder == Finder::Similar
&& let Some(files) = stored_as(photo)
{
let files = gtk4::Label::builder().label(files).build();
files.add_css_class("caption");
files.add_css_class("dim-label");
card.append(&files);
}
card.append(&toggle);
card.append(&outcome);
(card, toggle)
}
#[cfg(test)]
mod tests {
use super::*;
fn shot(files: u32, has_raw: bool) -> PhotoItem {
PhotoItem {
uid: "vol~shot".into(),
capture_time: 0,
thumb_path: None,
name: None,
ratio: None,
no_thumb: false,
kind: PhotoKind::Photo,
favorite: false,
group_size: files,
has_raw,
place_id: None,
}
}
/// One RAW+JPEG shot marked and another kept: the footer counts both.
#[test]
fn the_footer_counts_files_when_a_shot_is_several() {
let raw_jpeg = shot(2, true);
let files = files_of([&raw_jpeg].into_iter(), Finder::Similar);
assert_eq!(files, 2);
assert_eq!(
trash_label(Finder::Similar, 1, files),
"Move 1 photo (2 files) to Trash"
);
assert_eq!(trash_label(Finder::Similar, 2, 2), "Move 2 photos to Trash");
}
/// An exact copy is one file, whatever its shot holds.
#[test]
fn an_exact_copy_is_one_file() {
let raw_jpeg = shot(2, true);
assert_eq!(files_of([&raw_jpeg].into_iter(), Finder::Exact), 1);
assert_eq!(trash_label(Finder::Exact, 1, 1), "Move 1 copy to Trash");
}
#[test]
fn a_card_names_what_its_shot_is_stored_as() {
assert_eq!(stored_as(&shot(1, false)), None);
assert_eq!(stored_as(&shot(0, false)), None);
assert_eq!(
stored_as(&shot(2, true)).as_deref(),
Some("RAW + 1 more file")
);
assert_eq!(stored_as(&shot(3, false)).as_deref(), Some("3 files"));
assert_eq!(kept_label(1, 4), "Keeping 1 of 4");
}
}
+154 -22
View File
@@ -671,15 +671,34 @@ fn repaint_queue(ui: &Rc<Ui>, items: &[PendingOpInfo]) {
.map(|now| now.to_unix())
.unwrap_or_default();
let mut rows = queue.rows.borrow_mut();
for op in items.into_iter().take(QUEUE_ROWS_SHOWN) {
let row = queue_row(ui, op, now);
for op in items.iter().copied().take(QUEUE_ROWS_SHOWN) {
let scope = discard_scope(op, &items);
let row = queue_row(ui, op, &scope, now);
queue.group.add(&row);
rows.push(row);
}
}
fn queue_row(ui: &Rc<Ui>, op: &PendingOpInfo, now: i64) -> adw::ActionRow {
let (icon, action) = match op.kind.as_str() {
/// The queued ops a discard of `op` drops: every op on the same node, `op`
/// first and the rest in queue order. The daemon drops them all, since each
/// was made on top of the one before.
fn discard_scope<'a>(op: &'a PendingOpInfo, all: &[&'a PendingOpInfo]) -> Vec<&'a PendingOpInfo> {
let mut scope = vec![op];
if !op.node.is_empty() {
let mut others: Vec<&PendingOpInfo> = all
.iter()
.copied()
.filter(|other| other.node == op.node && other.id != op.id)
.collect();
others.sort_by_key(|other| other.id);
scope.extend(others);
}
scope
}
/// A queued op's kind, as an icon and a short action.
fn op_action(kind: &str) -> (&'static str, String) {
match kind {
"revision" => ("pdfs-upload-symbolic", gettext("Upload changes")),
"create" => ("pdfs-upload-symbolic", gettext("Upload new file")),
"mkdir" => ("folder-new-symbolic", gettext("Create folder")),
@@ -687,7 +706,28 @@ fn queue_row(ui: &Rc<Ui>, op: &PendingOpInfo, now: i64) -> adw::ActionRow {
"trash" => ("user-trash-symbolic", gettext("Move to trash")),
// Translators: a queued change of an unknown kind.
_ => ("pdfs-sync-symbolic", pgettext("noun", "Change")),
};
}
}
/// What the discard dialog needs to say about one discard.
#[derive(Clone)]
struct DiscardScope {
id: i64,
path: String,
/// The op whose content can be exported, if any of them carries some.
exportable: Option<i64>,
local_only: bool,
/// Each dropped op's action, the asked one first.
actions: Vec<String>,
}
fn queue_row(
ui: &Rc<Ui>,
op: &PendingOpInfo,
scope: &[&PendingOpInfo],
now: i64,
) -> adw::ActionRow {
let (icon, action) = op_action(&op.kind);
let state = match (op.parked, op.next_attempt_at) {
(true, _) => gettext("waiting for the app writing it to finish"),
(false, Some(at)) if at > now && op.attempts > 0 => {
@@ -769,10 +809,15 @@ fn queue_row(ui: &Rc<Ui>, op: &PendingOpInfo, now: i64) -> adw::ActionRow {
.build();
discard.add_css_class("flat");
let ui = ui.clone();
let id = op.id;
let path = op.path.clone();
let exportable = op.exportable;
discard.connect_clicked(move |_| prompt_discard_queued(&ui, id, &path, exportable));
let scope = DiscardScope {
id: op.id,
path: op.path.clone(),
// The newest content is the version the user would lose.
exportable: scope.iter().rev().find(|op| op.exportable).map(|op| op.id),
local_only: op.local_only,
actions: scope.iter().map(|op| op_action(&op.kind).1).collect(),
};
discard.connect_clicked(move |_| prompt_discard_queued(&ui, &scope));
row.add_suffix(&discard);
}
row
@@ -844,35 +889,77 @@ fn prompt_export_queued(ui: &Rc<Ui>, id: i64, name: &str) {
}
/// Confirm, then have the daemon drop a queued change and undo it here.
fn prompt_discard_queued(ui: &Rc<Ui>, id: i64, path: &str, exportable: bool) {
let body = if exportable {
// Translators: {path} is the file whose queued change would be dropped.
///
/// The daemon drops every change queued on the same file or folder, so the
/// dialog lists them all, says whether the item goes back to how Proton Drive
/// has it or disappears from this computer, and offers the export first.
fn prompt_discard_queued(ui: &Rc<Ui>, scope: &DiscardScope) {
let name = Path::new(&scope.path)
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| scope.path.clone());
let count = scope.actions.len() as u64;
let outcome = if scope.local_only {
// Translators: {path} is a file or folder made on this computer that never reached Proton Drive.
gettext_f(
"Your changes to {path} are undone here and never reach Proton Drive. Export the file first to keep your version.",
&[("path", path)],
"{path} was made on this computer and is not on Proton Drive yet. Discarding removes it from this computer.",
&[("path", &scope.path)],
)
} else {
// Translators: {path} is the file or folder whose queued change would be dropped.
// Translators: {path} is a file or folder that is on Proton Drive.
gettext_f(
"The change to {path} is undone here and never reaches Proton Drive.",
&[("path", path)],
"{path} goes back to how it is on Proton Drive, and the changes below are undone here.",
&[("path", &scope.path)],
)
};
let body = if scope.exportable.is_some() {
format!(
"{outcome}\n\n{}",
gettext("Export the file first to keep your version.")
)
} else {
outcome
};
let dialog = adw::AlertDialog::builder()
.heading(gettext("Discard Change?"))
// Translators: {name} is the file or folder name, {n} how many queued changes a discard drops.
.heading(ngettext_f(
"Discard the Change to “{name}”?",
"Discard {n} Changes to “{name}”?",
count,
&[("name", &name)],
))
.body(body)
.build();
let list = gtk4::ListBox::builder()
.selection_mode(gtk4::SelectionMode::None)
.css_classes(["boxed-list"])
.build();
for action in &scope.actions {
list.append(&adw::ActionRow::builder().title(action.as_str()).build());
}
dialog.set_extra_child(Some(&list));
dialog.add_response("cancel", &gettext("Cancel"));
dialog.add_response("discard", &gettext("Discard"));
if scope.exportable.is_some() {
dialog.add_response("export", &gettext("Export My Version…"));
}
dialog.add_response(
"discard",
&ngettext_f("Discard Change", "Discard {n} Changes", count, &[]),
);
dialog.set_response_appearance("discard", adw::ResponseAppearance::Destructive);
dialog.set_default_response(Some("cancel"));
dialog.set_close_response("cancel");
let window = ui_window(ui);
let ui = ui.clone();
dialog.connect_response(None, move |_, resp| {
if resp == "discard" {
discard_queued(&ui, id);
let scope = scope.clone();
dialog.connect_response(None, move |_, resp| match resp {
"discard" => discard_queued(&ui, scope.id),
"export" => {
if let Some(id) = scope.exportable {
prompt_export_queued(&ui, id, &name);
}
}
_ => {}
});
dialog.present(window.as_ref());
}
@@ -1786,6 +1873,51 @@ pub(crate) fn location_subtitle(spec: &MountSpec) -> String {
mod tests {
use super::*;
fn queued(id: i64, kind: &str, node: &str) -> PendingOpInfo {
PendingOpInfo {
id,
kind: kind.into(),
path: "Docs/report.odt".into(),
attempts: 0,
last_error: None,
queued_at: 0,
next_attempt_at: None,
parked: false,
failing: true,
issue: None,
exportable: kind == "revision",
node: node.into(),
local_only: false,
}
}
#[test]
fn a_discard_names_every_change_queued_on_the_same_node() {
let rename = queued(9, "rename", "vol~a");
let edit = queued(4, "revision", "vol~a");
let other = queued(5, "revision", "vol~b");
let all = [&rename, &edit, &other];
let scope: Vec<i64> = discard_scope(&rename, &all)
.iter()
.map(|op| op.id)
.collect();
assert_eq!(
scope,
[9, 4],
"the asked change first, then the rest by age"
);
}
#[test]
fn a_discard_from_an_older_daemon_names_only_its_own_change() {
let rename = queued(9, "rename", "");
let edit = queued(4, "revision", "");
let all = [&rename, &edit];
assert_eq!(discard_scope(&rename, &all).len(), 1);
}
fn spec(kind: MountKind, mode: MountMode, mounted: bool) -> MountSpec {
MountSpec {
id: 1,
+69 -20
View File
@@ -682,32 +682,40 @@ pub(crate) fn sign_out(ui: &Rc<Ui>) {
let rx = spawn_request(ui.dirs.control_socket(), Request::Status);
let ui = ui.clone();
glib::spawn_future_local(async move {
// `None` when the service did not answer: then nobody knows whether
// changes are still waiting, which is not the same as none.
let queued = match rx.recv().await {
Ok(Ok(Response::Status {
pending_uploads,
pending_changes,
parked_uploads,
..
})) => pending_uploads + pending_changes + parked_uploads,
_ => 0,
})) => Some(pending_uploads + pending_changes + parked_uploads),
_ => None,
};
confirm_sign_out(&ui, queued);
});
}
fn confirm_sign_out(ui: &Rc<Ui>, queued: u64) {
fn confirm_sign_out(ui: &Rc<Ui>, queued: Option<u64>) {
let Some(window) = ui_window(ui) else { return };
let ui = ui.clone();
let mut body = gettext(
"Proton Drive will disconnect and stop syncing until you sign in again. Files already on this computer stay where they are.",
);
if queued > 0 {
let warning = ngettext_f(
let warning = match queued {
Some(0) => None,
Some(queued) => Some(ngettext_f(
"{n} change is not on Proton Drive yet. It stays on this computer and is sent after you sign in again.",
"{n} changes are not on Proton Drive yet. They stay on this computer and are sent after you sign in again.",
queued,
&[],
);
)),
None => Some(gettext(
"The Proton Drive service didn't answer, so it isn't known whether changes are still waiting to be sent. Any that are stay on this computer and are sent after you sign in again.",
)),
};
if let Some(warning) = warning {
body = format!("{warning}\n\n{body}");
}
confirm_destructive(
@@ -720,24 +728,65 @@ fn confirm_sign_out(ui: &Rc<Ui>, queued: u64) {
if let Some(galleries) = galleries {
galleries.reset();
}
// systemctl and the keyring both block, so run them on a worker.
let ui = ui.clone();
glib::spawn_future_local(async move {
let result = gio::spawn_blocking(|| {
service::disable_stop();
auth::logout().map(|_| ()).map_err(|e| e.to_string())
})
.await;
if let Ok(Err(e)) = result {
tracing::error!("logout failed: {e}");
}
*ui.session.borrow_mut() = None;
refresh(&ui);
});
sign_out_now(&ui);
},
);
}
/// Stop the service and forget the stored session, then say what happened.
///
/// Two parts can fail on their own. Proton may not confirm that the session
/// ended, which leaves it listed in the account's security settings until it
/// expires. Removing the sign-in from the keyring may fail, which leaves this
/// computer signed in at the next start. The first is a notice, the second
/// needs the user, so it stays on screen with a way to try again.
fn sign_out_now(ui: &Rc<Ui>) {
// systemctl and the keyring both block, so run them on a worker.
let ui = ui.clone();
glib::spawn_future_local(async move {
let result = gio::spawn_blocking(|| {
service::disable_stop();
auth::logout().map_err(|e| e.to_string())
})
.await
.unwrap_or_else(|_| Err("the sign-out worker stopped".into()));
*ui.session.borrow_mut() = None;
refresh(&ui);
match result {
Ok(true) => {}
Ok(false) => toast(
&ui,
&gettext(
"Signed out on this computer. Proton didn't confirm that the session ended; you can end it in your Proton account's security settings.",
),
),
Err(error) => {
tracing::error!("logout failed: {error}");
present_sign_out_failure(&ui, &error);
}
}
});
}
fn present_sign_out_failure(ui: &Rc<Ui>, error: &str) {
let dialog = adw::AlertDialog::builder()
.heading(gettext("Sign-In Still Saved"))
// Translators: {error} is the reason the keyring gave.
.body(gettext_f(
"Proton Drive stopped, but your sign-in couldn't be removed from this computer: {error}\n\nUntil it is removed, Proton Drive may sign in again at the next start. Unlock your keyring, then try again.",
&[("error", error)],
))
.build();
dialog.add_response("close", &gettext("Close"));
dialog.add_response("again", &gettext("Try Again"));
dialog.set_response_appearance("again", adw::ResponseAppearance::Suggested);
dialog.set_default_response(Some("again"));
dialog.set_close_response("close");
let ui_c = ui.clone();
dialog.connect_response(Some("again"), move |_, _| sign_out_now(&ui_c));
dialog.present(ui_window(ui).as_ref());
}
#[cfg(test)]
mod tests {
use super::login_error_message;
@@ -24,6 +24,9 @@ pub(crate) struct AppsPrefs {
prompt_terminal_row: adw::EntryRow,
limit_row: adw::SpinRow,
icons_row: adw::SwitchRow,
remember_row: adw::SwitchRow,
clear_row: adw::ActionRow,
clear_button: gtk4::Button,
}
/// The launcher modes in the order the combo row lists them.
@@ -102,6 +105,23 @@ pub(crate) fn build_apps_prefs() -> AppsPrefs {
.title(gettext("Show icons"))
.subtitle(gettext("When the launcher can show them"))
.build();
let remember_row = adw::SwitchRow::builder()
.title(gettext("Remember recent files"))
.subtitle(gettext(
"List what you opened before you type, and rank it higher in results. Off, the list is cleared.",
))
.build();
let clear_button = gtk4::Button::builder()
.label(gettext("Clear"))
.valign(gtk4::Align::Center)
.build();
let clear_row = adw::ActionRow::builder()
.title(gettext("Clear recent files"))
.subtitle(gettext(
"The search window forgets what it opened. Your files are not touched.",
))
.build();
clear_row.add_suffix(&clear_button);
let launcher = adw::PreferencesGroup::builder()
.title(gettext("Search Launcher"))
.description(gettext(
@@ -113,6 +133,8 @@ pub(crate) fn build_apps_prefs() -> AppsPrefs {
launcher.add(&prompt_terminal_row);
launcher.add(&limit_row);
launcher.add(&icons_row);
launcher.add(&remember_row);
launcher.add(&clear_row);
let page = adw::PreferencesPage::builder()
.title(gettext("Apps"))
@@ -133,6 +155,9 @@ pub(crate) fn build_apps_prefs() -> AppsPrefs {
prompt_terminal_row,
limit_row,
icons_row,
remember_row,
clear_row,
clear_button,
}
}
@@ -183,6 +208,7 @@ pub(crate) fn wire_apps_prefs(ui: &Rc<Ui>, widgets: AppsPrefs) {
.set_text(&format_command(prompt.terminal.as_deref().unwrap_or(&[])));
w.limit_row.set_value(prompt.resolved_menu_limit() as f64);
w.icons_row.set_active(prompt.resolved_menu_icons());
w.remember_row.set_active(prompt.resolved_remember_recent());
show_mode_rows(w, mode);
ui.status.settings_suppress.set(suppress);
@@ -239,6 +265,56 @@ pub(crate) fn wire_apps_prefs(ui: &Rc<Ui>, widgets: AppsPrefs) {
prompt_of(config).menu_icons = (!on).then_some(false)
});
});
let a = apps.clone();
w.remember_row.connect_active_notify(move |row| {
if a.ui.status.settings_suppress.get() {
return;
}
let on = row.is_active();
// The window clears the list itself the next time it opens; clearing
// here as well means nothing waits on disk until then.
if !on {
clear_history(&a);
}
save(&a, move |config| {
prompt_of(config).remember_recent = (!on).then_some(false)
});
});
let a = apps.clone();
w.clear_button.connect_clicked(move |_| {
if clear_history(&a) {
prefs_toast(&a.ui, &gettext("Recent files cleared"));
}
});
}
/// Delete the search window's history. It reads the file again each time it
/// opens. Says whether that worked.
fn clear_history(apps: &Rc<Apps>) -> bool {
match std::fs::remove_file(history_path(&apps.ui)) {
Ok(()) => true,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
Err(e) => {
prefs_toast(
&apps.ui,
&gettext_f(
"{what}: {detail}",
&[
("what", &gettext("Couldn't clear recent files")),
("detail", &e.to_string()),
],
),
);
false
}
}
}
/// Where the search window keeps what it opened (`hud/history.rs`).
fn history_path(ui: &Ui) -> std::path::PathBuf {
ui.dirs
.state_dir()
.join(pdfs_core::menu::PROMPT_HISTORY_FILE)
}
/// Show only the rows the chosen launcher mode uses.
@@ -247,6 +323,9 @@ fn show_mode_rows(w: &AppsPrefs, mode: PromptMode) {
w.icons_row.set_visible(mode == PromptMode::Dmenu);
w.prompt_terminal_row.set_visible(mode == PromptMode::Fzf);
w.limit_row.set_visible(mode != PromptMode::Gtk);
// Only the search window keeps a history.
w.remember_row.set_visible(mode == PromptMode::Gtk);
w.clear_row.set_visible(mode == PromptMode::Gtk);
}
/// The `open_with` section, created when absent.
+160 -32
View File
@@ -955,16 +955,36 @@ pub(crate) fn prompt_leave_shared(ui: &Rc<Ui>, entries: &[DirEntry]) {
dialog.set_default_response(Some("cancel"));
dialog.set_close_response("cancel");
let ui_c = ui.clone();
let uids: Vec<String> = entries.iter().map(|e| e.uid.clone()).collect();
let targets: Vec<(String, String)> = entries
.iter()
.map(|e| (e.name.clone(), e.uid.clone()))
.collect();
dialog.connect_response(Some("leave"), move |_, _| {
let count = uids.len();
let count = targets.len();
let items = targets
.iter()
.map(|(name, uid)| BatchItem {
name: name.clone(),
uid: uid.clone(),
request: |uid| Request::LeaveShared { uid },
})
.collect();
let text = BatchText {
failed: gettext_noop("Couldn't leave the shared item"),
partial: |went, total| {
ngettext_f(
"Left {went} of {n} Shared Item",
"Left {went} of {n} Shared Items",
total,
&[("went", &went.to_string())],
)
},
};
run_requests(
&ui_c,
uids.iter()
.map(|uid| Request::LeaveShared { uid: uid.clone() })
.collect(),
gettext_noop("Couldn't leave the shared item"),
move |ui| {
items,
text,
Rc::new(move |ui| {
load_shared(ui);
toast(
ui,
@@ -975,50 +995,158 @@ pub(crate) fn prompt_leave_shared(ui: &Rc<Ui>, entries: &[DirEntry]) {
&[],
),
);
},
}),
);
});
dialog.present(ui_window(ui).as_ref());
}
/// Send `requests` one after the other, stopping at the first failure, which
/// is reported under `failed` (an untranslated msgid). `done` runs once all
/// succeeded. After a failure the page on screen is reloaded instead, since
/// the requests before it went through.
pub(crate) fn run_requests(
ui: &Rc<Ui>,
requests: Vec<Request>,
failed: &'static str,
done: impl FnOnce(&Rc<Ui>) + 'static,
) {
/// What became of one request of a batch.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Outcome {
Done,
/// The service refused it, with this message.
Failed(String),
/// The service did not answer, so it may or may not have happened.
Unknown,
/// Not sent: the service had stopped answering before its turn.
NotTried,
}
/// One item of a batch: its name, as the summary lists it, and the uid its
/// request acts on. A retry sends the request again, so it is built from the
/// uid each time.
pub(crate) struct BatchItem {
pub(crate) name: String,
pub(crate) uid: String,
pub(crate) request: fn(String) -> Request,
}
/// What runs once every item of a batch went through. Kept for a retry.
pub(crate) type BatchDone = Rc<dyn Fn(&Rc<Ui>)>;
/// The texts a batch reports with.
#[derive(Clone, Copy)]
pub(crate) struct BatchText {
/// The failure title, an untranslated msgid.
pub(crate) failed: &'static str,
/// The heading of a batch that partly went through, from how many items
/// went through and how many there were.
pub(crate) partial: fn(u64, u64) -> String,
}
/// Send each request in turn. `done` runs once all succeeded.
///
/// A request the service refuses does not stop the others, since each item
/// stands on its own. Once the service stops answering, the rest are not
/// sent. When any item did not go through, the page on screen is reloaded,
/// so a lost reply shows its real state, and a summary names every item that
/// did not, with a way to try those again. A batch of one reports as before,
/// with a toast.
pub(crate) fn run_requests(ui: &Rc<Ui>, items: Vec<BatchItem>, text: BatchText, done: BatchDone) {
ui.busy_begin();
let ui = ui.clone();
let socket = ui.dirs.control_socket();
glib::spawn_future_local(async move {
for req in requests {
let result = spawn_request(socket.clone(), req).recv().await;
let error = match result {
Ok(Ok(Response::Ok { .. })) => continue,
Ok(Ok(Response::Error { message, kind })) => Some((message, kind)),
_ => None,
};
ui.busy_end();
reload_current_page(&ui);
match error {
Some((message, kind)) => toast_failure(&ui, &gettext(failed), &message, kind),
let mut outcomes = Vec::with_capacity(items.len());
let mut first_error = None;
let mut answering = true;
for item in &items {
if !answering {
outcomes.push(Outcome::NotTried);
continue;
}
let result = spawn_request(socket.clone(), (item.request)(item.uid.clone()))
.recv()
.await;
outcomes.push(match result {
Ok(Ok(Response::Ok { .. })) => Outcome::Done,
Ok(Ok(Response::Error { message, kind })) => {
first_error.get_or_insert((message.clone(), kind));
Outcome::Failed(message)
}
_ => {
answering = false;
Outcome::Unknown
}
});
}
ui.busy_end();
if outcomes.iter().all(|outcome| *outcome == Outcome::Done) {
done(&ui);
return;
}
reload_current_page(&ui);
if items.len() == 1 {
match first_error {
Some((message, kind)) => toast_failure(&ui, &gettext(text.failed), &message, kind),
None => toast_error(
&ui,
&gettext(failed),
&gettext(text.failed),
&gettext("The Proton Drive service didn't respond."),
),
}
return;
}
ui.busy_end();
done(&ui);
present_batch_summary(&ui, items, outcomes, text, done);
});
}
/// Name every item of a batch that did not go through, and offer to try
/// them again.
fn present_batch_summary(
ui: &Rc<Ui>,
items: Vec<BatchItem>,
outcomes: Vec<Outcome>,
text: BatchText,
done: BatchDone,
) {
let total = items.len() as u64;
let went = outcomes.iter().filter(|o| **o == Outcome::Done).count() as u64;
let list = gtk4::ListBox::builder()
.selection_mode(gtk4::SelectionMode::None)
.css_classes(["boxed-list"])
.build();
let mut again = Vec::new();
for (item, outcome) in items.into_iter().zip(&outcomes) {
let state = match outcome {
Outcome::Done => continue,
// Translators: {error} is the reason the service gave.
Outcome::Failed(error) => gettext_f("Refused: {error}", &[("error", error)]),
Outcome::Unknown => {
gettext("The service didn't answer. The page shows whether it went through.")
}
Outcome::NotTried => gettext("Not tried yet"),
};
list.append(
&adw::ActionRow::builder()
.title(glib::markup_escape_text(&item.name).as_str())
.subtitle(glib::markup_escape_text(&state).as_str())
.subtitle_lines(3)
.build(),
);
again.push(item);
}
let dialog = adw::AlertDialog::builder()
.heading((text.partial)(went, total))
.body(gettext("These items did not go through:"))
.extra_child(&list)
.build();
dialog.add_response("close", &gettext("Close"));
dialog.add_response("again", &gettext("Try Again"));
dialog.set_response_appearance("again", adw::ResponseAppearance::Suggested);
dialog.set_default_response(Some("close"));
dialog.set_close_response("close");
let ui_c = ui.clone();
let again = RefCell::new(Some(again));
dialog.connect_response(Some("again"), move |_, _| {
if let Some(items) = again.borrow_mut().take() {
run_requests(&ui_c, items, text, done.clone());
}
});
dialog.present(ui_window(ui).as_ref());
}
/// Confirm, then remove a saved link. The shared item itself is untouched.
pub(crate) fn prompt_remove_bookmark(ui: &Rc<Ui>, token: &str, name: &str) {
let win = ui_window(ui);
+39 -11
View File
@@ -466,6 +466,16 @@ fn rebind_rows(ui: &Rc<Ui>, uids: &HashSet<String>) {
/// node by uid, so every shared item can be managed from here.
fn shared_by_me_menu(ui: &Rc<Ui>, entry: &DirEntry) -> ActionMenu {
let mut menu = ActionMenu::new();
let now = glib::real_time() / 1_000_000;
let link = find_item(&ui.shared_by_me.items, &entry.uid).and_then(|item| item.link);
// An expired link has nothing to copy or open; what it needs is a new
// expiry, which the Share dialog's link settings give it.
if link.as_ref().is_some_and(|link| link_expired(link, now)) {
let (ui_c, entry_c) = (ui.clone(), entry.clone());
menu.item(&gettext("Edit Link Expiry…"), move || {
open_share_dialog(&ui_c, &entry_c)
});
}
let (ui_c, entry_c) = (ui.clone(), entry.clone());
menu.item(&gettext("Manage Access…"), move || {
open_share_dialog(&ui_c, &entry_c)
@@ -481,9 +491,7 @@ fn shared_by_me_menu(ui: &Rc<Ui>, entry: &DirEntry) -> ActionMenu {
show_in_my_files(&ui_c, &entry_c)
});
}
let now = glib::real_time() / 1_000_000;
let url = find_item(&ui.shared_by_me.items, &entry.uid)
.and_then(|item| item.link)
let url = link
.filter(|link| !link_expired(link, now))
.and_then(|link| link.url);
if let Some(url) = url {
@@ -564,21 +572,41 @@ pub(crate) fn prompt_stop_sharing(ui: &Rc<Ui>, entries: &[DirEntry]) {
&[],
),
};
let uids: Vec<String> = entries.iter().map(|e| e.uid.clone()).collect();
let targets: Vec<(String, String)> = entries
.iter()
.map(|e| (e.name.clone(), e.uid.clone()))
.collect();
dialog.connect_response(Some("stop"), move |_, _| {
let done = done.clone();
let stopped = uids.clone();
let stopped: Vec<String> = targets.iter().map(|(_, uid)| uid.clone()).collect();
let items = targets
.iter()
.map(|(name, uid)| BatchItem {
name: name.clone(),
uid: uid.clone(),
request: |uid| Request::StopSharingByUid { uid },
})
.collect();
let text = BatchText {
failed: gettext_noop("Couldn't stop sharing"),
partial: |went, total| {
ngettext_f(
"Stopped Sharing {went} of {n} Item",
"Stopped Sharing {went} of {n} Items",
total,
&[("went", &went.to_string())],
)
},
};
run_requests(
&ui_c,
uids.iter()
.map(|uid| Request::StopSharingByUid { uid: uid.clone() })
.collect(),
gettext_noop("Couldn't stop sharing"),
move |ui| {
items,
text,
Rc::new(move |ui| {
forget_shared_by_me(ui, &stopped);
reload_listing(ui);
toast(ui, &done);
},
}),
);
});
dialog.present(ui_window(ui).as_ref());
+166 -21
View File
@@ -14,6 +14,10 @@ pub(crate) struct TrashState {
/// The bottom bar acting on the selection; revealed while anything is selected.
pub(crate) selection_bar: gtk4::Revealer,
pub(crate) selection_label: gtk4::Label,
/// The bar's actions, labelled for what they act on (see
/// [`sync_trash_selection`]).
pub(crate) restore_selected: gtk4::Button,
pub(crate) delete_selected: gtk4::Button,
/// Runs the loads; the rows stay up while one runs.
pub(crate) loader: Rc<Loader>,
/// Back, the breadcrumb and the search entry over the list.
@@ -312,11 +316,13 @@ fn trash_entry_menu(ui: &Rc<Ui>, entry: &DirEntry) -> ActionMenu {
&& !in_trash(ui, &entry.uid)
&& let Some(folder) = outer_folder(ui)
{
// Went to the trash with the folder, so only the folder goes back.
// Went to the trash with the folder, so only the folder goes back,
// and only the folder can be deleted for good.
menu.labelled_section(&gettext("Deleted with its folder"));
let ui_c = ui.clone();
let label = gettext_f(
// Translators: {name} is a folder name.
"Restore “{name}”",
"Restore Folder “{name}”",
&[("name", &folder.name)],
);
menu.item(&label, move || {
@@ -324,8 +330,16 @@ fn trash_entry_menu(ui: &Rc<Ui>, entry: &DirEntry) -> ActionMenu {
});
return menu;
}
let restore = match location_key(&entry.uid) {
// A location row stands for everything deleted from that folder.
Some(_) => {
let n = trashed_targets(ui, std::slice::from_ref(entry)).len() as u64;
ngettext_f("Restore {n} Item", "Restore {n} Items", n, &[])
}
None => pgettext("verb", "Restore"),
};
let (ui_c, entry_c) = (ui.clone(), entry.clone());
menu.item(&pgettext("verb", "Restore"), move || {
menu.item(&restore, move || {
restore_entries(&ui_c, std::slice::from_ref(&entry_c))
});
menu.section();
@@ -374,18 +388,52 @@ fn trash_background_menu(ui: &Rc<Ui>) -> ActionMenu {
menu
}
/// Reveal the selection bar while anything is selected and count what is.
/// Reveal the selection bar while anything is selected, count what is, and
/// label its actions for what they act on, which is not always the selection.
fn sync_trash_selection(ui: &Rc<Ui>) {
let count = ui.trash.files.selection.selection().size() as usize;
ui.trash.selection_bar.set_reveal_child(count > 0);
if count > 0 {
ui.trash.selection_label.set_label(&ngettext_f(
"{n} item selected",
"{n} items selected",
count as u64,
&[],
));
if count == 0 {
return;
}
ui.trash.selection_label.set_label(&ngettext_f(
"{n} item selected",
"{n} items selected",
count as u64,
&[],
));
let selected = ui.trash.files.selected();
let targets = {
let all = ui.trash.all.borrow();
resolve_targets(&all, outer_folder(ui).as_ref(), &selected)
};
let (restore, deletable) = match (&targets.inherited, targets.own.len()) {
(Some(folder), 0) => (
// Translators: {name} is a folder name.
gettext_f("Restore Folder “{name}”", &[("name", &folder.name)]),
false,
),
(inherited, own) if inherited.is_some() || own != count => {
let n = (own + usize::from(inherited.is_some())) as u64;
(
ngettext_f("Restore {n} Item", "Restore {n} Items", n, &[]),
own > 0,
)
}
_ => (pgettext("verb", "Restore"), true),
};
ui.trash.restore_selected.set_label(&restore);
let delete = &ui.trash.delete_selected;
delete.set_sensitive(deletable);
delete.set_tooltip_text(
(!deletable)
.then(|| {
gettext(
"These went to the trash with their folder. Only the whole folder can be deleted permanently, from the top of the trash.",
)
})
.as_deref(),
);
}
/// Fetch the trash listing and repaint the page.
@@ -727,14 +775,24 @@ fn outer_folder(ui: &Ui) -> Option<DirEntry> {
ui.trash.all.borrow().iter().find(|e| e.uid == uid).cloned()
}
/// What acting on `entries` acts on: a location row stands for everything
/// deleted from that folder, and an item that went with its folder for the
/// folder. Each node once.
fn trashed_targets(ui: &Ui, entries: &[DirEntry]) -> Vec<DirEntry> {
let all = ui.trash.all.borrow();
let outer = outer_folder(ui);
/// What acting on a selection acts on.
#[derive(Debug, Default, PartialEq)]
struct Targets {
/// The trashed items themselves: each selected item that is in the trash
/// on its own, and for a location row everything deleted from that folder.
own: Vec<DirEntry>,
/// The open trashed folder, when the selection holds items that went to
/// the trash with it. They can only go back with the folder, so a restore
/// restores it. A permanent deletion does not: deleting the folder for
/// good takes an explicit choice of the folder itself.
inherited: Option<DirEntry>,
}
/// Resolve `entries` against the trash listing `all`, inside `outer` when a
/// trashed folder is open. Each node once.
fn resolve_targets(all: &[DirEntry], outer: Option<&DirEntry>, entries: &[DirEntry]) -> Targets {
let mut seen = HashSet::new();
let mut targets = Vec::new();
let mut targets = Targets::default();
for entry in entries {
let picked: Vec<DirEntry> = if let Some(key) = location_key(&entry.uid) {
all.iter()
@@ -744,17 +802,38 @@ fn trashed_targets(ui: &Ui, entries: &[DirEntry]) -> Vec<DirEntry> {
} else if all.iter().any(|e| e.uid == entry.uid) {
vec![entry.clone()]
} else {
outer.clone().into_iter().collect()
if targets.inherited.is_none() {
targets.inherited = outer.cloned();
}
Vec::new()
};
for target in picked {
if seen.insert(target.uid.clone()) {
targets.push(target);
targets.own.push(target);
}
}
}
// The folder may be selected too, at a level that shows it.
if let Some(folder) = &targets.inherited
&& seen.contains(&folder.uid)
{
targets.inherited = None;
}
targets
}
/// What a restore of `entries` restores: the items, and the open folder for
/// those that went to the trash with it.
fn trashed_targets(ui: &Ui, entries: &[DirEntry]) -> Vec<DirEntry> {
let targets = {
let all = ui.trash.all.borrow();
resolve_targets(&all, outer_folder(ui).as_ref(), entries)
};
let mut restore = targets.own;
restore.extend(targets.inherited);
restore
}
/// Rebuild the path bar for `nav`: "Trash", then each place down to the
/// current one. Hidden at the top, where there is nowhere to go back to.
fn repaint_trash_crumb(ui: &Rc<Ui>) {
@@ -850,9 +929,26 @@ fn common_origin(entries: &[DirEntry]) -> Option<String> {
}
/// Confirm, then permanently delete trashed entries. Irreversible, so it asks.
///
/// Only what was selected is deleted. An item that went to the trash with its
/// folder cannot be deleted on its own, and is not taken to mean its folder.
pub(crate) fn prompt_delete_forever(ui: &Rc<Ui>, entries: &[DirEntry]) {
let entries = &trashed_targets(ui, entries)[..];
let targets = {
let all = ui.trash.all.borrow();
resolve_targets(&all, outer_folder(ui).as_ref(), entries)
};
let entries = &targets.own[..];
if entries.is_empty() {
if let Some(folder) = targets.inherited {
toast(
ui,
// Translators: {name} is a folder name.
&gettext_f(
"These went to the trash with “{name}”. Delete the whole folder from the top of the trash.",
&[("name", &folder.name)],
),
);
}
return;
}
let win = ui_window(ui);
@@ -973,6 +1069,55 @@ mod tests {
}
}
fn uids(entries: &[DirEntry]) -> Vec<&str> {
entries.iter().map(|e| e.uid.as_str()).collect()
}
#[test]
fn an_item_deleted_with_its_folder_restores_the_folder_and_deletes_nothing() {
let projects = DirEntry {
is_dir: true,
..trashed("projects", 5, 1, Some("Work"))
};
let all = vec![projects.clone()];
// Two siblings inside the open trashed folder: neither is in the trash
// on its own.
let a = trashed("a.txt", 5, 1, None);
let b = trashed("b.txt", 5, 1, None);
let targets = resolve_targets(&all, Some(&projects), &[a, b]);
assert!(targets.own.is_empty(), "nothing of its own to delete");
assert_eq!(targets.inherited, Some(projects));
}
#[test]
fn a_location_row_stands_for_every_item_deleted_from_that_folder() {
let all = vec![
trashed("one", 3, 1, Some("Work")),
trashed("two", 2, 1, Some("Work")),
trashed("other", 1, 1, Some("Home")),
inside("nested", "one"),
];
let row = location_row(Some("Work".into()));
let targets = resolve_targets(&all, None, &[row]);
assert_eq!(uids(&targets.own), ["one", "two"]);
assert_eq!(targets.inherited, None);
}
#[test]
fn a_selected_item_counts_once_and_stays_itself() {
let all = vec![trashed("one", 3, 1, Some("Work"))];
let one = all[0].clone();
let targets = resolve_targets(&all, None, &[one.clone(), one]);
assert_eq!(uids(&targets.own), ["one"]);
assert_eq!(targets.inherited, None);
}
#[test]
fn locations_group_top_level_items_by_folder() {
let all = vec![
+431 -111
View File
@@ -669,30 +669,70 @@ pub(crate) fn repaint_share_link(state: &Rc<ShareDialog>, link: Option<&PublicLi
match link {
Some(link) => {
let now = glib::real_time() / 1_000_000;
let url = link.url.clone().unwrap_or_default();
let role = role_label(&link.role).unwrap_or_else(|| capitalize(&link.role));
// Translators: {role} is the link's role, such as "Viewer".
let mut subtitle = gettext_f("Anyone with the link ({role})", &[("role", &role)]);
if link.has_password {
subtitle.push_str(" · ");
subtitle.push_str(&gettext("password-protected"));
}
if let Some(expires) = link.expires {
subtitle.push_str(" · ");
subtitle.push_str(&link_expiry_label(expires, glib::real_time() / 1_000_000));
}
let expired = link.expires.is_some_and(|at| at <= now);
// The row says how the link works, not where it is: the address
// is a key, and someone showing their screen should not hand it
// out by opening the dialog.
let row = adw::ActionRow::builder()
.title(if url.is_empty() {
gettext("Public link")
} else {
url.clone()
})
.subtitle(&subtitle)
.title(link_row_title(link.role == "editor", expired))
.subtitle(link_policy(
link.role == "editor",
link.has_password,
link.expires,
now,
))
.use_markup(false)
.build();
row.add_css_class("property");
let (settings, expiry_drop) = link_settings_row(state, link);
// The address, hidden until asked for. Every repaint hides it again.
let address = adw::ActionRow::builder()
.title(&url)
.title_selectable(true)
.use_markup(false)
.visible(false)
.build();
address.add_css_class("monospace");
if expired {
// An expired link gives nothing to copy: whoever gets it sees an
// error. What the owner can do is give it a new expiry.
let edit = gtk4::Button::builder()
.label(gettext("Edit Expiry"))
.valign(gtk4::Align::Center)
.build();
let (settings, expiry_drop) = (settings.clone(), expiry_drop.clone());
edit.connect_clicked(move |_| {
settings.set_expanded(true);
expiry_drop.grab_focus();
});
row.add_suffix(&edit);
} else if !url.is_empty() {
let reveal = gtk4::ToggleButton::builder()
.icon_name("view-reveal-symbolic")
.tooltip_text(gettext("Show link address"))
.valign(gtk4::Align::Center)
.build();
reveal.add_css_class("flat");
let address_t = address.clone();
reveal.connect_toggled(move |btn| {
address_t.set_visible(btn.is_active());
btn.set_icon_name(if btn.is_active() {
"view-conceal-symbolic"
} else {
"view-reveal-symbolic"
});
btn.set_tooltip_text(Some(&if btn.is_active() {
gettext("Hide link address")
} else {
gettext("Show link address")
}));
});
row.add_suffix(&reveal);
if !url.is_empty() {
let copy = gtk4::Button::builder()
.icon_name("edit-copy-symbolic")
.tooltip_text(gettext("Copy link"))
@@ -744,8 +784,8 @@ pub(crate) fn repaint_share_link(state: &Rc<ShareDialog>, link: Option<&PublicLi
state.link_group.add(&row);
rows.push(row.upcast());
let settings = link_settings_row(state, link);
state.link_group.add(&address);
rows.push(address.upcast());
state.link_group.add(&settings);
rows.push(settings.upcast());
}
@@ -757,11 +797,45 @@ pub(crate) fn repaint_share_link(state: &Rc<ShareDialog>, link: Option<&PublicLi
let expiry_names: Vec<String> =
LINK_EXPIRY.iter().map(|(name, _)| gettext(name)).collect();
let (expiry_row, expiry_drop) = dropdown_row(&gettext("Expires"), &expiry_names, 0);
// How the link will work, right above the button that makes it.
let now = glib::real_time() / 1_000_000;
let summary = adw::ActionRow::builder()
.title(gettext("The new link"))
.subtitle(link_policy(false, false, None, now))
.use_markup(false)
.build();
summary.add_css_class("property");
let create = group_button(&gettext("Create Public Link"));
// Enter in the password field creates the link.
let btn = create.clone();
pw_row.connect_entry_activated(move |_| btn.emit_clicked());
let refresh: Rc<dyn Fn()> = {
let (summary, role_drop, pw_row, expiry_drop) = (
summary.clone(),
role_drop.clone(),
pw_row.clone(),
expiry_drop.clone(),
);
Rc::new(move || {
let now = glib::real_time() / 1_000_000;
summary.set_subtitle(&link_policy(
role_drop.selected() == 1,
!pw_row.text().is_empty(),
link_expiry_at(expiry_drop.selected(), now),
now,
));
})
};
let r = refresh.clone();
role_drop.connect_selected_notify(move |_| r());
let r = refresh.clone();
pw_row.connect_changed(move |_| r());
expiry_drop.connect_selected_notify(move |_| refresh());
// Enter in the password field moves on to the expiry, which comes
// next: creating the link there would skip it.
let next = expiry_drop.clone();
pw_row.connect_entry_activated(move |_| {
next.grab_focus();
});
let state_c = Rc::downgrade(state);
let pw_for = pw_row.clone();
@@ -787,124 +861,265 @@ pub(crate) fn repaint_share_link(state: &Rc<ShareDialog>, link: Option<&PublicLi
state.link_group.add(&role_row);
state.link_group.add(&pw_row);
state.link_group.add(&expiry_row);
state.link_group.add(&summary);
state.link_group.add(&create);
rows.push(role_row.upcast());
rows.push(pw_row.upcast());
rows.push(expiry_row.upcast());
rows.push(summary.upcast());
rows.push(create.upcast());
}
}
*state.link_rows.borrow_mut() = rows;
}
/// The settings of an existing link, collapsed under one row. Each control
/// applies at once, the way a member's role does. While a change is on its way
/// the whole row is insensitive: the daemon fills in what a change keeps from
/// the link as it stands, so two changes in flight could undo each other.
fn link_settings_row(state: &Rc<ShareDialog>, link: &PublicLinkInfo) -> adw::ExpanderRow {
/// What the owner has chosen in an existing link's settings and not saved yet.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct LinkDraft {
/// Anyone with the link can edit.
pub(crate) editor: bool,
/// The chosen entry of [`link_expiry_choices`].
pub(crate) expiry: u32,
/// The link asks for a password.
pub(crate) protect: bool,
/// A new password; empty keeps the one the link has.
pub(crate) password: String,
}
impl LinkDraft {
/// The draft that changes nothing about `link`.
pub(crate) fn of(link: &PublicLinkInfo) -> Self {
Self {
editor: link.role == "editor",
expiry: 0,
protect: link.has_password,
password: String::new(),
}
}
}
/// The one update that saving a [`LinkDraft`] sends.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct LinkEdit {
pub(crate) role: Option<String>,
pub(crate) password: LinkChange<String>,
pub(crate) expires: LinkChange<i64>,
}
/// What saving `draft` would ask of `link`: `Ok(None)` when it changes
/// nothing, `Err(())` when it cannot be saved yet. That is a password asked for
/// on a link that has none, with no password typed.
pub(crate) fn link_edit(
link: &PublicLinkInfo,
draft: &LinkDraft,
now: i64,
) -> Result<Option<LinkEdit>, ()> {
let role = (draft.editor != (link.role == "editor"))
.then(|| if draft.editor { "editor" } else { "viewer" }.to_string());
let password = match (draft.protect, draft.password.is_empty(), link.has_password) {
(false, _, true) => LinkChange::Remove,
(false, _, false) | (true, true, true) => LinkChange::Keep,
(true, true, false) => return Err(()),
(true, false, _) => LinkChange::Set(draft.password.clone()),
};
let expires = link_expiry_change(draft.expiry, link.expires, now);
let edit = LinkEdit {
role,
password,
expires,
};
let unchanged = edit.role.is_none()
&& edit.password == LinkChange::Keep
&& edit.expires == LinkChange::Keep;
Ok((!unchanged).then_some(edit))
}
/// The title of an existing link's row: what kind of link it is, never its
/// address.
pub(crate) fn link_row_title(editor: bool, expired: bool) -> String {
match (expired, editor) {
(true, _) => gettext("Expired public link"),
(false, true) => gettext("Public editor link"),
(false, false) => gettext("Public viewer link"),
}
}
/// How a link works, in one line: who can do what, the password, the expiry.
pub(crate) fn link_policy(editor: bool, password: bool, expires: Option<i64>, now: i64) -> String {
let mut parts = vec![if editor {
gettext("Anyone with the link can edit")
} else {
gettext("Anyone with the link can view")
}];
parts.push(if password {
gettext("password-protected")
} else {
gettext("no password")
});
parts.push(match expires {
Some(at) => link_expiry_label(at, now),
None => gettext("never expires"),
});
parts.join(" · ")
}
/// How `link` works once `edit` is saved.
fn link_policy_after(
link: &PublicLinkInfo,
draft: &LinkDraft,
edit: &LinkEdit,
now: i64,
) -> String {
let expires = match edit.expires {
LinkChange::Keep => link.expires,
LinkChange::Remove => None,
LinkChange::Set(at) => Some(at),
};
link_policy(draft.editor, draft.protect, expires, now)
}
/// The settings of an existing link, collapsed under one row. Nothing reaches
/// Drive until Save: an owner turning a viewer link into an editor link with a
/// password must not hand out editing before the password is set, so every
/// change goes in one update. Closing the dialog drops what was not saved.
/// Returns the row and its Expires dropdown, which an expired link's Edit
/// Expiry button opens the row on.
fn link_settings_row(
state: &Rc<ShareDialog>,
link: &PublicLinkInfo,
) -> (adw::ExpanderRow, gtk4::DropDown) {
let now = glib::real_time() / 1_000_000;
let expander = adw::ExpanderRow::builder()
.title(gettext("Link settings"))
.subtitle(gettext(
"Change who can edit, the password or the expiry. The link stays the same.",
"Change who can edit, the password or the expiry, then save. The link stays the same.",
))
.build();
let draft = Rc::new(RefCell::new(LinkDraft::of(link)));
let selected_role = u32::from(link.role == "editor");
let (role_row, role_drop) = dropdown_row(&gettext("Link role"), &link_roles(), selected_role);
let (state_w, expander_w, id) = (Rc::downgrade(state), expander.clone(), link.id.clone());
role_drop.connect_selected_notify(move |d| {
let Some(state) = state_w.upgrade() else {
return;
};
let role = if d.selected() == 1 {
"editor"
} else {
"viewer"
};
let request = state.target.update_link(
id.clone(),
Some(role.into()),
LinkChange::Keep,
LinkChange::Keep,
);
share_dialog_update_link(&state, request, &expander_w);
});
let (role_row, role_drop) = dropdown_row(
&gettext("Link role"),
&link_roles(),
u32::from(draft.borrow().editor),
);
expander.add_row(&role_row);
let current = link.expires;
let (expiry_row, expiry_drop) =
dropdown_row(&gettext("Expires"), &link_expiry_choices(current, now), 0);
let (state_w, expander_w, id) = (Rc::downgrade(state), expander.clone(), link.id.clone());
expiry_drop.connect_selected_notify(move |d| {
let Some(state) = state_w.upgrade() else {
return;
};
let expires = link_expiry_change(d.selected(), current, glib::real_time() / 1_000_000);
if expires == LinkChange::Keep {
return;
}
let request = state
.target
.update_link(id.clone(), None, LinkChange::Keep, expires);
share_dialog_update_link(&state, request, &expander_w);
});
let (expiry_row, expiry_drop) = dropdown_row(
&gettext("Expires"),
&link_expiry_choices(link.expires, now),
0,
);
expander.add_row(&expiry_row);
let protect = adw::SwitchRow::builder()
.title(gettext("Require a password"))
.active(link.has_password)
.build();
expander.add_row(&protect);
let pw_row = adw::PasswordEntryRow::builder()
.title(if link.has_password {
gettext("New password")
gettext("New password (optional)")
} else {
gettext("Add a password")
gettext("Password")
})
.show_apply_button(true)
.visible(link.has_password)
.build();
let (state_w, expander_w, id) = (Rc::downgrade(state), expander.clone(), link.id.clone());
pw_row.connect_apply(move |row| {
expander.add_row(&pw_row);
// What the link will do once saved, right above the one action that sends it.
let summary = adw::ActionRow::builder()
.title(gettext("No changes"))
.use_markup(false)
.build();
summary.add_css_class("property");
let save = gtk4::Button::builder()
.label(gettext("Save Link Settings"))
.valign(gtk4::Align::Center)
.sensitive(false)
.build();
save.add_css_class("suggested-action");
summary.add_suffix(&save);
expander.add_row(&summary);
let refresh: Rc<dyn Fn()> = {
let (draft, link, summary, save) =
(draft.clone(), link.clone(), summary.clone(), save.clone());
Rc::new(move || {
let draft = draft.borrow();
let now = glib::real_time() / 1_000_000;
match link_edit(&link, &draft, now) {
Ok(None) => {
summary.set_title(&gettext("No changes"));
summary.set_subtitle("");
save.set_sensitive(false);
}
Ok(Some(edit)) => {
summary.set_title(&gettext("After saving"));
summary.set_subtitle(&link_policy_after(&link, &draft, &edit, now));
save.set_sensitive(true);
}
Err(()) => {
summary.set_title(&gettext("Enter a password to save"));
summary.set_subtitle("");
save.set_sensitive(false);
}
}
})
};
{
let (draft, refresh) = (draft.clone(), refresh.clone());
role_drop.connect_selected_notify(move |d| {
draft.borrow_mut().editor = d.selected() == 1;
refresh();
});
}
{
let (draft, refresh) = (draft.clone(), refresh.clone());
expiry_drop.connect_selected_notify(move |d| {
draft.borrow_mut().expiry = d.selected();
refresh();
});
}
{
let (draft, refresh, pw_row) = (draft.clone(), refresh.clone(), pw_row.clone());
protect.connect_active_notify(move |s| {
draft.borrow_mut().protect = s.is_active();
pw_row.set_visible(s.is_active());
if s.is_active() {
pw_row.grab_focus();
}
refresh();
});
}
{
let (draft, refresh) = (draft.clone(), refresh.clone());
pw_row.connect_changed(move |row| {
draft.borrow_mut().password = row.text().to_string();
refresh();
});
}
{
let save = save.clone();
pw_row.connect_entry_activated(move |_| {
if save.is_sensitive() {
save.emit_clicked();
}
});
}
let (state_w, expander_w, link) = (Rc::downgrade(state), expander.clone(), link.clone());
save.connect_clicked(move |_| {
let Some(state) = state_w.upgrade() else {
return;
};
let password = row.text().to_string();
if password.is_empty() {
let Ok(Some(edit)) = link_edit(&link, &draft.borrow(), glib::real_time() / 1_000_000)
else {
return;
}
let request = state.target.update_link(
id.clone(),
None,
LinkChange::Set(password),
LinkChange::Keep,
);
};
let request =
state
.target
.update_link(link.id.clone(), edit.role, edit.password, edit.expires);
share_dialog_update_link(&state, request, &expander_w);
});
expander.add_row(&pw_row);
if link.has_password {
let remove = gtk4::Button::builder()
.label(gettext("Remove"))
.valign(gtk4::Align::Center)
.build();
remove.add_css_class("flat");
let row = adw::ActionRow::builder()
.title(gettext("Remove the password"))
.subtitle(gettext(
"Anyone with the link can open it without a password.",
))
.build();
row.add_suffix(&remove);
let (state_w, expander_w, id) = (Rc::downgrade(state), expander.clone(), link.id.clone());
remove.connect_clicked(move |_| {
let Some(state) = state_w.upgrade() else {
return;
};
let request =
state
.target
.update_link(id.clone(), None, LinkChange::Remove, LinkChange::Keep);
share_dialog_update_link(&state, request, &expander_w);
});
expander.add_row(&row);
}
expander
(expander, expiry_drop)
}
/// Send a link change, then reload the dialog: on success to show the link as
@@ -1084,6 +1299,111 @@ mod tests {
);
}
fn viewer_link(has_password: bool, expires: Option<i64>) -> PublicLinkInfo {
PublicLinkInfo {
id: "link".into(),
url: Some("https://drive.proton.me/urls/X#y".into()),
role: "viewer".into(),
expires,
has_password,
created: 0,
}
}
#[test]
fn an_untouched_draft_sends_nothing() {
let link = viewer_link(true, Some(2_000_000_000));
assert_eq!(link_edit(&link, &LinkDraft::of(&link), 1_000), Ok(None));
}
/// Editor and a password go in one update, so link holders never get edit
/// access without the password.
#[test]
fn editor_and_a_password_are_saved_together() {
let link = viewer_link(false, None);
let draft = LinkDraft {
editor: true,
protect: true,
password: "hunter2".into(),
..LinkDraft::of(&link)
};
assert_eq!(
link_edit(&link, &draft, 1_000),
Ok(Some(LinkEdit {
role: Some("editor".into()),
password: LinkChange::Set("hunter2".into()),
expires: LinkChange::Keep,
}))
);
}
#[test]
fn asking_for_a_password_without_one_cannot_be_saved() {
let link = viewer_link(false, None);
let draft = LinkDraft {
editor: true,
protect: true,
..LinkDraft::of(&link)
};
assert_eq!(link_edit(&link, &draft, 1_000), Err(()));
}
#[test]
fn a_kept_password_stays_and_a_dropped_one_goes() {
let link = viewer_link(true, None);
let keep = LinkDraft {
expiry: 2,
..LinkDraft::of(&link)
};
assert_eq!(
link_edit(&link, &keep, 1_000).unwrap().unwrap().password,
LinkChange::Keep
);
let drop = LinkDraft {
protect: false,
password: "typed then switched off".into(),
..LinkDraft::of(&link)
};
assert_eq!(
link_edit(&link, &drop, 1_000),
Ok(Some(LinkEdit {
role: None,
password: LinkChange::Remove,
expires: LinkChange::Keep,
}))
);
}
#[test]
fn the_summary_shows_the_policy_after_saving() {
let link = viewer_link(true, Some(2_000_000_000));
let draft = LinkDraft {
editor: true,
expiry: 1,
protect: false,
..LinkDraft::of(&link)
};
let edit = link_edit(&link, &draft, 1_000).unwrap().unwrap();
assert_eq!(
link_policy_after(&link, &draft, &edit, 1_000),
"Anyone with the link can edit · no password · never expires"
);
}
/// The row names the kind of link and never its address.
#[test]
fn a_link_row_is_titled_by_what_the_link_does() {
assert_eq!(link_row_title(false, false), "Public viewer link");
assert_eq!(link_row_title(true, false), "Public editor link");
assert_eq!(link_row_title(true, true), "Expired public link");
let link = viewer_link(false, Some(10));
assert!(!link_row_title(false, false).contains(link.url.as_deref().unwrap()));
assert_eq!(
link_policy(false, false, link.expires, 20),
"Anyone with the link can view · no password · expired"
);
}
#[test]
fn past_expiry_reads_expired() {
assert_eq!(link_expiry_label(10, 20), "expired");
+213 -20
View File
@@ -5,6 +5,13 @@
//! searching a file opened often and lately gets a bonus on top of its match
//! score (see [`frecency_bonus`]).
//!
//! A Drive file is remembered with the account it was opened from, and only
//! that account's files are shown: after a switch to another account, the
//! first one's names and paths stay out of the window. Local files are shown
//! whoever is signed in. Preferences can turn the history off or clear it; the
//! window loads the file again each time it opens, so a clear made in the app
//! takes effect at once.
//!
//! One writer thread owns the file: it loads it, applies every recorded visit
//! in order and writes the result back atomically. A visit recorded before the
//! first load finished simply waits in the channel, so it is merged into the
@@ -42,6 +49,19 @@ pub(crate) struct Visit {
/// When the file was last opened, in epoch seconds.
pub(crate) last: i64,
pub(crate) count: u32,
/// The account a Drive file was opened from. `None` for a local file, and
/// for a Drive file remembered before accounts were recorded, which is
/// never shown since nobody can say whose it is.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) account: Option<String>,
}
/// Whether `visit` may be shown while `account` is signed in.
fn visible(visit: &Visit, account: Option<&str>) -> bool {
match visit.hit {
Hit::Local(_) => true,
Hit::Drive(_) => account.is_some() && visit.account.as_deref() == account,
}
}
/// The history bonus for a file opened `count` times, the last time
@@ -55,9 +75,16 @@ pub(crate) fn frecency_bonus(count: u32, age_secs: i64) -> i64 {
/// Count one more visit of `hit` at `now`, newest first, and keep at most
/// [`MAX_VISITS`]. The stored hit is replaced, so its size, date and sync
/// state are the ones from the latest search.
fn record(visits: &mut Vec<Visit>, hit: Hit, now: i64) {
fn record(visits: &mut Vec<Visit>, hit: Hit, now: i64, account: Option<String>) {
let key = hit.key();
let count = match visits.iter().position(|visit| visit.hit.key() == key) {
let account = match hit {
Hit::Local(_) => None,
Hit::Drive(_) => account,
};
let count = match visits
.iter()
.position(|visit| visit.hit.key() == key && visit.account == account)
{
Some(at) => visits.remove(at).count.saturating_add(1),
None => 1,
};
@@ -67,6 +94,7 @@ fn record(visits: &mut Vec<Visit>, hit: Hit, now: i64) {
hit,
last: now,
count,
account,
},
);
visits.truncate(MAX_VISITS);
@@ -107,9 +135,19 @@ fn save(path: &Path, visits: &[Visit]) -> std::io::Result<()> {
std::fs::rename(&tmp, path)
}
/// Delete the history file. Used by the window when the history is turned off,
/// and by the app's Clear Recent Files.
pub(crate) fn clear(path: &Path) -> std::io::Result<()> {
std::fs::remove_file(path)
}
enum Command {
Record(Hit, i64),
Record(Hit, i64, Option<String>),
Prune,
/// Read the file again: the app may have cleared it.
Reload,
/// Forget everything, on disk too.
Clear,
}
/// The writer thread's loop: load, then apply commands until the launcher
@@ -123,11 +161,29 @@ fn serve(path: &Path, commands: &async_channel::Receiver<Command>, publish: impl
}
while let Ok(command) = commands.recv_blocking() {
let changed = match command {
Command::Record(hit, now) => {
record(&mut visits, hit, now);
Command::Record(hit, now, account) => {
record(&mut visits, hit, now, account);
true
}
Command::Prune => prune(&mut visits),
Command::Reload => {
visits = load(path);
publish(visits.clone());
false
}
Command::Clear => {
if let Err(e) = clear(path)
&& e.kind() != std::io::ErrorKind::NotFound
{
tracing::warn!("cannot remove {}: {e}", path.display());
}
let had = !visits.is_empty();
visits.clear();
if had {
publish(Vec::new());
}
false
}
};
if changed {
if let Err(e) = save(path, &visits) {
@@ -142,6 +198,10 @@ fn serve(path: &Path, commands: &async_channel::Receiver<Command>, publish: impl
pub(crate) struct History {
visits: Rc<RefCell<Vec<Visit>>>,
commands: async_channel::Sender<Command>,
/// Who is signed in, as the service last said; `None` until it has.
account: RefCell<Option<String>>,
/// Whether to remember anything, as Preferences last said.
remember: std::cell::Cell<bool>,
}
impl History {
@@ -169,12 +229,38 @@ impl History {
changed();
}
});
Self { visits, commands }
Self {
visits,
commands,
account: RefCell::new(None),
remember: std::cell::Cell::new(true),
}
}
/// Who is signed in now. Drive files opened by anyone else stay hidden.
pub(crate) fn set_account(&self, account: Option<String>) {
*self.account.borrow_mut() = account;
}
/// Apply Preferences as the window opens: read the file again, since the
/// app may have cleared it, or clear it when the history is turned off.
pub(crate) fn refresh(&self, remember: bool) {
self.remember.set(remember);
let command = if remember {
Command::Reload
} else {
Command::Clear
};
let _ = self.commands.try_send(command);
}
/// Remember that `hit` was opened just now.
pub(crate) fn record(&self, hit: Hit) {
let _ = self.commands.try_send(Command::Record(hit, now()));
if !self.remember.get() {
return;
}
let account = self.account.borrow().clone();
let _ = self.commands.try_send(Command::Record(hit, now(), account));
}
/// Forget local files that were deleted since they were opened.
@@ -184,9 +270,11 @@ impl History {
/// The most recently opened files, newest first.
pub(crate) fn recent(&self, limit: usize) -> Vec<Hit> {
let account = self.account.borrow();
self.visits
.borrow()
.iter()
.filter(|visit| visible(visit, account.as_deref()))
.take(limit)
.map(|visit| visit.hit.clone())
.collect()
@@ -195,9 +283,11 @@ impl History {
/// The frecency bonus of every remembered file, by [`Hit::key`].
pub(crate) fn bonuses(&self) -> HashMap<(bool, String), i64> {
let now = now();
let account = self.account.borrow();
self.visits
.borrow()
.iter()
.filter(|visit| visible(visit, account.as_deref()))
.map(|visit| {
(
visit.hit.key(),
@@ -220,6 +310,8 @@ mod tests {
use pdfs_core::control::{LocalHit, SearchHit};
const DAY: i64 = 86_400;
/// The account the tests open Drive files from.
const A: &str = "a@proton.me";
fn drive(name: &str) -> Hit {
Hit::Drive(SearchHit {
@@ -266,9 +358,9 @@ mod tests {
#[test]
fn a_repeat_visit_moves_the_file_to_the_top_and_counts_it() {
let mut visits = Vec::new();
record(&mut visits, drive("a.pdf"), 10);
record(&mut visits, drive("b.pdf"), 20);
record(&mut visits, drive("a.pdf"), 30);
record(&mut visits, drive("a.pdf"), 10, Some(A.into()));
record(&mut visits, drive("b.pdf"), 20, Some(A.into()));
record(&mut visits, drive("a.pdf"), 30, Some(A.into()));
assert_eq!(visits.len(), 2);
assert_eq!(visits[0].hit.name(), "a.pdf");
assert_eq!((visits[0].count, visits[0].last), (2, 30));
@@ -279,7 +371,7 @@ mod tests {
fn the_history_keeps_the_newest_fifty_files() {
let mut visits = Vec::new();
for n in 0..60 {
record(&mut visits, drive(&format!("{n}.pdf")), n);
record(&mut visits, drive(&format!("{n}.pdf")), n, Some(A.into()));
}
assert_eq!(visits.len(), MAX_VISITS);
assert_eq!(visits[0].hit.name(), "59.pdf");
@@ -291,8 +383,8 @@ mod tests {
let dir = scratch_dir("round-trip");
let path = dir.join("prompt-history.json");
let mut visits = Vec::new();
record(&mut visits, drive("a.pdf"), 10);
record(&mut visits, drive("a.pdf"), 20);
record(&mut visits, drive("a.pdf"), 10, Some(A.into()));
record(&mut visits, drive("a.pdf"), 20, Some(A.into()));
save(&path, &visits).unwrap();
let loaded = load(&path);
@@ -308,17 +400,17 @@ mod tests {
let dir = scratch_dir("merge");
let path = dir.join("prompt-history.json");
let mut stored = Vec::new();
record(&mut stored, drive("old.pdf"), 10);
record(&mut stored, drive("old.pdf"), 20);
record(&mut stored, drive("old.pdf"), 10, Some(A.into()));
record(&mut stored, drive("old.pdf"), 20, Some(A.into()));
save(&path, &stored).unwrap();
// Both visits are queued before the writer has read the file.
let (commands, inbox) = async_channel::unbounded();
commands
.send_blocking(Command::Record(drive("old.pdf"), 30))
.send_blocking(Command::Record(drive("old.pdf"), 30, Some(A.into())))
.unwrap();
commands
.send_blocking(Command::Record(drive("new.pdf"), 40))
.send_blocking(Command::Record(drive("new.pdf"), 40, Some(A.into())))
.unwrap();
drop(commands);
@@ -351,13 +443,114 @@ mod tests {
})
};
let mut visits = Vec::new();
record(&mut visits, local(&kept), 1);
record(&mut visits, local(&dir.join("gone.txt")), 2);
record(&mut visits, drive("remote.pdf"), 3);
record(&mut visits, local(&kept), 1, Some(A.into()));
record(&mut visits, local(&dir.join("gone.txt")), 2, Some(A.into()));
record(&mut visits, drive("remote.pdf"), 3, Some(A.into()));
assert!(prune(&mut visits));
let names: Vec<&str> = visits.iter().map(|visit| visit.hit.name()).collect();
assert_eq!(names, ["remote.pdf", "kept.txt"]);
std::fs::remove_dir_all(dir).unwrap();
}
/// After a switch to account B, account A's Drive files are not shown and
/// give no ranking bonus. Local files stay.
#[test]
fn only_the_signed_in_accounts_drive_files_are_shown() {
let mut visits = Vec::new();
record(&mut visits, drive("a-secret.pdf"), 1, Some(A.into()));
record(
&mut visits,
drive("b-notes.pdf"),
2,
Some("b@proton.me".into()),
);
let local = Hit::Local(LocalHit {
name: "here.txt".into(),
path: "/home/me/here.txt".into(),
is_dir: false,
size: 1,
modified: 1,
score: 0,
});
record(&mut visits, local, 3, Some(A.into()));
assert_eq!(
visits[0].account, None,
"a local file belongs to no account"
);
let shown = |account: Option<&str>| -> Vec<&str> {
visits
.iter()
.filter(|visit| visible(visit, account))
.map(|visit| visit.hit.name())
.collect()
};
assert_eq!(shown(Some("b@proton.me")), ["here.txt", "b-notes.pdf"]);
assert_eq!(shown(Some(A)), ["here.txt", "a-secret.pdf"]);
// Before the service has said who is signed in, no Drive file shows.
assert_eq!(shown(None), ["here.txt"]);
}
/// A Drive file remembered before accounts were recorded has no owner, so
/// it is never shown.
#[test]
fn a_drive_file_from_before_accounts_were_recorded_stays_hidden() {
let old: Vec<Visit> = serde_json::from_value(
serde_json::json!([{"hit": drive("old.pdf"), "last": 1, "count": 1}]),
)
.unwrap();
assert!(!visible(&old[0], Some(A)));
}
#[test]
fn clearing_forgets_everything_on_disk_too() {
let dir = scratch_dir("clear");
let path = dir.join("prompt-history.json");
let mut stored = Vec::new();
record(&mut stored, drive("old.pdf"), 10, Some(A.into()));
save(&path, &stored).unwrap();
let (commands, inbox) = async_channel::unbounded();
commands.send_blocking(Command::Clear).unwrap();
drop(commands);
let published = RefCell::new(Vec::new());
serve(&path, &inbox, |visits| published.borrow_mut().push(visits));
assert!(published.borrow().last().unwrap().is_empty());
assert!(!path.exists());
std::fs::remove_dir_all(dir).unwrap();
}
/// The app clears the file while the window is hidden; the window reads
/// it again when it opens and shows nothing.
#[test]
fn a_reload_picks_up_a_clear_made_elsewhere() {
let dir = scratch_dir("reload");
let path = dir.join("prompt-history.json");
let mut stored = Vec::new();
record(&mut stored, drive("old.pdf"), 10, Some(A.into()));
save(&path, &stored).unwrap();
let (commands, inbox) = async_channel::unbounded();
let published = std::sync::Mutex::new(Vec::new());
std::thread::scope(|scope| {
scope.spawn(|| {
serve(&path, &inbox, |visits| {
published.lock().unwrap().push(visits)
})
});
// Let the first load happen, then clear behind the writer's back.
while published.lock().unwrap().is_empty() {
std::thread::yield_now();
}
clear(&path).unwrap();
commands.send_blocking(Command::Reload).unwrap();
drop(commands);
});
let published = published.into_inner().unwrap();
assert_eq!(published.first().unwrap().len(), 1);
assert!(published.last().unwrap().is_empty());
std::fs::remove_dir_all(dir).unwrap();
}
}
+22 -8
View File
@@ -286,13 +286,16 @@ pub(crate) fn build_window(app: &adw::Application) -> Option<Rc<Ui>> {
thumbs: Thumbs::new(socket.clone()),
// A visit recorded elsewhere, or the first load finishing, adds
// to the recent list the user may be looking at.
history: History::start(dirs.state_dir().join("prompt-history.json"), move || {
if let Some(ui) = weak.upgrade()
&& ui.showing_suggestions()
{
ui.render();
}
}),
history: History::start(
dirs.state_dir().join(pdfs_core::menu::PROMPT_HISTORY_FILE),
move || {
if let Some(ui) = weak.upgrade()
&& ui.showing_suggestions()
{
ui.render();
}
},
),
socket,
mountpoint: RefCell::new(dirs.default_mountpoint()),
opener: RefCell::new(dirs.load_config().resolved_open_with()),
@@ -536,6 +539,8 @@ impl Ui {
let config = dirs.load_config();
set_proton_theme(config.proton_theme.unwrap_or(false));
*self.opener.borrow_mut() = config.resolved_open_with();
self.history
.refresh(config.resolved_prompt().resolved_remember_recent());
}
self.history.prune();
// Supersede replies from the previous showing before clearing the
@@ -581,13 +586,22 @@ impl Ui {
let ui = self.clone();
glib::spawn_future_local(async move {
match rx.recv().await {
Ok(Ok(Response::Status { mountpoint, .. })) => {
Ok(Ok(Response::Status {
mountpoint,
username,
..
})) => {
// Recent Drive files are shown only to the account that
// opened them; asked again each time the window opens.
ui.history
.set_account((!username.is_empty()).then_some(username));
*ui.mountpoint.borrow_mut() = PathBuf::from(mountpoint);
ui.entry.set_sensitive(true);
ui.stack.set_visible_child_name("results");
ui.load_suggestions();
}
_ => {
ui.history.set_account(None);
ui.entry.set_sensitive(false);
ui.hint.set_label(&gettext("Proton Drive isn't running"));
ui.stack.set_visible_child_name("offline");
+58 -11
View File
@@ -28,6 +28,7 @@ use pdfs_core::control::{
use pdfs_core::service;
mod i18n;
mod tray_icons;
use i18n::{gettext, gettext_f, ngettext_f};
/// How long the tray lets a burst of events arrive before it repaints. Progress
@@ -54,17 +55,19 @@ enum Phase {
}
impl Phase {
/// A stock symbolic icon for the phase. Stock names follow the panel's
/// theme and colour, and need nothing installed beside the binary.
/// The tray's own symbolic icon for the phase ([`tray_icons`]). Symbolic
/// icons take the panel's text colour.
fn icon(self) -> &'static str {
match self {
Phase::Synced => "folder-remote-symbolic",
Phase::Syncing => "view-refresh-symbolic",
Phase::Paused => "media-playback-pause-symbolic",
Phase::Offline => "network-offline-symbolic",
Phase::Attention => "dialog-warning-symbolic",
Phase::SessionExpired => "dialog-password-symbolic",
Phase::Disconnected | Phase::SignedOut => "network-offline-symbolic",
Phase::Synced => "io.narl.proton-drive-linux-tray-synced-symbolic",
Phase::Syncing => "io.narl.proton-drive-linux-tray-syncing-symbolic",
Phase::Paused => "io.narl.proton-drive-linux-tray-paused-symbolic",
Phase::Offline => "io.narl.proton-drive-linux-tray-offline-symbolic",
Phase::Attention => "io.narl.proton-drive-linux-tray-attention-symbolic",
Phase::SessionExpired => "io.narl.proton-drive-linux-tray-session-expired-symbolic",
Phase::Disconnected | Phase::SignedOut => {
"io.narl.proton-drive-linux-tray-disconnected-symbolic"
}
}
}
}
@@ -154,6 +157,9 @@ fn sync_line(items: &[TransferItem], jobs: &[JobItem]) -> String {
struct DriveTray {
state: DriveState,
socket: PathBuf,
/// Where [`tray_icons::install`] put the icons, or empty when it could
/// not, which leaves the panel to the installed theme.
icon_theme_path: String,
}
/// Ask the daemon for its status, falling back to the stored session so the
@@ -422,6 +428,10 @@ impl Tray for DriveTray {
self.state.phase.icon().into()
}
fn icon_theme_path(&self) -> String {
self.icon_theme_path.clone()
}
fn attention_icon_name(&self) -> String {
self.icon_name()
}
@@ -608,9 +618,18 @@ fn main() -> Result<()> {
let socket = dirs.control_socket();
let default_mountpoint = dirs.default_mountpoint();
let icons = dirs.cache_dir().join("tray-icons");
let icon_theme_path = match tray_icons::install(&icons) {
Ok(()) => icons.to_string_lossy().into_owned(),
Err(e) => {
tracing::warn!(error = %e, "could not write the tray icons; using the installed theme");
String::new()
}
};
let tray = DriveTray {
state: poll_state(&socket, &default_mountpoint),
socket: socket.clone(),
icon_theme_path,
};
// The tray autostarts with the session and can beat the desktop's SNI
@@ -679,15 +698,43 @@ mod tests {
assert_eq!(phase_of(false, 0, true, false), Phase::Synced);
}
#[test]
fn every_phase_has_an_icon_the_tray_ships() {
for phase in [
Phase::Synced,
Phase::Syncing,
Phase::Paused,
Phase::Offline,
Phase::Attention,
Phase::SessionExpired,
Phase::Disconnected,
Phase::SignedOut,
] {
assert!(
tray_icons::ICONS
.iter()
.any(|(name, _)| *name == phase.icon()),
"{phase:?}"
);
}
}
#[test]
fn attention_states_supply_the_icon_the_tray_requests() {
let mut tray = DriveTray {
state: status_state(&status(""), &[], &[], Path::new("/m")),
socket: PathBuf::new(),
icon_theme_path: String::new(),
};
for (phase, icon) in [
(Phase::Attention, "dialog-warning-symbolic"),
(Phase::SessionExpired, "dialog-password-symbolic"),
(
Phase::Attention,
"io.narl.proton-drive-linux-tray-attention-symbolic",
),
(
Phase::SessionExpired,
"io.narl.proton-drive-linux-tray-session-expired-symbolic",
),
] {
tray.state.phase = phase;
assert_eq!(tray.status(), Status::NeedsAttention);
+89
View File
@@ -0,0 +1,89 @@
//! The tray's own status icons, drawn from the app icon's folder.
//!
//! The packages install them into the hicolor theme. The tray also writes
//! them to a directory of its own at start and names it as the item's
//! `IconThemePath`, so a build run from source, or a panel that does not
//! read the system theme again after an update, still finds them.
use std::path::Path;
macro_rules! icon {
($state:literal) => {
(
concat!("io.narl.proton-drive-linux-tray-", $state, "-symbolic"),
include_str!(concat!(
"../resources/icons/tray/io.narl.proton-drive-linux-tray-",
$state,
"-symbolic.svg"
)),
)
};
}
/// Every icon, by name, with its SVG.
pub const ICONS: [(&str, &str); 7] = [
icon!("synced"),
icon!("syncing"),
icon!("paused"),
icon!("offline"),
icon!("attention"),
icon!("session-expired"),
icon!("disconnected"),
];
/// A theme index just big enough for one scalable status directory.
const INDEX: &str = "[Icon Theme]\nName=Hicolor\nComment=Proton Drive tray icons\n\
Directories=scalable/status\n\n[scalable/status]\nSize=16\nMinSize=8\nMaxSize=512\n\
Type=Scalable\nContext=Status\n";
/// Write the icons under `base`: as a hicolor theme, which KDE looks for in
/// an `IconThemePath`, and loose, which GTK hosts also accept. A file that
/// already holds the right bytes is left alone.
pub fn install(base: &Path) -> std::io::Result<()> {
let status = base.join("hicolor/scalable/status");
std::fs::create_dir_all(&status)?;
write_if_changed(&base.join("hicolor/index.theme"), INDEX)?;
for (name, svg) in ICONS {
let file = format!("{name}.svg");
write_if_changed(&status.join(&file), svg)?;
write_if_changed(&base.join(&file), svg)?;
}
Ok(())
}
fn write_if_changed(path: &Path, contents: &str) -> std::io::Result<()> {
if std::fs::read(path).is_ok_and(|have| have == contents.as_bytes()) {
return Ok(());
}
std::fs::write(path, contents)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_icon_is_one_recolourable_path() {
for (name, svg) in ICONS {
assert!(name.ends_with("-symbolic"), "{name}");
assert_eq!(svg.matches("<path").count(), 1, "{name}");
for banned in ["stroke", "mask", "opacity", "<circle", "<rect"] {
assert!(!svg.contains(banned), "{name} has {banned}");
}
}
}
#[test]
fn install_writes_a_theme_and_loose_copies() {
let dir = std::env::temp_dir().join(format!("pdfs-tray-icons-{}", std::process::id()));
install(&dir).unwrap();
install(&dir).unwrap();
assert!(dir.join("hicolor/index.theme").is_file());
for (name, svg) in ICONS {
let themed = dir.join(format!("hicolor/scalable/status/{name}.svg"));
assert_eq!(std::fs::read_to_string(themed).unwrap(), svg);
assert!(dir.join(format!("{name}.svg")).is_file());
}
std::fs::remove_dir_all(&dir).unwrap();
}
}
+2
View File
@@ -71,6 +71,7 @@ const STOCK: &[&str] = &[
"text-x-generic-symbolic",
"user-trash-symbolic",
"video-x-generic-symbolic",
"view-conceal-symbolic",
"view-fullscreen-symbolic",
"view-grid-symbolic",
"view-list-symbolic",
@@ -79,6 +80,7 @@ const STOCK: &[&str] = &[
"view-pin-symbolic",
"view-refresh-symbolic",
"view-restore-symbolic",
"view-reveal-symbolic",
"window-close-symbolic",
"zoom-fit-best-symbolic",
"zoom-in-symbolic",
+7
View File
@@ -1900,6 +1900,13 @@ impl ContentCache {
Ok(())
}
/// Drop every pin recorded under `path`. Returns the uids it dropped,
/// whose blobs the caller evicts. For a pin whose node is gone, so its
/// path no longer resolves to a uid.
pub fn remove_pins_at(&self, path: &str) -> Result<Vec<String>> {
self.db.pin_remove_by_path(path)
}
/// All pins (files and recursive folders), ordered by uid.
pub fn list_pins(&self) -> Vec<Pin> {
self.db
+65 -1
View File
@@ -11,7 +11,7 @@ use super::Db;
use pdfs_core::Result;
/// Current schema version. Bump on every forward migration added below.
pub(super) const SCHEMA_VERSION: i64 = 50;
pub(super) const SCHEMA_VERSION: i64 = 52;
impl Db {
pub(super) fn migrate(&self) -> Result<()> {
@@ -553,6 +553,31 @@ impl Db {
tx.execute_batch(MIGRATION_V50)?;
}
}
if current < 51 {
let has_folders: bool = tx.query_row(
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'sync_folder'",
[],
|row| row.get::<_, i64>(0).map(|n| n > 0),
)?;
if has_folders {
tx.execute_batch(MIGRATION_V51)?;
}
}
if current < 52 {
let has_intents: bool = tx.query_row(
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'sync_intent'",
[],
|row| row.get::<_, i64>(0).map(|n| n > 0),
)?;
let has_column: bool = tx.query_row(
"SELECT COUNT(*) FROM pragma_table_info('sync_intent') WHERE name = 'sent_sha1s'",
[],
|row| row.get::<_, i64>(0).map(|n| n > 0),
)?;
if has_intents && !has_column {
tx.execute_batch(MIGRATION_V52)?;
}
}
tx.execute(
"INSERT INTO sync_state (key, value) VALUES ('schema_version', ?1)
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
@@ -1585,6 +1610,45 @@ BEGIN
END;
";
/// Schema v51: an intent for each effect a mirror pass sends, written before
/// it is sent and removed once its result is in (`docs/SYNC_ENGINE.md`).
///
/// One row a folder, path and kind of effect. A row left `issued` was sent by
/// a daemon that stopped before it heard back: the effect may or may not have
/// happened. A change to what the folder is, or its removal, drops its rows.
const MIGRATION_V51: &str = "
CREATE TABLE IF NOT EXISTS sync_intent (
id INTEGER PRIMARY KEY AUTOINCREMENT,
folder_id INTEGER NOT NULL,
rel_path TEXT NOT NULL,
kind TEXT NOT NULL,
state TEXT NOT NULL,
attempts INTEGER NOT NULL,
issued_at INTEGER NOT NULL,
last_error TEXT,
UNIQUE (folder_id, rel_path, kind)
);
DROP TRIGGER IF EXISTS sync_intent_drop_on_folder_update;
DROP TRIGGER IF EXISTS sync_intent_drop_on_folder_delete;
CREATE TRIGGER sync_intent_drop_on_folder_update
AFTER UPDATE OF local_path, remote_uid, mode ON sync_folder
BEGIN
DELETE FROM sync_intent WHERE folder_id = OLD.id;
END;
CREATE TRIGGER sync_intent_drop_on_folder_delete
AFTER DELETE ON sync_folder
BEGIN
DELETE FROM sync_intent WHERE folder_id = OLD.id;
END;
";
/// v52: the SHA-1s of the bytes each unsettled mirror upload sent, space
/// separated. A reply that never came may hide an upload that landed, and its
/// digest is how a later pass knows the file on Drive for its own.
const MIGRATION_V52: &str = "
ALTER TABLE sync_intent ADD COLUMN sent_sha1s TEXT;
";
/// See [`MIGRATION_V49_COLUMNS`].
const MIGRATION_V49: &str = "
CREATE TABLE IF NOT EXISTS sync_remote_dirty (
+2 -1
View File
@@ -66,7 +66,8 @@ pub use photos::{StoredPhoto, StoredPlace, THUMB_HAVE, THUMB_NONE, THUMB_UNKNOWN
pub use pins::PinRow;
pub use replace::ReplaceIntent;
pub use sync::{
DeleteWindow, SavedWalk, SavedWalkDir, SavedWalkItem, StoredSyncEntry, StoredSyncFolder,
DeleteWindow, SavedWalk, SavedWalkDir, SavedWalkItem, StoredIntent, StoredSyncEntry,
StoredSyncFolder,
};
pub use trash::StoredTrash;
+6
View File
@@ -259,6 +259,9 @@ impl Db {
if let Some(rowid) = rowid {
tx.execute("DELETE FROM nodes_fts WHERE rowid = ?1", params![rowid])?;
}
// A pin outlives its node otherwise, listed as kept offline with no
// path left to unpin it by.
tx.execute("DELETE FROM pins WHERE uid = ?1", params![uid])?;
tx.commit()?;
Ok(())
}
@@ -299,6 +302,9 @@ impl Db {
if let Some(rowid) = rowid {
tx.execute("DELETE FROM nodes_fts WHERE rowid = ?1", params![rowid])?;
}
// A pin outlives its node otherwise, listed as kept offline with no
// path left to unpin it by.
tx.execute("DELETE FROM pins WHERE uid = ?1", params![uid])?;
tx.execute("DELETE FROM pending_op WHERE id = ?1", params![op_id])?;
if let Some(name) = name {
wake_ops_waiting_for_tx(&tx, &name)?;
+15
View File
@@ -38,6 +38,21 @@ impl Db {
Ok(n > 0)
}
/// Drop every pin recorded under `path`. Returns the uids it dropped.
///
/// For a pin whose node is gone: the path no longer resolves to a uid, and
/// the recorded path is all that is left to name the pin by.
pub fn pin_remove_by_path(&self, path: &str) -> Result<Vec<String>> {
let conn = self.conn.lock();
let mut stmt = conn.prepare("DELETE FROM pins WHERE path = ?1 RETURNING uid")?;
let rows = stmt.query_map(params![path], |r| r.get::<_, String>(0))?;
let mut out = Vec::new();
for r in rows {
out.push(r?);
}
Ok(out)
}
/// Every directly-pinned entry, ordered by uid.
pub fn pin_list(&self) -> Result<Vec<PinRow>> {
let conn = self.read()?;
+6 -1
View File
@@ -100,8 +100,13 @@ impl Db {
/// so it still does once its create has landed and the row has the uid
/// Drive gave it. The tree learns that uid a moment later, and a rename in
/// between was refused (`docs/BUGS.md` B174).
///
/// Every statement reads one snapshot. Apart, a create that landed between
/// finding the row's uid and checking the row left the stand-in with no
/// row at all, and the change was refused (B306).
pub fn effective_node_access(&self, uid: &NodeUid) -> Result<Option<Access>> {
let conn = self.read()?;
let reader = self.read()?;
let conn = reader.unchecked_transaction()?;
let key = uid.to_string();
let key = match super::local_lid(&key) {
Some(lid) => conn
+173
View File
@@ -19,6 +19,26 @@ pub struct DeleteWindow {
pub deleted: u64,
}
/// An effect a mirror pass sent, or is about to send, and has not settled.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StoredIntent {
pub id: i64,
pub folder_id: i64,
pub rel_path: String,
/// What the effect does, such as `upload` or `download`.
pub kind: String,
/// Where it stands, as the effect reducer names it.
pub state: String,
/// How many times it was sent, this time included.
pub attempts: u32,
/// When it was last sent, in seconds since the epoch.
pub issued_at: i64,
pub last_error: Option<String>,
/// For an upload: the SHA-1s of the bytes its attempts streamed without
/// hearing a success back, lowercase. One of them may have landed.
pub sent_sha1s: Vec<String>,
}
/// What a mirror pass has walked of Drive, saved so a pass cut short
/// resumes the walk instead of listing every folder again (B294), and so a
/// finished walk serves as the next pass's picture of Drive.
@@ -828,6 +848,139 @@ impl Db {
Ok(())
}
/// Record that an effect is about to be sent: a new intent in state
/// `issued`, or the one already there for the same folder, path and kind,
/// sent once more. Returns the intent as it is now, and the state it was
/// in before, if there was one.
pub fn sync_intent_issue(
&self,
folder_id: i64,
rel_path: &str,
kind: &str,
now: i64,
) -> Result<(StoredIntent, Option<String>)> {
let mut conn = self.conn.lock();
let tx = conn.transaction()?;
let before: Option<String> = tx
.query_row(
"SELECT state FROM sync_intent WHERE folder_id = ?1 AND rel_path = ?2 AND kind = ?3",
params![folder_id, rel_path, kind],
|row| row.get(0),
)
.optional()?;
tx.execute(
"INSERT INTO sync_intent (folder_id, rel_path, kind, state, attempts, issued_at)
VALUES (?1, ?2, ?3, 'issued', 1, ?4)
ON CONFLICT(folder_id, rel_path, kind) DO UPDATE SET state = 'issued',
attempts = attempts + 1, issued_at = excluded.issued_at",
params![folder_id, rel_path, kind, now],
)?;
let intent = tx.query_row(
&format!(
"SELECT {INTENT_COLUMNS} FROM sync_intent
WHERE folder_id = ?1 AND rel_path = ?2 AND kind = ?3"
),
params![folder_id, rel_path, kind],
intent_row,
)?;
tx.commit()?;
Ok((intent, before))
}
/// Settle an intent whose effect is done: the row goes.
pub fn sync_intent_settle(&self, id: i64) -> Result<()> {
let conn = self.conn.lock();
conn.execute("DELETE FROM sync_intent WHERE id = ?1", params![id])?;
Ok(())
}
/// Move an intent to `state`, with the error that put it there.
pub fn sync_intent_set(&self, id: i64, state: &str, error: Option<&str>) -> Result<()> {
let conn = self.conn.lock();
conn.execute(
"UPDATE sync_intent SET state = ?2, last_error = ?3 WHERE id = ?1",
params![id, state, error],
)?;
Ok(())
}
/// Note that the upload `kind` of `rel_path` streamed bytes with SHA-1
/// `sha1` and heard no success back. Nothing happens without an intent for
/// it. A digest already noted is not added again.
pub fn sync_intent_sent(
&self,
folder_id: i64,
rel_path: &str,
kind: &str,
sha1: &str,
) -> Result<()> {
let sha1 = sha1.to_ascii_lowercase();
let conn = self.conn.lock();
conn.execute(
"UPDATE sync_intent SET sent_sha1s = CASE
WHEN sent_sha1s IS NULL OR sent_sha1s = '' THEN ?4
WHEN instr(' ' || sent_sha1s || ' ', ' ' || ?4 || ' ') > 0 THEN sent_sha1s
ELSE sent_sha1s || ' ' || ?4 END
WHERE folder_id = ?1 AND rel_path = ?2 AND kind = ?3",
params![folder_id, rel_path, kind, sha1],
)?;
Ok(())
}
/// Every intent not settled, oldest first; only `folder_id`'s when given.
pub fn sync_intents(&self, folder_id: Option<i64>) -> Result<Vec<StoredIntent>> {
let conn = self.read()?;
let mut stmt = conn.prepare(&format!(
"SELECT {INTENT_COLUMNS} FROM sync_intent
WHERE ?1 IS NULL OR folder_id = ?1 ORDER BY id"
))?;
let rows = stmt
.query_map(params![folder_id], intent_row)?
.collect::<rusqlite::Result<Vec<_>>>()?;
Ok(rows)
}
/// Move every intent in state `from` to `to`, across all folders.
/// Returns how many moved.
pub fn sync_intents_move(&self, from: &str, to: &str) -> Result<usize> {
let conn = self.conn.lock();
Ok(conn.execute(
"UPDATE sync_intent SET state = ?2 WHERE state = ?1",
params![from, to],
)?)
}
/// Settle the intents of `folder_id` in one of `states` that were last
/// sent before `before`: a pass that started after them looked at their
/// paths and did not send them again. Returns the intents settled.
pub fn sync_intents_settle_before(
&self,
folder_id: i64,
states: &[&str],
before: i64,
) -> Result<Vec<StoredIntent>> {
let mut conn = self.conn.lock();
let tx = conn.transaction()?;
let mut settled = Vec::new();
{
let mut stmt = tx.prepare(&format!(
"SELECT {INTENT_COLUMNS} FROM sync_intent
WHERE folder_id = ?1 AND issued_at < ?2 ORDER BY id"
))?;
for row in stmt.query_map(params![folder_id, before], intent_row)? {
let row = row?;
if states.contains(&row.state.as_str()) {
settled.push(row);
}
}
}
for intent in &settled {
tx.execute("DELETE FROM sync_intent WHERE id = ?1", params![intent.id])?;
}
tx.commit()?;
Ok(settled)
}
/// Drop the entire baseline for a folder. Used when flipping ondemand→mirror:
/// the local tree was evicted, so the old baseline is stale and would make the
/// next reconcile mistake "locally deleted" for "must re-download". Clearing it
@@ -842,6 +995,26 @@ impl Db {
}
}
const INTENT_COLUMNS: &str =
"id, folder_id, rel_path, kind, state, attempts, issued_at, last_error, sent_sha1s";
fn intent_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoredIntent> {
Ok(StoredIntent {
id: row.get(0)?,
folder_id: row.get(1)?,
rel_path: row.get(2)?,
kind: row.get(3)?,
state: row.get(4)?,
attempts: u32::try_from(row.get::<_, i64>(5)?).unwrap_or(u32::MAX),
issued_at: row.get(6)?,
last_error: row.get(7)?,
sent_sha1s: row
.get::<_, Option<String>>(8)?
.map(|s| s.split_whitespace().map(str::to_owned).collect())
.unwrap_or_default(),
})
}
fn clear_walk(tx: &rusqlite::Transaction<'_>, folder_id: i64) -> Result<()> {
for table in [
"sync_walk",
+169
View File
@@ -3726,6 +3726,66 @@ fn a_stand_in_keeps_its_access_once_its_create_has_landed() {
);
}
/// A stand-in asked about while its create lands is never missing: the
/// lookup that turns it into the landed row's uid and the check on that row
/// see one state of the database (`docs/BUGS.md` B306).
#[test]
fn a_stand_in_is_never_missing_while_its_create_lands() {
let path = std::env::temp_dir().join(format!("pdfs-db-landing-{}.db", std::process::id()));
let _ = std::fs::remove_file(&path);
let db = Db::open(&path).unwrap();
db.upsert_node(&folder("parent", None, "My Files")).unwrap();
let parent = uid("parent").to_string();
let current = std::sync::Mutex::new(None::<NodeUid>);
let done = std::sync::atomic::AtomicBool::new(false);
let missing = std::sync::atomic::AtomicUsize::new(0);
std::thread::scope(|scope| {
scope.spawn(|| {
while !done.load(std::sync::atomic::Ordering::Relaxed) {
let Some(stand_in) = current.lock().unwrap().clone() else {
std::thread::yield_now();
continue;
};
if db.effective_node_access(&stand_in).unwrap().is_none() {
missing.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
}
});
for n in 0..300 {
let name = format!("new-{n}.txt");
let lid = db.add_local_row(&parent, &name, false, 1).unwrap();
let local = local_uid(lid);
let stand_in = NodeUid::new(VolumeId::from("local"), LinkId::from(lid.to_string()));
let mut node = file(&format!("new-{n}"), "parent", &name, 1);
node.uid = stand_in.clone();
db.upsert_node(&node).unwrap();
let (id, _) = db
.enqueue_op(&op_on(OP_CREATE, &local, Some(&parent)))
.unwrap();
*current.lock().unwrap() = Some(stand_in);
db.claim_next_due_op(1).unwrap().unwrap();
let real = uid(&format!("real-{n}")).to_string();
db.finish_create(
id,
Some("/staging/create"),
&landing(&local, &real, &parent, &name),
|_| None,
)
.unwrap();
}
done.store(true, std::sync::atomic::Ordering::Relaxed);
});
drop(db);
let _ = std::fs::remove_file(&path);
assert_eq!(
missing.into_inner(),
0,
"a landing stand-in read as missing"
);
}
#[test]
fn a_stand_in_folder_stays_listed_once_its_create_has_landed() {
let db = Db::open_in_memory().unwrap();
@@ -5781,6 +5841,40 @@ fn pin_add_list_remove_roundtrip() {
assert_eq!(db.pin_list().unwrap().len(), 1);
}
#[test]
fn deleting_a_node_drops_its_pin() {
// A pin that outlived its node stayed listed as kept offline, and the path
// it was listed by no longer resolved, so it could not be unpinned.
let db = Db::open_in_memory().unwrap();
db.upsert_node(&folder("root", None, "My Files")).unwrap();
db.upsert_node(&file("gone", "root", "gone.mkv", 1))
.unwrap();
db.upsert_node(&file("kept", "root", "kept.mkv", 1))
.unwrap();
let du = |l: &str| uid(l).to_string();
db.pin_add(&du("gone"), "gone.mkv", false).unwrap();
db.pin_add(&du("kept"), "kept.mkv", false).unwrap();
db.delete_node(&uid("gone")).unwrap();
let pins: Vec<String> = db.pin_list().unwrap().into_iter().map(|p| p.uid).collect();
assert_eq!(pins, vec![du("kept")]);
}
#[test]
fn a_pin_left_behind_is_removed_by_its_path() {
let db = Db::open_in_memory().unwrap();
db.pin_add("vol~gone", "Videos/gone.mkv", false).unwrap();
db.pin_add("vol~kept", "Videos/kept.mkv", false).unwrap();
assert_eq!(
db.pin_remove_by_path("Videos/gone.mkv").unwrap(),
vec!["vol~gone".to_string()]
);
assert!(db.pin_remove_by_path("Videos/gone.mkv").unwrap().is_empty());
assert_eq!(db.pin_list().unwrap().len(), 1);
}
#[test]
fn is_pinned_direct_without_node_row() {
// A direct pin counts even when the node was never hydrated into `nodes`.
@@ -8452,3 +8546,78 @@ fn a_deletion_window_is_kept_per_folder_until_the_folder_changes() {
db.sync_folder_remove(other).unwrap();
assert_eq!(db.sync_delete_window(other).unwrap(), None);
}
/// An intent is one row per folder, path and kind: sent again, it counts the
/// attempt and says what state it was left in. It goes once settled, and with
/// the folder.
#[test]
fn an_upload_notes_each_digest_it_sent_once() {
let db = Db::open_in_memory().unwrap();
let id = db.sync_folder_add("/home/me/Docs", "v~root", "s").unwrap();
// Nothing to note without an intent.
db.sync_intent_sent(id, "a.txt", "upload", "AA").unwrap();
assert!(db.sync_intents(Some(id)).unwrap().is_empty());
db.sync_intent_issue(id, "a.txt", "upload", 10).unwrap();
db.sync_intent_sent(id, "a.txt", "upload", "AA").unwrap();
db.sync_intent_sent(id, "a.txt", "upload", "aa").unwrap();
// Sent again with other bytes: both may have landed.
db.sync_intent_issue(id, "a.txt", "upload", 20).unwrap();
db.sync_intent_sent(id, "a.txt", "upload", "bb").unwrap();
// Another kind of the same path keeps its own.
db.sync_intent_issue(id, "a.txt", "upload-revision", 21)
.unwrap();
let intents = db.sync_intents(Some(id)).unwrap();
let upload = intents.iter().find(|i| i.kind == "upload").unwrap();
assert_eq!(upload.sent_sha1s, ["aa", "bb"]);
let revision = intents
.iter()
.find(|i| i.kind == "upload-revision")
.unwrap();
assert!(revision.sent_sha1s.is_empty());
}
#[test]
fn an_effect_intent_is_kept_until_it_is_settled_or_its_folder_changes() {
let db = Db::open_in_memory().unwrap();
let id = db.sync_folder_add("/home/me/Docs", "v~root", "s").unwrap();
let other = db
.sync_folder_add("/home/me/Other", "v~other", "s")
.unwrap();
let (first, before) = db.sync_intent_issue(id, "a.txt", "upload", 10).unwrap();
assert_eq!(before, None);
assert_eq!((first.state.as_str(), first.attempts), ("issued", 1));
db.sync_intent_set(first.id, "retry", Some("timed out"))
.unwrap();
let (again, before) = db.sync_intent_issue(id, "a.txt", "upload", 20).unwrap();
assert_eq!(before.as_deref(), Some("retry"));
assert_eq!(again.id, first.id, "the same intent");
assert_eq!((again.attempts, again.issued_at), (2, 20));
assert_eq!(again.last_error.as_deref(), Some("timed out"));
let (download, _) = db.sync_intent_issue(id, "a.txt", "download", 21).unwrap();
db.sync_intent_issue(other, "b.txt", "upload", 5).unwrap();
assert_eq!(db.sync_intents(Some(id)).unwrap().len(), 2);
assert_eq!(db.sync_intents(None).unwrap().len(), 3);
db.sync_intent_settle(download.id).unwrap();
assert_eq!(db.sync_intents(Some(id)).unwrap().len(), 1);
// A start finds what a stopped daemon left sent.
assert_eq!(db.sync_intents_move("issued", "unsure").unwrap(), 2);
assert_eq!(db.sync_intents_move("issued", "unsure").unwrap(), 0);
// A pass that began after an intent was sent settles it.
let settled = db
.sync_intents_settle_before(other, &["unsure"], 6)
.unwrap();
assert_eq!(settled.len(), 1);
assert!(db.sync_intents(Some(other)).unwrap().is_empty());
assert!(
db.sync_intents_settle_before(id, &["unsure"], 20)
.unwrap()
.is_empty(),
"sent at 20, not before"
);
db.sync_folder_set_mode(id, "ondemand").unwrap();
assert!(db.sync_intents(Some(id)).unwrap().is_empty());
}
+157
View File
@@ -0,0 +1,157 @@
//! The effect reducer: where one effect a mirror pass sends stands, from the
//! moment it is about to be sent until its result is in
//! (`docs/SYNC_ENGINE.md`).
//!
//! An effect is an upload, a download, a folder made on Drive, and the other
//! [`Pending`](crate::model::Pending) ops. Before one is sent, an intent for it
//! is written to the database (`sync_intent`); when its result is in, the
//! intent is settled or kept with the failure. An intent still `issued` when
//! the daemon starts was sent by a daemon that stopped before it heard back,
//! so the effect may or may not have happened: it is `unsure`.
//!
//! [`step`] is pure, as the root reducer is: the I/O results, the restart and
//! the pass that looks again are inputs.
//!
//! For now the intents are kept in shadow: they record and log what happens,
//! and nothing reads them to decide what to send. The apply step's own checks
//! (a create that may have landed is looked up before it is sent again, B266;
//! a download checks the disk before it replaces a file, B39) still do that.
use std::fmt;
/// Failures in a row after which an effect is reported as blocked.
pub const BLOCKED_AFTER: u32 = 5;
/// The kind of intent for a file or folder removed from disk because Drive
/// deleted it. The other kinds are named by [`Pending::intent`](crate::model::Pending::intent).
pub const DELETE_LOCAL: &str = "delete-local";
/// The kind of intent for a file or folder moved to Drive's trash because it
/// was deleted on disk.
pub const TRASH: &str = "trash";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EffectState {
/// Sent, or about to be; no result yet.
Issued,
/// Found issued at a start: the daemon stopped before the result came,
/// so the effect may or may not have happened.
Unsure,
/// It failed, and a later pass may send it again.
Retry,
/// It failed [`BLOCKED_AFTER`] times in a row.
Blocked,
/// Its result is in. The intent goes.
Settled,
}
impl EffectState {
/// The name the database keeps.
pub fn name(self) -> &'static str {
match self {
EffectState::Issued => "issued",
EffectState::Unsure => "unsure",
EffectState::Retry => "retry",
EffectState::Blocked => "blocked",
EffectState::Settled => "settled",
}
}
pub fn from_name(name: &str) -> Option<EffectState> {
Some(match name {
"issued" => EffectState::Issued,
"unsure" => EffectState::Unsure,
"retry" => EffectState::Retry,
"blocked" => EffectState::Blocked,
"settled" => EffectState::Settled,
_ => return None,
})
}
}
impl fmt::Display for EffectState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
/// Something that happened to an effect.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EffectInput {
/// It is sent (again); `attempts` counts this one.
Issued { attempts: u32 },
/// It did what it was sent to do.
Succeeded,
/// It failed.
Failed,
/// The daemon started.
Restarted,
/// A pass that began after it was sent looked at its path and did not
/// send it again: what it was for has changed, or is done.
Superseded,
}
/// The state after `input`.
pub fn step(state: EffectState, input: EffectInput) -> EffectState {
use EffectState as S;
match (state, input) {
(S::Settled, _) => S::Settled,
(_, EffectInput::Issued { .. }) => S::Issued,
(_, EffectInput::Succeeded | EffectInput::Superseded) => S::Settled,
(S::Issued, EffectInput::Restarted) => S::Unsure,
(state, EffectInput::Restarted) => state,
(_, EffectInput::Failed) => S::Retry,
}
}
/// The state after a failure on the `attempts`th send. Counts are kept
/// outside [`step`], with the intent.
pub fn failed(attempts: u32) -> EffectState {
if attempts >= BLOCKED_AFTER {
EffectState::Blocked
} else {
step(EffectState::Issued, EffectInput::Failed)
}
}
#[cfg(test)]
mod tests {
use super::*;
use EffectInput as I;
use EffectState as S;
#[test]
fn an_effect_settles_once_it_succeeds() {
let sent = step(S::Retry, I::Issued { attempts: 2 });
assert_eq!(sent, S::Issued);
assert_eq!(step(sent, I::Succeeded), S::Settled);
assert_eq!(step(S::Settled, I::Failed), S::Settled, "settled stays");
}
#[test]
fn an_effect_sent_before_a_stop_is_unsure_after_the_start() {
assert_eq!(step(S::Issued, I::Restarted), S::Unsure);
// Only one that was sent: a failure is known, and stays one.
assert_eq!(step(S::Retry, I::Restarted), S::Retry);
assert_eq!(step(S::Blocked, I::Restarted), S::Blocked);
// Sent again, or found needless by a later pass.
assert_eq!(step(S::Unsure, I::Issued { attempts: 2 }), S::Issued);
assert_eq!(step(S::Unsure, I::Superseded), S::Settled);
}
#[test]
fn an_effect_that_keeps_failing_is_blocked() {
assert_eq!(failed(1), S::Retry);
assert_eq!(failed(BLOCKED_AFTER - 1), S::Retry);
assert_eq!(failed(BLOCKED_AFTER), S::Blocked);
assert_eq!(step(S::Blocked, I::Superseded), S::Settled);
}
#[test]
fn every_state_reads_back_by_its_name() {
for state in [S::Issued, S::Unsure, S::Retry, S::Blocked, S::Settled] {
assert_eq!(EffectState::from_name(state.name()), Some(state));
}
assert_eq!(EffectState::from_name("planned"), None);
}
}
+3 -3
View File
@@ -11,9 +11,9 @@
//! Only [`Presence::Absent`] may lead to a deletion. A pass classifies a path
//! only when both sides are known ([`Evidence::classifiable`]), and every
//! deletion it plans is checked against the evidence again
//! ([`Evidence::unproven_deletion`]). That check acts on nothing yet: it
//! counts and logs a deletion the evidence does not support, so a regression
//! in the filters shows up in the pass trace before it can cost data.
//! ([`Evidence::unproven_deletion`]). A deletion the evidence does not
//! support is not made: it is logged, counted in the pass trace and failed,
//! so a regression in the filters keeps files instead of costing them.
use std::collections::HashMap;
+3
View File
@@ -20,11 +20,14 @@ use pdfs_store::db::{DeleteWindow, StoredSyncEntry};
use proton_drive_rs::proton_sdk::ids::NodeUid;
use proton_drive_rs::{Node, NodeKind};
pub mod effect;
pub mod evidence;
pub mod local_dirty;
pub mod mirror;
pub mod model;
pub mod naming;
pub mod planner;
pub mod root;
pub mod store;
pub mod trace;
+353
View File
@@ -0,0 +1,353 @@
//! The local dirty set: where a mirror folder changed on disk since a pass
//! last looked, as the filesystem watcher reports it (`docs/SYNC_ENGINE.md`).
//!
//! The watcher marks each path an event names. A pass claims every mark made
//! so far and, once it has applied what it found, retires them. Marks made
//! while it ran are newer than its claim and stay for the next pass.
//!
//! A claim is only as good as the watch behind it. It is *trusted* when the
//! folder's watch has been live since before the last pass claimed: then
//! every change since that pass was reported. A watch that failed, a watcher
//! error, an overflowed queue or a restart breaks that, and the next pass has
//! nothing to trust until a pass claims again with the watch live throughout.
//!
//! A trusted claim stands in for most of the local walk. The set keeps the
//! last walk of each folder ([`LocalWalk`]), and a pass with a trusted claim
//! reads again only what the claim covers and takes the rest from that walk.
//! A walk is only kept after a pass that changed nothing on disk itself, and
//! a full walk still runs now and then: it checks the set, counting the
//! changes it finds that a trusted claim did not cover.
use std::collections::{HashMap, HashSet};
use std::time::Instant;
use parking_lot::Mutex;
use crate::model::LocalItem;
/// The dirty marks of every mirror folder, by folder id.
#[derive(Default)]
pub struct LocalDirty {
inner: Mutex<Dirty>,
}
#[derive(Default)]
struct Dirty {
/// The newest generation, across every folder: of a mark, or of a watch
/// coming up.
generation: u64,
folders: HashMap<i64, Marks>,
}
impl Dirty {
/// The next generation. A watch that comes up, or comes back after an
/// overflow, takes one of its own, so it is always later than the last
/// claim, even when no mark was made in between.
fn tick(&mut self) -> u64 {
self.generation += 1;
self.generation
}
}
#[derive(Default)]
struct Marks {
/// Folders whose direct children changed, with the generation of the
/// newest mark on each.
shallow: HashMap<String, u64>,
/// Paths that changed in full, with whatever is below them: a file
/// written, or a folder that appeared with its contents.
deep: HashMap<String, u64>,
/// The generation from which the watch has reported every change, or
/// `None` while the folder is not watched.
live_since: Option<u64>,
/// The generation the last pass claimed through.
claimed: Option<u64>,
/// What the last pass found on disk, when it may stand in for a walk.
walk: Option<LocalWalk>,
/// The folder's root as it was when it was watched, as device and
/// inode. A watch follows the folder it was set on, so a root moved away
/// and made again is another folder the watch does not see.
root: Option<RootId>,
}
/// A folder on disk, as device and inode.
pub type RootId = (u64, u64);
/// The identity of the folder at `path`, if there is one.
pub fn root_id(path: &std::path::Path) -> Option<RootId> {
use std::os::unix::fs::MetadataExt;
std::fs::metadata(path)
.ok()
.filter(|meta| meta.is_dir())
.map(|meta| (meta.dev(), meta.ino()))
}
/// What a pass found on disk, kept for the next pass to start from.
pub struct LocalWalk {
/// Every path the walk found, as a walk returns them.
pub items: HashMap<String, LocalItem>,
/// [`IgnoreRules::source`](pdfs_core::syncignore::IgnoreRules::source)
/// of the rules it was walked with: other rules would have found other
/// paths.
pub rules: u64,
/// When the folder was last walked in full.
pub walked_at: Instant,
}
/// The marks a pass claimed: what the watcher reported up to `through`.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Claim {
pub through: u64,
/// Whether the watch was live since before the last claim, so the marks
/// cover every change since.
pub trusted: bool,
shallow: HashSet<String>,
deep: HashSet<String>,
}
impl Claim {
/// Whether a change to `rel` was reported: its folder's children
/// changed, or it or a folder above it changed in full.
pub fn covers(&self, rel: &str) -> bool {
if self.shallow.contains(parent(rel)) {
return true;
}
let mut at = rel;
loop {
if self.deep.contains(at) {
return true;
}
if at.is_empty() {
return false;
}
at = parent(at);
}
}
/// The folders whose direct children changed.
pub fn shallow(&self) -> impl Iterator<Item = &str> {
self.shallow.iter().map(String::as_str)
}
/// The paths that changed with whatever is below them.
pub fn deep(&self) -> impl Iterator<Item = &str> {
self.deep.iter().map(String::as_str)
}
/// How many marks the claim holds.
pub fn len(&self) -> usize {
self.shallow.len() + self.deep.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl LocalDirty {
/// The watch on `folder` is in place, set on the root `root`: every
/// change from now on is reported.
pub fn watched(&self, folder: i64, root: Option<RootId>) {
let mut d = self.inner.lock();
let now = d.tick();
let marks = d.folders.entry(folder).or_default();
if marks.live_since.is_none() {
marks.live_since = Some(now);
}
marks.root = root;
}
/// The root `folder`'s watch was last set on.
pub fn watched_root(&self, folder: i64) -> Option<RootId> {
self.inner.lock().folders.get(&folder)?.root
}
/// The watch on `folder` is gone, or never came up.
pub fn unwatched(&self, folder: i64) {
if let Some(marks) = self.inner.lock().folders.get_mut(&folder) {
marks.live_since = None;
}
}
/// The watcher lost events it cannot name: an error, or an overflowed
/// queue. No folder's marks can be trusted until it is watched again.
pub fn lost(&self) {
for marks in self.inner.lock().folders.values_mut() {
marks.live_since = None;
}
}
/// The watcher's queue overflowed: the changes in it are lost, but the
/// watches stand, so every folder still watched reports changes again
/// from now on.
pub fn overflowed(&self) {
let mut d = self.inner.lock();
let now = d.tick();
for marks in d.folders.values_mut() {
if marks.live_since.is_some() {
marks.live_since = Some(now);
}
}
}
/// Note a change the watcher reported at `rel` in `folder`.
pub fn mark(&self, folder: i64, rel: &str) {
let mut d = self.inner.lock();
let generation = d.tick();
let marks = d.folders.entry(folder).or_default();
marks.deep.insert(rel.to_string(), generation);
marks.shallow.insert(parent(rel).to_string(), generation);
}
/// Claim every mark of `folder` made so far, for a pass about to look.
pub fn claim(&self, folder: i64) -> Claim {
let mut d = self.inner.lock();
let through = d.generation;
let marks = d.folders.entry(folder).or_default();
Claim {
through,
trusted: matches!(
(marks.live_since, marks.claimed),
(Some(live), Some(claimed)) if live <= claimed
),
shallow: marks.shallow.keys().cloned().collect(),
deep: marks.deep.keys().cloned().collect(),
}
}
/// A pass that claimed `claim` has looked. With `applied`, it applied
/// everything it found, and the marks it claimed are retired; without,
/// they stay for the next pass to claim again. Either way the next claim
/// is measured from this one.
pub fn looked(&self, folder: i64, claim: &Claim, applied: bool) {
let mut d = self.inner.lock();
let marks = d.folders.entry(folder).or_default();
if applied {
marks.shallow.retain(|_, g| *g > claim.through);
marks.deep.retain(|_, g| *g > claim.through);
}
marks.claimed = Some(claim.through);
}
/// Take the walk the last pass kept for `folder`. Taken, not read: a pass
/// that does not keep a walk again leaves the next one nothing to start
/// from.
pub fn take_walk(&self, folder: i64) -> Option<LocalWalk> {
self.inner
.lock()
.folders
.get_mut(&folder)
.and_then(|marks| marks.walk.take())
}
/// Keep what a pass found on disk for the next pass on `folder`.
pub fn keep_walk(&self, folder: i64, walk: LocalWalk) {
self.inner.lock().folders.entry(folder).or_default().walk = Some(walk);
}
/// Forget a folder that is no longer synced.
pub fn forget(&self, folder: i64) {
self.inner.lock().folders.remove(&folder);
}
}
/// The folder `rel` is in; the root's is the root.
fn parent(rel: &str) -> &str {
rel.rfind('/').map_or("", |i| &rel[..i])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_claim_covers_a_change_and_its_siblings_folder_but_not_cousins() {
let dirty = LocalDirty::default();
dirty.mark(1, "docs/a.txt");
let claim = dirty.claim(1);
assert!(claim.covers("docs/a.txt"));
// A file made or deleted next to it shows in the same folder.
assert!(claim.covers("docs/b.txt"));
assert!(!claim.covers("other/c.txt"));
assert!(!claim.covers("docs/sub/d.txt"));
assert!(!claim.covers("top.txt"));
}
#[test]
fn a_folder_moved_in_covers_everything_below_it() {
let dirty = LocalDirty::default();
dirty.mark(1, "photos/2024");
let claim = dirty.claim(1);
assert!(claim.covers("photos/2024/jan/1.jpg"));
assert!(claim.covers("photos/other"));
assert!(!claim.covers("music/x.mp3"));
}
#[test]
fn a_claim_is_trusted_only_with_the_watch_live_since_the_last_one() {
let dirty = LocalDirty::default();
dirty.watched(1, None);
// The first pass after the watch came up has nothing to measure from.
let first = dirty.claim(1);
assert!(!first.trusted);
dirty.looked(1, &first, true);
assert!(dirty.claim(1).trusted);
// Events lost: the next claim is not trusted, nor the one after the
// watch comes back, until a pass has claimed with it live.
dirty.lost();
let lost = dirty.claim(1);
assert!(!lost.trusted);
dirty.looked(1, &lost, true);
dirty.watched(1, None);
dirty.mark(1, "a.txt");
let back = dirty.claim(1);
assert!(!back.trusted, "watched again after the last claim");
dirty.looked(1, &back, true);
assert!(dirty.claim(1).trusted);
}
#[test]
fn marks_made_during_a_pass_stay_for_the_next_one() {
let dirty = LocalDirty::default();
dirty.mark(1, "a.txt");
let claim = dirty.claim(1);
dirty.mark(1, "b/c.txt");
dirty.looked(1, &claim, true);
let next = dirty.claim(1);
assert!(!next.covers("a.txt"));
assert!(next.covers("b/c.txt"));
}
#[test]
fn a_pass_that_did_not_apply_everything_keeps_its_marks() {
let dirty = LocalDirty::default();
dirty.mark(1, "a.txt");
let claim = dirty.claim(1);
dirty.looked(1, &claim, false);
assert!(dirty.claim(1).covers("a.txt"));
}
#[test]
fn an_overflow_breaks_trust_until_a_pass_claims_again() {
let dirty = LocalDirty::default();
dirty.watched(1, None);
let first = dirty.claim(1);
dirty.looked(1, &first, true);
dirty.mark(1, "a.txt");
dirty.overflowed();
let lost = dirty.claim(1);
assert!(!lost.trusted);
dirty.looked(1, &lost, true);
assert!(dirty.claim(1).trusted);
}
#[test]
fn folders_keep_their_own_marks() {
let dirty = LocalDirty::default();
dirty.mark(1, "a.txt");
assert!(dirty.claim(2).is_empty());
dirty.forget(1);
assert!(dirty.claim(1).is_empty());
}
}
+501 -34
View File
@@ -38,15 +38,20 @@ use proton_drive_rs::proton_sdk::ids::NodeUid;
use sha1::{Digest as _, Sha1};
use tracing::{debug, info, warn};
use crate::effect::{self, EffectState};
use crate::evidence::{Evidence, RemoteEvidence, Side};
use crate::local_dirty::{Claim, LocalWalk, root_id};
use crate::planner::HasKind;
use crate::root::{Doubt, Phase as RootPhase, RootInput, Suspension};
use pdfs_core::batch;
use pdfs_core::control::{ActivityKind, TransferDirection};
use pdfs_core::syncignore::IgnoreRules;
use pdfs_core::timestamp::now_secs;
use pdfs_core::transfers::{CountingWriter, OwnedCountingReader};
use pdfs_drive::parse_uid;
use pdfs_store::db::{DeleteWindow, SavedWalk, SavedWalkItem, StoredSyncEntry, StoredSyncFolder};
use pdfs_store::db::{
DeleteWindow, SavedWalk, SavedWalkItem, StoredIntent, StoredSyncEntry, StoredSyncFolder,
};
mod apply;
mod engine;
@@ -100,15 +105,21 @@ impl Syncer {
pub fn reconcile_folder(&self, folder: &StoredSyncFolder) {
// A paused folder skips the settle too: a queued switch to on-demand
// evicts the local tree, which is only safe after a pass uploaded it.
self.roots.begin(folder.id, folder.last_sync != 0);
if self.sync_folder_paused(folder.id) {
debug!(id = folder.id, "sync: folder paused, skipping reconcile");
self.roots
.input(folder.id, RootInput::Suspended(Suspension::Paused));
return;
}
self.roots.input(folder.id, RootInput::Resumed);
// `ondemand` folders are live FUSE mounts, not mirrored, so there is nothing
// to reconcile — but one may still carry a queued switch back to `mirror`,
// so the settle below is not skipped with it.
if folder.mode == "mirror" {
self.reconcile_pass(folder);
} else {
self.roots.input(folder.id, RootInput::HandedOff);
}
self.settle_pending_mode(folder.id);
}
@@ -149,8 +160,49 @@ impl Syncer {
let _ = self
.store
.sync_folder_set_state(folder.id, "error", now_secs());
self.roots
.input(folder.id, RootInput::Suspended(Suspension::RootMissing));
// A root removed takes its watch with it, and one made again in
// its place is not watched until the watches are set up again.
// Until then the disk is walked in full.
self.local_dirty.unwatched(folder.id);
self.roots
.input(folder.id, RootInput::Doubted(Doubt::WatchLost));
let _ = self.tx.send(SyncMsg::Rewatch);
return;
}
// Back after it was missing: watch it again. This pass walks the disk
// in full, as the root state owes it.
if self
.roots
.state(folder.id)
.is_some_and(|state| state.phase == RootPhase::Suspended(Suspension::RootMissing))
{
let _ = self.tx.send(SyncMsg::Rewatch);
}
// Moved away and made again between two passes, or before the engine
// got to drop the old watch: the watch is on a folder that is no
// longer the root, and reports nothing of this one.
if let Some(watched) = self.local_dirty.watched_root(folder.id)
&& root_id(&local_root).is_some_and(|now| now != watched)
{
info!(
id = folder.id,
"sync: the folder's root was replaced; watching it again"
);
self.local_dirty.unwatched(folder.id);
self.roots
.input(folder.id, RootInput::Doubted(Doubt::WatchLost));
let _ = self.tx.send(SyncMsg::Rewatch);
}
self.roots.input(
folder.id,
if push_only {
RootInput::HandoffQueued
} else {
RootInput::Mirrored
},
);
let _ = self
.store
@@ -211,6 +263,13 @@ impl Syncer {
let progress = self.progress.lock().get(&folder.id).cloned();
self.progress_end(folder.id);
self.log_trace(folder, &result, started.elapsed());
if let Ok(outcome) = &result
&& !push_only
{
let (local, remote) = outcome.walked_in_full;
self.roots
.input(folder.id, RootInput::Covered { local, remote });
}
match result {
Ok(outcome) => {
// A folder only reaches `idle` when every path applied cleanly —
@@ -354,25 +413,33 @@ impl Syncer {
}
}
/// Shadow check of a deletion the pass is about to make: count and log it
/// when the evidence does not prove the path gone on the side the
/// deletion is based on. Acts on nothing; the filters before the plan are
/// what keep such a path out of it, and this says when they did not.
fn check_deletion<L: HasKind, R: HasKind>(
/// Whether the pass must not make a deletion it planned: the evidence does
/// not prove the path gone on the side the deletion is based on. Such a
/// deletion is logged, counted in the trace and as a failed step, and left
/// out; its baseline row stays, so the next pass plans it again.
///
/// The filters before the plan keep such a path out of it, so this
/// should never fire. When it does, a file stays on both sides rather than
/// going on the strength of a walk that never saw it.
fn refuses_deletion<L: HasKind, R: HasKind>(
&self,
evidence: &Evidence<'_, L, R>,
rel: &str,
side: Side,
) {
if let Some(basis) = evidence.unproven_deletion(rel, side) {
warn!(
rel,
?side,
?basis,
"sync: a planned deletion is not backed by proof of absence"
);
self.trace_count(Count::UnprovenDeletions, 1);
}
outcome: &mut Outcome,
) -> bool {
let Some(basis) = evidence.unproven_deletion(rel, side) else {
return false;
};
warn!(
rel,
?side,
?basis,
"sync: not deleting a path whose absence is not proven"
);
self.trace_count(Count::UnprovenDeletions, 1);
outcome.failed(&format!("{rel}: not deleted, its absence is not proven"));
true
}
/// Add `took` to a stage of the running pass's trace.
@@ -468,6 +535,9 @@ impl Syncer {
remote_root: &NodeUid,
rules: &IgnoreRules,
) -> Result<Outcome, PassAbort> {
// Intents sent before this moment that the pass does not send again
// are settled at its end (`effect`).
let pass_began = now_secs();
// Loaded before the walks: the remote one uses it to tell which files are
// unchanged and so can skip decrypting their claimed size, and its size is
// the only estimate available of how much this pass has to check — the walks
@@ -483,20 +553,74 @@ impl Syncer {
let mut local: HashMap<String, LocalItem> = HashMap::new();
let mut unscanned = Unscanned::default();
// What the watcher reported since the last pass (`local_dirty`).
// Claimed before the walk: a change made while it runs is newer than
// the claim, and stays marked for the next pass.
let claim = self.local_dirty.claim(folder_id);
// What the root state says this pass must walk in full (`root`).
let owed = self.roots.owed(folder_id);
// The last pass's walk, when the claim can bring it up to date: the
// watch was live since that pass claimed, the ignore rules are the
// same, the folder was walked in full lately, and the root state owes
// the disk nothing.
let kept = self.local_dirty.take_walk(folder_id).filter(|kept| {
claim.trusted
&& kept.rules == rules.source()
&& kept.walked_at.elapsed() < LOCAL_AUDIT_INTERVAL
});
let kept = match (kept, owed.local) {
(Some(_), Some(doubt)) => {
info!(
id = folder_id,
?doubt,
"sync: the root state asks for a walk of the whole disk"
);
None
}
(kept, _) => kept,
};
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,
)?;
let (walked_at, walked_in_full) = match kept {
Some(kept) => {
local = kept.items;
self.trace_count(Count::LocalReused, local.len());
// What is taken from the kept walk counts as scanned at once.
self.progress_scanned_many(folder_id, local.len());
rewalk_local_tree(
local_root,
rules,
&writing,
&claim,
&mut local,
&mut unscanned,
&mut |rel| self.progress_scanned(folder_id, base_name(rel)),
)?;
(kept.walked_at, false)
}
None => {
self.walk_local(
folder_id,
local_root,
rules,
&writing,
&mut local,
&mut unscanned,
)?;
(step, true)
}
};
self.trace_phase(Phase::LocalWalk, step.elapsed());
self.trace_count(Count::LocalEntries, local.len());
// See `push_pass`: the guard must not count excluded paths as lost.
guard_local_wipe(&tracked_baseline(&baseline, rules, &unscanned), &local)?;
self.check_local_dirty(
folder_id,
&claim,
walked_in_full,
&tracked_baseline(&baseline, rules, &unscanned),
&local,
);
let mut remote: HashMap<String, RemoteItem> = HashMap::new();
let mut remote_dirs: HashMap<String, NodeUid> = HashMap::new();
@@ -512,11 +636,12 @@ impl Syncer {
gaps: &mut gaps,
},
&baseline,
owed.remote.is_none(),
);
// Timed even when cut short: a walk that never ends is the case the
// trace exists for.
self.trace_phase(Phase::RemoteWalk, step.elapsed());
walked?;
let remote_in_full = walked?;
guard_remote_wipe(&tracked_baseline(&baseline, rules, &unscanned), &remote)?;
let mut order = classification_order(&local, &remote, &baseline, rules);
@@ -542,6 +667,7 @@ impl Syncer {
unscanned_report.extend(gaps.report());
let mut outcome = Outcome {
unscanned: unscanned_report,
walked_in_full: (walked_in_full, remote_in_full),
..Default::default()
};
// Folders to delete, collected here and removed deepest-first at the end
@@ -622,15 +748,19 @@ impl Syncer {
}
(true, false) => {
// In baseline, gone remotely → the remote side deleted it.
self.check_deletion(
if self.refuses_deletion(
&pass_evidence(rules, &local, &unscanned, &remote, &remote_dirs, &gaps),
rel,
Side::Local,
);
&mut outcome,
) {
continue;
}
delete_local_dirs.push(rel.clone());
}
(false, true) if !in_base => {
// New remote folder → create locally (cheap, inline).
outcome.local_changes += 1;
if let Err(e) = std::fs::create_dir_all(local_root.join(rel_to_path(rel)))
.map_err(|e| format!("mkdir {rel}: {e}"))
.and_then(|()| self.baseline_dir(folder_id, rel, &remote[rel].uid))
@@ -641,11 +771,14 @@ impl Syncer {
}
(false, true) => {
// In baseline, gone locally → the local side deleted it.
self.check_deletion(
if self.refuses_deletion(
&pass_evidence(rules, &local, &unscanned, &remote, &remote_dirs, &gaps),
rel,
Side::Remote,
);
&mut outcome,
) {
continue;
}
delete_remote_dirs.push((rel.clone(), remote[rel].uid.clone()));
}
(false, false) => {
@@ -719,6 +852,18 @@ impl Syncer {
}
FilePlan::Conflict => {
let remote = r.expect("conflict requires a remote file");
if self.landed_unanswered(folder_id, rel, remote.sha1.as_deref()) {
info!(
rel,
"sync: the file on Drive is an upload of ours that went unanswered; sending the newer local bytes as a revision of it"
);
batch.push(Pending::UploadRevision {
rel: rel.clone(),
uid: remote.uid.clone(),
seen: RemoteSeen::from(remote),
});
continue;
}
batch.push(Pending::Conflict {
rel: rel.clone(),
uid: remote.uid.clone(),
@@ -736,11 +881,14 @@ impl Syncer {
}
},
FilePlan::DeleteLocal => {
self.check_deletion(
if self.refuses_deletion(
&pass_evidence(rules, &local, &unscanned, &remote, &remote_dirs, &gaps),
rel,
Side::Local,
);
&mut outcome,
) {
continue;
}
let path = local_root.join(rel_to_path(rel));
// The plan comes from a scan taken before the remote walk,
// which can take minutes. An edit saved since then is not
@@ -751,7 +899,12 @@ impl Syncer {
outcome.deferred += 1;
continue;
}
if let Err(e) = removed_locally(std::fs::remove_file(&path)) {
outcome.local_changes += 1;
let intent = self.issue_effect(folder_id, rel, effect::DELETE_LOCAL);
let removed = removed_locally(std::fs::remove_file(&path));
let error = removed.as_ref().err().map(ToString::to_string);
self.settle_effect(intent.as_ref(), error.as_deref());
if let Err(e) = removed {
warn!(rel, error = %e, "sync: remove local file failed");
self.log_activity(
ActivityKind::Trash,
@@ -767,18 +920,24 @@ impl Syncer {
outcome.deleted += 1;
}
FilePlan::DeleteRemote => {
self.check_deletion(
if self.refuses_deletion(
&pass_evidence(rules, &local, &unscanned, &remote, &remote_dirs, &gaps),
rel,
Side::Remote,
);
&mut outcome,
) {
continue;
}
let remote = r.expect("remote deletion requires a remote file");
let intent = self.issue_effect(folder_id, rel, effect::TRASH);
let step = Instant::now();
let trashed = self
.rt
.block_on(self.drive.trash_nodes(std::slice::from_ref(&remote.uid)))
.and_then(batch::into_unit);
self.trace_call(Call::Trash, step.elapsed());
let error = trashed.as_ref().err().map(ToString::to_string);
self.settle_effect(intent.as_ref(), error.as_deref());
if let Err(e) = trashed {
warn!(rel, error = %e, "sync: trash remote failed");
self.log_activity(
@@ -826,7 +985,21 @@ impl Syncer {
.store
.sync_entries(folder_id)
.map_err(|e| format!("reload baseline: {e:?}"))?;
let intents: HashMap<String, StoredIntent> = delete_local_dirs
.iter()
.filter_map(|rel| {
let intent = self.issue_effect(folder_id, rel, effect::DELETE_LOCAL)?;
Some((rel.clone(), intent))
})
.collect();
for removal in remove_local_dirs(local_root, delete_local_dirs, &mut current) {
outcome.local_changes += 1;
// Kept is settled too: nothing is left to do about it.
let (rel, error) = match &removal {
DirRemoval::Removed(rel) | DirRemoval::Kept(rel, _) => (rel, None),
DirRemoval::Failed(rel, e) => (rel, Some(e.to_string())),
};
self.settle_effect(intents.get(rel), error.as_deref());
match removal {
DirRemoval::Removed(rel) => {
let _ = self.store.sync_entry_remove(folder_id, &rel);
@@ -882,12 +1055,15 @@ impl Syncer {
);
continue;
}
let intent = self.issue_effect(folder_id, &rel, effect::TRASH);
let step = Instant::now();
let trashed = self
.rt
.block_on(self.drive.trash_nodes(&[uid]))
.and_then(batch::into_unit);
self.trace_call(Call::Trash, step.elapsed());
let error = trashed.as_ref().err().map(ToString::to_string);
self.settle_effect(intent.as_ref(), error.as_deref());
if let Err(e) = trashed {
warn!(rel, error = %e, "sync: trash remote folder failed");
self.log_activity(ActivityKind::Trash, base_name(&rel), e.to_string(), false);
@@ -908,10 +1084,79 @@ impl Syncer {
}
self.trace_phase(Phase::Cleanup, cleanup.elapsed());
self.settle_deletions(folder_id, window, outcome.deleted);
// Every path was looked at and planned: what an earlier pass left
// unsettled and this one did not send again is no longer owed.
if outcome.unscanned.is_empty() && outcome.deferred == 0 {
self.supersede_intents(folder_id, pass_began);
}
// A change the pass could not apply stays dirty for the next one.
self.local_dirty.looked(
folder_id,
&claim,
outcome.errors == 0 && outcome.deferred == 0,
);
// The walk is kept for the next pass only when the pass changed
// nothing on disk itself and could read everything. A change of its
// own is marked only once the watcher reports it, which may come
// after the next pass claims, and a path left out has to be looked
// at again anyway.
if outcome.local_changes == 0
&& outcome.errors == 0
&& outcome.deferred == 0
&& unscanned.is_empty()
{
self.local_dirty.keep_walk(
folder_id,
LocalWalk {
items: local,
rules: rules.source(),
walked_at,
},
);
}
Ok(outcome)
}
/// Count the claimed marks of the local dirty set, and, after a walk of
/// the whole folder with a trusted claim, the local changes the walk
/// found that the claim did not cover. Those are changes a pass that
/// trusted the claim would have missed until the next full walk.
fn check_local_dirty(
&self,
folder_id: i64,
claim: &Claim,
walked_in_full: bool,
tracked: &HashMap<String, &StoredSyncEntry>,
local: &HashMap<String, LocalItem>,
) {
self.trace_count(Count::LocalDirty, claim.len());
if !claim.trusted {
self.trace_count(Count::LocalUntrusted, 1);
return;
}
if !walked_in_full {
return;
}
let missed = missed_local(claim, tracked, local);
if missed.is_empty() {
return;
}
for rel in &missed {
debug!(
id = folder_id,
rel, "sync: a local change the watcher did not report"
);
}
info!(
id = folder_id,
missed = missed.len(),
first = %missed[0],
"sync: the local dirty set missed changes the walk found"
);
self.trace_count(Count::MissedLocal, missed.len());
}
/// Open or continue the folder's deletion window for a pass that plans
/// `planned` deletions, and refuse the pass when they would make the
/// window a wipe ([`guard_delete_window`]). `tracked` is how many paths
@@ -964,6 +1209,33 @@ impl Syncer {
}
}
/// The local changes the walk found since the baseline that `claim` does not
/// cover: paths new on disk, files whose size or mtime moved, and tracked
/// paths gone. Sorted, for a stable log.
fn missed_local(
claim: &Claim,
tracked: &HashMap<String, &StoredSyncEntry>,
local: &HashMap<String, LocalItem>,
) -> Vec<String> {
let changed = local.iter().filter_map(|(rel, item)| {
let moved = match tracked.get(rel) {
None => true,
Some(base) => {
!item.is_dir && (base.local_mtime != item.mtime || base.local_size != item.size)
}
};
moved.then_some(rel)
});
let gone = tracked.keys().filter(|rel| !local.contains_key(*rel));
let mut missed: Vec<String> = changed
.chain(gone)
.filter(|rel| !claim.covers(rel))
.cloned()
.collect();
missed.sort();
missed
}
/// A [`Read`] that hashes what an upload reads through it, so the digest Drive
/// reports afterwards can be compared with what was sent.
/// The evidence of a mirror pass, built where it is asked so it borrows the
@@ -1073,6 +1345,11 @@ fn dir_row(rel: &str, uid: &NodeUid) -> StoredSyncEntry {
/// stream marked dirty; this full walk catches what the stream may have missed.
const AUDIT_INTERVAL: Duration = Duration::from_secs(24 * 3600);
/// How long a pass may bring the last local walk up to date from the local
/// dirty set before it walks the whole folder again. The full walk is what
/// checks the set: it counts what the set missed.
const LOCAL_AUDIT_INTERVAL: Duration = Duration::from_secs(3600);
/// How lately Drive's event stream must have been read for a pass to rely on
/// it. A few polls' worth.
const EVENTS_FRESH: Duration = Duration::from_secs(3 * crate::EVENT_POLL_INTERVAL.as_secs());
@@ -1791,6 +2068,59 @@ mod tests {
)])
}
/// A walk's changes that a claim of the local dirty set did not cover:
/// one next to a reported change is covered, the rest are missed.
#[test]
fn missed_local_lists_the_changes_a_claim_does_not_cover() {
use crate::local_dirty::LocalDirty;
let row = |rel: &str, mtime: i64| StoredSyncEntry {
rel_path: rel.to_string(),
remote_uid: Some("v~l".into()),
local_mtime: mtime,
local_size: 1,
local_mtime_ns: None,
remote_rev: None,
remote_hash: None,
remote_revision_id: None,
};
let rows: HashMap<String, StoredSyncEntry> = [
("docs", 0),
("docs/a.txt", 1),
("same.txt", 1),
("top.txt", 1),
("old/x.txt", 1),
]
.into_iter()
.map(|(rel, mtime)| (rel.to_string(), row(rel, mtime)))
.collect();
let tracked: HashMap<String, &StoredSyncEntry> =
rows.iter().map(|(k, v)| (k.clone(), v)).collect();
let item = |is_dir: bool, mtime: i64| LocalItem {
mtime_ns: None,
is_dir,
mtime,
size: 1,
open_for_write: false,
};
let local: HashMap<String, LocalItem> = [
("docs", item(true, 9)),
("docs/a.txt", item(false, 2)),
("docs/new.txt", item(false, 1)),
("same.txt", item(false, 1)),
("top.txt", item(false, 2)),
]
.into_iter()
.map(|(rel, item)| (rel.to_string(), item))
.collect();
let dirty = LocalDirty::default();
dirty.mark(1, "docs/a.txt");
let claim = dirty.claim(1);
assert_eq!(
missed_local(&claim, &tracked, &local),
vec!["old/x.txt".to_string(), "top.txt".to_string()]
);
}
#[test]
fn an_unchanged_mtime_reuses_the_recorded_size() {
// The whole point: this file's node key never gets unlocked.
@@ -2698,4 +3028,141 @@ mod tests {
o.deferred = 1;
assert!(!o.is_empty());
}
/// What a walk found, comparable: kind, mtime and size by path.
fn shape(items: &HashMap<String, LocalItem>) -> Vec<(String, bool, i64, i64)> {
let mut shape: Vec<_> = items
.iter()
.map(|(rel, item)| (rel.clone(), item.is_dir, item.mtime, item.size))
.collect();
shape.sort();
shape
}
/// Bring `kept` up to date with what `dirty` marked for folder 1.
fn rewalk(
root: &Path,
rules: &IgnoreRules,
dirty: &crate::local_dirty::LocalDirty,
kept: &mut HashMap<String, LocalItem>,
) -> Unscanned {
let mut unscanned = Unscanned::default();
rewalk_local_tree(
root,
rules,
&HashSet::new(),
&dirty.claim(1),
kept,
&mut unscanned,
&mut no_progress(),
)
.unwrap();
unscanned
}
#[test]
fn a_rewalk_of_the_marked_paths_finds_what_a_full_walk_finds() {
let root = sync_test_dir("rewalk");
std::fs::create_dir_all(root.join("docs/old")).unwrap();
std::fs::create_dir_all(root.join("quiet/deep")).unwrap();
std::fs::write(root.join("docs/a.txt"), b"a").unwrap();
std::fs::write(root.join("docs/b.txt"), b"b").unwrap();
std::fs::write(root.join("docs/old/x.txt"), b"x").unwrap();
std::fs::write(root.join("quiet/deep/q.txt"), b"q").unwrap();
let (mut kept, _) = scan(&root).unwrap();
// Each kind of change, marked as the watcher reports it.
let dirty = crate::local_dirty::LocalDirty::default();
std::fs::write(root.join("docs/a.txt"), b"edited, and longer").unwrap();
dirty.mark(1, "docs/a.txt");
std::fs::remove_file(root.join("docs/b.txt")).unwrap();
dirty.mark(1, "docs/b.txt");
std::fs::write(root.join("docs/new.txt"), b"new").unwrap();
dirty.mark(1, "docs/new.txt");
std::fs::remove_dir_all(root.join("docs/old")).unwrap();
dirty.mark(1, "docs/old");
// A folder moved in: one event, for the folder only.
let outside = sync_test_dir("rewalk-outside");
std::fs::create_dir_all(outside.join("moved/sub")).unwrap();
std::fs::write(outside.join("moved/sub/m.txt"), b"m").unwrap();
std::fs::rename(outside.join("moved"), root.join("moved")).unwrap();
dirty.mark(1, "moved");
let unscanned = rewalk(&root, &rules_for(&[]), &dirty, &mut kept);
assert!(unscanned.is_empty());
let (full, _) = scan(&root).unwrap();
assert_eq!(shape(&kept), shape(&full));
let _ = std::fs::remove_dir_all(&root);
let _ = std::fs::remove_dir_all(&outside);
}
#[test]
fn a_rewalk_takes_what_nothing_marked_from_the_kept_walk() {
let root = sync_test_dir("rewalk-kept");
std::fs::create_dir_all(root.join("quiet")).unwrap();
std::fs::write(root.join("quiet/q.txt"), b"q").unwrap();
let (mut kept, _) = scan(&root).unwrap();
// Changed with no mark: the rewalk does not look, which is why only
// a trusted claim may stand in for the walk.
std::fs::write(root.join("quiet/q.txt"), b"changed unseen").unwrap();
let before = shape(&kept);
rewalk(
&root,
&rules_for(&[]),
&crate::local_dirty::LocalDirty::default(),
&mut kept,
);
assert_eq!(shape(&kept), before);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn a_rewalk_leaves_ignored_folders_out_and_walks_from_a_known_folder() {
let root = sync_test_dir("rewalk-ignored");
let rules = rules_for(&["build/"]);
let (mut kept, _) = scan(&root).unwrap();
let dirty = crate::local_dirty::LocalDirty::default();
std::fs::create_dir_all(root.join("build/out")).unwrap();
std::fs::write(root.join("build/out/o.bin"), b"o").unwrap();
dirty.mark(1, "build/out/o.bin");
// A file in a folder whose own mark never came.
std::fs::create_dir_all(root.join("src/mod")).unwrap();
std::fs::write(root.join("src/mod/s.rs"), b"s").unwrap();
dirty.mark(1, "src/mod/s.rs");
rewalk(&root, &rules, &dirty, &mut kept);
let found: Vec<String> = shape(&kept).into_iter().map(|(rel, ..)| rel).collect();
assert_eq!(found, ["src", "src/mod", "src/mod/s.rs"]);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn a_rewalk_reads_again_a_file_that_was_open_for_writing() {
let root = sync_test_dir("rewalk-open");
std::fs::write(root.join("log.txt"), b"one").unwrap();
let (mut kept, _) = scan(&root).unwrap();
kept.get_mut("log.txt").unwrap().open_for_write = true;
std::fs::write(root.join("log.txt"), b"one and two").unwrap();
rewalk(
&root,
&rules_for(&[]),
&crate::local_dirty::LocalDirty::default(),
&mut kept,
);
let item = &kept["log.txt"];
assert_eq!(item.size, 11);
assert!(!item.open_for_write, "closed now");
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn a_mark_on_the_root_walks_everything() {
let root = sync_test_dir("rewalk-root");
let (mut kept, _) = scan(&root).unwrap();
std::fs::write(root.join("top.txt"), b"t").unwrap();
let dirty = crate::local_dirty::LocalDirty::default();
dirty.mark(1, "");
rewalk(&root, &rules_for(&[]), &dirty, &mut kept);
assert!(kept.contains_key("top.txt"));
let _ = std::fs::remove_dir_all(&root);
}
}
+230 -25
View File
@@ -134,6 +134,165 @@ impl Syncer {
Ok(())
}
/// Write the intent of `op` before it is sent (`effect`). In shadow: a
/// failure to write it is logged, and the op is sent anyway.
fn issue_intent(&self, folder_id: i64, op: &Pending) -> Option<StoredIntent> {
self.issue_effect(folder_id, op.rel(), op.intent())
}
/// Write the intent of an effect of `kind` on `rel` before it is sent,
/// for the ops that are not a [`Pending`], such as a deletion.
pub(super) fn issue_effect(
&self,
folder_id: i64,
rel: &str,
kind: &'static str,
) -> Option<StoredIntent> {
let (intent, before) = match self
.store
.sync_intent_issue(folder_id, rel, kind, now_secs())
{
Ok(issued) => issued,
Err(e) => {
debug!(id = folder_id, rel, error = ?e, "sync: cannot record an intent");
return None;
}
};
match before.as_deref().and_then(EffectState::from_name) {
// Sent by a daemon that stopped before it heard back. The apply
// step's own checks tell whether it landed (B266, B39).
Some(EffectState::Unsure) => {
self.trace_count(Count::UnsureResent, 1);
info!(
id = folder_id,
rel,
kind,
attempts = intent.attempts,
"sync: sending again an effect a stopped daemon may have made"
);
}
Some(EffectState::Retry | EffectState::Blocked) => {
self.trace_count(Count::Retried, 1);
}
_ => {}
}
Some(intent)
}
/// Settle `intent` when its effect succeeded (`error` is `None`), or
/// keep it with the failure. No intent, when it could not be written,
/// does nothing.
pub(super) fn settle_effect(&self, intent: Option<&StoredIntent>, error: Option<&str>) {
let Some(intent) = intent else {
return;
};
let written = match error {
None => self.store.sync_intent_settle(intent.id),
Some(e) => {
let state = effect::failed(intent.attempts);
if state == EffectState::Blocked && intent.state != EffectState::Blocked.name() {
warn!(
id = intent.folder_id,
rel = %intent.rel_path,
kind = %intent.kind,
attempts = intent.attempts,
error = %e,
"sync: an effect keeps failing"
);
}
self.store.sync_intent_set(intent.id, state.name(), Some(e))
}
};
if let Err(e) = written {
debug!(
id = intent.folder_id,
rel = %intent.rel_path,
error = ?e,
"sync: cannot settle an intent"
);
}
}
/// Note that an upload of `rel` streamed bytes with SHA-1 `sha1` and did
/// not hear a success back. They may have landed all the same.
fn note_sent(&self, folder_id: i64, rel: &str, kind: &str, sha1: &str) {
if let Err(error) = self.store.sync_intent_sent(folder_id, rel, kind, sha1) {
debug!(rel, error = ?error, "sync: cannot note what an upload sent");
}
}
/// Whether the file Drive holds at `rel`, with SHA-1 `remote_sha1`, is one
/// of this daemon's own uploads whose answer never came: an upload of
/// `rel` not yet settled streamed exactly those bytes.
///
/// Then the file is ours, not another computer's, and a newer local edit
/// is not a conflict with it: it goes up as a revision. A file that only
/// happens to hold the same bytes loses nothing by that either.
pub(super) fn landed_unanswered(
&self,
folder_id: i64,
rel: &str,
remote_sha1: Option<&str>,
) -> bool {
let Some(remote_sha1) = remote_sha1 else {
return false;
};
let intents = match self.store.sync_intents(Some(folder_id)) {
Ok(intents) => intents,
Err(error) => {
debug!(rel, error = ?error, "sync: cannot read the effect intents");
return false;
}
};
intents.iter().any(|intent| {
intent.rel_path == rel
&& matches!(intent.kind.as_str(), "upload" | "upload-revision")
&& intent
.sent_sha1s
.iter()
.any(|sent| sent.eq_ignore_ascii_case(remote_sha1))
})
}
/// Settle the intents of `folder_id` that a pass begun at `began` did
/// not send again, though it looked at every path: what they were for has
/// changed, or is done.
pub(super) fn supersede_intents(&self, folder_id: i64, began: i64) {
let states = [
EffectState::Unsure.name(),
EffectState::Retry.name(),
EffectState::Blocked.name(),
];
match self
.store
.sync_intents_settle_before(folder_id, &states, began)
{
Ok(settled) => {
self.trace_count(Count::Superseded, settled.len());
for intent in settled {
let level_info = intent.state == EffectState::Unsure.name();
if level_info {
info!(
id = folder_id,
rel = %intent.rel_path,
kind = %intent.kind,
"sync: an effect a stopped daemon may have made is no longer needed"
);
} else {
debug!(
id = folder_id,
rel = %intent.rel_path,
kind = %intent.kind,
state = %intent.state,
"sync: an effect is no longer needed"
);
}
}
}
Err(e) => debug!(id = folder_id, error = ?e, "sync: cannot settle intents"),
}
}
/// 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)
@@ -150,9 +309,11 @@ impl Syncer {
op: Pending,
) -> Result<Applied, String> {
self.progress_started(folder_id, base_name(op.rel()));
let intent = self.issue_intent(folder_id, &op);
let step = Instant::now();
let result = self.apply_one(folder_id, local_root, &op).await;
self.trace_call(op.call(), step.elapsed());
self.settle_effect(intent.as_ref(), result.as_ref().err().map(String::as_str));
self.progress_finished(folder_id);
let name = base_name(op.rel());
match &result {
@@ -220,6 +381,15 @@ impl Syncer {
return Ok(Applied::Vanished);
}
if !digest.eq_ignore_ascii_case(sha1) {
if self.landed_unanswered(folder_id, rel, Some(sha1)) {
info!(
rel,
"sync: the file on Drive is an upload of ours that went unanswered; sending the newer local bytes as a revision of it"
);
return self
.upload_revision(folder_id, local_root, rel, uid, remote)
.await;
}
info!(
rel,
"sync: same size as on Drive but different content; keeping a conflict copy"
@@ -341,8 +511,14 @@ impl Syncer {
Some(mtime),
false,
)
.await
.map_err(|e| format!("upload {rel}: {e}"))?;
.await;
let uid = match uid {
Ok(uid) => uid,
Err(e) => {
self.note_sent(folder_id, rel, "upload", &sent.digest());
return Err(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).
@@ -362,9 +538,13 @@ impl Syncer {
/// 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.
/// local edit as a conflict copy (B249). A revision committed after the
/// upload is caught by the read-back.
///
/// When the pass knows the revision id, the check rides on the read of the
/// file the upload makes for its keys (`upload_new_revision_over`), and the
/// revision is created over that id, so Drive refuses one committed in
/// between. A baseline without an id still reads the node first.
pub(super) async fn upload_revision(
&self,
folder_id: i64,
@@ -377,22 +557,16 @@ impl Syncer {
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"
));
if seen.revision.is_none() {
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(moved_on_drive(rel)),
_ => return Err(gone_from_drive(rel)),
}
}
let meta = file.metadata().map_err(|e| format!("stat {rel}: {e}"))?;
@@ -410,10 +584,28 @@ impl Syncer {
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}"))?;
let size = meta.len() as i64;
let uploaded = match seen.revision.as_deref() {
Some(expected) => self
.drive
.upload_new_revision_over(uid, expected, reader, size, thumbnails, Some(mtime))
.await
.map(Some),
None => self
.drive
.upload_new_revision_from(uid, reader, size, thumbnails, Some(mtime))
.await
.map(|()| None),
};
match uploaded {
Ok(None | Some(pdfs_drive::RevisionUpload::Sealed(_))) => {}
Ok(Some(pdfs_drive::RevisionUpload::Moved)) => return Err(moved_on_drive(rel)),
Ok(Some(pdfs_drive::RevisionUpload::Trashed)) => return Err(gone_from_drive(rel)),
Err(e) => {
self.note_sent(folder_id, rel, "upload-revision", &sent.digest());
return Err(format!("upload revision {rel}: {e}"));
}
}
warn_if_torn(rel, &path, streamed);
let remote = self
.landed_as_sent(rel, uid, &sent.digest(), streamed)
@@ -582,3 +774,16 @@ impl Syncer {
.map_err(|e| format!("baseline {rel}: {e:?}"))
}
}
/// Why a revision was not sent: Drive's file moved on since the pass looked.
fn moved_on_drive(rel: &str) -> String {
format!("{rel} changed on Drive since this pass looked; it is compared again on the next pass")
}
/// Why a revision was not sent: the file is no longer on Drive where the pass
/// saw it.
fn gone_from_drive(rel: &str) -> String {
format!(
"{rel} is no longer on Drive where this pass saw it; it is compared again on the next pass"
)
}
+91 -8
View File
@@ -10,6 +10,8 @@ use std::collections::BTreeMap;
use super::trace::PassTrace;
use super::*;
use crate::local_dirty::{LocalDirty, root_id};
use crate::root::{Doubt, RootInput};
/// How long the watcher must go quiet before a burst counts as finished.
///
@@ -240,27 +242,52 @@ pub fn run(core: Syncer, rx: Receiver<SyncMsg>) {
),
Err(e) => warn!(error = ?e, "sync: cannot reset folders left syncing"),
}
// An effect still `issued` was sent by a daemon that stopped before it
// heard back: it may or may not have happened (`effect`).
match core.store.sync_intents_move(
effect::EffectState::Issued.name(),
effect::EffectState::Unsure.name(),
) {
Ok(0) => {}
Ok(n) => info!(
effects = n,
"sync: effects the last run sent and did not hear back from"
),
Err(e) => warn!(error = ?e, "sync: cannot read the effects the last run sent"),
}
// Paths the watcher currently covers, mapped to their folder id, so an event
// path can be resolved back to the folder it belongs to.
let watched: Arc<Mutex<Vec<(PathBuf, i64)>>> = Arc::new(Mutex::new(Vec::new()));
let tx_events = core.tx.clone();
let watched_events = watched.clone();
let dirty = core.local_dirty.clone();
let roots = core.roots.clone();
let handler = move |res: notify::Result<notify::Event>| {
let event = match res {
Ok(event) => event,
// Running out of inotify watches for a new subfolder, say: that
// subfolder's changes are then found by the poll only (B262).
// Nothing says which, so no folder's dirty set is whole now.
Err(e) => {
warn!(error = %e, "sync: filesystem watcher error");
dirty.lost();
roots.input_all(RootInput::Doubted(Doubt::WatchLost));
return;
}
};
if event.need_rescan() {
dirty.overflowed();
roots.input_all(RootInput::Doubted(Doubt::Overflow));
}
// Ignore pure metadata/access noise; content changes are what matter.
if matches!(event.kind, notify::EventKind::Access(_)) {
return;
}
let msg = event_target(&watched_events.lock(), &event.paths);
let watched = watched_events.lock();
mark_dirty(&dirty, &watched, &event.paths);
let msg = event_target(&watched, &event.paths);
drop(watched);
let _ = tx_events.send(msg);
};
// The local walk skips symlinks, so following them here would only watch
@@ -292,7 +319,7 @@ pub fn run(core: Syncer, rx: Receiver<SyncMsg>) {
.ok();
}
let mut unwatched = rewatch(&core, &mut watcher, &watched);
let (mut unwatched, _) = rewatch(&core, &mut watcher, &watched);
let mut last_rewatch = Instant::now();
run_burst(&core, &HashSet::new(), true);
@@ -313,7 +340,14 @@ pub fn run(core: Syncer, rx: Receiver<SyncMsg>) {
do_rewatch = true;
}
if do_rewatch {
unwatched = rewatch(&core, &mut watcher, &watched);
let newly;
(unwatched, newly) = rewatch(&core, &mut watcher, &watched);
// A change made before its folder was watched has no event. A
// folder whose root came back was watched only after the pass
// that found it walked it, so what was written in between waits
// for this pass, which walks it in full: its claim is not trusted
// yet.
ids.extend(newly);
last_rewatch = Instant::now();
}
run_burst(&core, &ids, all);
@@ -513,9 +547,33 @@ pub(super) fn event_target(watched: &[(PathBuf, i64)], paths: &[PathBuf]) -> Syn
}
}
/// Mark each of `paths` in the local dirty set of the folder it is in.
pub(super) fn mark_dirty(dirty: &LocalDirty, watched: &[(PathBuf, i64)], paths: &[PathBuf]) {
for path in paths {
let Some((root, id)) = watched
.iter()
.filter(|(root, _)| path.starts_with(root))
.max_by_key(|(root, _)| root.components().count())
else {
continue;
};
let Ok(rel) = path.strip_prefix(root) else {
continue;
};
// A name that is not UTF-8 cannot be keyed: the folder that holds
// it is marked instead, so the walk of it reports the name it leaves
// out.
let parts: Vec<&str> = rel
.components()
.map_while(|c| c.as_os_str().to_str())
.collect();
dirty.mark(*id, &parts.join("/"));
}
}
/// Bring the filesystem watches in line with the current mirror-folder set:
/// watch newly-added folders, drop removed ones. Returns whether a folder is
/// left unwatched because its watch failed.
/// left unwatched because its watch failed, and the folders watched anew.
///
/// The watch calls run on a copy, outside the lock: the watcher's event
/// callback takes the same lock, and a backend that hands a watch request to
@@ -524,7 +582,7 @@ fn rewatch(
core: &Syncer,
watcher: &mut notify::RecommendedWatcher,
watched: &Mutex<Vec<(PathBuf, i64)>>,
) -> bool {
) -> (bool, Vec<i64>) {
let want: Vec<(PathBuf, i64)> = match core.store.sync_folder_list() {
Ok(f) => f
.into_iter()
@@ -533,23 +591,48 @@ fn rewatch(
.collect(),
Err(e) => {
warn!(error = ?e, "sync: cannot list folders to watch");
return false;
return (false, Vec::new());
}
};
let mut have = watched.lock().clone();
let before = have.clone();
// Drop watches no longer wanted.
for path in keep_wanted(&mut have, &want) {
let _ = watcher.unwatch(&path);
if let Some((_, id)) = before.iter().find(|(p, _)| *p == path) {
core.local_dirty.forget(*id);
core.roots.forget(*id);
}
}
// A root that is gone took its watch with it, and a root made again is
// another folder than the one watched: drop the watch, so the root is
// watched again below.
have.retain(|(path, id)| {
let same = core
.local_dirty
.watched_root(*id)
.is_some_and(|root| root_id(path) == Some(root));
if !same {
let _ = watcher.unwatch(path);
core.local_dirty.unwatched(*id);
}
same
});
// Add newly wanted watches.
let mut failed = false;
let mut newly = Vec::new();
for (path, id) in &want {
if have.iter().any(|(p, _)| p == path) {
continue;
}
match watcher.watch(path, RecursiveMode::Recursive) {
Ok(()) => have.push((path.clone(), *id)),
Ok(()) => {
have.push((path.clone(), *id));
core.local_dirty.watched(*id, root_id(path));
newly.push(*id);
}
Err(e) => {
core.local_dirty.unwatched(*id);
// A recursive watch that fails partway keeps the watches it had
// added. Their events would match no folder and run a pass over
// every one, and they hold watches the next folder needs (B262).
@@ -565,7 +648,7 @@ fn rewatch(
}
}
*watched.lock() = have;
failed
(failed, newly)
}
/// Keep the watches in `have` that `want` still asks for, and return the paths
+5
View File
@@ -86,6 +86,11 @@ pub struct SyncParts {
/// first read. A pass trusts the feed's dirty folders only while it is
/// being read.
pub events_read_at: Arc<AtomicI64>,
/// Where each mirror folder changed on disk since a pass last looked,
/// as the filesystem watcher reports it.
pub local_dirty: Arc<crate::local_dirty::LocalDirty>,
/// What each mirror folder's sync knows about its coverage (`root`).
pub roots: Arc<crate::root::Roots>,
/// When each step of a pass may start: its uploads, downloads and folder
/// creations.
pub admission: Arc<dyn pdfs_sched::Admission>,
+254 -72
View File
@@ -19,8 +19,9 @@ use tracing::{debug, warn};
use super::model::{LocalItem, LocalSig, system_mtime, system_mtime_ns};
use super::planner::{
Unscanned, conflict_path_with_suffix, filter_baseline, join_rel, rel_to_path,
Unscanned, conflict_path_with_suffix, filter_baseline, join_rel, parent_rel, rel_to_path,
};
use crate::local_dirty::Claim;
/// A local file's identity and content SHA-1, both read from one descriptor,
/// or `None` when it is gone. The identity is taken after the hash, so a file
@@ -270,90 +271,271 @@ pub(super) fn walk_local_dir(
let entries = std::fs::read_dir(dir).map_err(io(format!("read {}", dir.display())))?;
for entry in entries {
let entry = entry.map_err(io(format!("read entry in {}", dir.display())))?;
let path = entry.path();
let stripped = path.strip_prefix(root).map_err(|e| {
ScanError::Failed(format!(
"local path {} escaped sync root {}: {e}",
path.display(),
root.display()
))
})?;
let Some(rel) = stripped.to_str() else {
// Nothing can be keyed by this name: not the baseline, which only
// ever held paths this scan produced, and not Drive, whose names are
// UTF-8. Leaving it out cannot read as a deletion of anything.
warn!(path = %path.display(), "sync: name is not valid UTF-8; leaving it out of the pass");
unscanned.unreadable(
stripped.to_string_lossy().into_owned(),
"name is not valid UTF-8",
);
continue;
};
// Ignore our own in-flight download temp files.
if rel.contains(".pdfs-tmp-") {
walk_local_entry(root, &entry.path(), rules, writing, out, unscanned, scanned)?;
}
Ok(())
}
/// Collect one entry of the local tree, at `path`, into `out`: a file, or a
/// folder with everything under it. What cannot be read goes to `unscanned`,
/// as in [`walk_local_tree`].
pub(super) fn walk_local_entry(
root: &Path,
path: &Path,
rules: &IgnoreRules,
writing: &HashSet<PathBuf>,
out: &mut HashMap<String, LocalItem>,
unscanned: &mut Unscanned,
scanned: &mut dyn FnMut(&str),
) -> Result<(), ScanError> {
let stripped = path.strip_prefix(root).map_err(|e| {
ScanError::Failed(format!(
"local path {} escaped sync root {}: {e}",
path.display(),
root.display()
))
})?;
let Some(rel) = stripped.to_str() else {
// Nothing can be keyed by this name: not the baseline, which only
// ever held paths this scan produced, and not Drive, whose names are
// UTF-8. Leaving it out cannot read as a deletion of anything.
warn!(path = %path.display(), "sync: name is not valid UTF-8; leaving it out of the pass");
unscanned.unreadable(
stripped.to_string_lossy().into_owned(),
"name is not valid UTF-8",
);
return Ok(());
};
// Ignore our own in-flight download temp files.
if rel.contains(".pdfs-tmp-") {
return Ok(());
}
let meta = match std::fs::symlink_metadata(path) {
Ok(meta) => meta,
// Gone since the listing, or in a folder that lists but does not
// allow `stat`. Either way this pass cannot say what it is.
Err(error) => {
let what = format!("stat {}", path.display());
return leave_out(rel, ScanError::Io { what, error }, unscanned);
}
};
// Ignored paths are dropped here as well as from the classification
// union — not for correctness (the union filter is what makes this
// safe) but so an ignored `node_modules/` is never descended into or
// counted against scan progress.
if rules.is_ignored(rel, meta.is_dir()) {
return Ok(());
}
if meta.is_dir() {
out.insert(
rel.to_string(),
LocalItem {
is_dir: true,
mtime: 0,
mtime_ns: None,
size: 0,
open_for_write: false,
},
);
scanned(rel);
if let Err(failure) = walk_local_dir(root, path, rules, writing, out, unscanned, scanned) {
leave_out(rel, failure, unscanned)?;
// What the folder did list before failing goes with it: a
// half-read folder is as unknown as an unread one.
let prefix = format!("{rel}/");
out.retain(|k, _| k != rel && !k.starts_with(&prefix));
}
} else if meta.is_file() {
// Check whether any process holds this file open for writing.
// The canonical path is used because /proc/*/fd links resolve
// to canonical targets.
let ofw = std::fs::canonicalize(path)
.map(|canon| writing.contains(&canon))
.unwrap_or(false);
out.insert(
rel.to_string(),
LocalItem {
is_dir: false,
mtime: system_mtime(&meta),
mtime_ns: system_mtime_ns(&meta),
size: meta.len() as i64,
open_for_write: ofw,
},
);
scanned(rel);
}
Ok(())
}
/// Bring `items`, a walk of `root` that an earlier pass kept, up to date with
/// what `claim` reports changed since, instead of walking the whole tree:
///
/// - each folder whose direct children changed is listed again: a child gone
/// from it goes with everything under it, a child that is new or no longer
/// the same kind is walked, and a subfolder still there keeps what the
/// earlier walk found under it;
/// - each path that changed in full is walked again, with what is under it;
/// - each file that was open for writing is read again, since closing it is
/// not a change the watcher reports.
///
/// Everything else stands as the earlier walk found it. That is only sound
/// for a claim that is trusted, of a walk taken before it, with the same
/// ignore rules: see `local_dirty`.
pub(super) fn rewalk_local_tree(
root: &Path,
rules: &IgnoreRules,
writing: &HashSet<PathBuf>,
claim: &Claim,
items: &mut HashMap<String, LocalItem>,
unscanned: &mut Unscanned,
scanned: &mut dyn FnMut(&str),
) -> Result<(), String> {
let walked = |rel: &str, items: &HashMap<String, LocalItem>| {
rel.is_empty() || items.get(rel).is_some_and(|item| item.is_dir)
};
// A path whose folder the earlier walk did not find (a mark that came
// before its folder's, or one in an ignored folder) is walked from the
// nearest folder it did find.
let anchored = |mut rel: String, items: &HashMap<String, LocalItem>| {
while !walked(parent_rel(&rel), items) {
rel = parent_rel(&rel).to_string();
}
rel
};
// Paths walked again in full.
let mut again: Vec<String> = claim
.deep()
.map(str::to_string)
.chain(
items
.iter()
.filter(|(_, item)| item.open_for_write)
.map(|(rel, _)| rel.clone()),
)
.map(|rel| anchored(rel, items))
.collect();
if again.iter().any(String::is_empty) {
items.clear();
return walk_local_tree(root, rules, writing, items, unscanned, scanned);
}
let mut folders: Vec<&str> = claim.shallow().collect();
folders.sort_by_key(|dir| (dir.matches('/').count(), *dir));
let mut children: HashMap<&str, Vec<String>> =
folders.iter().map(|dir| (*dir, Vec::new())).collect();
for rel in items.keys() {
if let Some(of) = children.get_mut(parent_rel(rel)) {
of.push(rel.clone());
}
}
// Subtrees to drop from the earlier walk before walking anything again.
let mut dropped: HashSet<String> = again.iter().cloned().collect();
for dir in folders {
if !walked(dir, items) {
// Not a folder the earlier walk found: new, ignored, or no
// longer a folder. It is walked in full.
let rel = anchored(dir.to_string(), items);
dropped.insert(rel.clone());
again.push(rel);
continue;
}
let meta = match std::fs::symlink_metadata(&path) {
Ok(meta) => meta,
// Gone since the listing, or in a folder that lists but does not
// allow `stat`. Either way this pass cannot say what it is.
let path = root.join(rel_to_path(dir));
let listing = std::fs::read_dir(&path).and_then(|entries| {
entries
.map(|entry| entry.map(|entry| entry.path()))
.collect::<std::io::Result<Vec<PathBuf>>>()
});
let listing = match listing {
Ok(listing) => listing,
Err(error) if dir.is_empty() => {
return Err(format!("read {}: {error}", path.display()));
}
Err(error) => {
let what = format!("stat {}", path.display());
leave_out(rel, ScanError::Io { what, error }, unscanned)?;
dropped.insert(dir.to_string());
if error.kind() != std::io::ErrorKind::NotFound {
let what = format!("read {}", path.display());
leave_out(dir, ScanError::Io { what, error }, unscanned)
.map_err(|e| e.to_string())?;
}
continue;
}
};
// Ignored paths are dropped here as well as from the classification
// union — not for correctness (the union filter is what makes this
// safe) but so an ignored `node_modules/` is never descended into or
// counted against scan progress.
if rules.is_ignored(rel, meta.is_dir()) {
continue;
let mut present: HashSet<String> = HashSet::with_capacity(listing.len());
for child in listing {
let Some(rel) = child
.strip_prefix(root)
.ok()
.and_then(|rel| rel.to_str())
.map(str::to_string)
else {
// Walked again, so a name that cannot be keyed is reported
// as a full walk reports it.
again.push(dir.to_string());
dropped.insert(dir.to_string());
break;
};
let still_a_folder = items.get(&rel).is_some_and(|item| item.is_dir)
&& std::fs::symlink_metadata(&child).is_ok_and(|meta| meta.is_dir());
if !still_a_folder {
dropped.insert(rel.clone());
again.push(rel.clone());
}
present.insert(rel);
}
if meta.is_dir() {
out.insert(
rel.to_string(),
LocalItem {
is_dir: true,
mtime: 0,
mtime_ns: None,
size: 0,
open_for_write: false,
},
);
scanned(rel);
if let Err(failure) =
walk_local_dir(root, &path, rules, writing, out, unscanned, scanned)
{
leave_out(rel, failure, unscanned)?;
// What the folder did list before failing goes with it: a
// half-read folder is as unknown as an unread one.
let prefix = format!("{rel}/");
out.retain(|k, _| k != rel && !k.starts_with(&prefix));
for rel in &children[dir] {
if !present.contains(rel) {
dropped.insert(rel.clone());
}
} else if meta.is_file() {
// Check whether any process holds this file open for writing.
// The canonical path is used because /proc/*/fd links resolve
// to canonical targets.
let ofw = std::fs::canonicalize(&path)
.map(|canon| writing.contains(&canon))
.unwrap_or(false);
out.insert(
rel.to_string(),
LocalItem {
is_dir: false,
mtime: system_mtime(&meta),
mtime_ns: system_mtime_ns(&meta),
size: meta.len() as i64,
open_for_write: ofw,
},
);
scanned(rel);
}
}
items.retain(|rel, _| !under_any(rel, &dropped));
again.sort_by_key(|rel| (rel.matches('/').count(), rel.clone()));
again.dedup();
let mut walked_again: HashSet<String> = HashSet::new();
for rel in again {
if under_any(&rel, &walked_again) {
continue;
}
let path = root.join(rel_to_path(&rel));
match std::fs::symlink_metadata(&path) {
Ok(_) => {
walk_local_entry(root, &path, rules, writing, items, unscanned, scanned)
.map_err(|e| e.to_string())?;
}
// Gone since it was marked, or its folder is no longer one:
// nothing to find.
Err(error)
if matches!(
error.kind(),
std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
) => {}
Err(error) => {
let what = format!("stat {}", path.display());
leave_out(&rel, ScanError::Io { what, error }, unscanned)
.map_err(|e| e.to_string())?;
}
}
walked_again.insert(rel);
}
Ok(())
}
/// Whether `rel` is one of `roots` or lies under one.
fn under_any(rel: &str, roots: &HashSet<String>) -> bool {
if roots.is_empty() {
return false;
}
let mut at = rel;
loop {
if roots.contains(at) {
return true;
}
match at.rfind('/') {
Some(i) => at = &at[..i],
None => return false,
}
}
}
/// Why the mirror copy at `rel` holds something Proton Drive does not, or
/// `None` when everything under it is on Drive exactly as it is on disk.
///
+10 -6
View File
@@ -314,9 +314,10 @@ impl Syncer {
unscanned: &unscanned,
remote: None,
};
for rel in &deletions {
self.check_deletion(&evidence, rel, Side::Remote);
}
let deletions: Vec<String> = deletions
.into_iter()
.filter(|rel| !self.refuses_deletion(&evidence, rel, Side::Remote, &mut outcome))
.collect();
let mut trashed: Vec<String> = Vec::new();
for rel in &deletions {
if trashed
@@ -330,11 +331,14 @@ impl Syncer {
let _ = self.store.sync_entry_remove(folder_id, rel);
continue;
};
if let Err(e) = self
let intent = self.issue_effect(folder_id, rel, effect::TRASH);
let result = self
.rt
.block_on(self.drive.trash_nodes(&[uid]))
.and_then(batch::into_unit)
{
.and_then(batch::into_unit);
let error = result.as_ref().err().map(ToString::to_string);
self.settle_effect(intent.as_ref(), error.as_deref());
if let Err(e) = result {
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}"));
+22 -5
View File
@@ -79,18 +79,25 @@ impl Syncer {
/// 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.
///
/// With `reuse` false, a complete saved walk is not used: the root state
/// owes Drive a walk in full. Returns whether the walk covered all of
/// Drive's side, rather than only the folders marked dirty.
pub(super) fn walk_remote(
&self,
folder_id: i64,
root: &NodeUid,
walk: &mut RemoteWalk<'_>,
baseline: &HashMap<String, StoredSyncEntry>,
) -> Result<(), PassAbort> {
reuse: bool,
) -> Result<bool, PassAbort> {
let WalkStart {
mut todo,
mut children,
dirty_upto,
} = self.start_walk(folder_id, root, walk);
} = self.start_walk(folder_id, root, walk, reuse);
// Started from the saved picture, the walk lists only what changed.
let in_full = children.is_none();
// Folders to list again next pass: their listing failed or came back
// short this time.
let mut again: Vec<String> = Vec::new();
@@ -221,7 +228,8 @@ impl Syncer {
return Err(PassAbort::Stopped);
}
self.finish_walk(folder_id, dirty_upto, &again)
.map_err(|e| PassAbort::from(format!("save the walk of Drive: {e:?}")))
.map_err(|e| PassAbort::from(format!("save the walk of Drive: {e:?}")))?;
Ok(in_full)
}
/// Keep a walk that reached its end as the next pass's picture of Drive.
@@ -264,6 +272,7 @@ impl Syncer {
folder_id: i64,
root: &NodeUid,
walk: &mut RemoteWalk<'_>,
reuse: bool,
) -> WalkStart {
let root_uid = root.to_string();
let saved = match self.store.sync_walk_load(folder_id) {
@@ -277,9 +286,17 @@ impl Syncer {
&& saved.root_uid == root_uid
{
let age = now_secs().saturating_sub(saved.started);
if saved.complete
let fresh = saved.complete
&& age < AUDIT_INTERVAL.as_secs() as i64
&& self.events_trusted(root)
&& self.events_trusted(root);
if fresh && !reuse {
info!(
id = folder_id,
"sync: the root state asks for a walk of all of Drive"
);
}
if fresh
&& reuse
&& let Some(start) = self.walk_dirty(folder_id, &saved, walk)
{
return start;
+30 -2
View File
@@ -146,6 +146,15 @@ pub struct Outcome {
/// The first step that failed in this pass, so the line that ends a pass
/// in `error` says why without a search back through the journal.
pub first_error: Option<String>,
/// Changes the pass made on disk itself: files downloaded, conflict
/// copies kept, folders made, and files and folders removed. Not part of
/// the summary, which counts them by kind; a pass that made any does not
/// keep its walk for the next one (`local_dirty`).
pub local_changes: usize,
/// Which sides the pass walked in full, rather than bringing the last
/// walk up to date from the dirty set: the disk, and Drive. The root
/// state counts a side covered only after a walk in full (`root`).
pub walked_in_full: (bool, bool),
}
impl Outcome {
@@ -162,8 +171,14 @@ impl Outcome {
match applied {
Applied::Dir(..) => self.created += 1,
Applied::Uploaded => self.uploaded += 1,
Applied::Downloaded => self.downloaded += 1,
Applied::Conflict => self.conflicts += 1,
Applied::Downloaded => {
self.downloaded += 1;
self.local_changes += 1;
}
Applied::Conflict => {
self.conflicts += 1;
self.local_changes += 1;
}
Applied::Vanished | Applied::Adopted => {}
}
}
@@ -292,6 +307,19 @@ impl Pending {
}
}
/// The kind of effect its intent records (`effect`).
pub fn intent(&self) -> &'static str {
match self {
Pending::CreateDir { .. } => "create-folder",
Pending::UploadNew { .. } => "upload",
Pending::UploadRevision { .. } => "upload-revision",
Pending::Download { .. } => "download",
Pending::Adopt { .. } => "adopt",
Pending::Conflict { .. } => "conflict",
Pending::PushConflict { .. } => "push-conflict",
}
}
/// The activity line's detail, which distinguishes ops that share a kind.
pub fn detail(&self) -> &'static str {
match self {
+5
View File
@@ -126,6 +126,11 @@ impl Unscanned {
.insert(rel, crate::evidence::Unknown::Unreadable);
}
/// Whether nothing was left out.
pub fn is_empty(&self) -> bool {
self.covered.is_empty()
}
/// Whether `rel` is a left-out path or lies under one.
pub fn covers(&self, rel: &str) -> bool {
self.why(rel).is_some()
+474
View File
@@ -0,0 +1,474 @@
//! The root reducer: what a mirror folder's sync knows about its coverage,
//! as one state machine per folder (`docs/SYNC_ENGINE.md`).
//!
//! [`step`] is pure: it takes the state and one input and returns the next
//! state. Time, the watcher, the event stream and the passes stay outside, as
//! inputs, so a sequence of inputs replays exactly.
//!
//! The phases say how far the engine can trust what it has seen:
//!
//! - **Discovering**: no pass over the folder has finished yet.
//! - **Following**: passes covered the whole folder, and nothing since says a
//! change could have gone unreported. A pass may work from the dirty sets.
//! - **Auditing**: something did (a lost watch, an overflowed queue, a gap in
//! Drive's event stream, a restart). Only a pass that walks the doubted
//! side in full brings it back to Following.
//! - **Suspended**: the folder cannot be synced for now: its local root is
//! missing, or sync is paused.
//! - **Draining**: a switch to on-demand is queued; passes only push.
//! - **HandedOff**: the folder is on-demand.
//!
//! A doubt is about one side. The disk is followed by the watcher and Drive
//! by its event stream, and each can fail on its own: a restart misses what
//! happened on disk while the daemon was down, but the event stream resumes
//! from its cursor. So the state keeps a doubt for each side ([`Owed`]), and
//! a pass walks in full only the side that is owed.
//!
//! A pass asks [`Roots::owed`] before it walks. The checks a pass made
//! before the reducer was acted on (a trusted watch, a fresh event stream,
//! the audit intervals) still apply on top: the reducer can make a pass walk
//! more, never less.
use std::collections::HashMap;
use std::fmt;
use parking_lot::Mutex;
use tracing::info;
/// Why a side of a folder is in doubt.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Doubt {
/// Nothing has walked this side yet.
FirstSync,
/// The daemon started: nothing watched the disk while it was down.
Restart,
/// The filesystem watcher reported an error, or the folder's watch is
/// gone.
WatchLost,
/// The watcher's event queue overflowed.
Overflow,
/// Drive's event stream lost changes.
EventGap,
/// The folder only pushed for a while, which drops its picture of Drive.
Pushed,
}
impl Doubt {
/// Whether this doubt is about the disk, and whether about Drive.
fn sides(self) -> (bool, bool) {
match self {
Doubt::FirstSync => (true, true),
Doubt::Restart | Doubt::WatchLost | Doubt::Overflow => (true, false),
Doubt::EventGap | Doubt::Pushed => (false, true),
}
}
}
/// What a pass owes a folder: the sides it must walk in full, each with the
/// first doubt that made it so.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Owed {
pub local: Option<Doubt>,
pub remote: Option<Doubt>,
}
impl Owed {
/// Both sides, for a folder nothing has walked.
pub const ALL: Owed = Owed {
local: Some(Doubt::FirstSync),
remote: Some(Doubt::FirstSync),
};
pub fn is_empty(&self) -> bool {
self.local.is_none() && self.remote.is_none()
}
/// Add `doubt` to the sides it is about. The first doubt on a side
/// stays: it is the one to report.
fn doubt(self, doubt: Doubt) -> Owed {
let (local, remote) = doubt.sides();
Owed {
local: self.local.or(local.then_some(doubt)),
remote: self.remote.or(remote.then_some(doubt)),
}
}
/// What is left once a pass walked the sides given in full.
fn cover(self, local: bool, remote: bool) -> Owed {
Owed {
local: self.local.filter(|_| !local),
remote: self.remote.filter(|_| !remote),
}
}
}
impl fmt::Display for Owed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match (self.local, self.remote) {
(None, None) => f.write_str("nothing"),
(Some(l), None) => write!(f, "local: {l:?}"),
(None, Some(r)) => write!(f, "remote: {r:?}"),
(Some(l), Some(r)) => write!(f, "local: {l:?}, remote: {r:?}"),
}
}
}
/// Why a folder is not synced for now.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Suspension {
RootMissing,
Paused,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Phase {
Discovering,
Following,
Auditing,
Suspended(Suspension),
Draining,
HandedOff,
}
/// A folder's state: its phase, and what a pass owes it. Following owes
/// nothing and Auditing owes something; a suspended folder keeps what it is
/// owed for when it comes back.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RootState {
pub phase: Phase,
pub owed: Owed,
}
impl RootState {
/// A folder no pass has walked.
pub const NEW: RootState = RootState {
phase: Phase::Discovering,
owed: Owed::ALL,
};
/// A folder synced before the daemon started: what happened on disk
/// meanwhile went unwatched. Drive's event stream resumes from its
/// cursor, and reports a gap when it cannot.
pub const RESTARTED: RootState = RootState {
phase: Phase::Auditing,
owed: Owed {
local: Some(Doubt::Restart),
remote: None,
},
};
/// Following once nothing is owed. Otherwise a folder still discovering
/// stays so, and any other is audited.
fn settled(phase: Phase, owed: Owed) -> RootState {
let phase = match phase {
_ if owed.is_empty() => Phase::Following,
Phase::Discovering => Phase::Discovering,
_ => Phase::Auditing,
};
RootState { phase, owed }
}
}
/// Something that happened to a folder, as the reducer takes it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RootInput {
/// A pass finished. It walked the disk in full when `local`, and Drive
/// when `remote`; otherwise it worked from that side's dirty set.
Covered { local: bool, remote: bool },
/// A change may have gone unreported.
Doubted(Doubt),
/// The folder cannot be synced for now.
Suspended(Suspension),
/// Sync is no longer paused. The watcher and the event stream kept
/// running meanwhile, so the folder owes what it owed before. A missing
/// root is only found again by a pass that covers it.
Resumed,
/// A switch to on-demand is queued.
HandoffQueued,
/// The folder is on-demand.
HandedOff,
/// The folder is a mirror again after being on-demand.
Mirrored,
}
/// The state after `input`.
pub fn step(state: RootState, input: RootInput) -> RootState {
use Phase as P;
let RootState { phase, owed } = state;
let with = |phase| RootState { phase, owed };
match (phase, input) {
// An on-demand folder is not synced: only going back to a mirror
// changes it, and that is a first sync over again.
(P::HandedOff, RootInput::Mirrored) => RootState::NEW,
(P::HandedOff, _) => state,
(P::Draining, RootInput::HandedOff) => with(P::HandedOff),
// A switch called off: a mirror again. The push passes dropped the
// picture of Drive; the disk stayed watched.
(P::Draining, RootInput::Mirrored) => {
RootState::settled(P::Auditing, owed.doubt(Doubt::Pushed))
}
(P::Draining, _) => state,
(_, RootInput::HandoffQueued) => with(P::Draining),
(_, RootInput::HandedOff) => with(P::HandedOff),
// A suspended folder is still watched, and owes what went wrong
// meanwhile when it comes back.
(P::Suspended(_), RootInput::Doubted(why)) => RootState {
phase,
owed: owed.doubt(why),
},
(P::Suspended(_), RootInput::Covered { local, remote }) => {
RootState::settled(P::Auditing, owed.cover(local, remote))
}
(P::Suspended(Suspension::Paused), RootInput::Resumed) => {
RootState::settled(P::Auditing, owed)
}
(P::Suspended(_), RootInput::Suspended(why)) => with(P::Suspended(why)),
(P::Suspended(_), _) => state,
(_, RootInput::Suspended(why)) => with(P::Suspended(why)),
(_, RootInput::Doubted(why)) => RootState::settled(phase, owed.doubt(why)),
(_, RootInput::Covered { local, remote }) => {
RootState::settled(phase, owed.cover(local, remote))
}
(_, RootInput::Resumed | RootInput::Mirrored) => state,
}
}
impl fmt::Display for RootState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.phase {
Phase::Discovering => f.write_str("discovering")?,
Phase::Following => f.write_str("following")?,
Phase::Auditing => f.write_str("auditing")?,
Phase::Suspended(why) => write!(f, "suspended ({why:?})")?,
Phase::Draining => f.write_str("draining")?,
Phase::HandedOff => f.write_str("handed off")?,
}
if !self.owed.is_empty() && self.phase != Phase::Discovering {
write!(f, " ({})", self.owed)?;
}
Ok(())
}
}
/// The root state of every mirror folder the engine has seen, by id.
#[derive(Default)]
pub struct Roots {
states: Mutex<HashMap<i64, RootState>>,
}
impl Roots {
/// Start following `folder`, unless it already is: from discovery for a
/// folder never synced, and otherwise from an audit of the disk, since
/// nothing watched it while the daemon was down.
pub fn begin(&self, folder: i64, synced_before: bool) {
self.states
.lock()
.entry(folder)
.or_insert(if synced_before {
RootState::RESTARTED
} else {
RootState::NEW
});
}
/// Feed `input` to `folder`'s reducer, and log the transition it makes.
/// A folder not begun yet is left alone: its first pass begins it.
pub fn input(&self, folder: i64, input: RootInput) {
let mut states = self.states.lock();
let Some(state) = states.get_mut(&folder) else {
return;
};
let next = step(*state, input);
if next != *state {
info!(id = folder, from = %state, to = %next, ?input, "sync: root state");
*state = next;
}
}
/// Feed `input` to every folder's reducer.
pub fn input_all(&self, input: RootInput) {
let folders: Vec<i64> = self.states.lock().keys().copied().collect();
for folder in folders {
self.input(folder, input);
}
}
/// The state of `folder`, if the engine has begun it.
pub fn state(&self, folder: i64) -> Option<RootState> {
self.states.lock().get(&folder).copied()
}
/// What a pass over `folder` must walk in full. A folder not begun is
/// owed everything.
pub fn owed(&self, folder: i64) -> Owed {
self.state(folder).map_or(Owed::ALL, |state| state.owed)
}
/// Forget a folder that is no longer synced.
pub fn forget(&self, folder: i64) {
self.states.lock().remove(&folder);
}
}
#[cfg(test)]
mod tests {
use super::*;
use Phase as P;
use RootInput as I;
fn run(from: RootState, inputs: &[RootInput]) -> RootState {
inputs.iter().fold(from, |state, input| step(state, *input))
}
const BOTH: RootInput = I::Covered {
local: true,
remote: true,
};
const NEITHER: RootInput = I::Covered {
local: false,
remote: false,
};
const LOCAL: RootInput = I::Covered {
local: true,
remote: false,
};
const REMOTE: RootInput = I::Covered {
local: false,
remote: true,
};
const FOLLOWING: RootState = RootState {
phase: P::Following,
owed: Owed {
local: None,
remote: None,
},
};
fn auditing(local: Option<Doubt>, remote: Option<Doubt>) -> RootState {
RootState {
phase: P::Auditing,
owed: Owed { local, remote },
}
}
#[test]
fn a_first_sync_follows_once_a_pass_walks_both_sides() {
assert_eq!(run(RootState::NEW, &[BOTH]), FOLLOWING);
let half = run(RootState::NEW, &[LOCAL]);
assert_eq!(half.phase, P::Discovering);
assert_eq!(half.owed.remote, Some(Doubt::FirstSync));
assert_eq!(step(half, REMOTE), FOLLOWING);
// A doubt during discovery changes nothing: the pass walks it all.
assert_eq!(
run(RootState::NEW, &[I::Doubted(Doubt::Overflow)]),
RootState::NEW
);
}
#[test]
fn a_pass_from_the_dirty_sets_keeps_a_followed_folder_following() {
assert_eq!(run(FOLLOWING, &[NEITHER, NEITHER]), FOLLOWING);
}
#[test]
fn a_doubt_is_owed_on_its_side_until_a_pass_walks_that_side() {
let audit = run(
FOLLOWING,
&[
I::Doubted(Doubt::WatchLost),
I::Doubted(Doubt::Overflow),
I::Doubted(Doubt::EventGap),
],
);
assert_eq!(
audit,
auditing(Some(Doubt::WatchLost), Some(Doubt::EventGap)),
"the first doubt on each side stays"
);
let local_done = step(audit, LOCAL);
assert_eq!(local_done, auditing(None, Some(Doubt::EventGap)));
assert_eq!(step(local_done, NEITHER), local_done);
assert_eq!(step(local_done, REMOTE), FOLLOWING);
}
#[test]
fn a_restart_owes_the_disk_and_not_drive() {
assert_eq!(RootState::RESTARTED, auditing(Some(Doubt::Restart), None));
assert_eq!(step(RootState::RESTARTED, LOCAL), FOLLOWING);
assert_eq!(step(RootState::RESTARTED, REMOTE), RootState::RESTARTED);
}
#[test]
fn a_suspension_keeps_what_is_owed_and_what_goes_wrong_meanwhile() {
let paused = step(FOLLOWING, I::Suspended(Suspension::Paused));
assert_eq!(paused.phase, P::Suspended(Suspension::Paused));
assert_eq!(
step(paused, I::Resumed),
FOLLOWING,
"nothing went unwatched"
);
let overflowed = step(paused, I::Doubted(Doubt::Overflow));
assert_eq!(overflowed.phase, P::Suspended(Suspension::Paused));
assert_eq!(
step(overflowed, I::Resumed),
auditing(Some(Doubt::Overflow), None)
);
let missing = step(FOLLOWING, I::Suspended(Suspension::RootMissing));
assert_eq!(step(missing, I::Resumed), missing);
assert_eq!(step(missing, NEITHER), FOLLOWING);
let lost = run(
FOLLOWING,
&[
I::Suspended(Suspension::RootMissing),
I::Doubted(Doubt::WatchLost),
],
);
assert_eq!(step(lost, LOCAL), FOLLOWING);
// Paused during discovery: still owed everything after.
let paused_new = run(
RootState::NEW,
&[I::Suspended(Suspension::Paused), I::Resumed],
);
assert_eq!(paused_new.owed, Owed::ALL);
}
#[test]
fn a_handoff_drains_then_stays_until_the_folder_is_a_mirror_again() {
let draining = step(FOLLOWING, I::HandoffQueued);
assert_eq!(draining.phase, P::Draining);
assert_eq!(step(draining, BOTH), draining);
let off = step(draining, I::HandedOff);
assert_eq!(off.phase, P::HandedOff);
assert_eq!(step(off, BOTH), off);
assert_eq!(step(off, I::Mirrored), RootState::NEW);
assert_eq!(
step(draining, I::Mirrored),
auditing(None, Some(Doubt::Pushed)),
"a switch called off walks Drive again"
);
}
#[test]
fn roots_begin_once_and_feed_every_folder() {
let roots = Roots::default();
roots.input(1, BOTH);
assert_eq!(roots.state(1), None, "not begun");
assert_eq!(roots.owed(1), Owed::ALL);
roots.begin(1, false);
roots.begin(2, true);
assert_eq!(roots.state(2), Some(RootState::RESTARTED));
roots.input_all(BOTH);
roots.begin(1, false);
assert_eq!(roots.state(1), Some(FOLLOWING), "begun only once");
roots.input_all(I::Doubted(Doubt::EventGap));
assert_eq!(
roots.owed(2),
Owed {
local: None,
remote: Some(Doubt::EventGap)
}
);
roots.forget(2);
assert_eq!(roots.state(2), None);
}
}
+91 -1
View File
@@ -13,7 +13,7 @@ use std::collections::HashMap;
use pdfs_core::Result;
use pdfs_store::db::{
Db, DeleteWindow, SavedWalk, SavedWalkItem, StoredSyncEntry, StoredSyncFolder,
Db, DeleteWindow, SavedWalk, SavedWalkItem, StoredIntent, StoredSyncEntry, StoredSyncFolder,
};
/// The sync tables, as the mirror engine uses them.
@@ -80,6 +80,43 @@ pub trait SyncStore: Send + Sync {
fn sync_delete_window(&self, folder_id: i64) -> Result<Option<DeleteWindow>>;
/// Record the folder's deletion window.
fn sync_delete_window_set(&self, folder_id: i64, window: &DeleteWindow) -> Result<()>;
// The intent of each effect sent (`effect`).
/// Record that an effect is about to be sent; returns the intent and the
/// state it was in before, if any.
fn sync_intent_issue(
&self,
folder_id: i64,
rel_path: &str,
kind: &str,
now: i64,
) -> Result<(StoredIntent, Option<String>)>;
/// Drop a settled intent.
fn sync_intent_settle(&self, id: i64) -> Result<()>;
/// Move an intent to `state`, with the error that put it there.
fn sync_intent_set(&self, id: i64, state: &str, error: Option<&str>) -> Result<()>;
/// Note that upload `kind` of `rel_path` streamed bytes with SHA-1 `sha1`
/// and heard no success back.
fn sync_intent_sent(
&self,
folder_id: i64,
rel_path: &str,
kind: &str,
sha1: &str,
) -> Result<()>;
/// Every intent not settled; only `folder_id`'s when given.
fn sync_intents(&self, folder_id: Option<i64>) -> Result<Vec<StoredIntent>>;
/// Move every intent in state `from` to `to`.
fn sync_intents_move(&self, from: &str, to: &str) -> Result<usize>;
/// Settle the intents of `folder_id` in one of `states` last sent before
/// `before`.
fn sync_intents_settle_before(
&self,
folder_id: i64,
states: &[&str],
before: i64,
) -> Result<Vec<StoredIntent>>;
}
impl SyncStore for Db {
@@ -154,6 +191,44 @@ impl SyncStore for Db {
fn sync_delete_window_set(&self, folder_id: i64, window: &DeleteWindow) -> Result<()> {
Db::sync_delete_window_set(self, folder_id, window)
}
fn sync_intent_issue(
&self,
folder_id: i64,
rel_path: &str,
kind: &str,
now: i64,
) -> Result<(StoredIntent, Option<String>)> {
Db::sync_intent_issue(self, folder_id, rel_path, kind, now)
}
fn sync_intent_settle(&self, id: i64) -> Result<()> {
Db::sync_intent_settle(self, id)
}
fn sync_intent_set(&self, id: i64, state: &str, error: Option<&str>) -> Result<()> {
Db::sync_intent_set(self, id, state, error)
}
fn sync_intent_sent(
&self,
folder_id: i64,
rel_path: &str,
kind: &str,
sha1: &str,
) -> Result<()> {
Db::sync_intent_sent(self, folder_id, rel_path, kind, sha1)
}
fn sync_intents(&self, folder_id: Option<i64>) -> Result<Vec<StoredIntent>> {
Db::sync_intents(self, folder_id)
}
fn sync_intents_move(&self, from: &str, to: &str) -> Result<usize> {
Db::sync_intents_move(self, from, to)
}
fn sync_intents_settle_before(
&self,
folder_id: i64,
states: &[&str],
before: i64,
) -> Result<Vec<StoredIntent>> {
Db::sync_intents_settle_before(self, folder_id, states, before)
}
}
#[cfg(test)]
@@ -216,5 +291,20 @@ mod tests {
);
store.sync_remote_dirty_consume(id, dirty[0].0).unwrap();
assert!(store.sync_remote_dirty(id).unwrap().is_empty());
let (intent, _) = store.sync_intent_issue(id, "a.txt", "upload", 1).unwrap();
store.sync_intent_set(intent.id, "retry", None).unwrap();
assert_eq!(store.sync_intents(Some(id)).unwrap()[0].state, "retry");
assert_eq!(store.sync_intents_move("retry", "blocked").unwrap(), 1);
assert_eq!(
store
.sync_intents_settle_before(id, &["blocked"], 2)
.unwrap()
.len(),
1
);
let (intent, _) = store.sync_intent_issue(id, "a.txt", "upload", 3).unwrap();
store.sync_intent_settle(intent.id).unwrap();
assert!(store.sync_intents(None).unwrap().is_empty());
}
}
+37 -4
View File
@@ -133,14 +133,33 @@ pub enum Count {
Reused,
/// Folders on Drive marked as changed since the last pass listed them.
Dirty,
/// Deletions the pass planned that the evidence does not back: the path
/// was not proven gone on the side the deletion is based on. Should stay
/// zero; see `evidence`.
/// Deletions the pass planned that the evidence does not back, and so
/// did not make: the path was not proven gone on the side the deletion is
/// based on. Should stay zero; see `evidence`.
UnprovenDeletions,
/// Marks of the local dirty set the pass claimed.
LocalDirty,
/// One when the pass's claim of the local dirty set was not trusted: the
/// watch was not live throughout since the last pass claimed.
LocalUntrusted,
/// Local changes the pass found that a trusted claim of the local dirty
/// set did not cover. Should stay zero; see `local_dirty`.
MissedLocal,
/// Paths on disk taken from the last pass's walk, which a trusted claim
/// of the local dirty set keeps up to date, instead of walked again.
LocalReused,
/// Effects sent again that a stopped daemon had sent and not heard back
/// from: each may have happened already (`effect`).
UnsureResent,
/// Effects sent again after they failed.
Retried,
/// Unsettled effects of earlier passes that this pass looked at and no
/// longer sent.
Superseded,
}
impl Count {
const ALL: [Count; 10] = [
const ALL: [Count; 17] = [
Count::LocalEntries,
Count::RemoteFolders,
Count::Nodes,
@@ -151,6 +170,13 @@ impl Count {
Count::Reused,
Count::Dirty,
Count::UnprovenDeletions,
Count::LocalDirty,
Count::LocalUntrusted,
Count::MissedLocal,
Count::LocalReused,
Count::UnsureResent,
Count::Retried,
Count::Superseded,
];
fn name(self) -> &'static str {
@@ -165,6 +191,13 @@ impl Count {
Count::Reused => "reused",
Count::Dirty => "dirty folders",
Count::UnprovenDeletions => "unproven deletions",
Count::LocalDirty => "local dirty",
Count::LocalUntrusted => "local dirty untrusted",
Count::MissedLocal => "missed local changes",
Count::LocalReused => "local reused",
Count::UnsureResent => "unsure resent",
Count::Retried => "retried",
Count::Superseded => "superseded",
}
}
}
+52 -1
View File
@@ -320,6 +320,14 @@ impl<H: FilesHost> Files<H> {
}
}
}
// A queued revision is the whole file, so its length is the
// file's, whatever the tree says. The tree can be behind it: an
// upload that lands as the next write queues puts its own size
// back over the one that write stamped. Taken from the tree, a
// longer length left the copied bytes past the blob unauthored,
// and the commit refilled them from the older revision. A
// shorter one cut the file at that length (docs/BUGS.md B308).
let len = pending_base.as_ref().map_or(base.size, |p| p.meta.len);
let fh = st.open.open_writer(ino, || {
WriteHandle {
ino,
@@ -329,7 +337,7 @@ impl<H: FilesHost> Files<H> {
written: initial_written,
// Starts at the current size; reads in [0, base_size)
// come from the base until overwritten.
len: base.size,
len,
base_size: base.size,
base_mtime: base.mtime,
base_revision_id: base.revision_id.clone(),
@@ -977,6 +985,49 @@ mod tests {
assert_eq!(fx.open_count(ino), 0);
}
/// A queued edit is the whole file, so a write open over it starts at the
/// edit's length even when the tree still has an older, longer size.
/// Started at the tree's 23 bytes, the hole a write past the edit leaves
/// was refilled from the older revision at commit (B308).
#[test]
fn a_write_open_over_a_queued_edit_takes_the_edits_length() {
let fx = Fixture::new();
let ino = fx.add("f", false);
// The tree has the revision that landed as the edit was queued.
if let NodeKind::File { claimed_size, .. } =
&mut fx.state().entries.get_mut(&ino).unwrap().node.kind
{
*claimed_size = Some(23);
}
let path = fx._dir.0.join("queued");
std::fs::write(&path, b"mnopqrst").unwrap();
fx.writes.pending.lock().insert(
uid("f"),
PendingRevision {
path,
meta: StagedWrite {
uid: uid("f").to_string(),
len: 8,
base_size: 23,
base_mtime: 1,
authored: vec![(0, 8)],
complete: true,
based_on: None,
},
},
);
let fh = fx.files.open(ino, true).unwrap();
fx.files.write(ino, fh, 12, b"hijk").unwrap();
let st = fx.state();
let handle = st.open.by_fh(fh).unwrap();
assert_eq!(handle.len, 16);
// Everything is the user's: the edit, the hole and the write.
assert_eq!(handle.written.0, vec![(0, 16)]);
let mut bytes = vec![0; 16];
std::os::unix::fs::FileExt::read_exact_at(&*handle.file, &mut bytes, 0).unwrap();
assert_eq!(&bytes, b"mnopqrst\0\0\0\0hijk");
}
/// A write open over a partial queued edit has to fill its gaps from
/// Drive first. Offline it fails with the host's own error.
#[test]
+28 -2
View File
@@ -349,8 +349,9 @@ Safety rules:
not tell, and why (`Unknown`: unreadable or vanished here; unread, under a short listing or
under a failed listing on Drive). Only a path known on both sides is classified, and only
`Absent` backs a deletion. Every deletion a pass plans is checked against the evidence once
more. For now that check acts on nothing: it logs the deletion and counts it as `unproven
deletions` in the pass trace, which should stay at zero.
more, and one it does not back is not made: the pass logs it, counts it as `unproven
deletions` in its trace and fails the step, and the next pass plans it again. The count
should stay at zero.
- **Wipe guard.** A pass in which every previously synced file has vanished locally is refused
instead of trashing the whole folder on Drive. It applies to any non-empty baseline.
- **Deletion window.** The wipe guard sees one pass. A tree lost a little at a time passes it once
@@ -918,6 +919,31 @@ follower whose leader failed lists the folder itself, so each caller still gets
A shared folder's refresh stays out of the flight, since its generation check settles races of
its own.
Step 4 has started, inside `pdfs-sync`:
- **Typed absence.** `evidence` says, for each path a walk touched, what the walk proved about it:
present, absent, excluded by the ignore rules, or unknown, with the reason: a folder that could
not be read, a path that vanished during the scan, or a Drive listing that failed or came back
short. The mirror pass and the push pass both ask it, and a deletion without
proof that the path is gone is not made: it is logged and counted, and the next pass plans it
again.
- **A delete guard over time.** Each mirror folder counts its deletions over the last day
(`sync_delete_window`), on either side. A pass that would bring the count to nine in ten of
what the folder held is refused, so a wipe spread over several passes is caught as one.
- **The local dirty set.** `local_dirty::LocalDirty` holds where each folder changed on disk since
a pass last looked, as the watcher reports it, and whether the watch was live throughout. A pass
still walks the whole folder and counts the changes the set did not cover.
- **The root reducer.** `root::Roots` holds one state machine per folder (discovering, following,
auditing, suspended, draining, handed off) that says how far the engine can trust what it has
seen. Its transitions are logged; nothing acts on them yet.
Where step 3 stopped: `Core` no longer holds raw state, only the handles of the parts that own it,
and the areas that are services of their own build from those handles. Taking `Core` apart
further would change how hundreds of call sites reach the tree without changing who owns what, so
the mounted-files side stays in `Core` until step 5 moves it out. The inner crates still see the
SDK's id and node types (`NodeUid`, `Node`), which come with the whole `proton-sdk` crate; a
crate in the SDK with only those types is the way out, and comes with an SDK release.
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
macOS adapters, and a separate repository for the sync engine.
+218 -1
View File
@@ -68,6 +68,8 @@ original wording.
| Entry | Title | What is left |
|---|---|---|
| [B310](#b310--a-write-soon-after-a-create-landed-was-kept-as-a-conflict-copy-of-it) | A write soon after a create landed was kept as a conflict copy of it | Cause not found; seen once in CI |
| [B307](#b307--a-write-in-the-echoes-simulation-can-wait-20-s-for-a-drive-call-that-never-answers) | A write in the echoes simulation can wait 20 s for a Drive call that never answers | Cause not found; seen once in CI |
| [B275](#b275--on-a-slow-link-a-files-last-write-can-land-only-in-a-conflict-copy) | On a slow link, a file's last write can land only in a conflict copy | Cause not found; seen once in CI |
| [B273](#b273--a-restore-proposes-another-computers-paths-when-the-two-share-a-hostname) | A restore proposes another computer's paths when the two share a hostname | Not fixed |
| [B267](#b267--a-key-failure-at-a-start-from-a-warm-cache-shows-as-offline-for-good) | A key failure at a start from a warm cache shows as offline for good | Not fixed |
@@ -108,6 +110,9 @@ a live account since.
| Entry | Title |
|---|---|
| [B306](#b306--a-change-made-as-its-nodes-create-lands-is-refused-with-permission-denied) | A change made as its node's create lands is refused with "Permission denied" |
| [B305](#b305--a-mirrored-file-whose-upload-went-unanswered-gets-a-conflict-copy-of-its-own-edit) | A mirrored file whose upload went unanswered gets a conflict copy of its own edit |
| [B304](#b304--a-write-released-while-its-files-create-lands-is-kept-as-a-conflict-copy) | A write released while its file's create lands is kept as a conflict copy |
| [B303](#b303--a-file-made-where-a-withdrawn-create-was-listed-refuses-every-write) | A file made where a withdrawn create was listed refuses every write |
| [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 |
@@ -315,6 +320,8 @@ a live account since.
| Entry | Title |
|---|---|
| [B309](#b309--a-file-renamed-while-its-create-was-read-back-went-back-to-its-old-name) | A file renamed while its create was read back went back to its old name |
| [B308](#b308--a-write-opened-over-a-queued-edit-took-the-trees-older-size) | A write opened over a queued edit took the tree's older size |
| [B295](#b295--a-resize-the-scratch-file-refused-still-succeeded) | A resize the scratch file refused still succeeded |
| [B293](#b293--a-large-trash-never-lists-and-empty-trash-never-empties-it) | A large trash never lists, and Empty Trash never empties it |
| [B292](#b292--two-programs-changing-settings-at-once-lose-one-of-the-changes) | Two programs changing settings at once lose one of the changes |
@@ -406,6 +413,216 @@ a live account since.
Newest first.
### B310 — A write soon after a create landed was kept as a conflict copy of it
**Status:** Open
**Found:** 2026-11-28, CI on `main` at `d79c26f`
([run](https://github.com/narrrl/proton-drive-linux/actions/runs/46152926170), artifact
`simulation-diagnostics`): `one_client_on_a_good_link` seed 5. `e.md` was created with 28
bytes, and 0.6 s later `write e.md at 27 (47 bytes)` took 111 ms. The write landed only as
`e (sync-conflict …).md`, and `e.md` kept its 28 bytes. The daemon logged `the remote revision
changed under the queued write (expected 28 bytes at mtime 1795875819, found 28 at
1795875820)`. Seed 5 passed 30 runs locally on the same commit, and 25 on `9667b7d`.
**Where:** not located; the write's baseline, from `Files::install_writer` through
`Core::remote_baseline`, against `placeholder_base` in `crates/pdfs-fuse/src/drain.rs`
**Cause.** Not known. The baseline has no revision id and the placeholder's local mtime, one
second before the stamp Drive gave the create. That is the base of a write opened over the
create's placeholder (B113). But the create had landed long before the write, and the tree
should have had Drive's node with its revision id by then. `placeholder_base` maps exactly this
base to the create's revision, but only while the `placeholders` entry exists. Either the tree
still had the placeholder's stamp, or the entry was gone or never written. The log does not say
which.
**Fix.** Not done. A debug log of a failing run would show the write open's base
(`write open took the base the file has now`) and whether adoption saw a placeholder.
---
### B309 — A file renamed while its create was read back went back to its old name
**Status:** Fixed
**Found:** 2026-11-28, looping `one_client_on_a_good_link` seed 5 on `d79c26f` with debug logging,
after a CI failure of the same seed on that commit. It failed once in 38 runs:
`liveness: the queues did not drain within 4s`, with a rename owing `b.txt is still held by a node
whose trash or rename is queued`. Drive had `b.txt` with the bytes of the file created as `d`,
and the model had the file renamed over it.
**Where:** `Core::adopt_real_uid` in `crates/pdfs-fuse/src/drain/create.rs`
**Repro:** Create `d` and let its create land. While the drain reads the new node back, rename
`d` to `b.txt`, and let the rename land before the read-back answers.
**Cause.** Adoption keeps the tree's name while a rename is queued. It asks once before the
read-back (B161) and once under the tree lock (B152). A rename queued after the first look and
landed before the second leaves no op for either to see, and the read-back still has the old name.
The tree took `d` back while Drive had `b.txt`. A later `rename z/b.txt b.txt` then found no
`b.txt` to replace, so it queued no trash. On Drive the name was taken. The rename also counted
as a move away from `b.txt` (it left `z/b.txt`), so it waited on itself for four attempts.
**Fix.** Adoption notes where the tree has the node before the read-back. The tree moves an
entry when its rename is queued, so a placement that changed meanwhile keeps the tree's name and
folder, like a queued rename.
**Verified:** sim test `a_file_renamed_while_its_create_is_read_back_keeps_its_new_name`, which
holds the adoption's read-back until the rename has landed. It fails without the fix (the mount
shows `d`) and passes with it.
The CI failure of seed 5 itself is a different bug, B310.
---
### B308 — A write opened over a queued edit took the tree's older size
**Status:** Fixed (unverified)
**Found:** 2026-11-28, looping `one_client_with_stale_hashes_and_reordered_echoes` seed 4 under
`stress-ng --cpu 4 --cpu-load 70` while chasing B307. Three runs of 89 failed with `liveness: the
queues did not drain within 6s`, none with B307's 20 s stall. Run 45 ended with `a.txt` holding
`mnopqrstcdefhijk…` where the model has `mnopqrst\0\0\0\0hijk…`, and run 33 with `f.txt` cut at 62
bytes of 81.
**Where:** `crates/pdfs-vfs/src/files.rs` (`Files::install_writer`) and
`crates/pdfs-fuse/src/drain/revision.rs` (`Core::place_landed`)
**Repro:** Create `a.txt` with 23 bytes and let its upload start. As it lands, open `a.txt` with
`O_TRUNC`, write 8 bytes and close. Then open it again and write 4 bytes at offset 12.
**Cause.** Two steps, each harmless alone:
- `place_landed` asks `rebaseline_pending` whether a write is queued, and if none is, puts the node
it read back into the tree. A write queued between the two stamps its own size first, and the
landed node then puts the old size back. The tree said 23 bytes while the queued edit held 8.
- `install_writer` copies the queued blob into the new handle's scratch file and marks `[0, 8)` as
written, but it started the handle at the tree's size. With 23, the write at 12 left `[8, 12)`
unmarked, and the commit filled it from the 23-byte revision instead of zeros. Run 33 was the
same with a tree size below the queued edit's, so the handle was cut short.
**Fix.** A write open over a queued edit starts at the edit's length, since the blob is the whole
file. `place_landed` applies queued sizes to the node it read back before putting it in the tree,
as listings already do.
**Verified:** `a_write_open_over_a_queued_edit_takes_the_edits_length` in `pdfs-vfs` fails
without the fix (`left: 23, right: 16`) and passes with it. The seed-4 loop under load has not
been rerun on the fix yet.
The third failure, run 59, is likely the same cause by another route. The edit to `a.txt`
landed only as a conflict copy ("based on revision rev2, remote now at rev5"). The handle had
started at the tree's 23 bytes over the queued 8, so the hole at `[8, 12)` was unauthored and
the write was queued with `complete: false`. `is_own_self_supersede` only chains a complete write
onto a revision this daemon sealed, so the incomplete one forked. With the length fixed, the hole
counts as written and the write is complete.
---
### B307 — A write in the echoes simulation can wait 20 s for a Drive call that never answers
**Status:** Open
**Found:** 2026-11-28, CI on #210 ([run](https://github.com/narrrl/proton-drive-linux/actions/runs/46140440107)):
`one_client_with_stale_hashes_and_reordered_echoes`, profile `one-client-echoes` seed 4, failed
with `liveness: client 0: write c.bin at 25 (4 bytes) took 20.961719651s, over 2s`. #210
changes only the GUI, and the same seed passed 28 times locally on `cf2632a`. In the same run,
`three_clients_one_writer_each` seed 2 failed with `truncate c.bin to 12 took 2.089572866s`, which is
just over the budget and looks like runner load.
**Where:** not located; a foreground call bounded by `INTERACTIVE_CALL_TIMEOUT` in
`crates/pdfs-fuse/src/link.rs`
**Repro:** The client creates `c.bin`, writes to it, renames `d` over it, and lets the queue
settle. The next write into `c.bin` then succeeds, but only after 21 s.
**Cause.** Not known. 21 s is the 20 s `INTERACTIVE_CALL_TIMEOUT` plus about a second, so a
call the write waited on got no answer from the fake Drive and timed out. The echoes profile
delays, duplicates and reorders events, but it never drops a reply or stalls a call. So the
call either waited on something held elsewhere, or the fake left it without an answer.
**Fix.** Not done. Needs a reproduction under load with the state directory and `daemon.log`
of a failing run, which the simulation keeps.
---
### B306 — A change made as its node's create lands is refused with "Permission denied"
**Status:** Fixed (unverified)
**Found:** 2026-11-28, from two simulation failures on #204, a GUI-only change.
`one_client_with_stale_hashes_and_reordered_echoes` seed 5: `write e.md` was kept in staging
with "access changed before the staged write could be queued", and the queues did not drain.
`a_move_blocked_by_trash_can_be_retried_after_restore`: `mkdir source/nested` right after
`mkdir source` failed with `EACCES`. The evidence logging from #177 said
`refused=Unknown persisted=Ok(Some(Owner)) live=[Owner]`. By the time the evidence was read,
both authorities called the node writable.
**Where:** `Db::effective_node_access` in `crates/pdfs-store/src/db/share_access.rs`
**Cause.** B174's fix was incomplete. It finds a stand-in's row by local id, then checks that a
row with the uid it found exists, then walks the ancestors. Each statement on a pooled reader is
its own read, so each sees whatever was last committed. When a create landed between the first
two, the first statement found the stand-in uid and the second checked a row that by then had
Drive's uid. The answer was "no such node", which is `WriteAuthority::Unknown`, and the change
was refused.
**Fix.** The statements run in one read transaction, so they see one snapshot.
**Verified:** `a_stand_in_is_never_missing_while_its_create_lands` lands 300 creates on a
file-backed database while another thread asks for the stand-in's access. Without the fix it read
the stand-in as missing 37 to 47 times in each of four runs. With the fix it read none in five
runs.
### B305 — A mirrored file whose upload went unanswered gets a conflict copy of its own edit
**Status:** Fixed (unverified)
**Found:** 2026-11-27, writing the simulation for the case the effect reducer is meant to handle
(`FURTHER_IMPROVEMENTS.md`): a create accepted by Drive, the reply lost, a restart, and a newer
local edit. The simulation failed on the first run. Drive held `new.txt` with the first bytes and
`new (sync-conflict …).txt` with the edit.
**Where:** the `FilePlan::Conflict` arm of the plan in `crates/pdfs-sync/src/mirror.rs`, and
`Pending::Adopt` in `crates/pdfs-sync/src/mirror/apply.rs`
**Repro:** In a mirror folder, write a new file. Lose the answer to its upload after Drive has
made the file. Stop the daemon, write the file again, and start the daemon.
**Cause.** The upload failed as far as the daemon knew, so no baseline was recorded. The next pass
found the path on both sides with no baseline and different bytes, which is what two computers
writing one new file look like, so it kept the local copy as a conflict copy. The edit itself is
not lost. The one-request small upload makes this ending of a lost reply the usual one: it
leaves a whole file, never a draft for the next attempt to replace.
**Fix.** An upload that hears no success back notes the SHA-1 of the bytes it streamed in its
effect intent (`sent_sha1s`, schema 52). Before keeping a conflict copy, the plan checks the
intents. If Drive's file holds exactly bytes an unsettled upload of that path sent, the file is
this daemon's own. The local bytes then go up as a revision of it. A first-sync adopt of a
same-size file with other bytes does the same. A file that holds those bytes by chance loses
nothing either: they are what this computer sent.
**Verified:** `a_mirror_create_whose_reply_was_lost_is_adopted_after_a_restart_and_its_edit_lands`
fails without the fix and passes with it. `an_upload_notes_each_digest_it_sent_once` covers the
store.
### B304 — A write released while its file's create lands is kept as a conflict copy
**Status:** Fixed (unverified)
**Found:** 2026-11-27, from a CI failure of the `one_client_with_stale_hashes_and_reordered_echoes`
simulation (seed 5): the queues did not drain in time, and Drive held a conflict copy of `e.md`.
The daemon log said "the remote revision changed under the queued write (expected 28 bytes at
mtime 1795799834, found 28 at 1795799835)".
**Where:** `Core::adopt_real_uid` in `crates/pdfs-fuse/src/drain/create.rs` and
`Core::revision_conflict` in `crates/pdfs-fuse/src/drain/revision.rs`
**Repro:** Make a file with some content, and let its create reach Drive in a later second than
the file was made locally. As the create lands, write part of the file and close it. Rare: the
close has to fall in a window of a few milliseconds.
**Cause.** The write opened over the create's placeholder, whose base is the local mtime and no
revision id. Landing the create rebases the handles open on the file and the writes queued for
it onto the node Drive made. A release takes its handle out of the tree before it queues the
write, so a release that started before the rebase and queued after it was caught by neither.
The drain then had no revision id to compare and fell back to the mtime, which Drive had stamped
a second later. The write was not complete, so the check that chains a write onto a revision this
daemon sealed did not apply either, and the write went up as a conflict copy of the file's own
create.
**Fix.** Landing a create remembers the placeholder's mtime and size with the revision the create
sealed. A base with no revision id and that stamp is read as that revision: its bytes are the ones
the create sent. The record goes once a later upload of the file lands, or the file is trashed.
**Verified:** `a_write_based_on_a_landed_create_placeholder_is_not_a_conflict` checks the
comparison. The race itself is not reproduced on demand; 40 local replays of the seed passed.
### B303 — A file made where a withdrawn create was listed refuses every write
**Status:** Fixed (unverified)
@@ -4052,7 +4269,7 @@ tree does (B173's gap). A rename in between asked by the stand-in the tree still
row under it, and was refused.
**Fix.** A stand-in is looked up by its local id, so it finds its row before and after the
create lands.
create lands. The lookup still left a gap while the create landed, closed by B306.
**Test:** `a_stand_in_keeps_its_access_once_its_create_has_landed` in
`crates/pdfs-core/src/db/tests.rs`.
+138 -2
View File
@@ -11,11 +11,36 @@ scratch (user data in `staging/` and `recovery/` is never touched by this).
## [Unreleased]
Schema: **50**. New tables save a mirror folder's walk of Proton Drive (48). A finished walk is
## [4.0.0] — 2026-11-28
4.0.0 splits the daemon into services that each own their state. The sync engine, the mounted
files, Drive access, the database and the admission of background work each have a crate of
their own (`pdfs-sync`, `pdfs-vfs`, `pdfs-drive`, `pdfs-store`, `pdfs-sched`), and the daemon
builds them in `pdfs-daemon` (see [Architecture](ARCHITECTURE.md#40-from-one-daemon-to-composed-services)).
A sync pass now keeps track of what each side owes: it lists only what changed on Proton Drive,
trusts the watcher for the folder on disk, resumes a walk a restart cut short, and records every
effect it sends until the result is in. Small files go up in one request.
**Upgrading:** the database moves from schema 47 to 52 on first start. 3.10 and older refuse to
open it, so going back to 3.10 means removing the cache and letting it build again. Files in
`staging/` and `recovery/`, and synced folders on disk, are not touched by this. Nothing else
needs doing: configuration, sign-in and synced folders carry over.
Schema: **52**. New tables save a mirror folder's walk of Proton Drive (48). A finished walk is
kept, with a list of the folders that changed on Proton Drive since (49). Each mirror folder
counts the deletions it made in the last day (50).
counts the deletions it made in the last day (50). Each upload, download or folder a mirror pass
sends is recorded until its result is in (51), and an upload that heard no answer keeps the
digest of what it sent (52).
### Added
- **Small files go up to Proton Drive in one request.** A file whose encrypted size is under
128 KiB, and a new revision of one, is now sent in a single request instead of a draft, its
block and a commit. This covers synced folders and the drive mount. On a test account, a first
sync of 200 small files ran 58% faster, and 50 edits of them 97% faster. Larger files go up in
blocks as before. `proton-sdk` and `proton-drive-rs` are now 0.12.7.
- **`small_uploads` in `config.json` turns off the one-request upload for small files.** It is
on by default. Set it to `false` to send every file as a draft, its blocks and a commit, as
before. The service reads it at start. See [Configuration](CONFIGURATION.md#small_uploads).
- **`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. It also lists the jobs running
@@ -25,6 +50,16 @@ counts the deletions it made in the last day (50).
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
write to the new revision on Proton Drive.
- **`pdfs diagnostics` lists the sync effects that have not settled.** An upload, download,
folder or deletion a synced folder's pass sent and has not heard a success for is listed,
oldest first, with how many times it was sent, how long ago, and its last error. Deletions on
either side are now recorded like the other effects, so one that keeps failing says so in the
journal too. The JSON report has them as `effects`.
- **`pdfs diagnostics` says how many uploads went up in one request.** It counts the uploads
since start that took the one-request path for small files and those that went up in blocks,
with their failures and times. If small files stop taking the one-request path, because
`small_uploads` is off or Proton Drive refuses it, this shows it. The JSON report has them as
`upload_paths`.
- **`pdfs diagnostics` counts every call the daemon makes to Proton Drive.** Per kind of call it
shows how many were made since start, how many failed, and their total and longest time. The
JSON report has them as `drive_calls`.
@@ -45,6 +80,21 @@ counts the deletions it made in the last day (50).
any more.
### Changed
- **The tray has its own icons.** They are the app's folder, solid when everything is up to date,
with a badge for syncing, paused, a failing change or an expired sign-in, and hollow when
offline or stopped. They used to be stock icons from the desktop theme. They take the panel's
text colour like other tray icons, and the packages install them into the hicolor theme.
- **An upload into a folder and an edit of a synced file make fewer requests.** The key that
hashes a folder's file names is now read once per folder, not once per upload. A synced
folder no longer reads a file again before it sends an edit. It checks that nobody else
changed the file through the read the upload already makes, and it still sends nothing over
a revision it has not seen. `proton-sdk` and `proton-drive-rs` are now 0.12.8.
- **A sync pass over a quiet folder no longer reads the whole folder on disk.** While the
filesystem watcher has been running without a break, a pass reads again only the folders and
files it reported changed, and takes the rest from the pass before. The whole folder is still
read at least once an hour, after a start, after a pass that downloaded or removed files, and
whenever the watcher may have lost a change. `pdfs diagnostics` shows how many paths a pass
took over as `local reused`.
- **Deletions in a mirror folder add up across passes.** A sync pass already refuses to delete
nearly every file of a folder at once. Now a folder lost a little at a time is stopped too:
once nine in ten of its synced files would have been deleted within a day, on either side,
@@ -65,6 +115,91 @@ counts the deletions it made in the last day (50).
first pass, and whenever the change feed lost track (#53).
### Fixed
- **A file renamed just as it reached Proton Drive keeps its new name.** If the rename landed
while the app was reading the new file back, the folder could show the old name again, and a
later rename over the new name waited and then failed (B309).
- **A write right after another can no longer bring back old bytes or cut the file short.** When
an upload landed just as the next edit to the same file was queued, the file could keep the
size of the upload that landed. A write opened next then started at that size, not the queued
edit's. If the landed size was larger, a gap the write left past the edit was filled from the
older revision instead of zeros. If it was smaller, the file was cut at that size. Seen in
the echoes simulation about once in 40 runs under CPU load (B308).
- **A file kept offline and then deleted can be made online only again.** Deleting or trashing a
file left its entry under Settings → Storage → Available offline, and making it online only
failed with "could not resolve", because its path no longer led anywhere. Deleting a file now
drops the entry with it, and an entry already left behind is removed by the path it is listed
under. The app also stops asking for that file's thumbnail every second.
- **A share can be stopped from Shared by me when its file was never opened here.** Stopping the
share, or changing its people or link, failed with "node is not present in any location" for a
file in a folder this computer had not loaded. Drive's own list of what you shared now counts as
proof that the file is yours.
- **Stopping a sync with "Also delete from Proton Drive" says that it deletes, and says so when
the deletion failed.** With the switch on, the dialog now reads "Stop Syncing and Delete
Folder?" and its button "Stop Syncing and Delete". If the folder stopped syncing but its folder
in Proton Drive could not be moved to the trash, for example while offline, the app and
`pdfs sync rm --delete-remote` now report an error that says so. Before, they reported plain
success, and the copy in Proton Drive stayed without a word.
- **Discarding a queued change lists every change it undoes.** A discard drops every change
queued on the same file or folder, but the dialog spoke of one change. It now lists them all,
says whether the item goes back to how Proton Drive has it or is removed from this computer,
and offers "Export My Version…" when the change carries file content.
- **A file or folder changed just as its upload finishes is no longer refused with "Permission
denied".** For a moment after Proton Drive took a new file or folder, the mount could find no
record of it and refused the change: a write was kept in staging instead of being sent, and a
folder made inside a new folder failed. The check now reads the database in one consistent
view.
- **The Trash page acts on what is selected, and says so when it cannot.** Inside a trashed
folder, its items went to the trash with it, and only the folder can be restored. Restore now
reads "Restore Folder “Projects”" there. Delete Permanently, from the bar or the
Delete key, no longer deletes the whole folder for a selected item inside it. It explains that
only the whole folder can be deleted, from the top of the trash. Restore on a row that groups
the items deleted from one folder now shows how many items it restores.
- **Stopping sharing or leaving several items says which ones did not go through.** The app
sent one request per item and stopped at the first failure, with a generic error, so the items
before it had already stopped sharing and the ones after it were never tried. Now every item is
tried. If any did not go through, a summary names it, with the reason or "not tried yet", and
offers to try only those again. If the service stopped answering, the page is reloaded first,
so it shows which items really changed.
- **Sign Out says what it could not finish.**
- If the service did not answer, the confirmation no longer reads as if no changes were waiting.
It says that this is not known.
- If your sign-in could not be removed from the keyring, a dialog says so and offers to try
again. Before, the sign-in page appeared while the sign-in was still saved.
- If Proton did not confirm that the session ended, a notice says where in your Proton account
you can end it.
- **A public link's settings change only when you save them.** Before, choosing Editor changed
the link at once, so anyone holding a viewer link could edit before the password you were about
to add was set. Removing the password also took effect at once. Now the role, the password and
the expiry are sent together by "Save Link Settings". Above that button is a line that says how
the link will work. Closing the dialog sends nothing. When you create a link, Enter in the
password field moves on to Expires instead of creating the link.
- **The Share dialog no longer shows a public link's address until you ask.** The row is titled by
what the link does, for example "Public viewer link", with how it works below. The eye button
shows the address, and reopening the dialog hides it again. An expired link offers no Copy;
"Edit Expiry" opens its settings instead. In Shared by me, an expired link's menu leads with
"Edit Link Expiry…".
- **Find Similar Photos counts files as well as photos.** A shot stored as a RAW and a JPEG moves
both to Trash. The footer now reads, for example, "Move 1 photo (2 files) to Trash", and each
card shows what its shot is stored as, such as "RAW + 1 more file". Each card says whether the
photo stays or moves to Trash, and each set's heading says how many of the set stay. A set wider
than the window still shows what happens to it.
- **The search window shows recent Drive files only to the account that opened them.** Before, an
empty search listed the last files opened from any account signed in on this computer. Now
each Drive file is remembered with its account. Recent Drive files from before this change are
no longer shown, because nobody can say whose they are. Preferences → Apps adds "Remember
recent files" and "Clear recent files", and a clear takes effect the next time the window
opens. See [Configuration](CONFIGURATION.md#prompt) for `remember_recent`.
- **Dragging onto a folder in Files says what the drop will do.** A label over the view reads, for
example, "Move 3 items to “Receipts”" for rows dragged within the app, and "Copy 3 items to
“Receipts”" for files dragged from a file manager browsing the drive. Files from elsewhere read
"Upload…". It also says how many items can't go there, such as the folder itself in a
selection.
- **A mirrored file whose upload went unanswered no longer gets a conflict copy of its own
edit.** Proton Drive can make a file and lose the answer. If the file was then written again
before the next sync, for example while the daemon was stopped, that sync saw two different
files under one name. It kept this computer's newer edit as a conflict copy next to its own
first upload. Now an upload that hears no answer keeps the digest of the bytes it sent. When
Proton Drive holds exactly those bytes, the newer edit goes up as a new version of that file.
- **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
@@ -2541,6 +2676,7 @@ First stable release: FUSE files-on-demand mount, sync daemon under `proton-driv
- The outstanding FUSE defects tracked in `docs/BUGS.md`, plus a truncate defect, validated
by a new POSIX compliance suite for the filesystem.
[4.0.0]: https://github.com/narrrl/proton-drive-linux/releases/tag/v4.0.0
[3.10.0]: https://github.com/narrrl/proton-drive-linux/releases/tag/v3.10.0
[3.9.0]: https://github.com/narrrl/proton-drive-linux/releases/tag/v3.9.0
[3.8.1]: https://github.com/narrrl/proton-drive-linux/releases/tag/v3.8.1
+12
View File
@@ -88,6 +88,7 @@ fix it.
| `device_uid` | string | none | Computers → Continue This Backup Here… or Sync With This Computer… | The computer this machine syncs into. Unset means "match by hostname" |
| `conflict_sweep` | `off` / `report` / `enforce` | `report` | Sync → Conflict Copies | See [`conflict_sweep`](#conflict_sweep) |
| `local_first` | bool | `true` | — | See [`local_first`](#local_first) |
| `small_uploads` | bool | `true` | — | See [`small_uploads`](#small_uploads) |
| `language` | gettext code | system | General → Appearance | Language of the app, tray and prompt, such as `de` or `pt_BR` |
| `proton_theme` | bool | follow system | General → Appearance | Proton's colours instead of the system theme |
| `online_map` | bool | `false` | General → Appearance | Street map for Places from OpenFreeMap |
@@ -145,6 +146,16 @@ call returns at once. The change goes to Drive from the queue, the same way it d
Set it to `false` to have these calls wait for Drive again, as before 3.0.0. The switch is there
for one release, in case the queued path misbehaves for you; please report it if it does.
### `small_uploads`
A file that fits in 128 KiB with its thumbnails goes to Proton Drive in one request. A larger one
goes as a draft, its blocks, and a commit, which takes three requests or more. Most synced files
are small, so this is what decides how fast a folder of many small files syncs.
Set it to `false` to upload every file in blocks again. The setting is read when the service
starts. The journal says `small files are uploaded in blocks` while it is off. Please report it if
you need to turn it off.
### `open_with`
Decides how files picked in the search launcher or the app are opened. Rules are tried in order;
@@ -185,6 +196,7 @@ Settings for `pdfs-prompt`.
| `terminal` | first installed of foot, ghostty, kitty, alacritty, wezterm, xterm | Terminal for `fzf` mode. `{cmd}` is replaced by the command; without it, the command is appended |
| `menu_limit` | `50` | Results shown in `dmenu` and `fzf` mode |
| `menu_icons` | `true` | File-type icons in launchers that support them |
| `remember_recent` | `true` | The `gtk` window remembers what it opens, in `prompt-history.json` under the state directory. It lists those files before a search and ranks them higher in one. A Drive file is shown only while the account that opened it is signed in. `false` clears the list the next time the window opens and keeps nothing more |
```json
{
+1 -1
View File
@@ -103,7 +103,7 @@ That URL follows `main`. To stay on releases, pin the input to a release tag ins
the tag to update:
```nix
inputs.proton-drive-linux.url = "github:narrrl/proton-drive-linux/v3.10.0";
inputs.proton-drive-linux.url = "github:narrrl/proton-drive-linux/v4.0.0";
```
Each release tag is built with Nix before the release is published.
+7
View File
@@ -80,6 +80,13 @@ Which program opens a file you pick is set under **Preferences → Apps → Open
offline. Its menu opens the app or `~/ProtonDrive`, pauses or resumes sync, and stops or connects
the service.
![The tray icons on a dark and a light panel](../images/tray-icons.png)
The icon is the app's folder. A solid folder is up to date. A badge in its corner says it is
syncing, paused, needs a look (a failing change), or needs you to sign in again (a lock). A hollow
folder means it is offline and showing cached files, and with a cross that the service is not
running or nobody is signed in. The icons take the panel's text colour.
- **GNOME** shows tray icons only with the
[AppIndicator extension](https://extensions.gnome.org/extension/615/appindicator-support/).
KDE Plasma and most other desktops show it without help.
+148 -3
View File
@@ -200,8 +200,129 @@ that grows into hours: it is network-bound, while the local walk only reads the
`a_pass_lists_only_the_folders_changed_on_drive` (sim: an edit, a new folder with a folder
in it, and a deletion arrive, and a folder nothing changed in is never listed).
What a quiet pass still costs: loading the baseline and the picture from the database, and the
local walk. The local dirty set removes the local walk.
What a quiet pass still costs: loading the baseline and the picture from the database. The local
dirty set takes the place of the local walk, as described below.
## Root reducer as built
`pdfs_sync::root` holds one reducer per mirror folder. `step(state, input)` is pure: the passes,
the watcher, the event stream and pause are inputs, so a sequence of inputs replays exactly.
| Phase | Meaning |
|---|---|
| Discovering | No pass over the folder has finished yet. |
| Following | Passes covered the whole folder, and nothing since says a change went unreported. |
| Auditing | A doubt arrived, and the side it is about has not been walked in full since. |
| Suspended | The local root is missing, or the folder is paused. |
| Draining | A switch to on-demand is queued, and passes only push. |
| HandedOff | The folder is on-demand. Going back to a mirror starts discovery again. |
A doubt is about one side, since the disk and Drive are followed by different things that fail
on their own. The state keeps, for each side, the first doubt not yet answered (`Owed`):
| Doubt | Side | Where it comes from |
|---|---|---|
| FirstSync | both | A folder no pass has walked, or one that is a mirror again. |
| Restart | disk | The daemon started: nothing watched the disk while it was down. Drive's event stream resumes from its cursor. |
| WatchLost | disk | A watcher error, or a root that went missing and took its watch with it. |
| Overflow | disk | The watcher's queue overflowed. |
| EventGap | Drive | The event stream reported `ContinuityLost`. |
| Pushed | Drive | A switch to on-demand was called off; the push passes dropped the picture of Drive. |
A pause owes nothing by itself: the watcher and the event stream keep running for a paused
folder. A doubt that arrives while a folder is suspended is kept for when it comes back.
**Acted on:** a pass asks the state what it owes before it walks. A side that is owed is walked
in full: the disk without the kept walk, and Drive without the saved picture (a walk an earlier
pass cut short still resumes). The pass reports which sides it walked in full
(`Outcome::walked_in_full`), and only those answer a doubt. A pass from the dirty sets keeps a
Following folder Following.
The checks a pass made before (a trusted claim, a fresh event stream, the audit intervals) still
apply on top: the state can make a pass walk more, never less. Today each doubt also breaks one
of those checks, so the state adds no full walks except after a missing root. When the state is
what forces a walk, the journal says `the root state asks for a walk of the whole disk` or `of
all of Drive`.
A watch follows the folder it was set on, so a root moved away and made again is another folder
that the old watch does not see. The engine keeps the root's device and inode with each watch.
A pass that finds the root missing, or finds a root with another inode, drops the folder's trust
in its claims and asks for the watches to be set up again. Setting them up drops any watch whose
root is gone or replaced and watches the new one. Then it runs a pass over each folder it watched
anew, since a file written before the watch was in place has no event. Until a watch is back,
the disk is walked in full.
**Tests:** the `root::tests` unit tests (a doubt per side, a restart, a suspension, a handoff),
`a_restart_walks_the_disk_in_full_and_not_drive` (sim: the first pass after a restart walks the
disk and reuses the picture of Drive), and `a_root_made_again_is_watched_again` and
`a_root_replaced_between_passes_is_watched_again` (sims: a file written in a root moved away and
made again reaches Drive within a minute; the second fails without the inode check).
## Effect intents as built
The second reducer, `pdfs_sync::effect`, follows one effect a mirror pass sends: a folder made on
Drive, an upload, a new revision, a download, an adopted file or a conflict copy (the `Pending`
ops), and the deletions a pass makes: `trash` for a file or folder moved to Drive's trash because
it went from disk, `delete-local` for one removed from disk because Drive deleted it. A folder Drive
deleted that still holds something Drive never had is kept, and its intent settles: nothing is left
to do about it. Before an op is sent, its intent is written to `sync_intent` (schema 51): one row per
folder, path and kind, with the number of attempts and the time it was last sent. Its result
decides what happens next:
| State | Meaning |
|---|---|
| issued | Sent, or about to be; no result yet. |
| unsure | Found `issued` at a start: the daemon stopped before the result came, so the effect may or may not have happened. |
| retry | It failed, and a later pass may send it again. |
| blocked | It failed five times in a row. The journal says `sync: an effect keeps failing` once. |
| settled | Its result is in. The row goes. |
- A start moves every `issued` row to `unsure`, and says how many in the journal.
- An op sent again keeps its row and counts the attempt. When the row was `unsure`, the journal
says `sync: sending again an effect a stopped daemon may have made`.
- A pass that looked at every path (none unscanned or deferred) settles the rows from before it
began that it did not send again: what they were for has changed, or is done. An `unsure` one
is logged at info.
- A change to what the folder is, or its removal, drops its rows.
The intents decide one thing so far: whether a file on Drive is an upload of this daemon's
that went unanswered.
- An upload that does not hear a success back notes the SHA-1 of the bytes it streamed in its
intent (`sent_sha1s`, schema 52). Each attempt adds its digest.
- When a later pass would keep a conflict copy, it checks the intent first. The path may be new
on both sides, or changed on both sides since the baseline. If Drive's file holds exactly
bytes an unsettled upload of that path sent, the file is ours. The newer local bytes then go up
as a revision of it, with no conflict copy. The same holds for a first-sync adopt of a
same-size file whose bytes differ.
- This is the usual end of a lost reply to a one-request small upload. Such an upload leaves a
whole file, never a draft. If the file was written again before the next pass, for example
while the daemon was stopped, the next pass used to see two different files and fork a
conflict copy of this computer's own edit.
- A file that only happens to hold the same bytes loses nothing either: its content is what
this computer sent.
- A daemon killed in the middle of an upload notes no digest, so that case still ends in a
conflict copy when the file is edited before the next pass. It is kept, and nothing is lost.
Otherwise nothing reads the intents to decide what to send. The apply step's own checks still
decide whether an effect that may have landed is sent again (B266 for a create, B39 for a
download). Trace counts: `unsure resent`, `retried`, `superseded`.
`pdfs diagnostics` lists the intents not settled yet, oldest first (at most 20, with the count of
all of them), with their kind, state, attempts, age and last error. The list is the
`effects` field of the JSON report.
**Tests:**
- the `effect::tests` unit tests;
- DB: `an_effect_intent_is_kept_until_it_is_settled_or_its_folder_changes`, and
`an_upload_notes_each_digest_it_sent_once`;
- sim `a_deletion_is_an_effect_until_it_lands`: a trash held on its way to Drive is listed
`issued` in `pdfs diagnostics`, and the list is empty once it lands, and once a file Drive
deleted is gone from disk;
- sim `an_effect_left_unsure_by_a_stop_is_sent_again_or_settled`: of two uploads a stopped daemon
left unsure, the one still needed is sent again and the other is settled;
- sim `a_mirror_create_whose_reply_was_lost_is_adopted_after_a_restart_and_its_edit_lands`:
Drive makes the file and the answer is lost, then the daemon stops and the file is written
again. After the start there is one file, holding the newer bytes, and no conflict copy.
## Plan of work (separate PRs)
@@ -210,7 +331,31 @@ local walk. The local dirty set removes the local walk.
- Left: per-subtree apply, once a round-level guard exists. A resumable local walk matters
less now that the local walk is the only full walk left, and is cheap next to Drive.
2. **Remote dirty set.** Done, described above.
3. **Local dirty set.** `SyncMsg::Dirty`, the `sync_dirty` table, overflow leading to FullCheck.
3. **Local dirty set.** Done:
- The watcher marks each path an event names in `LocalDirty` (in memory): the path, with
what is under it, and the folder it is in. A pass claims the marks before it looks at the
disk, so a change made while it looks stays marked for the next pass, and retires them once
it applied everything it found. A claim is trusted when the watch was live since the last
pass claimed; a watcher error, an overflow or a restart breaks that.
- A pass keeps what it found on disk (`LocalWalk`) for the next one, unless it changed the
disk itself (a download, a conflict copy, a folder made or removed), failed a step, deferred
a file or could not read a path. Its own changes are marked only once the watcher reports
them, which may come after the next pass claims, so that pass walks in full instead.
- The next pass with a trusted claim, the same ignore rules (`IgnoreRules::source`) and a
full walk less than an hour old starts from the kept walk (`local reused` in the trace).
It lists each marked folder again, walks each marked path again with what is under it, and
reads again each file that was open for writing. Everything else is taken as it was.
- A full walk with a trusted claim still counts the changes the claim did not cover
(`missed local changes`). It runs at least once an hour, and after anything that breaks
the trust.
- A mark that was missed delays a change until the next full walk. It cannot lose one: a
download and a local deletion check the file on disk against what the pass planned from
before they act, and a path missing from the kept walk is one a walk found gone.
- **Tests:** the `rewalk` unit tests in `mirror.rs` (each kind of change, ignored folders, a
mark that came before its folder's, a file that was open for writing), and
`a_trusted_local_dirty_set_stands_in_for_the_walk` (sim: an edit, a new folder, a deletion
and a folder moved in reach Drive through reused walks; it fails with the watcher's marks
switched off).
4. **Step scheduler.** Replace `run_burst` and the per-pass lock with steps and priorities.
5. **Drop the 120 s poll** for the daily audit, once 2 and 3 have run for a release with the
poll still on, and traces show the dirty sets catch everything the poll finds.
+26 -3
View File
@@ -307,9 +307,32 @@ instance's keyring entry so the next run does not sign in again; `--logout` forg
Proton asks for a CAPTCHA, sign in once by hand with `PDFS_INSTANCE=bench pdfs login`.
The script refuses a `pdfs` built without `PDFS_INSTANCE`, which would act on your own account.
A new folder's first sync uploads about one small file every four seconds, so with a 500-file
tree the edit is timed about 35 minutes in. A run that is cut short leaves its folder behind; the
next run removes it.
A new folder's first sync uploads about two small files a second (eight at a time), so with a
500-file tree the edit is timed a few minutes in. A run that is cut short leaves its folder behind;
the next run removes it.
### The small-file benchmark
`--scenario small` times many small files instead, the case that the API's one-request small
upload is for. For each tree size (200 by default) it makes files of `--small-size` random bytes
(4096 by default), plus `--images` noise PNGs that get thumbnails (10 by default). It then:
- times the first sync, until every file is uploaded and the folder is quiet
- rewrites `--edits` of the files at once (50 by default) and times until all are uploaded again
For each phase it reports wall time, files per second, the daemon's CPU time, and the requests
the daemon sent. The requests are API calls by method, plus storage uploads. It counts them from
the SDK's telemetry: the daemon runs with `RUST_LOG=info,pgp=error,proton_sdk::telemetry=debug`,
and its log goes to the work directory. If the SDK tags each request with its endpoint, the JSON
output also counts requests per endpoint.
```bash
scripts/live-bench.py --account-env path/to/.env --pdfs target/release/pdfs --scenario small \
--json small.json
```
Wall time varies by 2x between runs against the live service. Compare medians of three runs,
and treat the request counts as the stable measure.
## Before a release
+28 -3
View File
@@ -309,9 +309,34 @@ What the parts mean:
happens on the first pass, once a day, and after the daemon lost track of Proton Drive's
changes. **`resumed`** counts the paths a pass took from a listing that a restart cut short.
- **`unproven deletions`** counts deletions a pass planned for a path it had not proven gone.
It should never appear. If it does, the journal has a `sync: a planned deletion is not backed
by proof of absence` line for each one; please report it with those lines.
- **`unproven deletions`** counts deletions a pass planned for a path it had not proven gone,
and so did not make. It should never appear. If it does, the folder shows an error, the path
stays on both sides, and the journal has a `sync: not deleting a path whose absence is not
proven` line for each one; please report it with those lines.
- **`local dirty`** counts the places on disk the filesystem watcher reported changed since the
last pass. **`local dirty untrusted`** is 1 when the watch was not live the whole time since
then: after a start, a watch that failed, or an overflowed event queue. **`missed local
changes`** counts changes the pass found on disk that a trusted watch did not report. It
should stay at zero; the journal then has a `sync: the local dirty set missed changes the walk
found` line naming the first one. **`local reused`** counts the paths on disk a pass took from
the last pass's walk instead of walking the folder again: it then read only what the watcher
reported. A pass with no `local reused` count walked the whole folder. That happens on the
first pass, at least once an hour, after the pass before it changed files on disk itself,
and after anything that breaks trust in the watch. Only those passes count `missed local
changes`.
A `sync: root state` line in the journal says when a folder's state changes, for example
`from=following to=auditing (local: Overflow)`: the side named is walked in full by the next
pass, which takes the folder back to `following`.
**`unsure resent`** counts effects sent again that a daemon stopped before it heard back
from; the apply step checks whether each already landed before it sends it. **`retried`**
counts effects sent again after a failure, and **`superseded`** counts unsettled effects of
earlier passes that were no longer needed. A `sync: an effect keeps failing` line names an
upload, download, folder or deletion that failed five times in a row.
The `sync effects not settled` lines in `pdfs diagnostics` list the oldest of these effects
now, one per line, for example
`folder 2 trash Old/report.pdf: retry, sent 3 times, 12m4s ago (timed out)`. `issued` means
sent and waiting for an answer, `unsure` means a stopped daemon sent it and the next pass has
not looked yet, and `retry` or `blocked` means it failed.
Please include these lines when you report a slow folder.
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

+2 -1
View File
@@ -9,7 +9,7 @@
# Build + install: cd packaging && makepkg -fi
pkgname=proton-drive-linux
pkgver=3.10.0
pkgver=4.0.0
pkgrel=1
pkgdesc="Unofficial Proton Drive client for Linux: files-on-demand FUSE mount, CLI, GTK4 app + tray"
arch=('x86_64')
@@ -71,6 +71,7 @@ package() {
"$pkgdir/etc/xdg/autostart/io.narl.proton-drive-linux-tray.desktop"
install -Dm644 "packaging/io.narl.proton-drive-linux.svg" \
"$pkgdir/usr/share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg"
install -Dm644 -t "$pkgdir/usr/share/icons/hicolor/scalable/status" crates/pdfs-gui/resources/icons/tray/*.svg
# systemd user service that runs the auto-mount daemon. Enabled per-user by
# the GUI on login (`systemctl --user enable --now proton-drive.service`).
@@ -44,6 +44,8 @@ package() {
"$pkgdir/etc/xdg/autostart/io.narl.proton-drive-linux-tray.desktop"
install -Dm644 share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg \
"$pkgdir/usr/share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg"
install -Dm644 -t "$pkgdir/usr/share/icons/hicolor/scalable/status" \
share/icons/hicolor/scalable/status/*.svg
# systemd user unit for the auto-mount daemon; enabled per user, not by pacman.
install -Dm644 lib/systemd/user/proton-drive.service \
@@ -75,6 +75,7 @@ package() {
"$pkgdir/etc/xdg/autostart/io.narl.proton-drive-linux-tray.desktop"
install -Dm644 packaging/io.narl.proton-drive-linux.svg \
"$pkgdir/usr/share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg"
install -Dm644 -t "$pkgdir/usr/share/icons/hicolor/scalable/status" crates/pdfs-gui/resources/icons/tray/*.svg
# systemd user unit for the auto-mount daemon; enabled per user, not by pacman.
install -Dm644 packaging/proton-drive.service \
@@ -70,6 +70,7 @@ package() {
"$pkgdir/etc/xdg/autostart/io.narl.proton-drive-linux-tray.desktop"
install -Dm644 packaging/io.narl.proton-drive-linux.svg \
"$pkgdir/usr/share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg"
install -Dm644 -t "$pkgdir/usr/share/icons/hicolor/scalable/status" crates/pdfs-gui/resources/icons/tray/*.svg
# systemd user unit for the auto-mount daemon; enabled per user, not by pacman.
install -Dm644 packaging/proton-drive.service \
+1
View File
@@ -103,6 +103,7 @@ rustPlatform.buildRustPackage {
$out/etc/xdg/autostart/io.narl.proton-drive-linux-tray.desktop
install -Dm644 packaging/io.narl.proton-drive-linux.svg \
$out/share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg
install -Dm644 -t $out/share/icons/hicolor/scalable/status crates/pdfs-gui/resources/icons/tray/*.svg
substituteInPlace $out/share/applications/io.narl.proton-drive-linux.desktop \
--replace-fail "Exec=pdfs-app" "Exec=$out/bin/pdfs-app"
substituteInPlace $out/etc/xdg/autostart/io.narl.proton-drive-linux-tray.desktop \
+4 -1
View File
@@ -10,7 +10,7 @@
# Match Arch PKGBUILD `!lto` — LTO has broken some GTK/Rust links in practice.
%global _lto_cflags %{nil}
%{!?version: %global version 3.10.0}
%{!?version: %global version 4.0.0}
%global forge https://github.com/narrrl/proton-drive-linux
# Files come from the checkout, or from the unpacked tag archive.
%global src %{?git_dir}%{!?git_dir:.}
@@ -119,6 +119,8 @@ install -D -m0644 %{src}/packaging/io.narl.proton-drive-linux-tray.desktop \
%{buildroot}%{_sysconfdir}/xdg/autostart/io.narl.proton-drive-linux-tray.desktop
install -D -m0644 %{src}/packaging/io.narl.proton-drive-linux.svg \
%{buildroot}%{_datadir}/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg
install -D -m0644 -t %{buildroot}%{_datadir}/icons/hicolor/scalable/status \
%{src}/crates/pdfs-gui/resources/icons/tray/*.svg
install -D -m0644 %{src}/packaging/io.narl.proton-drive-linux.policy \
%{buildroot}/usr/share/polkit-1/actions/io.narl.proton-drive-linux.policy
install -D -m0644 %{src}/packaging/proton-drive.service \
@@ -166,6 +168,7 @@ fi
%{_datadir}/applications/io.narl.proton-drive-linux.desktop
%{_sysconfdir}/xdg/autostart/io.narl.proton-drive-linux-tray.desktop
%{_datadir}/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg
%{_datadir}/icons/hicolor/scalable/status/io.narl.proton-drive-linux-tray-*-symbolic.svg
/usr/lib/systemd/user/proton-drive.service
%{_datadir}/polkit-1/actions/io.narl.proton-drive-linux.policy
%{_datadir}/locale/*/LC_MESSAGES/pdfs.mo
+1
View File
@@ -32,6 +32,7 @@ install -Dm644 "$repo/packaging/io.narl.proton-drive-linux-tray.desktop" \
"$root/etc/xdg/autostart/io.narl.proton-drive-linux-tray.desktop"
install -Dm644 "$repo/packaging/io.narl.proton-drive-linux.svg" \
"$root/share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg"
install -Dm644 -t "$root/share/icons/hicolor/scalable/status" "$repo"/crates/pdfs-gui/resources/icons/tray/*.svg
install -Dm644 "$repo/packaging/io.narl.proton-drive-linux.policy" \
"$root/share/polkit-1/actions/io.narl.proton-drive-linux.policy"
install -Dm644 "$repo/packaging/proton-drive.service" \
+1
View File
@@ -63,6 +63,7 @@ grep -qx "Exec=\"$prefix/bin/pdfs-tray\"" "$tray" || fail "the tray's Exec= was
grep -qx "ExecStart=\"$prefix/bin/pdfs\" daemon" "$unit" || fail "ExecStart= was not rewritten: $(grep ^ExecStart= "$unit")"
[ -f "$prefix/share/locale/de/LC_MESSAGES/pdfs.mo" ] || fail "no translations"
[ -f "$prefix/share/icons/hicolor/scalable/apps/io.narl.proton-drive-linux.svg" ] || fail "no icon"
[ -f "$prefix/share/icons/hicolor/scalable/status/io.narl.proton-drive-linux-tray-synced-symbolic.svg" ] || fail "no tray icons"
[ -f "$prefix/share/bash-completion/completions/pdfs" ] || fail "no bash completion"
[ -f "$prefix/share/proton-drive-linux/basemap-v1.pmtiles" ] || fail "no Places basemap"
[ ! -e "$prefix/share/proton-drive-linux/managed-updates" ] || fail "the update check must stay on offer"
+1087 -751
View File
File diff suppressed because it is too large. Load diff
+1079 -749
View File
File diff suppressed because it is too large. Load diff
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more