Compare commits
1
Commits
aad8ae46dd
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f33bcac32e |
No files matched your search
@@ -5,6 +5,8 @@ commits follow Conventional Commits (release notes are generated from them by `C
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [1.2.0] — 2026-11-18
|
||||||
|
|
||||||
Owner review 6 for v1.2.0 (`docs/requests/2026-11-16-owner-review-6.md`; issue #73). Upgrading from 1.1 keeps the
|
Owner review 6 for v1.2.0 (`docs/requests/2026-11-16-owner-review-6.md`; issue #73). Upgrading from 1.1 keeps the
|
||||||
archive, the database and the settings: migration 0012 runs at start and turns every existing link into a linked
|
archive, the database and the settings: migration 0012 runs at start and turns every existing link into a linked
|
||||||
match. A 1.1 server works as before, without Integrate; a 1.2 server adds the photo lookup and uploads into a target.
|
match. A 1.1 server works as before, without Integrate; a 1.2 server adds the photo lookup and uploads into a target.
|
||||||
@@ -223,6 +225,35 @@ match. A 1.1 server works as before, without Integrate; a 1.2 server adds the ph
|
|||||||
- Download originals of a server sequence unlinked or kept apart from its earlier download makes a new local
|
- Download originals of a server sequence unlinked or kept apart from its earlier download makes a new local
|
||||||
sequence instead of filling the old one again, re-linking it and overwriting its details.
|
sequence instead of filling the old one again, re-linking it and overwriting its details.
|
||||||
- An upload retried after its pair was kept apart makes a new server sequence instead of linking the old one again.
|
- An upload retried after its pair was kept apart makes a new server sequence instead of linking the old one again.
|
||||||
|
- A second version a Union merge copies in is left out of Main at once, so a merge that stops before its details
|
||||||
|
(an edit meanwhile, a cancel) no longer leaves both versions in Main for good.
|
||||||
|
- A merge whose other sequence is not hashed lists as a last copy a photo matched by size and time whose content the
|
||||||
|
kept sequence deleted, instead of failing its verify on every retry.
|
||||||
|
- Download originals of a server sequence whose link a 404 forgot fills and links its own local copy again instead
|
||||||
|
of duplicating every photo into a new local sequence.
|
||||||
|
- A match whose server sequence was deleted, with no local copy linked to it, goes: *Upload all local* sends the
|
||||||
|
local sequence again and the Library stops reading it as a copy found.
|
||||||
|
- A merge whose photo held by a third sequence is held nowhere by the time of its verify asks for a new comparison,
|
||||||
|
which lists it as a last copy, instead of failing with "did not match after copying" on every retry.
|
||||||
|
- A background sync no longer pushes or pulls the details of a pair being integrated, and the Integrate stops
|
||||||
|
instead of taking this PC's own value over a line the user decided as the server's.
|
||||||
|
- A *Keep apart* answer survives a server sequence answering 404 for a moment: it is counted as a linked pair's 404
|
||||||
|
is, so the pair is neither asked again nor linked by itself; only a confirmed deletion lets *Upload all local*
|
||||||
|
send the local sequence.
|
||||||
|
- Download originals into the local copy of a pair asked about again keeps the photos deleted there deleted and
|
||||||
|
compares its details instead of overwriting them with the server's.
|
||||||
|
- An upload of a sequence asked about again makes a new server sequence instead of joining, re-linking and
|
||||||
|
overwriting the one an earlier upload made; one that joins a server sequence this PC already knows compares its
|
||||||
|
details instead of overwriting them.
|
||||||
|
- A second version a merge's verify files is left out of Main also when the run stopped right after filing it (a
|
||||||
|
drive dropping out, project.json held, the app closing): the resumed merge leaves it out then.
|
||||||
|
- A merge whose verify stopped before filing a second version, and whose photo changed before the retry, files the
|
||||||
|
photo as it is now instead of failing on every retry; one that had filed it leaves it out of Main and asks for a
|
||||||
|
new comparison.
|
||||||
|
- *Upload all local* leaves out again a sequence answered *Keep here* after its server copy was deleted, and the
|
||||||
|
answer stays; only a *Keep apart* given before the deletion lets it send the sequence.
|
||||||
|
- An upload that joined a server sequence this PC already knew still compares its details when it is resumed or
|
||||||
|
retried, instead of overwriting the server's title, tags, rating, notes and settings.
|
||||||
|
|
||||||
## [1.1.1] — 2026-11-16
|
## [1.1.1] — 2026-11-16
|
||||||
|
|
||||||
|
|||||||
@@ -1019,3 +1019,16 @@ One line per decision: date · decision · alternative · reason.
|
|||||||
| 2026-11-18 | The Integrate journal keeps the losers the plan listed as last copies (`LastHere`, `LastThere`); before each trash step a loser not listed must still be held by another usable copy (the local copy's other frames, another sequence of this index, the server sequence's fresh manifest; for a server loser its other frames or any sequence of this index), else the journal goes and the job fails as a stale plan (#73) | Keep the loser and end Linked | As the merge's Replace stage: nothing goes to a trash as a last copy without being shown |
|
| 2026-11-18 | The Integrate journal keeps the losers the plan listed as last copies (`LastHere`, `LastThere`); before each trash step a loser not listed must still be held by another usable copy (the local copy's other frames, another sequence of this index, the server sequence's fresh manifest; for a server loser its other frames or any sequence of this index), else the journal goes and the job fails as a stale plan (#73) | Keep the loser and end Linked | As the merge's Replace stage: nothing goes to a trash as a last copy without being shown |
|
||||||
| 2026-11-18 | Download originals of a server sequence without a local copy goes under a key of the job (`chronos-sync:<remote:N>:<job:N>`, the same on a retry) when the sequence holding the server sequence's own key has a pair or a link for that server (kept apart, unlinked, asked again, linked elsewhere): a new local sequence, and its details are taken only by it; a holder with neither (a run that stopped before linking) is joined as before (#73) | Refuse the download and ask for Link or Ask again | The download twin of the round-7 upload rule: the shared key filed the photos back into the sequence the user kept separate, re-linked it and overwrote its details |
|
| 2026-11-18 | Download originals of a server sequence without a local copy goes under a key of the job (`chronos-sync:<remote:N>:<job:N>`, the same on a retry) when the sequence holding the server sequence's own key has a pair or a link for that server (kept apart, unlinked, asked again, linked elsewhere): a new local sequence, and its details are taken only by it; a holder with neither (a run that stopped before linking) is joined as before (#73) | Refuse the download and ask for Link or Ask again | The download twin of the round-7 upload rule: the shared key filed the photos back into the sequence the user kept separate, re-linked it and overwrote its details |
|
||||||
| 2026-11-18 | An upload never links again from its checkpoint a server sequence whose pair with the local sequence is Kept apart (unlinked or kept apart since the attempt that made it): the upload goes on as one without a target, under the job's key (#73) | Make Unlink and Keep apart cancel a pending upload | The checkpoint branch never reached the session-key rule, and a retry or a restart moved the Kept apart pair back to Linked |
|
| 2026-11-18 | An upload never links again from its checkpoint a server sequence whose pair with the local sequence is Kept apart (unlinked or kept apart since the attempt that made it): the upload goes on as one without a target, under the job's key (#73) | Make Unlink and Keep apart cancel a pending upload | The checkpoint branch never reached the session-key rule, and a retry or a restart moved the Kept apart pair back to Linked |
|
||||||
|
| 2026-11-18 | A merge leaves each second version out of Main as it files it (the Copy stage's keep-both and SameUnhashed versions, the Verify stage's), under the kept sequence's lease at the settings version read just before, not cancellable halfway; when that was the plan's version the journal's `KeepSettingsVersion` moves to the one written, so the Details stage still writes the plan's payload (#73) | Have the re-plan exclude a shared version the kept sequence already holds twice | Only the merge knows which version it brought; the re-plan cannot tell it from two versions the user chose to keep in Main |
|
||||||
|
| 2026-11-18 | A merge plan whose kept sequence has tombstones also hashes in memory the other's unhashed frames matched by size and time (every frame of that size and instant); a verify that finds unhashed content the kept sequence deleted, held nowhere and not listed, drops the journal and fails as a stale plan (#73) | Hash them always | Only a tombstone makes such a frame a last copy nothing lists; the rest the verify files as a second version, and an adopted folder is not hashed twice for nothing |
|
||||||
|
| 2026-11-18 | Supersedes the 2026-11-18 download-key row: Download originals goes under a key of the job only when the holder of the server sequence's own key is Kept apart from that server sequence (kept apart or unlinked) or linked to another sequence of that server; a Candidate, Linked or Integrated pair, a pair with another server sequence, or a link a 404 forgot keeps the own key, so the download refills and links its own local copy (#73) | Any pair or link for that server | A link a 404 forgot left a Candidate pair, and the download duplicated every photo into a new local sequence |
|
||||||
|
| 2026-11-18 | A 404 for a server sequence no local copy is linked to (an observation-only link) deletes the Candidate and Kept apart pairs naming it (`FoundCopyStore.SettleUnlinkedGoneAsync`); Linked, Integrated and Integrating pairs are left to their link's 404 (#73) | Count the hit on those pairs (read as deleted on the server) | Neither is a copy of anything the server still has: Upload all local must send the local sequence, and a server sequence listed again is found anew |
|
||||||
|
| 2026-11-18 | A merge verify that finds a hashed photo of the other the plan did not copy (held by a third sequence when planned) held by nothing now drops the journal and fails as a stale plan; "did not match after copying" stays, with the journal kept, for a photo the plan copied that the kept sequence does not hold (#73) | Keep the journal and let a retry ask the third sequence again | A third copy gone never comes back: every retry failed the same way, and the new plan lists the photo as a last copy |
|
||||||
|
| 2026-11-18 | A comparison settles no details (push, pull or conflict) of a pair whose found-copy row reads Integrating; the Integrate's Details stage also refuses (details changed, photos kept) a line the user decided as the server's whose server value is now this PC's planned one, instead of absorbing it (#73) | Count the Integrate's ids in the transfers an event refresh skips | The planner's own Busy check reads that set, and the photos must still be compared; only the settling reversed the user's line-by-line choice (owner Q4) |
|
||||||
|
| 2026-11-18 | Supersedes the 2026-11-18 unlinked-404 row: a 404 for a server sequence no local copy is linked to deletes only its Candidate pairs; each Kept apart pair naming it counts the hit as a linked pair does (once per refresh, a second only after `GoneRecheck`), a listing clears the count, and Upload all local sends the local sequence only once the pair reads deleted on the server (two hits) (#73) | Count observation links in the sweep test | A single 404 (trash and restore, access withdrawn for a moment) erased the Keep apart answer, and the pair was asked again or linked by itself (owner Q1) |
|
||||||
|
| 2026-11-18 | Download originals whose server-sequence key names a local copy paired with that server sequence (Candidate, Linked or Integrated, no link) links that copy first and fills it as a linked copy (its tombstones honoured), then compares it as a new link instead of taking the server's details; a holder with no pair (a run that stopped before linking) is joined as before (#73) | Use a key of the job for a Candidate holder too | The round-9 rule refills the local copy a 404 or Ask again left without a link; treated as new it got photos deleted here back and lost its details (owner Q3, Q4, Q6) |
|
||||||
|
| 2026-11-18 | An upload without a target goes under a key of the job when its local sequence has a Candidate or Kept apart pair with that server, and one whose first original joins a server sequence this PC already knows (listed, linked or paired) compares it as a new link instead of sending all its details (#73) | Keep the own key for a Candidate pair | The own key filed the photos into the sequence an earlier upload made, linked it unasked and overwrote edits made there (owner Q1, Q4) |
|
||||||
|
| 2026-11-18 | A merge's Verify stage journals a second version (`SecondVersions`, and in `VersionShas` the SHA-256 it is filed as) before it files it; a resumed verify that finds such a frame in the kept sequence leaves it out of Main again (a no-op when it already is), and one that reads other bytes for it stops with "changed" (#73) | Save the journal right after filing | The ingest commits the frame before any save can follow: a failed exclusion or a crash in between left the version in Main for good, since a resumed verify read it as the kept sequence's own |
|
||||||
|
| 2026-11-18 | Supersedes the 2026-11-18 unlinked-404 rows on Upload all local: a Kept apart pair whose server sequence reads deleted on the server holds nothing back only when it was answered before the first 404 (`AnsweredAt < RemoteGoneAt`); a Keep here (answered after the deletion was shown) still skips the local sequence (#73) | A separate Keep here state or marker | Both answers are stored as Kept apart with the gone mark; the answer time already tells them apart, and Keep here's tooltip and design §6.3 promise Upload all local leaves it out |
|
||||||
|
| 2026-11-18 | An upload's checkpoint names the server sequence its first original reached with `:joined` appended when that was one this PC already knew; a resumed or retried upload sends all its details only when the checkpoint names the target without that mark (a plain id from an older run still means made by this job) (#73) | Look the sequence up again in the known remotes on resume | After the first attempt the link to it exists, so a resume cannot tell a sequence it made from one it joined; only the attempt that sent the first original knows |
|
||||||
|
| 2026-11-18 | Supersedes the 2026-11-18 `VersionShas` row where a resumed verify reads other bytes for a journalled second version: when the kept sequence does not hold the journalled SHA-256 (nothing was filed) the frame leaves `SecondVersions` and `VersionShas` and is verified as on a first visit, which files the bytes it reads now; when it holds them, they are left out of Main and the merge stops with "changed" and drops its journal, so the next run plans again (#73) | Treat the new bytes as another second version in the same run | A stop that kept the journal failed the same way on every retry once the file changed (an editor saving, a sync tool, an edit before a retry after a failed copy), and a cancel then left a filed version in Main; filing a third version unplanned goes further than the plan the user confirmed, while a new plan compares the new bytes and shows them |
|
||||||
+2
-2
@@ -20,7 +20,7 @@ by its `windows` job once a Windows runner is registered (`WINDOWS_RUNNER`), and
|
|||||||
| 8.4 Owner review 4 | Done (request and plan: `docs/requests/2026-11-06-owner-review-4.md`): released as `v0.1.0-rc.14` with owner review 1 phase 6 (the deploy guide `docs/deploy/`), then as `v1.0.0` (#23), the first stable release: R1 work board of every video made or published, the published apart from workspace work (#29); R2 the anonymous usage counts removed, nothing sent by itself (#30); R3 the archive's whole folder structure created inside the chosen archive path, desktop and server (#31); R4 the repository on Gitea in order (earlier work as closed issues #32–#54 in their milestones, the original documentation in `docs/reference/original`, `fe50b877`); R5 licensing set aside and recorded in #24. |
|
| 8.4 Owner review 4 | Done (request and plan: `docs/requests/2026-11-06-owner-review-4.md`): released as `v0.1.0-rc.14` with owner review 1 phase 6 (the deploy guide `docs/deploy/`), then as `v1.0.0` (#23), the first stable release: R1 work board of every video made or published, the published apart from workspace work (#29); R2 the anonymous usage counts removed, nothing sent by itself (#30); R3 the archive's whole folder structure created inside the chosen archive path, desktop and server (#31); R4 the repository on Gitea in order (earlier work as closed issues #32–#54 in their milestones, the original documentation in `docs/reference/original`, `fe50b877`); R5 licensing set aside and recorded in #24. |
|
||||||
| 8.5 Owner review 5 | Done (request, answers and plan: `docs/requests/2026-11-15-owner-review-5.md`; issues #64–#67, milestone v1.1.0), released as `v1.1.0`: one setup for Chronos Desktop and Chronos Uploader with the Uploader's update check (#64); the detail of mass passes (step, photo x of y, sequence n of m, rate, time left) on the desktop, the admin panel and, for the connected server's jobs, the desktop's Server section (#65); separate homes per server keyed by a stable server id, with the 1.0 workspace and cache sorted at the first start and a separate originals archive per server (#66); Chronos Desktop sharing its library on the LAN in place of Chronos Server for Windows, running on in the tray while it shares (#67). One review round, 15 findings fixed; strings in all 38 languages. Not run on the PC: the Windows-only smoke tests, `installer-test.ps1` and the release dry run (CI runs them). Follow-ups: a firewall status row, Change…/Forget on known servers, the LAN beacon announcing the server id, docs/ui DESIGN and mockups for the new screens. |
|
| 8.5 Owner review 5 | Done (request, answers and plan: `docs/requests/2026-11-15-owner-review-5.md`; issues #64–#67, milestone v1.1.0), released as `v1.1.0`: one setup for Chronos Desktop and Chronos Uploader with the Uploader's update check (#64); the detail of mass passes (step, photo x of y, sequence n of m, rate, time left) on the desktop, the admin panel and, for the connected server's jobs, the desktop's Server section (#65); separate homes per server keyed by a stable server id, with the 1.0 workspace and cache sorted at the first start and a separate originals archive per server (#66); Chronos Desktop sharing its library on the LAN in place of Chronos Server for Windows, running on in the tray while it shares (#67). One review round, 15 findings fixed; strings in all 38 languages. Not run on the PC: the Windows-only smoke tests, `installer-test.ps1` and the release dry run (CI runs them). Follow-ups: a firewall status row, Change…/Forget on known servers, the LAN beacon announcing the server id, docs/ui DESIGN and mockups for the new screens. |
|
||||||
| 8.6 Windows test of 1.1.0 | Done (#70, milestone v1.1.1), released as `v1.1.1`: the App and Core.Windows suites run whole on the development PC (5 stale screen tests brought up to date); a hands-on test of a portable 1.1.0 (import, Reorganize, sharing, a client, tray, Exit with clients); fixes: job log times in local time, the Jobs Type column, Forget in Bulgarian, the Reorganize capture. Still to do by the owner: the real 1.0 → 1.1 upgrade on this PC (UAC). |
|
| 8.6 Windows test of 1.1.0 | Done (#70, milestone v1.1.1), released as `v1.1.1`: the App and Core.Windows suites run whole on the development PC (5 stale screen tests brought up to date); a hands-on test of a portable 1.1.0 (import, Reorganize, sharing, a client, tray, Exit with clients); fixes: job log times in local time, the Jobs Type column, Forget in Bulgarian, the Reorganize capture. Still to do by the owner: the real 1.0 → 1.1 upgrade on this PC (UAC). |
|
||||||
| 8.7 Owner review 6 | In progress (request, answers and plan: `docs/requests/2026-11-16-owner-review-6.md`; #73, milestone v1.2.0), implemented on `or6-duplicates`, not released: matches, the same time-lapse on a server and on this PC under different ids or twice on this PC, found after each sync refresh (the server's new photo lookup) and after jobs that change photos (migration 0012, `Chronos.Data.Copies`); Server › Matches with Keep apart, Link only, Unlink and the Compare dialog (Photos, Details line by line, Projects, Plan); Integrate of a local and a server sequence (job 25: photos both ways under Union by default, details as one change, projects copied across, losers to the trash only after a hash check) and the merge of two local sequences (job 26: the other to its archive's trash once every photo is verified); new photos of integrated pairs moved by themselves, *deleted there* and *deleted on server* reviewed by the user; Settings › Server › Link matches (Ask always), Integrate photos (Union), Integrate projects (Copy across); Upload all local skips suspected matches. Eight parcels, one review round (correctness, safety, conformance) with every verified finding fixed, a gap round and six verification rounds; the strings in all 38 languages, the match terms in every language's glossary; the Windows captures of the new screens are committed as screenshot baselines (`server-copies-*`, `library-copies-*`, `server-sync-copyfound-*`, `edit-picker-twins-*`); the photos a sequence keeps in two versions are listed with Drop… from the Library (Two versions…) and a merge job's Open. Still to do: the PostgreSQL tests in CI, the release. Follow-ups: a field-level merge of an integrated pair's settings (to ask the owner), the Import › Folder… warning, the same two-versions list in Edit, a capture scene of the Two versions… dialog. |
|
| 8.7 Owner review 6 | Done (request, answers and plan: `docs/requests/2026-11-16-owner-review-6.md`; #73, milestone v1.2.0), released as `v1.2.0`: matches, the same time-lapse on a server and on this PC under different ids or twice on this PC, found after each sync refresh (the server's new photo lookup) and after jobs that change photos (migration 0012, `Chronos.Data.Copies`); Server › Matches with Keep apart, Link only, Unlink and the Compare dialog (Photos, Details line by line, Projects, Plan); Integrate of a local and a server sequence (job 25: photos both ways under Union by default, details as one change, projects copied across, losers to the trash only after a hash check) and the merge of two local sequences (job 26: the other to its archive's trash once every photo is verified); new photos of integrated pairs moved by themselves, *deleted there* and *deleted on server* reviewed by the user; Settings › Server › Link matches (Ask always), Integrate photos (Union), Integrate projects (Copy across); Upload all local skips suspected matches. Eight parcels, one review round (correctness, safety, conformance) with every verified finding fixed, a gap round and twelve verification rounds (the last seven on the data engines only, with three-vote confirmation, until one found nothing); the strings in all 38 languages, the match terms in every language's glossary; the Windows captures of the new screens are committed as screenshot baselines (`server-copies-*`, `library-copies-*`, `server-sync-copyfound-*`, `edit-picker-twins-*`); the photos a sequence keeps in two versions are listed with Drop… from the Library (Two versions…) and a merge job's Open. Follow-ups: a field-level merge of an integrated pair's settings (to ask the owner), the Import › Folder… warning, the same two-versions list in Edit, a capture scene of the Two versions… dialog. |
|
||||||
| 9 Monetization | Not started: requires explicit approval (§22); the proposal is recorded in issue #24 (owner review 4, R5). |
|
| 9 Monetization | Not started: requires explicit approval (§22); the proposal is recorded in issue #24 (owner review 4, R5). |
|
||||||
|
|
||||||
## Verification (2026-10-12)
|
## Verification (2026-10-12)
|
||||||
@@ -69,7 +69,7 @@ src/Chronos.App/bin/Release/net10.0-windows/Chronos.exe --capture out/screenshot
|
|||||||
- Job log time (1.1.1): Jobs › expand a job: the log times match the row times (local).
|
- Job log time (1.1.1): Jobs › expand a job: the log times match the row times (local).
|
||||||
- Share this library: Settings › Server › *Share this library*, then Server › This library; connect the Uploader or
|
- Share this library: Settings › Server › *Share this library*, then Server › This library; connect the Uploader or
|
||||||
another PC to the address shown.
|
another PC to the address shown.
|
||||||
- Owner review 6 (v1.2.0, in progress): send a folder of photos to a 1.2 server with Chronos Uploader; on the desktop
|
- Owner review 6 (v1.2.0): send a folder of photos to a 1.2 server with Chronos Uploader; on the desktop
|
||||||
import the same folder plus a few more photos (Import › *Folder…*), give it another title and sign in. After the
|
import the same folder plus a few more photos (Import › *Folder…*), give it another title and sign in. After the
|
||||||
refresh Server › *Matches* lists it as *match found*; *Compare…* shows the photos only here and the differing title;
|
refresh Server › *Matches* lists it as *match found*; *Compare…* shows the photos only here and the differing title;
|
||||||
*Integrate…* opens on Details: *All this PC*, then *Integrate*. The row reads *integrating · x of y*, then
|
*Integrate…* opens on Details: *All this PC*, then *Integrate*. The row reads *integrating · x of y*, then
|
||||||
|
|||||||
@@ -67,10 +67,10 @@ local folders and *Upload all local*). The owner answered in Italian; quoted wor
|
|||||||
|
|
||||||
| Phase | Content | State | Commit |
|
| Phase | Content | State | Commit |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| 1 | `v1.2.0`: R1–R7 (#73); R8 tracking. Parcels: P0 foundation (contracts, migration 0012, store, wire, trash and job hooks, keys), P1a pure comparison and rules, P1b detection and sync integration, P2 server photo lookup and uploads into a target, P3 Integrate, P4 merge of two local sequences, P5 engine composition and automatic photos, P6 the desktop surfaces; then one review round (correctness, safety, conformance) with every verified finding fixed, a gap round and six verification rounds. BRIEF §5, §6.2, §12.2, §12.3, §12.5, §12.7, §12.8, §14.3, §14.4, §14.5, §14.6, §24 and Appendix C amended; DESIGN §4 *Matches*; DECISIONS rows dated 2026-11-16 and 2026-11-17 citing #73 | in progress: implemented on `or6-duplicates`, not released; strings in all 38 languages and their glossaries; the Windows captures committed as baselines; the PostgreSQL tests in CI still to run | `283d04d9` … `38764972`, then the documentation pass |
|
| 1 | `v1.2.0`: R1–R7 (#73); R8 tracking. Parcels: P0 foundation (contracts, migration 0012, store, wire, trash and job hooks, keys), P1a pure comparison and rules, P1b detection and sync integration, P2 server photo lookup and uploads into a target, P3 Integrate, P4 merge of two local sequences, P5 engine composition and automatic photos, P6 the desktop surfaces; then one review round (correctness, safety, conformance) with every verified finding fixed, a gap round and twelve verification rounds (the last seven on the data engines only, each finding confirmed by two of three independent checks, the last three on the latest fixes only, until one found nothing). BRIEF §5, §6.2, §12.2, §12.3, §12.5, §12.7, §12.8, §14.3, §14.4, §14.5, §14.6, §24 and Appendix C amended; DESIGN §4 *Matches*; DECISIONS rows dated 2026-11-16 to 2026-11-18 citing #73 | done: released as `v1.2.0` on 2026-11-18; strings in all 38 languages and their glossaries; the Windows captures committed as baselines; CI green with PostgreSQL 16 and 17 | `283d04d9` … `65b7cdf9` on `or6-duplicates`, squash-merged into `main` |
|
||||||
|
|
||||||
Follow-ups kept out of 1.2.0: a field-level three-way merge of an integrated pair's settings (settings sync as today,
|
Follow-ups kept out of 1.2.0: a field-level three-way merge of an integrated pair's settings (settings sync as today,
|
||||||
owner Q6; to be asked of the owner), the Import › Folder… warning for photos already on a server, merging two
|
owner Q6; to be asked of the owner), the Import › Folder… warning for photos already on a server, merging two
|
||||||
sequences of one server, the list of second versions with *Drop…* in Edit (the Library has it: *Two versions…*).
|
sequences of one server, the list of second versions with *Drop…* in Edit (the Library has it: *Two versions…*).
|
||||||
|
|
||||||
Tracking: issue #73, milestone `v1.2.0`, board card; status **in progress**.
|
Tracking: issue #73, milestone `v1.2.0`, board card; status **done**.
|
||||||
@@ -52,6 +52,12 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
|||||||
/// <summary>Called before each stage runs (tests: a crash, a change made between stages).</summary>
|
/// <summary>Called before each stage runs (tests: a crash, a change made between stages).</summary>
|
||||||
internal Func<MergeStage, Task>? BeforeStage { get; set; }
|
internal Func<MergeStage, Task>? BeforeStage { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Called before a second version is left out of Main (tests: a failure between filing it and saving the journal).</summary>
|
||||||
|
internal Func<string, Task>? BeforeLeaveOutOfMain { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Called before the verify files a second version, once the journal names it (tests: its file rewritten meanwhile).</summary>
|
||||||
|
internal Func<Guid, Task>? BeforeFileVersion { get; set; }
|
||||||
|
|
||||||
public async Task RunAsync(JobContext context)
|
public async Task RunAsync(JobContext context)
|
||||||
{
|
{
|
||||||
var job = context.Job;
|
var job = context.Job;
|
||||||
@@ -372,12 +378,58 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
|||||||
var frame = await _db.Frames.GetAsync(copy.DropFrameId, _ct).ConfigureAwait(false) ?? throw Changed(_dropTitle);
|
var frame = await _db.Frames.GetAsync(copy.DropFrameId, _ct).ConfigureAwait(false) ?? throw Changed(_dropTitle);
|
||||||
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.CopyPhoto, copy.FileName, n, journal.Copies.Count)).ConfigureAwait(false);
|
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.CopyPhoto, copy.FileName, n, journal.Copies.Count)).ConfigureAwait(false);
|
||||||
var result = await FileAsync(frame, copy.Sha256, planned: copy.Sha256 is { Length: > 0 }).ConfigureAwait(false);
|
var result = await FileAsync(frame, copy.Sha256, planned: copy.Sha256 is { Length: > 0 }).ConfigureAwait(false);
|
||||||
|
// A version kept beside the kept sequence's own (a Union keep-both, or another photo after all) is left out of
|
||||||
|
// Main as it is filed, before the journal says so: a resumed run files it again (a duplicate) and asks again.
|
||||||
|
if (copy is { Action: PhotoAction.FetchVersion, Sha256: { Length: > 0 } version } && journal.Replaces.All(r => r.Key != copy.Key))
|
||||||
|
await LeaveOutOfMainAsync(version).ConfigureAwait(false);
|
||||||
journal.Committed[copy.DropFrameId] = result.FrameId;
|
journal.Committed[copy.DropFrameId] = result.FrameId;
|
||||||
Save();
|
Save();
|
||||||
context.Log(Loc.L("Archive.Log.MergeCopied", copy.FileName));
|
context.Log(Loc.L("Archive.Log.MergeCopied", copy.FileName));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Leaves the second version <paramref name="sha"/> just filed in the kept sequence out of Main at once (owner Q3), not
|
||||||
|
/// only at the Details stage: a merge abandoned before that stage (its details changed meanwhile, a stale stage, a
|
||||||
|
/// cancel) would otherwise leave both versions in Main for good, and a new plan, which reads both as the kept
|
||||||
|
/// sequence's own photos, leaves neither out. Written under the kept sequence's lease at the settings version read
|
||||||
|
/// just before (asked again when an edit lands in between); when that was the version the plan read, the Details
|
||||||
|
/// stage then writes at the version this write made (the plan's payload leaves the version out as well). Settings
|
||||||
|
/// that are not a project of this Chronos are left as they are, as the plan leaves them. Not cancelled halfway: a
|
||||||
|
/// filed version is never left in Main by a cancel.
|
||||||
|
/// </summary>
|
||||||
|
private async Task LeaveOutOfMainAsync(string sha)
|
||||||
|
{
|
||||||
|
var ct = CancellationToken.None;
|
||||||
|
if (owner.BeforeLeaveOutOfMain is { } hook) await hook(sha).ConfigureAwait(false);
|
||||||
|
for (var attempt = 1; ; attempt++)
|
||||||
|
{
|
||||||
|
var keep = await _db.Sequences.GetAsync(journal.KeepId, ct).ConfigureAwait(false) ?? throw new StaleCopyPlanException();
|
||||||
|
var basis = CopyPayload.Portable(SyncPayload.Of(keep), await SequencePayloadWriter.PhotosAsync(_db, journal.KeepId, null, ct).ConfigureAwait(false));
|
||||||
|
SyncPayload excluded;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
excluded = CopyPayload.ExcludeVersions(basis, [sha.ToLowerInvariant()]);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is System.Text.Json.JsonException or InvalidDataException)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (excluded.SameAs(basis)) return;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var updated = await new SequencePayloadWriter(_db, owner.Archives).ApplyAsync(journal.KeepId, excluded, keep.SettingsVersion, ct)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
if (journal.KeepSettingsVersion == keep.SettingsVersion) journal.KeepSettingsVersion = updated.SettingsVersion;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
catch (SyncConflictChangedException) when (attempt < 3)
|
||||||
|
{
|
||||||
|
// Edited between the read and the lease: read again.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Copies a frame of the other into staging (hash-checked against <paramref name="expected"/>) and files it in the
|
/// Copies a frame of the other into staging (hash-checked against <paramref name="expected"/>) and files it in the
|
||||||
/// kept sequence. <paramref name="planned"/>: the plan knew the photo's content (else a tombstone of the kept sequence
|
/// kept sequence. <paramref name="planned"/>: the plan knew the photo's content (else a tombstone of the kept sequence
|
||||||
@@ -598,7 +650,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
|||||||
|
|
||||||
var keepRemoved = (await _db.FrameRemovals.ListBySequenceAsync(journal.KeepId, _ct).ConfigureAwait(false))
|
var keepRemoved = (await _db.FrameRemovals.ListBySequenceAsync(journal.KeepId, _ct).ConfigureAwait(false))
|
||||||
.Select(r => r.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
|
.Select(r => r.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
|
||||||
var failed = new List<(Guid FrameId, string Sha256)>();
|
var failed = new List<(Guid FrameId, string Sha256, bool Unhashed)>();
|
||||||
foreach (var frame in dropFrames)
|
foreach (var frame in dropFrames)
|
||||||
{
|
{
|
||||||
_ct.ThrowIfCancellationRequested();
|
_ct.ThrowIfCancellationRequested();
|
||||||
@@ -610,9 +662,35 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
|||||||
?? throw new InvalidOperationException(Loc.L("Errors.Copies.ChangedFile", frame.FileName));
|
?? throw new InvalidOperationException(Loc.L("Errors.Copies.ChangedFile", frame.FileName));
|
||||||
if (frame.Sha256 is { Length: > 0 } recorded && !string.Equals(recorded, sha, StringComparison.OrdinalIgnoreCase))
|
if (frame.Sha256 is { Length: > 0 } recorded && !string.Equals(recorded, sha, StringComparison.OrdinalIgnoreCase))
|
||||||
throw new InvalidOperationException(Loc.L("Errors.Copies.ChangedFile", frame.FileName));
|
throw new InvalidOperationException(Loc.L("Errors.Copies.ChangedFile", frame.FileName));
|
||||||
|
var version = journal.SecondVersions.Contains(frame.Id);
|
||||||
|
if (version && journal.VersionShas.GetValueOrDefault(frame.Id) is var filedAs
|
||||||
|
&& !string.Equals(filedAs, sha, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
// A run that stopped while filing it as a second version read other bytes: changed since.
|
||||||
|
if (filedAs is null || !held.ContainsKey(filedAs))
|
||||||
|
{
|
||||||
|
// Nothing was filed (the copy failed or read other bytes): visited as for the first time.
|
||||||
|
journal.SecondVersions.Remove(frame.Id);
|
||||||
|
journal.VersionShas.Remove(frame.Id);
|
||||||
|
Save();
|
||||||
|
version = false;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// The old bytes were filed: left out of Main now (a new plan reads them as the kept sequence's
|
||||||
|
// own photo), then the merge stops and is planned again, which compares the new bytes.
|
||||||
|
await LeaveOutOfMainAsync(filedAs).ConfigureAwait(false);
|
||||||
|
ForgetJournal();
|
||||||
|
throw new InvalidOperationException(Loc.L("Errors.Copies.ChangedFile", frame.FileName));
|
||||||
|
}
|
||||||
|
}
|
||||||
if (held.TryGetValue(sha, out var keepFrame))
|
if (held.TryGetValue(sha, out var keepFrame))
|
||||||
{
|
{
|
||||||
|
// Filed as a second version by a run that stopped before the journal said so: left out of Main again
|
||||||
|
// (nothing changes when it already is), and still left out at the Details stage.
|
||||||
|
if (version) await LeaveOutOfMainAsync(sha).ConfigureAwait(false);
|
||||||
journal.Verified[frame.Id] = new MergeVerified(sha, keepFrame);
|
journal.Verified[frame.Id] = new MergeVerified(sha, keepFrame);
|
||||||
|
if (version) Save();
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (journal.Absent.Contains(sha))
|
if (journal.Absent.Contains(sha))
|
||||||
@@ -624,14 +702,20 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
|||||||
if (frame.Sha256 is not { Length: > 0 } && !keepRemoved.Contains(sha))
|
if (frame.Sha256 is not { Length: > 0 } && !keepRemoved.Contains(sha))
|
||||||
{
|
{
|
||||||
// Compared by size and time only, and another photo after all: filed in the kept sequence as a second version.
|
// Compared by size and time only, and another photo after all: filed in the kept sequence as a second version.
|
||||||
|
// The journal says so before it is filed: a run that stops before it is left out of Main (the exclusion
|
||||||
|
// fails, the app ends) finds it in the kept sequence on resume and leaves it out then.
|
||||||
|
if (!version) journal.SecondVersions.Add(frame.Id);
|
||||||
|
journal.VersionShas[frame.Id] = sha.ToLowerInvariant();
|
||||||
|
Save();
|
||||||
|
if (owner.BeforeFileVersion is { } fileHook) await fileHook(frame.Id).ConfigureAwait(false);
|
||||||
var filed = await FileAsync(frame, sha, planned: false).ConfigureAwait(false);
|
var filed = await FileAsync(frame, sha, planned: false).ConfigureAwait(false);
|
||||||
journal.SecondVersions.Add(frame.Id);
|
await LeaveOutOfMainAsync(sha).ConfigureAwait(false);
|
||||||
journal.Verified[frame.Id] = new MergeVerified(sha, filed.FrameId);
|
journal.Verified[frame.Id] = new MergeVerified(sha, filed.FrameId);
|
||||||
held.TryAdd(sha, filed.FrameId);
|
held.TryAdd(sha, filed.FrameId);
|
||||||
Save();
|
Save();
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
failed.Add((frame.Id, sha));
|
failed.Add((frame.Id, sha, frame.Sha256 is not { Length: > 0 }));
|
||||||
}
|
}
|
||||||
if (failed.Count > 0)
|
if (failed.Count > 0)
|
||||||
{
|
{
|
||||||
@@ -639,7 +723,24 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
|||||||
// sequence's index rows prove nothing: its files were hashed again above and did not hold it.
|
// sequence's index rows prove nothing: its files were hashed again above and did not hold it.
|
||||||
var others = await new CopySides(_db).HeldElsewhereAsync([.. failed.Select(f => f.Sha256)], [journal.DropId, journal.KeepId], _ct)
|
var others = await new CopySides(_db).HeldElsewhereAsync([.. failed.Select(f => f.Sha256)], [journal.DropId, journal.KeepId], _ct)
|
||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
var lost = failed.Where(f => !others.Contains(f.Sha256)).Select(f => f.Sha256).Distinct(StringComparer.Ordinal).Count();
|
var lostFrames = failed.Where(f => !others.Contains(f.Sha256)).ToList();
|
||||||
|
if (lostFrames.Any(f => f.Unhashed && keepRemoved.Contains(f.Sha256)))
|
||||||
|
{
|
||||||
|
// Content the kept sequence deleted, which the plan never compared by content (unhashed, matched by size
|
||||||
|
// and time): a last copy the plan did not list. Retrying this journal would fail the same way: it goes,
|
||||||
|
// and the new plan lists it.
|
||||||
|
ForgetJournal();
|
||||||
|
throw new StaleCopyPlanException();
|
||||||
|
}
|
||||||
|
if (lostFrames.Any(f => !f.Unhashed && !journal.Copies.Any(c => c.DropFrameId == f.FrameId)))
|
||||||
|
{
|
||||||
|
// A hashed photo the plan did not copy (held by a third sequence when planned, by nothing now): a last
|
||||||
|
// copy the plan did not list. Retrying this journal would fail the same way: it goes, and the new plan
|
||||||
|
// lists it. Only a photo the plan copied and the kept sequence does not hold is a failed copy.
|
||||||
|
ForgetJournal();
|
||||||
|
throw new StaleCopyPlanException();
|
||||||
|
}
|
||||||
|
var lost = lostFrames.Select(f => f.Sha256).Distinct(StringComparer.Ordinal).Count();
|
||||||
if (lost > 0) throw new InvalidOperationException(Loc.Plural("Errors.Copies.VerifyFailed", lost));
|
if (lost > 0) throw new InvalidOperationException(Loc.Plural("Errors.Copies.VerifyFailed", lost));
|
||||||
journal.Settled.AddRange(failed.Select(f => f.FrameId));
|
journal.Settled.AddRange(failed.Select(f => f.FrameId));
|
||||||
// Held by a third sequence now: asked again before the trash, which that sequence may not wait for.
|
// Held by a third sequence now: asked again before the trash, which that sequence may not wait for.
|
||||||
|
|||||||
@@ -105,6 +105,14 @@ internal sealed class MergeJournal
|
|||||||
/// <summary>Drop frames the verify found to be another photo than keep's (unhashed, same size and time) and filed as a second version.</summary>
|
/// <summary>Drop frames the verify found to be another photo than keep's (unhashed, same size and time) and filed as a second version.</summary>
|
||||||
public List<Guid> SecondVersions { get; set; } = [];
|
public List<Guid> SecondVersions { get; set; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Drop frame of <see cref="SecondVersions"/> → the SHA-256 it is filed as, written before it is filed: a resumed verify
|
||||||
|
/// that finds it in the kept sequence leaves it out of Main again. One that reads other bytes starts over for that frame
|
||||||
|
/// when the kept sequence does not hold the old ones (nothing was filed), else leaves them out of Main and stops, and the
|
||||||
|
/// merge is planned again.
|
||||||
|
/// </summary>
|
||||||
|
public Dictionary<Guid, string> VersionShas { get; set; } = [];
|
||||||
|
|
||||||
/// <summary>Drop frames the verify found nothing of to lose: last copies the plan listed, or photos a third sequence holds.</summary>
|
/// <summary>Drop frames the verify found nothing of to lose: last copies the plan listed, or photos a third sequence holds.</summary>
|
||||||
public List<Guid> Settled { get; set; } = [];
|
public List<Guid> Settled { get; set; } = [];
|
||||||
|
|
||||||
|
|||||||
@@ -124,10 +124,10 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
|||||||
var here = await _sides.LocalAsync(keep, ct).ConfigureAwait(false);
|
var here = await _sides.LocalAsync(keep, ct).ConfigureAwait(false);
|
||||||
var there = await _sides.LocalAsync(drop, ct).ConfigureAwait(false);
|
var there = await _sides.LocalAsync(drop, ct).ConfigureAwait(false);
|
||||||
var comparison = CopyComparer.Compare(here, there);
|
var comparison = CopyComparer.Compare(here, there);
|
||||||
if (online && await HashOnlyThereAsync(comparison, there, dropPaths, ct).ConfigureAwait(false) is { } hashed)
|
if (online && await HashUnhashedThereAsync(comparison, there, dropPaths, here.Removed.Count > 0, ct).ConfigureAwait(false) is { } hashed)
|
||||||
{
|
{
|
||||||
// Compared by content now: a photo the kept sequence deleted reads Deleted here (a last copy when nothing else
|
// Compared by content now: a photo the kept sequence deleted reads Deleted here (a last copy when nothing else
|
||||||
// holds it), never a copy the kept sequence's tombstone refuses.
|
// holds it), never a copy the kept sequence's tombstone refuses nor a photo the verify cannot find held.
|
||||||
there = hashed;
|
there = hashed;
|
||||||
comparison = CopyComparer.Compare(here, there);
|
comparison = CopyComparer.Compare(here, there);
|
||||||
}
|
}
|
||||||
@@ -288,11 +288,22 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// The other's unhashed photos only it holds, hashed now (in memory: a dry run writes nothing); null when there are none.
|
/// The other's unhashed photos only it holds, hashed now (in memory: a dry run writes nothing); null when there are none.
|
||||||
/// Matched by size and time only they would be copied blindly, even a photo whose content the kept sequence deleted.
|
/// Matched by size and time only they would be copied blindly, even a photo whose content the kept sequence deleted.
|
||||||
|
/// When the kept sequence has tombstones (<paramref name="keepDeleted"/>), also every unhashed frame of the other that
|
||||||
|
/// the comparison matched by size and time with a photo of the kept one (<see cref="PhotoClass.SameUnhashed"/>, each
|
||||||
|
/// frame of that size and instant): one of them may be content the kept sequence deleted (a burst of one size in one
|
||||||
|
/// whole second), which nothing would copy, list or find held, so the merge would fail at its verify on every retry.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private async Task<CopySideInput?> HashOnlyThereAsync(CopyComparisonResult comparison, CopySideInput there, ArchivePaths dropPaths, CancellationToken ct)
|
private async Task<CopySideInput?> HashUnhashedThereAsync(CopyComparisonResult comparison, CopySideInput there, ArchivePaths dropPaths, bool keepDeleted,
|
||||||
|
CancellationToken ct)
|
||||||
{
|
{
|
||||||
var keys = comparison.Photos.Where(p => p.Class == PhotoClass.OnlyThere && p.Key.StartsWith(CopyComparer.UnhashedPrefix, StringComparison.Ordinal))
|
var keys = comparison.Photos.Where(p => p.Class == PhotoClass.OnlyThere && p.Key.StartsWith(CopyComparer.UnhashedPrefix, StringComparison.Ordinal))
|
||||||
.Select(p => p.Key).ToHashSet(StringComparer.Ordinal);
|
.Select(p => p.Key).ToHashSet(StringComparer.Ordinal);
|
||||||
|
if (keepDeleted)
|
||||||
|
{
|
||||||
|
foreach (var photo in comparison.Photos)
|
||||||
|
if (photo is { Class: PhotoClass.SameUnhashed, There: { Sha256: null or { Length: 0 }, CapturedAt: not null } theirs })
|
||||||
|
keys.Add(CopyComparer.UnhashedKey(theirs.Size, theirs.CapturedAt, theirs.FrameId));
|
||||||
|
}
|
||||||
if (keys.Count == 0) return null;
|
if (keys.Count == 0) return null;
|
||||||
var photos = new List<CopyPhotoInput>(there.Photos.Count);
|
var photos = new List<CopyPhotoInput>(there.Photos.Count);
|
||||||
var changed = false;
|
var changed = false;
|
||||||
|
|||||||
@@ -199,14 +199,20 @@ public sealed class FoundCopyStore(ChronosDatabase db, TimeProvider? time = null
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// A 404 for the remote side (design §6.3): nothing when <paramref name="localId"/> is null (an observation-only link);
|
/// A 404 for the remote side (design §6.3): the pair's row (made when the link had none) counts one hit per
|
||||||
/// else the pair's row (made when the link had none) counts one hit per <paramref name="refreshId"/>, and a hit after the
|
/// <paramref name="refreshId"/>, and a hit after the first only once <see cref="GoneRecheck"/> has passed since it, and
|
||||||
/// first only once <see cref="GoneRecheck"/> has passed since it, and every Candidate row naming that remote is deleted.
|
/// every Candidate row naming that remote is deleted. With <paramref name="localId"/> null (an observation-only link: no
|
||||||
|
/// local copy is linked to it) the Candidate rows naming that remote go and its Kept apart rows count the hit the same way
|
||||||
|
/// (<see cref="SettleUnlinkedGoneAsync"/>).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public async Task MarkRemoteGoneAsync(string server, Guid remoteId, Guid? localId, Guid refreshId, DateTimeOffset at, CancellationToken ct)
|
public async Task MarkRemoteGoneAsync(string server, Guid remoteId, Guid? localId, Guid refreshId, DateTimeOffset at, CancellationToken ct)
|
||||||
{
|
{
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(server);
|
ArgumentException.ThrowIfNullOrWhiteSpace(server);
|
||||||
if (localId is not { } local) return;
|
if (localId is not { } local)
|
||||||
|
{
|
||||||
|
await SettleUnlinkedGoneAsync(server, remoteId, refreshId, at, ct).ConfigureAwait(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
var refreshes = GoneRefreshes.GetOrCreateValue(db.Database);
|
var refreshes = GoneRefreshes.GetOrCreateValue(db.Database);
|
||||||
var counted = refreshes.TryGetValue((server, remoteId), out var last) && last == refreshId;
|
var counted = refreshes.TryGetValue((server, remoteId), out var last) && last == refreshId;
|
||||||
await _db.InTransactionAsync(async session =>
|
await _db.InTransactionAsync(async session =>
|
||||||
@@ -231,6 +237,40 @@ public sealed class FoundCopyStore(ChronosDatabase db, TimeProvider? time = null
|
|||||||
refreshes[(server, remoteId)] = refreshId;
|
refreshes[(server, remoteId)] = refreshId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A server sequence no local copy is linked to answered 404 (design §6.3; owner Q1, Q8): the unanswered (Candidate) rows
|
||||||
|
/// naming it go, so a local sequence matched only with it reads as local only again (Upload all local sends it, the
|
||||||
|
/// Library stops saying "copy found"); listed again, it is found anew. Its Kept apart rows are the user's answer and stay:
|
||||||
|
/// each counts the hit as a linked pair does (one per <paramref name="refreshId"/>, a second only once
|
||||||
|
/// <see cref="GoneRecheck"/> has passed since the first), so a server sequence answering 404 for a moment (moved to the
|
||||||
|
/// server's trash and restored, access withdrawn briefly) keeps the answer and a listing clears the count; only a
|
||||||
|
/// confirmed deletion (<see cref="FoundCopy.RemoteGone"/>) lets Upload all local send the local sequence
|
||||||
|
/// (<see cref="UploadAllRule"/>). Linked, Integrated and Integrating rows are left to their link's own 404.
|
||||||
|
/// </summary>
|
||||||
|
public async Task SettleUnlinkedGoneAsync(string server, Guid remoteId, Guid refreshId, DateTimeOffset at, CancellationToken ct)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(server);
|
||||||
|
var refreshes = GoneRefreshes.GetOrCreateValue(db.Database);
|
||||||
|
var counted = refreshes.TryGetValue((server, remoteId), out var last) && last == refreshId;
|
||||||
|
await _db.InTransactionAsync(async session =>
|
||||||
|
{
|
||||||
|
var inner = new DbAccess(session);
|
||||||
|
await inner.ExecuteAsync($"DELETE FROM found_copies WHERE kind = 0 AND server = $1 AND remote_id = $2 AND {Effective} = 0",
|
||||||
|
[server, remoteId], ct).ConfigureAwait(false);
|
||||||
|
if (counted) return 0;
|
||||||
|
var apart = await inner.ListAsync($"{Select} WHERE kind = 0 AND server = $1 AND remote_id = $2 AND {Effective} = 1", [server, remoteId], Map, ct)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
foreach (var row in apart.Where(r => r.RemoteGoneHits == 0 || r.RemoteGoneAt is not { } first || at - first >= GoneRecheck))
|
||||||
|
{
|
||||||
|
await inner.ExecuteAsync(
|
||||||
|
"UPDATE found_copies SET remote_gone_hits = remote_gone_hits + 1, remote_gone_at = COALESCE(remote_gone_at, $2), updated_at = $3 WHERE id = $1",
|
||||||
|
[row.Id, at, _time.GetUtcNow()], ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}, ct).ConfigureAwait(false);
|
||||||
|
refreshes[(server, remoteId)] = refreshId;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>The server answered for the remote again: hits back to 0, no gone time.</summary>
|
/// <summary>The server answered for the remote again: hits back to 0, no gone time.</summary>
|
||||||
public Task ClearRemoteGoneAsync(string server, Guid remoteId, CancellationToken ct)
|
public Task ClearRemoteGoneAsync(string server, Guid remoteId, CancellationToken ct)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -55,7 +55,10 @@ public static class UploadAllRule
|
|||||||
foreach (var entry in localOnly)
|
foreach (var entry in localOnly)
|
||||||
{
|
{
|
||||||
if (entry.Local is not { } local) continue;
|
if (entry.Local is not { } local) continue;
|
||||||
var pairs = bySequence.GetValueOrDefault(local.Id) ?? [];
|
// A Kept apart answer given before a server sequence was confirmed deleted there (two 404s apart) holds nothing
|
||||||
|
// back: that sequence is no copy of anything any more, and the local one is this PC's only. A Keep here, answered
|
||||||
|
// once the deletion was shown, is the user's answer about the deletion itself: it still skips.
|
||||||
|
var pairs = (bySequence.GetValueOrDefault(local.Id) ?? []).Where(p => !ApartBeforeDeletion(p)).ToList();
|
||||||
UploadSkip? why =
|
UploadSkip? why =
|
||||||
busy.Contains(local.Id) || pairs.Any(p => p.State == CopyState.Integrating) ? UploadSkip.Busy
|
busy.Contains(local.Id) || pairs.Any(p => p.State == CopyState.Integrating) ? UploadSkip.Busy
|
||||||
: pairs.Any(p => p.Kind == CopyKind.LocalServer && p.RemoteGoneHits >= 1) ? UploadSkip.DeletedOnServer
|
: pairs.Any(p => p.Kind == CopyKind.LocalServer && p.RemoteGoneHits >= 1) ? UploadSkip.DeletedOnServer
|
||||||
@@ -68,6 +71,10 @@ public static class UploadAllRule
|
|||||||
}
|
}
|
||||||
return (upload, skipped);
|
return (upload, skipped);
|
||||||
|
|
||||||
|
static bool ApartBeforeDeletion(FoundCopy p) =>
|
||||||
|
p is { Kind: CopyKind.LocalServer, State: CopyState.KeptApart, RemoteGone: true, AnsweredAt: { } answered, RemoteGoneAt: { } gone }
|
||||||
|
&& answered < gone;
|
||||||
|
|
||||||
void Add(Guid id, FoundCopy copy)
|
void Add(Guid id, FoundCopy copy)
|
||||||
{
|
{
|
||||||
if (!bySequence.TryGetValue(id, out var list)) bySequence[id] = list = [];
|
if (!bySequence.TryGetValue(id, out var list)) bySequence[id] = list = [];
|
||||||
|
|||||||
@@ -643,13 +643,15 @@ public sealed class SyncService
|
|||||||
// Title, tags, rating and notes the user decided as this PC's (the plan had a line there and the final payload
|
// Title, tags, rating and notes the user decided as this PC's (the plan had a line there and the final payload
|
||||||
// keeps this PC's value) are never taken over from a server edit made since: no analysis moves them, and they
|
// keeps this PC's value) are never taken over from a server edit made since: no analysis moves them, and they
|
||||||
// keep no history. The pair goes back to Linked and the sync shows the conflict. Settings paths are absorbed.
|
// keep no history. The pair goes back to Linked and the sync shows the conflict. Settings paths are absorbed.
|
||||||
|
var lined = CopyPayload.Moved(plannedLocal, plannedRemote);
|
||||||
|
var notLocal = CopyPayload.Moved(plannedLocal, finalPortable);
|
||||||
var metadata = absorbed.Where(p => p.StartsWith(SyncRules.MetadataPath, StringComparison.Ordinal)).ToList();
|
var metadata = absorbed.Where(p => p.StartsWith(SyncRules.MetadataPath, StringComparison.Ordinal)).ToList();
|
||||||
if (metadata.Count > 0)
|
if (metadata.Any(p => lined.Contains(p) && !notLocal.Contains(p))) throw DetailsChanged();
|
||||||
{
|
// A line the user decided as the server's whose server value is now this PC's planned one: this PC's own
|
||||||
var lined = CopyPayload.Moved(plannedLocal, plannedRemote);
|
// value sent there since the plan (a background push), not a newer edit. Absorbing it would reverse the
|
||||||
var notLocal = CopyPayload.Moved(plannedLocal, finalPortable);
|
// user's choice on both sides.
|
||||||
if (metadata.Any(p => lined.Contains(p) && !notLocal.Contains(p))) throw DetailsChanged();
|
var sinceLocal = CopyPayload.Moved(plannedLocal, freshRemote);
|
||||||
}
|
if (absorbed.Any(p => lined.Contains(p) && notLocal.Contains(p) && !sinceLocal.Any(q => Overlaps(p, q)))) throw DetailsChanged();
|
||||||
final = CopyPayload.Merge(final, freshRemote, absorbed.ToDictionary(p => p, _ => CopySide.Other, StringComparer.Ordinal),
|
final = CopyPayload.Merge(final, freshRemote, absorbed.ToDictionary(p => p, _ => CopySide.Other, StringComparer.Ordinal),
|
||||||
[.. absorbed.Select(p => new DetailLine(p, null, null))]);
|
[.. absorbed.Select(p => new DetailLine(p, null, null))]);
|
||||||
}
|
}
|
||||||
@@ -710,6 +712,10 @@ public sealed class SyncService
|
|||||||
return result;
|
return result;
|
||||||
|
|
||||||
static SyncConflictChangedException DetailsChanged() => new(Loc.L("Errors.Copies.DetailsChanged"));
|
static SyncConflictChangedException DetailsChanged() => new(Loc.L("Errors.Copies.DetailsChanged"));
|
||||||
|
|
||||||
|
static bool Overlaps(string path, string other) =>
|
||||||
|
string.Equals(path, other, StringComparison.Ordinal)
|
||||||
|
|| other.StartsWith(path + ".", StringComparison.Ordinal) || path.StartsWith(other + ".", StringComparison.Ordinal);
|
||||||
}
|
}
|
||||||
|
|
||||||
private const int AgreeAttempts = 3;
|
private const int AgreeAttempts = 3;
|
||||||
@@ -981,6 +987,10 @@ public sealed class SyncService
|
|||||||
var localChanged = link.BaseLocalSettings != local.SettingsVersion;
|
var localChanged = link.BaseLocalSettings != local.SettingsVersion;
|
||||||
var remoteChanged = link.BaseRemoteSettings != link.RemoteSettingsVersion;
|
var remoteChanged = link.BaseRemoteSettings != link.RemoteSettingsVersion;
|
||||||
if (!localChanged && !remoteChanged) return (link, local);
|
if (!localChanged && !remoteChanged) return (link, local);
|
||||||
|
// A pair being integrated has its details settled once, line by line, by its Integrate job: a push or pull now would
|
||||||
|
// be absorbed there as a newer edit and reverse the user's choice (owner Q4).
|
||||||
|
if (await Copies.FindRemoteAsync(local.Id, link.Server, link.RemoteId, cancellationToken).ConfigureAwait(false) is { State: CopyState.Integrating })
|
||||||
|
return (link, local);
|
||||||
// Frames inserted here since the copy was listed moved its positions without a new settings version.
|
// Frames inserted here since the copy was listed moved its positions without a new settings version.
|
||||||
if (await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false) is { } current && current.SettingsVersion == local.SettingsVersion)
|
if (await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false) is { } current && current.SettingsVersion == local.SettingsVersion)
|
||||||
local = current;
|
local = current;
|
||||||
|
|||||||
@@ -37,6 +37,9 @@ internal sealed class SyncTransfers(SyncService sync)
|
|||||||
{
|
{
|
||||||
private const long SpaceReserve = 512L << 20;
|
private const long SpaceReserve = 512L << 20;
|
||||||
|
|
||||||
|
/// <summary>The upload checkpoint's suffix for a server sequence the job joined (one this PC already knew), not made.</summary>
|
||||||
|
private const string JoinedMark = ":joined";
|
||||||
|
|
||||||
/// <summary>Space a cached proxy is assumed to take before it is downloaded (1920 px JPEG, BRIEF §8.5).</summary>
|
/// <summary>Space a cached proxy is assumed to take before it is downloaded (1920 px JPEG, BRIEF §8.5).</summary>
|
||||||
private const long ProxyEstimate = 3L << 19;
|
private const long ProxyEstimate = 3L << 19;
|
||||||
|
|
||||||
@@ -81,6 +84,9 @@ internal sealed class SyncTransfers(SyncService sync)
|
|||||||
// is filed into the new sequence once there is one).
|
// is filed into the new sequence once there is one).
|
||||||
var heldElsewhere = new List<Frame>();
|
var heldElsewhere = new List<Frame>();
|
||||||
var sessionKey = remoteId is null ? await SessionKeyAsync(context, remote, local).ConfigureAwait(false) : null;
|
var sessionKey = remoteId is null ? await SessionKeyAsync(context, remote, local).ConfigureAwait(false) : null;
|
||||||
|
// Server sequences this PC knows already (listed, linked, or paired with this one): one the key files the first
|
||||||
|
// original into was not made by this upload, and its details are compared as a new link's, never overwritten.
|
||||||
|
var knownRemotes = remoteId is null ? await KnownRemotesAsync(remote, local.Id, ct).ConfigureAwait(false) : [];
|
||||||
while (remoteId is null && pending.TryDequeue(out var first))
|
while (remoteId is null && pending.TryDequeue(out var first))
|
||||||
{
|
{
|
||||||
var sent = await UploadFrameAsync(context, remote, null, sessionKey, paths.FromRelative(first.RelativePath), first, tombstones,
|
var sent = await UploadFrameAsync(context, remote, null, sessionKey, paths.FromRelative(first.RelativePath), first, tombstones,
|
||||||
@@ -90,7 +96,10 @@ internal sealed class SyncTransfers(SyncService sync)
|
|||||||
else if (sent.SequenceId != Guid.Empty)
|
else if (sent.SequenceId != Guid.Empty)
|
||||||
{
|
{
|
||||||
remoteId = sent.SequenceId;
|
remoteId = sent.SequenceId;
|
||||||
await context.CheckpointAsync(sent.SequenceId.ToString(), progress.Done + 1, frames.Count).ConfigureAwait(false);
|
if (knownRemotes.Contains(sent.SequenceId)) created = false;
|
||||||
|
// Saved with the target: a resumed or retried attempt reads whether this job made it, never infers it.
|
||||||
|
await context.CheckpointAsync(sent.SequenceId.ToString() + (created ? string.Empty : JoinedMark), progress.Done + 1, frames.Count)
|
||||||
|
.ConfigureAwait(false);
|
||||||
await sync.LinkAsync(remote.Server, sent.SequenceId, local, ct).ConfigureAwait(false);
|
await sync.LinkAsync(remote.Server, sent.SequenceId, local, ct).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
await progress.StepAsync().ConfigureAwait(false);
|
await progress.StepAsync().ConfigureAwait(false);
|
||||||
@@ -501,6 +510,21 @@ internal sealed class SyncTransfers(SyncService sync)
|
|||||||
var paths = new ArchivePaths(archive.RootPath);
|
var paths = new ArchivePaths(archive.RootPath);
|
||||||
ArchiveVolume.EnsureWritable(paths);
|
ArchiveVolume.EnsureWritable(paths);
|
||||||
|
|
||||||
|
// Without a local copy, the first original goes under the server sequence's key (DownloadKeyAsync). A local copy that
|
||||||
|
// key already names, which this PC compared with the server sequence (a link a 404 forgot, a pair asked about again),
|
||||||
|
// is that copy: linked first, filled as a linked copy (its tombstones honoured), and compared as a new link, so its own
|
||||||
|
// details are never overwritten by the server's (owner Q3, Q4, Q6).
|
||||||
|
string? key = null;
|
||||||
|
if (local is null)
|
||||||
|
{
|
||||||
|
(key, var joins) = await DownloadKeyAsync(context, remote, remoteId, archive.Id).ConfigureAwait(false);
|
||||||
|
if (joins is { } holderId && await db.Sequences.GetAsync(holderId, ct).ConfigureAwait(false) is { } holder)
|
||||||
|
{
|
||||||
|
await sync.LinkAsync(remote.Server, remoteId, holder, ct).ConfigureAwait(false);
|
||||||
|
local = holder;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false);
|
var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false);
|
||||||
var captured = (await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
|
var captured = (await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
|
||||||
var (have, restore, photos, missing) = local is null ? ([], [], new FramePhotos([]), []) : await LocalContentAsync(archive, local, ct).ConfigureAwait(false);
|
var (have, restore, photos, missing) = local is null ? ([], [], new FramePhotos([]), []) : await LocalContentAsync(archive, local, ct).ConfigureAwait(false);
|
||||||
@@ -538,7 +562,6 @@ internal sealed class SyncTransfers(SyncService sync)
|
|||||||
if (local is null && wanted.Count > 0)
|
if (local is null && wanted.Count > 0)
|
||||||
{
|
{
|
||||||
// The first original creates the local sequence (grouped by the server id); the others join it.
|
// The first original creates the local sequence (grouped by the server id); the others join it.
|
||||||
var key = await DownloadKeyAsync(context, remote, remoteId, archive.Id).ConfigureAwait(false);
|
|
||||||
var (staged, sha) = await FetchOriginalAsync(remote, wanted[0], staging, ct).ConfigureAwait(false);
|
var (staged, sha) = await FetchOriginalAsync(remote, wanted[0], staging, ct).ConfigureAwait(false);
|
||||||
var first = await CommitAsync(key, archive.Id, null, wanted[0], staged, sha, captured, ct).ConfigureAwait(false);
|
var first = await CommitAsync(key, archive.Id, null, wanted[0], staged, sha, captured, ct).ConfigureAwait(false);
|
||||||
local = await db.Sequences.GetAsync(first.SequenceId, ct).ConfigureAwait(false)
|
local = await db.Sequences.GetAsync(first.SequenceId, ct).ConfigureAwait(false)
|
||||||
@@ -944,11 +967,15 @@ internal sealed class SyncTransfers(SyncService sync)
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// The server sequence an upload fills and whether this job creates it: the linked one, the one an interrupted
|
/// The server sequence an upload fills and whether this job creates it: the linked one, the one an interrupted
|
||||||
/// attempt created (unless the user kept it apart or unlinked it since), or none yet (the first original creates it).
|
/// attempt created (unless the user kept it apart or unlinked it since), or none yet (the first original creates it).
|
||||||
|
/// The checkpoint names the server sequence an earlier attempt reached, with <see cref="JoinedMark"/> when that attempt
|
||||||
|
/// joined one this PC already knew (its details are compared, never sent all over the server's, on every attempt).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private async Task<(Guid? RemoteId, bool Created)> TargetAsync(JobContext context, ISyncRemote remote, Sequence local)
|
private async Task<(Guid? RemoteId, bool Created)> TargetAsync(JobContext context, ISyncRemote remote, Sequence local)
|
||||||
{
|
{
|
||||||
var ct = context.Cancellation;
|
var ct = context.Cancellation;
|
||||||
Guid? started = Guid.TryParse(context.Checkpoint, out var saved) ? saved : null;
|
var checkpoint = context.Checkpoint ?? string.Empty;
|
||||||
|
var joined = checkpoint.EndsWith(JoinedMark, StringComparison.Ordinal);
|
||||||
|
Guid? started = Guid.TryParse(joined ? checkpoint[..^JoinedMark.Length] : checkpoint, out var saved) ? saved : null;
|
||||||
var link = await sync.Links.FindByLocalAsync(remote.Server, local.Id, ct).ConfigureAwait(false);
|
var link = await sync.Links.FindByLocalAsync(remote.Server, local.Id, ct).ConfigureAwait(false);
|
||||||
foreach (var candidate in new[] { link?.RemoteId, started })
|
foreach (var candidate in new[] { link?.RemoteId, started })
|
||||||
{
|
{
|
||||||
@@ -960,7 +987,7 @@ internal sealed class SyncTransfers(SyncService sync)
|
|||||||
if (await ExistsAsync(remote, id, ct).ConfigureAwait(false))
|
if (await ExistsAsync(remote, id, ct).ConfigureAwait(false))
|
||||||
{
|
{
|
||||||
if (link?.RemoteId != id) await sync.LinkAsync(remote.Server, id, local, ct).ConfigureAwait(false);
|
if (link?.RemoteId != id) await sync.LinkAsync(remote.Server, id, local, ct).ConfigureAwait(false);
|
||||||
return (id, id == started);
|
return (id, id == started && !joined);
|
||||||
}
|
}
|
||||||
// Deleted on the server meanwhile: the originals go into a new sequence.
|
// Deleted on the server meanwhile: the originals go into a new sequence.
|
||||||
if (id == link?.RemoteId) await sync.ForgetGoneAsync(remote.Server, id, ct).ConfigureAwait(false);
|
if (id == link?.RemoteId) await sync.ForgetGoneAsync(remote.Server, id, ct).ConfigureAwait(false);
|
||||||
@@ -970,35 +997,58 @@ internal sealed class SyncTransfers(SyncService sync)
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The session key the first original of an upload without a target goes under: this sequence's own
|
/// The session key the first original of an upload without a target goes under: this sequence's own
|
||||||
/// (<see cref="SyncService.SessionKey"/>), unless the user kept it apart from (or unlinked it from) a sequence of this
|
/// (<see cref="SyncService.SessionKey"/>), unless it has a pair with a sequence of this server that the user has not
|
||||||
/// server. The server files that key into the sequence an earlier upload made, which the user chose to keep separate;
|
/// linked (kept apart, unlinked, or asked about again). The server files that key into the sequence an earlier upload
|
||||||
/// such an upload makes a new sequence instead, under a key of this job (the same on a retry).
|
/// made, which the user separated; such an upload makes a new sequence instead, under a key of this job (the same on a
|
||||||
|
/// retry).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private async Task<string> SessionKeyAsync(JobContext context, ISyncRemote remote, Sequence local)
|
private async Task<string> SessionKeyAsync(JobContext context, ISyncRemote remote, Sequence local)
|
||||||
{
|
{
|
||||||
var own = SyncService.SessionKey(local.Id);
|
var own = SyncService.SessionKey(local.Id);
|
||||||
|
// Kept apart, unlinked, or asked about again (Candidate: unlinked then Ask again, a Keep apart undone): the user has
|
||||||
|
// not linked the two, so the upload never joins one through the key and links it unasked (owner Q1).
|
||||||
var apart = (await sync.Copies.ListByLocalAsync(local.Id, context.Cancellation).ConfigureAwait(false))
|
var apart = (await sync.Copies.ListByLocalAsync(local.Id, context.Cancellation).ConfigureAwait(false))
|
||||||
.Any(c => c is { Kind: CopyKind.LocalServer, State: CopyState.KeptApart } && string.Equals(c.Server, remote.Server, StringComparison.Ordinal)
|
.Any(c => c is { Kind: CopyKind.LocalServer, State: CopyState.KeptApart or CopyState.Candidate }
|
||||||
&& c.LocalId == local.Id);
|
&& string.Equals(c.Server, remote.Server, StringComparison.Ordinal) && c.LocalId == local.Id);
|
||||||
return apart ? string.Create(CultureInfo.InvariantCulture, $"{own}:{context.Job.Id:N}") : own;
|
return apart ? string.Create(CultureInfo.InvariantCulture, $"{own}:{context.Job.Id:N}") : own;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The session key the first original of a download without a local copy goes under: the server sequence's own
|
/// The session key the first original of a download without a local copy goes under: the server sequence's own
|
||||||
/// (<see cref="SyncService.SessionKey"/>), which groups the download in the local sequence an earlier download of it made,
|
/// (<see cref="SyncService.SessionKey"/>), which groups the download in the local sequence an earlier download of it made
|
||||||
/// unless that sequence has been unlinked or kept apart from it, or linked to another sequence of this server since (it
|
/// (refilled and linked again: a link a 404 forgot, a pair asked about again), unless the user separated that sequence
|
||||||
/// has a pair or a link for this server). The user chose to keep such a sequence separate: the download makes a new
|
/// from it: their pair is Kept apart (kept apart, or unlinked), or it is linked to another sequence of this server. Such
|
||||||
/// local sequence instead, under a key of this job (the same on a retry), and never fills or overwrites the other.
|
/// a download makes a new local sequence instead, under a key of this job (the same on a retry), and never fills or
|
||||||
|
/// overwrites the other.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private async Task<string> DownloadKeyAsync(JobContext context, ISyncRemote remote, Guid remoteId, Guid archiveId)
|
/// <returns>
|
||||||
|
/// The key, and the holder it joins when that holder is a copy this PC already compared with the server sequence (a pair
|
||||||
|
/// of the two exists: Candidate, Linked or Integrated): the download then fills it as a linked copy, honouring its
|
||||||
|
/// tombstones, and compares its details as a new link's. Null when the key makes a new sequence or joins one a run of
|
||||||
|
/// this download made and stopped before linking.
|
||||||
|
/// </returns>
|
||||||
|
private async Task<(string Key, Guid? Joins)> DownloadKeyAsync(JobContext context, ISyncRemote remote, Guid remoteId, Guid archiveId)
|
||||||
{
|
{
|
||||||
var ct = context.Cancellation;
|
var ct = context.Cancellation;
|
||||||
var own = SyncService.SessionKey(remoteId);
|
var own = SyncService.SessionKey(remoteId);
|
||||||
if (await sync.Database.Sequences.FindBySessionKeyAsync(archiveId, own, ct).ConfigureAwait(false) is not { } holder) return own;
|
if (await sync.Database.Sequences.FindBySessionKeyAsync(archiveId, own, ct).ConfigureAwait(false) is not { } holder) return (own, null);
|
||||||
var apart = (await sync.Copies.ListByLocalAsync(holder, ct).ConfigureAwait(false))
|
var pairs = (await sync.Copies.ListByLocalAsync(holder, ct).ConfigureAwait(false))
|
||||||
.Any(c => c.Kind == CopyKind.LocalServer && string.Equals(c.Server, remote.Server, StringComparison.Ordinal) && c.LocalId == holder)
|
.Where(c => c.Kind == CopyKind.LocalServer && string.Equals(c.Server, remote.Server, StringComparison.Ordinal) && c.LocalId == holder
|
||||||
|| await sync.Links.FindByLocalAsync(remote.Server, holder, ct).ConfigureAwait(false) is not null;
|
&& c.RemoteId == remoteId)
|
||||||
return apart ? string.Create(CultureInfo.InvariantCulture, $"{own}:{context.Job.Id:N}") : own;
|
.ToList();
|
||||||
|
var apart = pairs.Any(c => c.State == CopyState.KeptApart)
|
||||||
|
|| await sync.Links.FindByLocalAsync(remote.Server, holder, ct).ConfigureAwait(false) is { } link && link.RemoteId != remoteId;
|
||||||
|
if (apart) return (string.Create(CultureInfo.InvariantCulture, $"{own}:{context.Job.Id:N}"), null);
|
||||||
|
return (own, pairs.Count > 0 ? holder : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The server sequences of <paramref name="remote"/> this PC knows of: listed or linked, or paired with <paramref name="localId"/>.</summary>
|
||||||
|
private async Task<HashSet<Guid>> KnownRemotesAsync(ISyncRemote remote, Guid localId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var known = (await sync.Links.ListAsync(remote.Server, ct).ConfigureAwait(false)).Select(l => l.RemoteId).ToHashSet();
|
||||||
|
foreach (var pair in await sync.Copies.ListByLocalAsync(localId, ct).ConfigureAwait(false))
|
||||||
|
if (pair is { Kind: CopyKind.LocalServer, RemoteId: { } id } && string.Equals(pair.Server, remote.Server, StringComparison.Ordinal)) known.Add(id);
|
||||||
|
return known;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static async Task<bool> ExistsAsync(ISyncRemote remote, Guid id, CancellationToken cancellationToken)
|
private static async Task<bool> ExistsAsync(ISyncRemote remote, Guid id, CancellationToken cancellationToken)
|
||||||
|
|||||||
@@ -599,6 +599,204 @@ public abstract class SequenceMergerTests(TestContext context) : DatabaseTest(co
|
|||||||
AssertVersions(await new CopySides(fx.Db).VersionsAsync(keep.Id, Ct), Sha(mine, 0), Sha(theirs, 0));
|
AssertVersions(await new CopySides(fx.Db).VersionsAsync(keep.Id, Ct), Sha(mine, 0), Sha(theirs, 0));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task AVersionTheVerifyFiledBeforeTheRunStoppedIsLeftOutOfMainOnResume()
|
||||||
|
{
|
||||||
|
var fx = await FixtureAsync();
|
||||||
|
var (mine, theirs) = EqualSizeSeeds(0);
|
||||||
|
var keep = await SequenceAsync(fx, "keep", [(mine, 0, "IMG_0001.JPG")]);
|
||||||
|
var drop = await SequenceAsync(fx, "drop", [(theirs, 0, "IMG_0001.JPG")]);
|
||||||
|
await new DbAccess(fx.Db.Database).ExecuteAsync("UPDATE frames SET sha256 = NULL WHERE sequence_id = $1 OR sequence_id = $2", [keep.Id, drop.Id], Ct);
|
||||||
|
var copy = await PairAsync(fx, keep.Id, drop.Id);
|
||||||
|
var merger = Merger(fx);
|
||||||
|
var (engine, handler) = Engine(fx, merger, new FakeProjects(), new FakeWorkspace());
|
||||||
|
await engine.StartAsync(Ct);
|
||||||
|
// Filed at the verify, then the exclusion fails (a drive drops out, project.json is held) before the journal says so.
|
||||||
|
var failedOnce = false;
|
||||||
|
handler.BeforeLeaveOutOfMain = _ =>
|
||||||
|
{
|
||||||
|
if (failedOnce) return Task.CompletedTask;
|
||||||
|
failedOnce = true;
|
||||||
|
throw new IOException("project.json is in use");
|
||||||
|
};
|
||||||
|
var plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
|
||||||
|
Assert.Empty(plan.Photos);
|
||||||
|
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
|
||||||
|
await fx.WaitForAsync(job.Id, JobState.Failed);
|
||||||
|
Assert.True((await HashesAsync(fx, keep.Id)).SetEquals([Sha(mine, 0), Sha(theirs, 0)]));
|
||||||
|
|
||||||
|
await engine.ResumeAsync(job.Id, Ct);
|
||||||
|
await fx.WaitForAsync(job.Id, JobState.Done);
|
||||||
|
|
||||||
|
// The resumed verify finds the version in the kept sequence and leaves it out of Main: one photo at that instant.
|
||||||
|
Assert.Null(await fx.Db.Sequences.GetAsync(drop.Id));
|
||||||
|
AssertVersions(await new CopySides(fx.Db).VersionsAsync(keep.Id, Ct), Sha(mine, 0), Sha(theirs, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task AVersionWhoseFileChangedBeforeItWasFiledIsFiledAsItIsOnResume()
|
||||||
|
{
|
||||||
|
var fx = await FixtureAsync();
|
||||||
|
var (mine, theirs) = EqualSizeSeeds(0);
|
||||||
|
var edited = EqualSizeSeed(0, theirs, mine);
|
||||||
|
var keep = await SequenceAsync(fx, "keep", [(mine, 0, "IMG_0001.JPG")]);
|
||||||
|
var drop = await SequenceAsync(fx, "drop", [(theirs, 0, "IMG_0001.JPG")]);
|
||||||
|
await new DbAccess(fx.Db.Database).ExecuteAsync("UPDATE frames SET sha256 = NULL WHERE sequence_id = $1 OR sequence_id = $2", [keep.Id, drop.Id], Ct);
|
||||||
|
var path = fx.Paths.FromRelative((await fx.Db.Frames.ListBySequenceAsync(drop.Id)).Single().RelativePath);
|
||||||
|
var copy = await PairAsync(fx, keep.Id, drop.Id);
|
||||||
|
var merger = Merger(fx);
|
||||||
|
var (engine, handler) = Engine(fx, merger, new FakeProjects(), new FakeWorkspace());
|
||||||
|
await engine.StartAsync(Ct);
|
||||||
|
// The file is rewritten (an editor saving a rotation) between its hash and its copy: the copy reads other bytes.
|
||||||
|
var rewritten = false;
|
||||||
|
handler.BeforeFileVersion = _ =>
|
||||||
|
{
|
||||||
|
if (rewritten) return Task.CompletedTask;
|
||||||
|
rewritten = true;
|
||||||
|
File.WriteAllBytes(path, Photos.Jpeg(Start, edited));
|
||||||
|
return Task.CompletedTask;
|
||||||
|
};
|
||||||
|
var plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
|
||||||
|
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
|
||||||
|
await fx.WaitForAsync(job.Id, JobState.Failed);
|
||||||
|
Assert.True((await HashesAsync(fx, keep.Id)).SetEquals([Sha(mine, 0)]), "nothing was filed");
|
||||||
|
|
||||||
|
await engine.ResumeAsync(job.Id, Ct);
|
||||||
|
await fx.WaitForAsync(job.Id, JobState.Done);
|
||||||
|
|
||||||
|
// Nothing was filed: the retry files the photo as it is now, as a second version left out of Main.
|
||||||
|
Assert.Null(await fx.Db.Sequences.GetAsync(drop.Id));
|
||||||
|
Assert.True((await HashesAsync(fx, keep.Id)).SetEquals([Sha(mine, 0), Sha(edited, 0)]));
|
||||||
|
AssertVersions(await new CopySides(fx.Db).VersionsAsync(keep.Id, Ct), Sha(mine, 0), Sha(edited, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task AVersionFiledBeforeItsFileChangedIsLeftOutOfMainAndTheMergePlannedAgain()
|
||||||
|
{
|
||||||
|
var fx = await FixtureAsync();
|
||||||
|
var (mine, theirs) = EqualSizeSeeds(0);
|
||||||
|
var edited = EqualSizeSeed(0, theirs, mine);
|
||||||
|
var keep = await SequenceAsync(fx, "keep", [(mine, 0, "IMG_0001.JPG")]);
|
||||||
|
var drop = await SequenceAsync(fx, "drop", [(theirs, 0, "IMG_0001.JPG")]);
|
||||||
|
await new DbAccess(fx.Db.Database).ExecuteAsync("UPDATE frames SET sha256 = NULL WHERE sequence_id = $1 OR sequence_id = $2", [keep.Id, drop.Id], Ct);
|
||||||
|
var dropFrame = (await fx.Db.Frames.ListBySequenceAsync(drop.Id)).Single();
|
||||||
|
var path = fx.Paths.FromRelative(dropFrame.RelativePath);
|
||||||
|
var copy = await PairAsync(fx, keep.Id, drop.Id);
|
||||||
|
var merger = Merger(fx);
|
||||||
|
var (engine, handler) = Engine(fx, merger, new FakeProjects(), new FakeWorkspace());
|
||||||
|
await engine.StartAsync(Ct);
|
||||||
|
// Filed at the verify, then the exclusion fails; the file is rewritten before the retry.
|
||||||
|
var failedOnce = false;
|
||||||
|
handler.BeforeLeaveOutOfMain = _ =>
|
||||||
|
{
|
||||||
|
if (failedOnce) return Task.CompletedTask;
|
||||||
|
failedOnce = true;
|
||||||
|
File.WriteAllBytes(path, Photos.Jpeg(Start, edited));
|
||||||
|
throw new IOException("project.json is in use");
|
||||||
|
};
|
||||||
|
var plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
|
||||||
|
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
|
||||||
|
await fx.WaitForAsync(job.Id, JobState.Failed);
|
||||||
|
Assert.True((await HashesAsync(fx, keep.Id)).SetEquals([Sha(mine, 0), Sha(theirs, 0)]));
|
||||||
|
|
||||||
|
await engine.ResumeAsync(job.Id, Ct);
|
||||||
|
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
|
||||||
|
|
||||||
|
// The filed version is left out of Main, the other stays, and the journal goes: the next run plans again.
|
||||||
|
Assert.Equal(Chronos.Core.Localization.Loc.L("Errors.Copies.ChangedFile", dropFrame.FileName), failed.Error);
|
||||||
|
Assert.NotNull(await fx.Db.Sequences.GetAsync(drop.Id));
|
||||||
|
AssertVersions(await new CopySides(fx.Db).VersionsAsync(keep.Id, Ct), Sha(mine, 0), Sha(theirs, 0));
|
||||||
|
Assert.False(File.Exists(MergeJournal.PathFor(fx.Paths, job.Id)), "the next run plans again");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ASecondVersionCopiedInByAMergeAbandonedBeforeItsDetailsStaysOutOfMain()
|
||||||
|
{
|
||||||
|
var fx = await FixtureAsync();
|
||||||
|
var keep = await SequenceAsync(fx, "keep", [(1, 0, "IMG_0001.JPG"), (4, 30_250, "IMG_0004.JPG")]);
|
||||||
|
var drop = await SequenceAsync(fx, "drop", [(1, 0, "IMG_0001.JPG"), (5, 30_250, "IMG_0004.JPG")]);
|
||||||
|
var copy = await PairAsync(fx, keep.Id, drop.Id);
|
||||||
|
var merger = Merger(fx);
|
||||||
|
var (engine, handler) = Engine(fx, merger, new FakeProjects(), new FakeWorkspace());
|
||||||
|
await engine.StartAsync(Ct);
|
||||||
|
// While the photos are copied the user tags the kept one: its details moved, so the Details stage abandons the merge.
|
||||||
|
handler.BeforeStage = stage => stage == MergeStage.Details ? fx.Db.Sequences.SetTagsAsync(keep.Id, ["edited"], Ct) : Task.CompletedTask;
|
||||||
|
var plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
|
||||||
|
Assert.SequenceEqual([(PhotoAction.FetchVersion, Sha(5, 30_250))], plan.Photos.Select(p => (p.Action, p.Sha256!)));
|
||||||
|
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
|
||||||
|
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
|
||||||
|
Assert.Equal(Chronos.Core.Localization.Loc.L("Errors.Copies.DetailsChanged"), failed.Error);
|
||||||
|
|
||||||
|
// The version copied in is already left out of Main.
|
||||||
|
AssertVersions(await new CopySides(fx.Db).VersionsAsync(keep.Id, Ct), Sha(4, 30_250), Sha(5, 30_250));
|
||||||
|
|
||||||
|
// Planned again (the kept one holds both versions now) and merged: still one photo in Main at that instant.
|
||||||
|
handler.BeforeStage = null;
|
||||||
|
plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
|
||||||
|
Assert.Empty(plan.Photos);
|
||||||
|
job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
|
||||||
|
await fx.WaitForAsync(job.Id, JobState.Done);
|
||||||
|
Assert.Null(await fx.Db.Sequences.GetAsync(drop.Id));
|
||||||
|
AssertVersions(await new CopySides(fx.Db).VersionsAsync(keep.Id, Ct), Sha(4, 30_250), Sha(5, 30_250));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task AnUnhashedPhotoMatchedBySizeAndTimeWhoseContentTheKeptOneDeletedIsALastCopy()
|
||||||
|
{
|
||||||
|
var fx = await FixtureAsync();
|
||||||
|
// A whole-second camera shooting a burst of one size: the other holds two photos at one second, not hashed; the kept
|
||||||
|
// one holds one of them, hashed, and deleted the other.
|
||||||
|
var (deleted, kept) = EqualSizeSeeds(0);
|
||||||
|
var keep = await SequenceAsync(fx, "keep", [(kept, 0, "IMG_0002.JPG")]);
|
||||||
|
var drop = await SequenceAsync(fx, "drop", [(deleted, 0, "IMG_0001.JPG"), (kept, 0, "IMG_0002.JPG")]);
|
||||||
|
await fx.Db.FrameRemovals.SyncSequenceAsync(keep.Id, [new FrameRemoval(keep.Id, Sha(deleted, 0), null, RemovalReason.Deleted, DateTimeOffset.UtcNow)], Ct);
|
||||||
|
await new DbAccess(fx.Db.Database).ExecuteAsync("UPDATE frames SET sha256 = NULL WHERE sequence_id = $1", [drop.Id], Ct);
|
||||||
|
var copy = await PairAsync(fx, keep.Id, drop.Id);
|
||||||
|
var merger = Merger(fx);
|
||||||
|
var (engine, _) = Engine(fx, merger, new FakeProjects(), new FakeWorkspace());
|
||||||
|
await engine.StartAsync(Ct);
|
||||||
|
|
||||||
|
// Compared by content: the deleted photo is a last copy to confirm, nothing to copy.
|
||||||
|
var plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
|
||||||
|
Assert.Empty(plan.Photos);
|
||||||
|
Assert.SequenceEqual([(CopySide.Other, Sha(deleted, 0))], plan.LastCopies.Select(l => (l.Side, l.Key)));
|
||||||
|
|
||||||
|
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
|
||||||
|
await fx.WaitForAsync(job.Id, JobState.Done);
|
||||||
|
Assert.True((await HashesAsync(fx, keep.Id)).SetEquals([Sha(kept, 0)]));
|
||||||
|
Assert.Null(await fx.Db.Sequences.GetAsync(drop.Id));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task APhotoTheKeptOneDeletesAfterThePlanMakesTheVerifyAskForANewPlan()
|
||||||
|
{
|
||||||
|
var fx = await FixtureAsync();
|
||||||
|
var (deleted, kept) = EqualSizeSeeds(0);
|
||||||
|
var keep = await SequenceAsync(fx, "keep", [(kept, 0, "IMG_0002.JPG")]);
|
||||||
|
var drop = await SequenceAsync(fx, "drop", [(deleted, 0, "IMG_0001.JPG"), (kept, 0, "IMG_0002.JPG")]);
|
||||||
|
await new DbAccess(fx.Db.Database).ExecuteAsync("UPDATE frames SET sha256 = NULL WHERE sequence_id = $1", [drop.Id], Ct);
|
||||||
|
var copy = await PairAsync(fx, keep.Id, drop.Id);
|
||||||
|
var merger = Merger(fx);
|
||||||
|
var (engine, handler) = Engine(fx, merger, new FakeProjects(), new FakeWorkspace());
|
||||||
|
await engine.StartAsync(Ct);
|
||||||
|
var plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
|
||||||
|
Assert.Empty(plan.LastCopies);
|
||||||
|
// Once planned, the kept one's tombstone for the other photo arrives (a sync of a deletion made elsewhere).
|
||||||
|
handler.BeforeStage = stage => stage == MergeStage.Verify
|
||||||
|
? fx.Db.FrameRemovals.SyncSequenceAsync(keep.Id, [new FrameRemoval(keep.Id, Sha(deleted, 0), null, RemovalReason.Deleted, DateTimeOffset.UtcNow)], Ct)
|
||||||
|
: Task.CompletedTask;
|
||||||
|
|
||||||
|
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
|
||||||
|
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
|
||||||
|
|
||||||
|
// Not a verify that fails on every retry: the journal goes, and the new plan lists the photo as a last copy.
|
||||||
|
Assert.Equal(Chronos.Core.Localization.Loc.L("Errors.Copies.StalePlan"), failed.Error);
|
||||||
|
Assert.False(File.Exists(MergeJournal.PathFor(fx.Paths, job.Id)));
|
||||||
|
Assert.NotNull(await fx.Db.Sequences.GetAsync(drop.Id));
|
||||||
|
plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
|
||||||
|
Assert.SequenceEqual([(CopySide.Other, Sha(deleted, 0))], plan.LastCopies.Select(l => (l.Side, l.Key)));
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>One photo listed in two versions: <paramref name="kept"/> in Main, <paramref name="incoming"/> left out.</summary>
|
/// <summary>One photo listed in two versions: <paramref name="kept"/> in Main, <paramref name="incoming"/> left out.</summary>
|
||||||
private static void AssertVersions(IReadOnlyList<PhotoVersions> listed, string kept, string incoming)
|
private static void AssertVersions(IReadOnlyList<PhotoVersions> listed, string kept, string incoming)
|
||||||
{
|
{
|
||||||
@@ -621,6 +819,14 @@ public abstract class SequenceMergerTests(TestContext context) : DatabaseTest(co
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>A seed other than <paramref name="like"/> and <paramref name="not"/> whose photo at <paramref name="ms"/> has the same size as <paramref name="like"/>'s.</summary>
|
||||||
|
private static int EqualSizeSeed(int ms, int like, params int[] not)
|
||||||
|
{
|
||||||
|
var length = Photos.Jpeg(Start.AddMilliseconds(ms), like).Length;
|
||||||
|
for (var seed = 1; ; seed++)
|
||||||
|
if (seed != like && !not.Contains(seed) && Photos.Jpeg(Start.AddMilliseconds(ms), seed).Length == length) return seed;
|
||||||
|
}
|
||||||
|
|
||||||
[Test]
|
[Test]
|
||||||
public async Task AnUnhashedPhotoOfTheKeptOneWithTheSameContentIsNoLastCopy()
|
public async Task AnUnhashedPhotoOfTheKeptOneWithTheSameContentIsNoLastCopy()
|
||||||
{
|
{
|
||||||
@@ -1005,6 +1211,43 @@ public abstract class SequenceMergerTests(TestContext context) : DatabaseTest(co
|
|||||||
Assert.Contains(again.LastCopies, l => l.Key == Sha(5, 30_250));
|
Assert.Contains(again.LastCopies, l => l.Key == Sha(5, 30_250));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task APhotoHeldByAThirdSequenceThatIsGoneByTheVerifyMakesTheRetryPlanAgain()
|
||||||
|
{
|
||||||
|
var fx = await FixtureAsync();
|
||||||
|
var keep = await SequenceAsync(fx, "keep", [(1, 0, "IMG_0001.JPG"), (4, 30_250, "IMG_0004.JPG")]);
|
||||||
|
var drop = await SequenceAsync(fx, "drop", [(1, 0, "IMG_0001.JPG"), (5, 30_250, "IMG_0004.JPG")]);
|
||||||
|
// A third sequence holds the other's losing version: not a last copy when planned.
|
||||||
|
var third = await SequenceAsync(fx, "third", [(5, 30_250, "IMG_0004.JPG")]);
|
||||||
|
var copy = await PairAsync(fx, keep.Id, drop.Id);
|
||||||
|
var merger = Merger(fx);
|
||||||
|
var (engine, handler) = Engine(fx, merger, new FakeProjects(), new FakeWorkspace());
|
||||||
|
await engine.StartAsync(Ct);
|
||||||
|
var plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.ThisPcWins), NoContext, Ct);
|
||||||
|
Assert.Empty(plan.LastCopies);
|
||||||
|
handler.BeforeStage = async stage =>
|
||||||
|
{
|
||||||
|
if (stage == MergeStage.Verify) await fx.Db.Sequences.DeleteAsync(third.Id, Ct);
|
||||||
|
};
|
||||||
|
|
||||||
|
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
|
||||||
|
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
|
||||||
|
|
||||||
|
// A last copy the plan did not list, not a failed copy: the journal goes and nothing goes to the trash.
|
||||||
|
Assert.Equal(Chronos.Core.Localization.Loc.L("Errors.Copies.StalePlan"), failed.Error);
|
||||||
|
Assert.Contains(Sha(5, 30_250), await HashesAsync(fx, drop.Id));
|
||||||
|
Assert.False(File.Exists(MergeJournal.PathFor(fx.Paths, job.Id)), "the next run plans again");
|
||||||
|
|
||||||
|
// The Retry asks for a new comparison instead of the same verify error, and the new plan lists the photo.
|
||||||
|
handler.BeforeStage = null;
|
||||||
|
await engine.ResumeAsync(job.Id, Ct);
|
||||||
|
failed = await fx.WaitForAsync(job.Id, JobState.Failed);
|
||||||
|
Assert.Equal(Chronos.Core.Localization.Loc.L("Errors.Copies.StalePlan"), failed.Error);
|
||||||
|
Assert.NotNull(await fx.Db.Sequences.GetAsync(drop.Id));
|
||||||
|
var again = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.ThisPcWins), NoContext, Ct);
|
||||||
|
Assert.Contains(again.LastCopies, l => l.Key == Sha(5, 30_250));
|
||||||
|
}
|
||||||
|
|
||||||
[Test]
|
[Test]
|
||||||
public async Task APhotoAddedToTheOtherOrDeletedFromTheKeptOneMeanwhileKeepsTheOtherOutOfTheTrash()
|
public async Task APhotoAddedToTheOtherOrDeletedFromTheKeptOneMeanwhileKeepsTheOtherOutOfTheTrash()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -183,6 +183,30 @@ public sealed class CopyEngineTests(TestContext context)
|
|||||||
Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct));
|
Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task KeepHereOfASequenceDeletedOnTheServerIsLeftOutOfUploadAllLocal()
|
||||||
|
{
|
||||||
|
await using var f = await FixtureAsync(context);
|
||||||
|
var local = await f.LocalAsync("Comet", f.NewPhotos(2));
|
||||||
|
var gone = Guid.CreateVersion7();
|
||||||
|
var pair = await f.Sync.Copies.EnsureLinkedAsync(f.Server, gone, local.Id, f.Ct);
|
||||||
|
// Deleted on the server: two 404s the re-check apart, read as deleted on server.
|
||||||
|
var at = DateTimeOffset.UtcNow.AddHours(-2);
|
||||||
|
await f.Sync.Copies.MarkRemoteGoneAsync(f.Server, gone, local.Id, Guid.NewGuid(), at, f.Ct);
|
||||||
|
await f.Sync.Copies.MarkRemoteGoneAsync(f.Server, gone, local.Id, Guid.NewGuid(), at.AddHours(1), f.Ct);
|
||||||
|
using var engine = Engine(f);
|
||||||
|
|
||||||
|
await engine.KeepHereAsync(pair.Id, f.Ct);
|
||||||
|
|
||||||
|
// Kept here: Upload all local leaves it out, and the answer stays.
|
||||||
|
var row = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
|
||||||
|
Assert.Equal((CopyState.KeptApart, true), (row.State, row.RemoteGone));
|
||||||
|
var entry = new SyncEntry(local, null, SyncStatus.LocalOnly);
|
||||||
|
var (upload, skipped) = UploadAllRule.Select([entry], await f.Sync.Copies.ListAsync(f.Ct), new HashSet<Guid>(), new HashSet<Guid>());
|
||||||
|
Assert.Empty(upload);
|
||||||
|
Assert.Equal(local.Id, skipped.Single().Entry.Local!.Id);
|
||||||
|
}
|
||||||
|
|
||||||
[Test]
|
[Test]
|
||||||
public async Task LinkIsRefusedWhenTheLocalCopyIsLinkedToAnotherServerSequence()
|
public async Task LinkIsRefusedWhenTheLocalCopyIsLinkedToAnotherServerSequence()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -275,6 +275,51 @@ public abstract class FoundCopyStoreTests(TestContext context) : RepositoryTest(
|
|||||||
Assert.Equal(1, (await store.GetAsync(row.Id, Ct))!.RemoteGoneHits);
|
Assert.Equal(1, (await store.GetAsync(row.Id, Ct))!.RemoteGoneHits);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task A404OfAServerSequenceNoLocalCopyIsLinkedToDeletesItsCandidatesAndCountsOnItsKeptApartAnswers()
|
||||||
|
{
|
||||||
|
var (db, _, s) = await SetupAsync(4);
|
||||||
|
var store = new FoundCopyStore(db);
|
||||||
|
var remote = Guid.CreateVersion7();
|
||||||
|
var candidate = await store.UpsertFoundAsync(Remote(s[0].Id, remote), Ct);
|
||||||
|
var apart = await store.UpsertFoundAsync(Remote(s[1].Id, remote), Ct);
|
||||||
|
Assert.True(await store.SetStateAsync(apart.Id, CopyState.Candidate, CopyState.KeptApart, Answer(), Ct));
|
||||||
|
var linked = await store.UpsertFoundAsync(Remote(s[2].Id, remote), Ct);
|
||||||
|
Assert.True(await store.SetStateAsync(linked.Id, CopyState.Candidate, CopyState.Linked, Answer(), Ct));
|
||||||
|
var elsewhere = await store.UpsertFoundAsync(Remote(s[3].Id, Guid.CreateVersion7()), Ct);
|
||||||
|
|
||||||
|
// After the answers, an observation-only link answers 404: no local copy is linked to it.
|
||||||
|
var first = Guid.NewGuid();
|
||||||
|
await store.MarkRemoteGoneAsync(Nas, remote, null, first, TestData.Now.AddMinutes(1), Ct);
|
||||||
|
await store.MarkRemoteGoneAsync(Nas, remote, null, first, TestData.Now.AddMinutes(2), Ct);
|
||||||
|
|
||||||
|
// The unanswered match is gone; the Keep apart answer stays and counts the 404 once, not read as deleted yet.
|
||||||
|
Assert.Null(await store.GetAsync(candidate.Id, Ct));
|
||||||
|
var row = (await store.GetAsync(apart.Id, Ct))!;
|
||||||
|
Assert.Equal((CopyState.KeptApart, 1, false), (row.State, row.RemoteGoneHits, row.RemoteGone));
|
||||||
|
Assert.Equal(CopyState.Linked, (await store.GetAsync(linked.Id, Ct))!.State);
|
||||||
|
Assert.Equal(CopyState.Candidate, (await store.GetAsync(elsewhere.Id, Ct))!.State);
|
||||||
|
var entries = s[..2].Select(q => new SyncEntry(q, null, SyncStatus.LocalOnly)).ToList();
|
||||||
|
var (upload, skipped) = UploadAllRule.Select(entries, await store.ListAsync(Ct), new HashSet<Guid>(), new HashSet<Guid>());
|
||||||
|
Assert.Equal(s[0].Id, upload.Single().Local!.Id);
|
||||||
|
Assert.Equal((s[1].Id, UploadSkip.DeletedOnServer), (skipped.Single().Entry.Local!.Id, skipped.Single().Why));
|
||||||
|
|
||||||
|
// A second 404 within the re-check is the same moment; one after it confirms the deletion.
|
||||||
|
await store.MarkRemoteGoneAsync(Nas, remote, null, Guid.NewGuid(), TestData.Now.AddMinutes(5), Ct);
|
||||||
|
Assert.Equal(1, (await store.GetAsync(apart.Id, Ct))!.RemoteGoneHits);
|
||||||
|
await store.MarkRemoteGoneAsync(Nas, remote, null, Guid.NewGuid(), TestData.Now.AddHours(1), Ct);
|
||||||
|
row = (await store.GetAsync(apart.Id, Ct))!;
|
||||||
|
Assert.Equal((CopyState.KeptApart, true), (row.State, row.RemoteGone));
|
||||||
|
(upload, skipped) = UploadAllRule.Select(entries, await store.ListAsync(Ct), new HashSet<Guid>(), new HashSet<Guid>());
|
||||||
|
Assert.Empty(skipped);
|
||||||
|
Assert.Count(2, upload);
|
||||||
|
|
||||||
|
// Listed again: the count clears and the answer is the user's as before.
|
||||||
|
await store.ClearRemoteGoneAsync(Nas, remote, Ct);
|
||||||
|
row = (await store.GetAsync(apart.Id, Ct))!;
|
||||||
|
Assert.Equal((CopyState.KeptApart, 0), (row.State, row.RemoteGoneHits));
|
||||||
|
}
|
||||||
|
|
||||||
[Test]
|
[Test]
|
||||||
public async Task MoveToKeptMovesKeysLinksAndPairsAndIsIdempotent()
|
public async Task MoveToKeptMovesKeysLinksAndPairsAndIsIdempotent()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -800,6 +800,73 @@ public sealed class IntegrateTests(TestContext context)
|
|||||||
Assert.Equal("Comet (night)", remote.Title);
|
Assert.Equal("Comet (night)", remote.Title);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A linked pair whose details were agreed, then edited on this PC (Window41, not sent yet), with every detail line
|
||||||
|
/// decided as the server's (Window33): the plan of an Integrate the user confirmed.
|
||||||
|
/// </summary>
|
||||||
|
private static async Task<(Sequence Local, FakeSequence Remote, FoundCopy Pair, IntegratePlan Plan)> EditedHereServerChosenAsync(SyncFixture f)
|
||||||
|
{
|
||||||
|
var photos = f.NewPhotos(3);
|
||||||
|
var local = await f.LocalAsync("Comet", photos.Take(2).ToList(), SyncFixture.Window33);
|
||||||
|
var remote = f.Remote.Add("Comet", [photos[0], photos[2]], SyncFixture.Window33);
|
||||||
|
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||||
|
await f.Sync.RefreshSequencesAsync(f.Remote, [remote.Id], new SyncPolicy(AutoSyncSettings: false), f.Ct);
|
||||||
|
Assert.Equal(local.SettingsVersion, (await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct))!.BaseLocalSettings);
|
||||||
|
local = await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
|
||||||
|
var pair = (await f.Sync.Copies.FindRemoteAsync(local.Id, f.Server, remote.Id, f.Ct))!;
|
||||||
|
var choices = await ChoicesAsync(f, local.Id, remote.Id, CopyPhotoPolicy.Union);
|
||||||
|
Assert.NotEmpty(choices.Details);
|
||||||
|
choices = choices with { Details = choices.Details.ToDictionary(d => d.Key, _ => CopySide.Other) };
|
||||||
|
var plan = await Planner(f).PlanAsync(f.Remote, pair, choices, PlanContext(), f.Ct);
|
||||||
|
return (local, remote, pair, plan);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ABackgroundSyncDuringTheIntegrateLeavesTheDetailsToTheUsersChoice()
|
||||||
|
{
|
||||||
|
await using var f = await FixtureAsync(context);
|
||||||
|
var (engine, handler) = Engine(f);
|
||||||
|
await using var _ = engine;
|
||||||
|
await engine.StartAsync(f.Ct);
|
||||||
|
var (local, remote, _, plan) = await EditedHereServerChosenAsync(f);
|
||||||
|
// The server fires sequenceChanged as the photos land (or the periodic refresh runs): the agent compares the pair.
|
||||||
|
handler.BeforeStage = async stage =>
|
||||||
|
{
|
||||||
|
if (stage == IntegrateStage.Details) await f.Sync.RefreshSequencesAsync(f.Remote, [remote.Id], new SyncPolicy(), f.Ct);
|
||||||
|
};
|
||||||
|
|
||||||
|
var job = await CopyJobs.EnqueueIntegrateAsync(engine, f.Sync.Copies, plan, local.DisplayTitle, f.Ct);
|
||||||
|
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||||
|
|
||||||
|
// The server's settings the user kept are on both sides: this PC's edit was not pushed over them meanwhile.
|
||||||
|
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, remote.SettingsJson), remote.SettingsJson);
|
||||||
|
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task AServerValueThatIsThisPcsOwnOverALineDecidedAsTheServersStopsTheDetails()
|
||||||
|
{
|
||||||
|
await using var f = await FixtureAsync(context);
|
||||||
|
var (engine, handler) = Engine(f);
|
||||||
|
await using var _ = engine;
|
||||||
|
await engine.StartAsync(f.Ct);
|
||||||
|
var (local, remote, pair, plan) = await EditedHereServerChosenAsync(f);
|
||||||
|
// This PC's planned value reaches the server while the photos travel (a push the job did not make).
|
||||||
|
handler.BeforeStage = stage =>
|
||||||
|
{
|
||||||
|
if (stage == IntegrateStage.Photos) f.Remote.EditSettings(remote.Id, SyncFixture.Window41);
|
||||||
|
return Task.CompletedTask;
|
||||||
|
};
|
||||||
|
|
||||||
|
var job = await CopyJobs.EnqueueIntegrateAsync(engine, f.Sync.Copies, plan, local.DisplayTitle, f.Ct);
|
||||||
|
var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
|
||||||
|
|
||||||
|
// Not absorbed as a newer edit, which would reverse the user's choice on both sides: the details stop, the photos stay.
|
||||||
|
Assert.Equal(Loc.L("Errors.Copies.DetailsChanged"), failed.Error);
|
||||||
|
Assert.Equal(CopyState.Linked, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
|
||||||
|
Assert.Equal(3, RemoteHashes(remote).Count);
|
||||||
|
}
|
||||||
|
|
||||||
[Test]
|
[Test]
|
||||||
public async Task ACancelledQueuedJobSetsThePairBack()
|
public async Task ACancelledQueuedJobSetsThePairBack()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -177,6 +177,60 @@ public sealed class SyncServiceCopyTests(TestContext context)
|
|||||||
Assert.True(pair.NeedsAttention);
|
Assert.True(pair.NeedsAttention);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task AMatchWhoseServerSequenceIsDeletedIsGoneAfterTheRefreshAndUploadAllSendsTheLocalOne()
|
||||||
|
{
|
||||||
|
await using var f = await SyncFixture.CreateAsync(context);
|
||||||
|
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
|
||||||
|
var photos = f.NewPhotos(3);
|
||||||
|
var local = await f.LocalAsync("Comet", photos);
|
||||||
|
var remote = nas.Add("2026-09-28 Canon", photos);
|
||||||
|
remote.FirstCapture = local.FirstCapture;
|
||||||
|
remote.CameraModel = local.CameraModel;
|
||||||
|
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||||
|
var pair = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
|
||||||
|
Assert.Equal((CopyState.Candidate, local.Id), (pair.State, pair.LocalId));
|
||||||
|
Assert.Null((await f.Sync.Links.GetAsync(nas.Server, remote.Id, f.Ct))!.LocalId);
|
||||||
|
|
||||||
|
// Deleted on the server: no longer listed, and a 404 when asked for.
|
||||||
|
nas.Sequences.Remove(remote.Id);
|
||||||
|
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||||
|
|
||||||
|
Assert.Null(await f.Sync.Copies.GetAsync(pair.Id, f.Ct));
|
||||||
|
var entries = (await f.Sync.ListAsync(nas.Server, f.Ct)).Where(e => e.Local?.Id == local.Id).ToList();
|
||||||
|
var (upload, skipped) = UploadAllRule.Select(entries, await f.Sync.Copies.ListAsync(f.Ct), new HashSet<Guid>(), new HashSet<Guid>());
|
||||||
|
Assert.Empty(skipped);
|
||||||
|
Assert.Equal(local.Id, upload.Single().Local!.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task AKeptApartServerSequenceAnswering404OnceKeepsTheAnswerAndIsNeverLinkedByItself()
|
||||||
|
{
|
||||||
|
await using var f = await SyncFixture.CreateAsync(context);
|
||||||
|
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
|
||||||
|
var photos = f.NewPhotos(3);
|
||||||
|
var local = await f.LocalAsync("Comet", photos);
|
||||||
|
var remote = nas.Add("2026-09-28 Canon", photos);
|
||||||
|
remote.FirstCapture = local.FirstCapture;
|
||||||
|
remote.CameraModel = local.CameraModel;
|
||||||
|
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||||
|
var pair = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
|
||||||
|
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.Candidate, CopyState.KeptApart,
|
||||||
|
new CopyAnswer(pair.Fingerprint, pair.Score.Shared, null, false, DateTimeOffset.UtcNow), f.Ct));
|
||||||
|
|
||||||
|
// Moved to the server's trash and restored: one refresh gets a 404, the next lists it again.
|
||||||
|
nas.Sequences.Remove(remote.Id);
|
||||||
|
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||||
|
Assert.Equal((CopyState.KeptApart, 1), ((await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.RemoteGoneHits));
|
||||||
|
nas.Sequences[remote.Id] = remote;
|
||||||
|
await f.Sync.RefreshAsync(nas, new SyncPolicy { Linking = CopyLinking.WhenIdentical }, f.Ct);
|
||||||
|
|
||||||
|
// Keep separate is remembered (owner Q1): not asked again, and not linked although the photos are identical.
|
||||||
|
var after = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
|
||||||
|
Assert.Equal((pair.Id, CopyState.KeptApart, 0), (after.Id, after.State, after.RemoteGoneHits));
|
||||||
|
Assert.Null(await f.Sync.LinkOfAsync(nas.Server, local.Id, f.Ct));
|
||||||
|
}
|
||||||
|
|
||||||
[Test]
|
[Test]
|
||||||
public async Task ASequenceReadAsDeletedOnTheServerIsClearedWhenItIsListedAgainOrLinkedAgain()
|
public async Task ASequenceReadAsDeletedOnTheServerIsClearedWhenItIsListedAgainOrLinkedAgain()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -263,6 +263,193 @@ public sealed class SyncTransferCopyTests(TestContext context)
|
|||||||
Assert.True((await LocalHashesAsync(f, copy)).SetEquals(photos.Select(Sha)));
|
Assert.True((await LocalHashesAsync(f, copy)).SetEquals(photos.Select(Sha)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task DownloadingAgainAServerSequenceWhoseLinkA404ForgotRefillsAndLinksItsOwnLocalCopy()
|
||||||
|
{
|
||||||
|
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||||
|
var photos = f.NewPhotos(3);
|
||||||
|
var remote = f.Remote.Add("Comet", photos);
|
||||||
|
var engine = await f.StartEngineAsync();
|
||||||
|
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
|
||||||
|
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||||
|
var local = Assert.NotNull(Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
|
||||||
|
await WaitIdleAsync(f, local);
|
||||||
|
|
||||||
|
// A refresh's 404 forgot the link (the archive was briefly offline); listed again, the pair is asked about again.
|
||||||
|
await f.Sync.Links.DeleteAsync(f.Server, remote.Id, f.Ct);
|
||||||
|
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == remote.Id && c.LocalId == local);
|
||||||
|
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, pair.State, CopyState.Candidate, null, f.Ct));
|
||||||
|
|
||||||
|
// Download originals of the server-only sequence: it goes back into its own local copy, linked again.
|
||||||
|
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
|
||||||
|
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||||
|
|
||||||
|
Assert.Equal(local, Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
|
||||||
|
Assert.Count(3, await f.Db.Frames.ListBySequenceAsync(local, cancellationToken: f.Ct));
|
||||||
|
Assert.True((await LocalHashesAsync(f, local)).SetEquals(photos.Select(Sha)));
|
||||||
|
var keys = await f.Db.Sequences.ListSessionKeysAsync(f.Archive.Archive.Id, SyncService.SessionKey(remote.Id) + "%", f.Ct);
|
||||||
|
Assert.True(keys.All(k => k.SequenceId == local), "no second local sequence holds a key of the server sequence");
|
||||||
|
Assert.Equal(1, (await f.Db.Sequences.ListAsync(new SequenceQuery(), f.Ct)).Items.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task DownloadingAgainIntoTheOwnLocalCopyOfAPairAskedAgainKeepsItsDeletionsAndDetails()
|
||||||
|
{
|
||||||
|
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||||
|
var photos = f.NewPhotos(3);
|
||||||
|
var remote = f.Remote.Add("Comet", photos);
|
||||||
|
var engine = await f.StartEngineAsync();
|
||||||
|
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
|
||||||
|
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||||
|
var local = Assert.NotNull(Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
|
||||||
|
await WaitIdleAsync(f, local);
|
||||||
|
|
||||||
|
// While linked: one photo deleted here (the server keeps it, owner Q6) and the title edited; then unlinked and
|
||||||
|
// asked about again (Ask again, or a Keep apart undone).
|
||||||
|
var sequence = (await f.Db.Sequences.GetAsync(local, f.Ct))!;
|
||||||
|
var gone = (await f.Db.Frames.ListBySequenceAsync(local, cancellationToken: f.Ct))[0];
|
||||||
|
var delete = await f.Archive.Service.FrameTrash.PlanDeleteAsync(local, [gone.Id], sequence.FramesVersion, f.Ct);
|
||||||
|
await f.Archive.Service.FrameTrash.DeleteAsync(delete, cancellationToken: f.Ct);
|
||||||
|
await f.Db.Sequences.EditAsync(local, new SequenceEdit { Title = "Mine" }, null, f.Ct);
|
||||||
|
await f.Sync.UnlinkAsync(f.Server, remote.Id, local, f.Ct);
|
||||||
|
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == remote.Id && c.LocalId == local);
|
||||||
|
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.KeptApart, CopyState.Candidate, null, f.Ct));
|
||||||
|
|
||||||
|
// Download originals of the server sequence: it refills its own local copy, as a linked copy.
|
||||||
|
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
|
||||||
|
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||||
|
|
||||||
|
// The photo deleted here stays deleted, and the title is not overwritten by the server's.
|
||||||
|
Assert.Equal(local, Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
|
||||||
|
Assert.Count(2, await f.Db.Frames.ListBySequenceAsync(local, cancellationToken: f.Ct));
|
||||||
|
Assert.Contains(gone.Sha256, (await f.Db.FrameRemovals.ListBySequenceAsync(local, f.Ct)).Select(r => r.Sha256));
|
||||||
|
Assert.Equal("Mine", (await f.Db.Sequences.GetAsync(local, f.Ct))!.Title);
|
||||||
|
Assert.Equal("Comet", remote.Title);
|
||||||
|
Assert.Equal(1, (await f.Db.Sequences.ListAsync(new SequenceQuery(), f.Ct)).Items.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task AnUploadOfASequenceAskedAboutAgainMakesANewServerSequenceAndLeavesTheOtherAlone()
|
||||||
|
{
|
||||||
|
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||||
|
var photos = f.NewPhotos(3);
|
||||||
|
var local = await f.LocalAsync("Comet", [photos[0], photos[1]]);
|
||||||
|
var engine = await f.StartEngineAsync();
|
||||||
|
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
|
||||||
|
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||||
|
var first = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId;
|
||||||
|
// Unlinked, then asked about again: the pair is a Candidate and nothing links the two.
|
||||||
|
await f.Sync.UnlinkAsync(f.Server, first, local.Id, f.Ct);
|
||||||
|
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == first);
|
||||||
|
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.KeptApart, CopyState.Candidate, null, f.Ct));
|
||||||
|
// Renamed on the server (the web, another desktop); a new photo here.
|
||||||
|
var server = f.Remote.Sequences[first];
|
||||||
|
server.Title = "Comet NAS";
|
||||||
|
server.SettingsVersion++;
|
||||||
|
server.UpdatedAt = DateTimeOffset.UtcNow;
|
||||||
|
await f.AddLocalAsync(local.Id, photos[2]);
|
||||||
|
|
||||||
|
job = await f.Sync.EnqueueUploadAsync(engine, f.Server, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!);
|
||||||
|
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||||
|
|
||||||
|
// The other is not joined through the key, linked unasked or overwritten: a new server sequence holds every photo.
|
||||||
|
Assert.Equal("Comet NAS", server.Title);
|
||||||
|
Assert.True(server.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals([Sha(photos[0]), Sha(photos[1])]));
|
||||||
|
Assert.Equal(CopyState.Candidate, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
|
||||||
|
Assert.Null((await f.Sync.Links.GetAsync(f.Server, first, f.Ct))!.LocalId);
|
||||||
|
var link = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct));
|
||||||
|
Assert.NotEqual(first, link.RemoteId);
|
||||||
|
Assert.True(f.Remote.Sequences[link.RemoteId].Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task AnUploadThatJoinsAServerSequenceItKnowsAlreadyComparesItsDetailsInsteadOfOverwritingThem()
|
||||||
|
{
|
||||||
|
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||||
|
var photos = f.NewPhotos(3);
|
||||||
|
var local = await f.LocalAsync("Comet", [photos[0], photos[1]]);
|
||||||
|
var engine = await f.StartEngineAsync();
|
||||||
|
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
|
||||||
|
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||||
|
var first = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId;
|
||||||
|
// The link and its pair were forgotten (a sweep of 404s: the server served another archive for a while); the
|
||||||
|
// server sequence is listed again, as an observation.
|
||||||
|
var observed = Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, first, f.Ct)) with { LocalId = null };
|
||||||
|
await f.Sync.Links.UpsertAsync(observed, f.Ct);
|
||||||
|
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
|
||||||
|
await session.ExecuteAsync("DELETE FROM found_copies WHERE remote_id = $1", [first], f.Ct);
|
||||||
|
var server = f.Remote.Sequences[first];
|
||||||
|
server.Title = "Comet NAS";
|
||||||
|
server.SettingsVersion++;
|
||||||
|
server.UpdatedAt = DateTimeOffset.UtcNow;
|
||||||
|
await f.AddLocalAsync(local.Id, photos[2]);
|
||||||
|
|
||||||
|
job = await f.Sync.EnqueueUploadAsync(engine, f.Server, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!);
|
||||||
|
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||||
|
|
||||||
|
// Joined through this sequence's key, not made by this upload: the server's title is not overwritten unseen.
|
||||||
|
Assert.Equal(first, Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId);
|
||||||
|
Assert.True(server.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
|
||||||
|
Assert.Equal("Comet NAS", server.Title);
|
||||||
|
Assert.Equal("Comet", (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Title);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ARetriedUploadThatJoinedAServerSequenceItKnewStillComparesItsDetails()
|
||||||
|
{
|
||||||
|
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||||
|
var photos = f.NewPhotos(4);
|
||||||
|
var local = await f.LocalAsync("Comet", [photos[0], photos[1]]);
|
||||||
|
var engine = await f.StartEngineAsync();
|
||||||
|
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
|
||||||
|
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||||
|
var first = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId;
|
||||||
|
// The link and its pair were forgotten; the server sequence is listed again and renamed there.
|
||||||
|
var observed = Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, first, f.Ct)) with { LocalId = null };
|
||||||
|
await f.Sync.Links.UpsertAsync(observed, f.Ct);
|
||||||
|
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
|
||||||
|
await session.ExecuteAsync("DELETE FROM found_copies WHERE remote_id = $1", [first], f.Ct);
|
||||||
|
var server = f.Remote.Sequences[first];
|
||||||
|
server.Title = "Comet NAS";
|
||||||
|
server.SettingsVersion++;
|
||||||
|
server.UpdatedAt = DateTimeOffset.UtcNow;
|
||||||
|
await f.AddLocalAsync(local.Id, photos[2]);
|
||||||
|
await f.AddLocalAsync(local.Id, photos[3]);
|
||||||
|
// One original unreadable for the first attempt: it fails after joining the known sequence.
|
||||||
|
var damaged = (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).Single(fr => fr.Sha256 == Sha(photos[3]));
|
||||||
|
var path = f.Archive.Paths.FromRelative(damaged.RelativePath);
|
||||||
|
var bytes = await File.ReadAllBytesAsync(path, f.Ct);
|
||||||
|
var broken = bytes.ToArray();
|
||||||
|
broken[^3] ^= 0xFF;
|
||||||
|
await File.WriteAllBytesAsync(path, broken, f.Ct);
|
||||||
|
|
||||||
|
var row = new Job
|
||||||
|
{
|
||||||
|
Id = Guid.CreateVersion7(),
|
||||||
|
Kind = JobKind.UploadCommit,
|
||||||
|
TargetIds = [local.Id],
|
||||||
|
State = JobState.Running,
|
||||||
|
NodeId = "t#0",
|
||||||
|
Created = DateTimeOffset.UtcNow,
|
||||||
|
Started = DateTimeOffset.UtcNow,
|
||||||
|
};
|
||||||
|
await f.Db.Jobs.EnqueueAsync(row, f.Ct);
|
||||||
|
var jobs = new JobEngine(f.Db, [], new JobEngineOptions { WorkerId = "t" });
|
||||||
|
var attempt = new JobContext(jobs, row, f.Ct);
|
||||||
|
await Assert.ThrowsAsync<InvalidDataException>(() => new SyncTransfers(f.Sync).UploadAsync(attempt, f.Remote, local.Id));
|
||||||
|
Assert.Equal(first, Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId);
|
||||||
|
|
||||||
|
// Retried from that attempt's checkpoint, the original readable again.
|
||||||
|
await File.WriteAllBytesAsync(path, bytes, f.Ct);
|
||||||
|
var retry = new JobContext(jobs, row with { Checkpoint = attempt.Checkpoint }, f.Ct);
|
||||||
|
await new SyncTransfers(f.Sync).UploadAsync(retry, f.Remote, local.Id);
|
||||||
|
|
||||||
|
// Still joined, not made by this upload: the server's title is not overwritten unseen.
|
||||||
|
Assert.True(server.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
|
||||||
|
Assert.Equal("Comet NAS", server.Title);
|
||||||
|
Assert.Equal("Comet", (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Title);
|
||||||
|
}
|
||||||
|
|
||||||
[Test]
|
[Test]
|
||||||
public async Task AnAutomaticUploadAfterTheServerCopyIsGoneFailsAndCreatesNothing()
|
public async Task AnAutomaticUploadAfterTheServerCopyIsGoneFailsAndCreatesNothing()
|
||||||
{
|
{
|
||||||
|
|||||||
Reference in new issue
Block a user