diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx
index c1581591..e6c1f139 100644
--- a/i18n/en/Errors.resx
+++ b/i18n/en/Errors.resx
@@ -53,6 +53,7 @@
Its local copy could not be removed now: Remove local copy takes it later. long
{0} did not match its source after it was copied. {0} file path
A file of this project in the workspace cannot be read; the log names it.
+ This project was deleted in the library; nothing was removed. Discard changes removes its local copy.
The workspace drive needs {0} GB more for this copy. {0} gigabytes missing
The last edit could not be stored yet; it is tried again, try once more in a moment.
The library's copy of this project does not match what was sent; nothing was removed.
diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx
index 84954535..82039775 100644
--- a/i18n/it/Errors.it.resx
+++ b/i18n/it/Errors.it.resx
@@ -53,6 +53,7 @@
La sua copia locale ora non è stata rimossa: Rimuovi copia locale la toglie più tardi.
{0} non corrispondeva all'originale dopo la copia.
Un file di questo progetto nello spazio di lavoro non è leggibile; il log lo indica.
+ Questo progetto è stato eliminato nella libreria; non è stato rimosso nulla. Scarta modifiche rimuove la sua copia locale.
Al disco dello spazio di lavoro servono altri {0} GB per questa copia.
L'ultima modifica non è ancora stata memorizzata; viene ritentata, riprova tra un momento.
La copia di questo progetto nella libreria non corrisponde a quanto inviato; non è stato rimosso nulla.
diff --git a/src/Chronos.App/Workspace/WorkspaceHost.cs b/src/Chronos.App/Workspace/WorkspaceHost.cs
index 45374e7c..c1e18d3f 100644
--- a/src/Chronos.App/Workspace/WorkspaceHost.cs
+++ b/src/Chronos.App/Workspace/WorkspaceHost.cs
@@ -600,6 +600,11 @@ public sealed class WorkspaceHost
held = basis is not null && await home.HoldsAsync(projectId, head, cancellationToken).ConfigureAwait(false)
&& (basis.Id == head.Id || await home.HoldsAsync(projectId, basis, cancellationToken).ConfigureAwait(false));
}
+ catch (ProjectException ex) when (ex.Reason is ProjectError.NotFound or ProjectError.SequenceNotFound)
+ {
+ // Deleted at the home (its trash keeps every version sent): this copy goes only when its user discards it.
+ throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"), ex);
+ }
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException)
{
throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"), ex);
diff --git a/src/Chronos.Data/Archiving/ArchiveIndexer.cs b/src/Chronos.Data/Archiving/ArchiveIndexer.cs
index 7eb22a7d..0fc05c19 100644
--- a/src/Chronos.Data/Archiving/ArchiveIndexer.cs
+++ b/src/Chronos.Data/Archiving/ArchiveIndexer.cs
@@ -368,6 +368,11 @@ public sealed class ArchiveIndexer
{
Log.Warning("projects", $"The projects of {row.Folder} could not be read back; the next project operation tries again", ex);
}
+ catch (DatabaseException ex)
+ {
+ // The index refused a project of this sequence: the scan goes on with the others, and the next project operation tries again.
+ Log.Warning("projects", $"The projects of {row.Folder} could not be indexed; the next project operation tries again", ex);
+ }
}
/// Indexes one folder; returns its sequence and the sidecar bytes when they were read and not rewritten since (for the snapshot).
diff --git a/src/Chronos.Data/Projects/IProjectHome.cs b/src/Chronos.Data/Projects/IProjectHome.cs
index 098ec3b8..d34d1222 100644
--- a/src/Chronos.Data/Projects/IProjectHome.cs
+++ b/src/Chronos.Data/Projects/IProjectHome.cs
@@ -27,7 +27,10 @@ public interface IProjectHome
/// A new project named from (a version of any project of the sequence), or from Main's head.
Task CreateAsync(string name, Guid? fromVersionId, string? author, CancellationToken cancellationToken);
- /// The project's newest version.
+ ///
+ /// The project's newest version; a project deleted at the home has none ( ,
+ /// ), so a workspace's copy of it reads as gone, never as in step.
+ ///
Task HeadAsync(Guid projectId, CancellationToken cancellationToken);
/// A version of the project by id; null when the home has none.
diff --git a/src/Chronos.Data/Projects/ProjectIndexer.cs b/src/Chronos.Data/Projects/ProjectIndexer.cs
index 84401b38..a32ce0a9 100644
--- a/src/Chronos.Data/Projects/ProjectIndexer.cs
+++ b/src/Chronos.Data/Projects/ProjectIndexer.cs
@@ -53,11 +53,21 @@ internal sealed class ProjectIndexer(ChronosDatabase db)
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
- Log.Warning("projects", $"The project in {directory} cannot be read; it stays as the index has it", ex);
- // Its folder names it (, or - in the trash): its row stays as it is, never taken for gone nor written
- // again, and a live one is held back (it may be Main).
+ // Its folder names it (, or - in the trash).
var name = Path.GetFileName(directory);
- if (Guid.TryParseExact(trashed && name.Length > 32 ? name[..32] : name, "N", out var named) && seen.Add(named) && !trashed) heldBack.Add(named);
+ if (!Guid.TryParseExact(trashed && name.Length > 32 ? name[..32] : name, "N", out var named)) continue;
+ if (!trashed && !File.Exists(Path.Combine(directory, ArchiveLayout.ProjectFile))
+ && await db.Projects.GetAsync(named, cancellationToken).ConfigureAwait(false) is null)
+ {
+ // Versions with no record, of a project no index row names: a creation a crash or a lost disk cut short before its
+ // record (versions are written first), or one a sync tool is still bringing. No project of the sequence is
+ // hidden in it, so it holds nothing back; it is left as it is, and indexed once its record is there.
+ Log.Info("projects", $"{directory} holds no project record; it is left as it is");
+ continue;
+ }
+ Log.Warning("projects", $"The project in {directory} cannot be read; it stays as the index has it", ex);
+ // Its row stays as it is, never taken for gone nor written again, and a live one is held back (it may be Main).
+ if (seen.Add(named) && !trashed) heldBack.Add(named);
continue;
}
// A sequence folder copied by hand carries the projects of its source, which stay that sequence's.
@@ -79,9 +89,61 @@ internal sealed class ProjectIndexer(ChronosDatabase db)
if (record.Deleted is null) heldBack.Add(record.Id);
}
}
+ try
+ {
+ await SettleMainAsync(sequenceId, live, heldBack, cancellationToken).ConfigureAwait(false);
+ }
+ catch (DatabaseException ex) when (ex.IsUniqueViolation || ex.IsForeignKeyViolation)
+ {
+ Log.Warning("projects", $"The Main of sequence {sequenceId} could not be taken from its records; tried again next time", ex);
+ }
return new ProjectReconcile(false, seen, heldBack, live);
}
+ ///
+ /// Stores and , Main passing from the first to the second, each
+ /// with its new name, in one transaction: the first goes through a name no project has, so no two live projects of the
+ /// sequence ever hold one name, nor both Main.
+ ///
+ internal static async Task SwapMainAsync(ChronosDatabase db, SequenceProject demoted, SequenceProject promoted, CancellationToken cancellationToken)
+ {
+ await using var tx = await db.BeginAsync(cancellationToken).ConfigureAwait(false);
+ await tx.Projects.UpdateAsync(demoted with { IsMain = false, Name = "~" + demoted.Id.ToString("N") }, cancellationToken).ConfigureAwait(false);
+ await tx.Projects.UpdateAsync(promoted with { IsMain = true }, cancellationToken).ConfigureAwait(false);
+ await tx.Projects.UpdateAsync(demoted with { IsMain = false }, cancellationToken).ConfigureAwait(false);
+ await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// The index's Main taken from the records, which say which project is Main (another index of the archive passed it on:
+ /// an index-only Main written back beside the one made into the archive meanwhile): when the index's Main is read and its
+ /// record no longer says it is Main, or the index has none, the oldest project whose record says it is becomes Main, and
+ /// both take their records' names where free. Only records in step with the index count (a record behind it, put back
+ /// from an older backup, says what was): never while the index's Main is held back or its record is not in step, and
+ /// never more than one Main.
+ ///
+ private async Task SettleMainAsync(Guid sequenceId, IReadOnlyDictionary live, IReadOnlySet heldBack, CancellationToken cancellationToken)
+ {
+ var rows = await db.Projects.ListBySequenceAsync(sequenceId, includeDeleted: false, cancellationToken).ConfigureAwait(false);
+ ProjectRecord? InStep(SequenceProject row) =>
+ !heldBack.Contains(row.Id) && live.TryGetValue(row.Id, out var record) && record.Head?.Id == row.HeadVersionId ? record : null;
+ var main = rows.FirstOrDefault(p => p.IsMain);
+ var own = main is null ? null : InStep(main);
+ if (main is not null && own is not { IsMain: false }) return;
+ var claimant = rows.Where(p => !p.IsMain && InStep(p) is { IsMain: true }).OrderBy(p => p.CreatedAt).ThenBy(p => p.Id).FirstOrDefault();
+ if (claimant is null) return;
+ var others = rows.Where(p => p.Id != claimant.Id && p.Id != main?.Id).ToList();
+ var promoted = claimant with { IsMain = true, Name = FreeName(others, live[claimant.Id].Name, claimant.Id), MirroredVersionId = null, MirroredSettingsVersion = null };
+ Log.Warning("projects", $"The records of sequence {sequenceId} name project {claimant.Id} as Main{(main is null ? string.Empty : $", not {main.Id}")}; the index takes it");
+ if (main is null)
+ {
+ await db.Projects.UpdateAsync(promoted, cancellationToken).ConfigureAwait(false);
+ return;
+ }
+ var demoted = main with { IsMain = false, Name = FreeName([.. others, promoted], own!.Name, main.Id), MirroredVersionId = null, MirroredSettingsVersion = null };
+ await SwapMainAsync(db, demoted, promoted, cancellationToken).ConfigureAwait(false);
+ }
+
///
/// , or " (2)", "(3)"… (within ):
/// the first no project of but has.
diff --git a/src/Chronos.Data/Projects/ProjectService.cs b/src/Chronos.Data/Projects/ProjectService.cs
index 893acbd2..1a83040b 100644
--- a/src/Chronos.Data/Projects/ProjectService.cs
+++ b/src/Chronos.Data/Projects/ProjectService.cs
@@ -134,6 +134,11 @@ public sealed class ProjectService
/// Whether an archive takes writes now ( ; tests stand in a read-only one).
internal Func Availability { get; set; } = ArchiveVolume.Probe;
+ /// Called at each named step between two writes, so a test can stop there as a crash would.
+ internal Action? Cut { get; set; }
+
+ private void Step(string name) => Cut?.Invoke(name);
+
/// The live projects of a sequence, Main first; read from the index alone while the archive is offline.
/// The sequence is not in the index.
public async Task> ListAsync(Guid sequenceId, CancellationToken cancellationToken = default)
@@ -224,7 +229,7 @@ public sealed class ProjectService
var current = await LiveAsync(projectId, ct).ConfigureAwait(false);
if (current.Name == trimmed) return current;
await EnsureNameFreeAsync(current.SequenceId, projectId, trimmed, ct).ConfigureAwait(false);
- var record = OwnRecord(context, projectId);
+ var record = await OwnRecordAsync(context, current, ct).ConfigureAwait(false);
var renamed = current with { Name = trimmed, UpdatedAt = DateTimeOffset.UtcNow };
ProjectSidecars.WriteRecord(context.Folder.ProjectRecordPath(projectId), ProjectRecord.Of(renamed, record.Mirrored));
await _db.Projects.UpdateAsync(renamed, ct).ConfigureAwait(false);
@@ -245,7 +250,7 @@ public sealed class ProjectService
await UnderLeaseAsync(project.SequenceId, async (context, ct) =>
{
var current = await LiveAsync(projectId, ct).ConfigureAwait(false);
- var record = OwnRecord(context, projectId);
+ var record = await OwnRecordAsync(context, current, ct).ConfigureAwait(false);
var now = DateTimeOffset.UtcNow;
var deleted = current with { DeletedAt = now, UpdatedAt = now };
Directory.CreateDirectory(context.Folder.ProjectsTrashDirectory);
@@ -288,13 +293,15 @@ public sealed class ProjectService
public Task GetVersionAsync(Guid versionId, CancellationToken cancellationToken = default) =>
_db.Projects.GetVersionAsync(versionId, cancellationToken);
- /// The newest version of a project, after catching up.
- /// Unknown project.
+ /// The newest version of a live project, after catching up.
+ ///
+ /// Unknown project, or one deleted ( ): a workspace's copy of it is gone from its home.
+ ///
public async Task HeadAsync(Guid projectId, CancellationToken cancellationToken = default)
{
var project = await KnownAsync(projectId, cancellationToken).ConfigureAwait(false);
await ReadAsync(project.SequenceId, cancellationToken).ConfigureAwait(false);
- project = await KnownAsync(projectId, cancellationToken).ConfigureAwait(false);
+ project = await LiveAsync(projectId, cancellationToken).ConfigureAwait(false);
return await _db.Projects.GetVersionAsync(project.HeadVersionId ?? Guid.Empty, cancellationToken).ConfigureAwait(false)
?? throw new ProjectException(ProjectError.NotFound, $"Project {projectId} has no version.");
}
@@ -409,16 +416,25 @@ public sealed class ProjectService
{
try
{
- await UnderLeaseAsync(sequenceId, (_, _) => Task.FromResult(true), cancellationToken, ReadWait).ConfigureAwait(false);
- }
- catch (ArchiveOfflineException ex) when (ex.Availability == ArchiveAvailability.ReadOnly)
- {
- await ReadOnlyCatchUpAsync(sequenceId, cancellationToken).ConfigureAwait(false);
+ try
+ {
+ await UnderLeaseAsync(sequenceId, (_, _) => Task.FromResult(true), cancellationToken, ReadWait).ConfigureAwait(false);
+ }
+ catch (ArchiveOfflineException ex) when (ex.Availability == ArchiveAvailability.ReadOnly)
+ {
+ await ReadOnlyCatchUpAsync(sequenceId, cancellationToken).ConfigureAwait(false);
+ }
}
catch (Exception ex) when (ex is ArchiveOfflineException or LeaseUnavailableException or SequenceFolderMovedException or ProjectsUnreadableException)
{
Log.Info("projects", $"The projects of sequence {sequenceId} are read from the index: {ex.Message}");
}
+ catch (DatabaseException ex)
+ {
+ // The index refused a step of the catch-up (a row, a lock held a moment too long): the read answers from it as it
+ // is, and the next operation tries again.
+ Log.Warning("projects", $"The projects of sequence {sequenceId} could not be caught up; they are read from the index", ex);
+ }
}
///
@@ -536,41 +552,63 @@ public sealed class ProjectService
return;
}
// The head is newer than the mirror: a push whose mirror a crash (or a settings edit at the same moment) cut short.
+ var mirrored = await _db.Projects.GetVersionAsync(main.MirroredVersionId.Value, cancellationToken).ConfigureAwait(false);
if (sameAsHead)
{
+ // A head that is the external version of a merge a crash stopped before its merge version (its parent a push no
+ // mirror wrote): the merge is finished now, else that push would never be in force. Any other: in force already.
+ if (head.Kind == ProjectVersionKind.External && head.ParentId is { } pushedId && pushedId != main.MirroredVersionId
+ && mirrored is { } basis && basis.ProjectId == main.Id
+ && await _db.Projects.GetVersionAsync(pushedId, cancellationToken).ConfigureAwait(false) is { } pushed && pushed.ProjectId == main.Id)
+ {
+ Log.Warning("projects", $"The merge of version {pushed.Number} of Main of sequence {context.Row.Id} stopped after version {head.Number}; it is finished");
+ await MergeIntoMainAsync(context, main, basis, pushed, head.SettingsJson, head, frames.Photos, cancellationToken).ConfigureAwait(false);
+ return;
+ }
await _db.Projects.SetMirroredAsync(main.Id, head.Id, context.Row.SettingsVersion, cancellationToken).ConfigureAwait(false);
return;
}
- var mirrored = await _db.Projects.GetVersionAsync(main.MirroredVersionId.Value, cancellationToken).ConfigureAwait(false);
if (main.MirroredSettingsVersion == context.Row.SettingsVersion || mirrored is null || ProjectContent.SameChoices(mirrored.SettingsJson, current, frames.Photos))
{
// Nobody changed the settings since the last mirror: the mirror completes.
await MirrorAsync(context, main, head, cancellationToken).ConfigureAwait(false);
return;
}
- // Both moved: the settings written meanwhile merge with the head (the version made in a workspace wins where both changed),
- // each photo named as the frames hold it now so the same photo merges as one. Where both changed, the settings written
- // meanwhile become an external version first, so the values the merge leaves out stay in the history to restore.
+ await MergeIntoMainAsync(context, main, mirrored, head, current, null, frames.Photos, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Both moved: the settings written meanwhile ( ) merge with , the head no
+ /// mirror wrote, over , the version mirrored last (the version made in a workspace wins where both
+ /// changed), each photo named as the frames hold it now so the same photo merges as one. Where both changed, the settings
+ /// written meanwhile become an external version first, so the values the merge leaves out stay in the history to restore;
+ /// the merge version follows it and is mirrored. is that external version when a crash
+ /// stopped the pair between its two versions: the merge version is made on it, so a cut anywhere is finished next time.
+ ///
+ private async Task MergeIntoMainAsync(LeaseContext context, SequenceProject main, ProjectVersion basis, ProjectVersion pushed, string theirs,
+ ProjectVersion? external, FramePhotos photos, CancellationToken cancellationToken)
+ {
ProjectMergeResult merged;
try
{
- merged = ProjectMerge.MergeWithConflicts(ProjectMerge.Read(ProjectContent.Rebind(mirrored.SettingsJson, frames.Photos)),
- ProjectMerge.Read(ProjectContent.Rebind(head.SettingsJson, frames.Photos)), ProjectMerge.Read(ProjectContent.Rebind(current, frames.Photos)));
+ merged = ProjectMerge.MergeWithConflicts(ProjectMerge.Read(ProjectContent.Rebind(basis.SettingsJson, photos)),
+ ProjectMerge.Read(ProjectContent.Rebind(pushed.SettingsJson, photos)), ProjectMerge.Read(ProjectContent.Rebind(theirs, photos)));
}
catch (NewerSettingsException ex)
{
// A newer Chronos's version is never merged with this one's settings: both are left as they are, recorded as seen.
- Log.Warning("projects", $"Version {head.Number} of Main of sequence {context.Row.Id} and its settings written meanwhile are left as they are", ex);
- await _db.Projects.SetMirroredAsync(main.Id, head.Id, context.Row.SettingsVersion, cancellationToken).ConfigureAwait(false);
+ Log.Warning("projects", $"Version {pushed.Number} of Main of sequence {context.Row.Id} and its settings written meanwhile are left as they are", ex);
+ await _db.Projects.SetMirroredAsync(main.Id, main.HeadVersionId, context.Row.SettingsVersion, cancellationToken).ConfigureAwait(false);
return;
}
- var parent = head;
- if (merged.HasConflicts)
+ var parent = external ?? pushed;
+ if (merged.HasConflicts && external is null)
{
- parent = await AppendDerivedAsync(context, main, head, current, ProjectVersionKind.External, cancellationToken).ConfigureAwait(false);
+ parent = await AppendDerivedAsync(context, main, pushed, theirs, ProjectVersionKind.External, cancellationToken).ConfigureAwait(false);
main = (await _db.Projects.GetAsync(main.Id, cancellationToken).ConfigureAwait(false))!;
- Log.Info("projects", $"Version {head.Number} of Main of sequence {context.Row.Id} and its settings written meanwhile both changed "
- + $"{string.Join(", ", merged.Conflicts.Select(c => c.Path))}: version {head.Number}'s values are kept, the others are version {parent.Number}");
+ Log.Info("projects", $"Version {pushed.Number} of Main of sequence {context.Row.Id} and its settings written meanwhile both changed "
+ + $"{string.Join(", ", merged.Conflicts.Select(c => c.Path))}: version {pushed.Number}'s values are kept, the others are version {parent.Number}");
+ Step("catchup.external");
}
var version = await AppendDerivedAsync(context, main, parent, ProjectContent.Canonical(merged.Merged.ToJson()), ProjectVersionKind.Merge, cancellationToken)
.ConfigureAwait(false);
@@ -582,9 +620,11 @@ public sealed class ProjectService
/// Main as this index meets it with no mirror known (an index rebuilt from the sidecars, another PC's index of the archive,
/// an index taken back from a backup): the sequence's settings are what its project.json holds, the file every
/// mirror writes, never this index's copy, which may have been read long ago. The head's choices: in step, this index's
- /// copy brought up to them. Those of the version Main's record says was mirrored last (an older record names none: of a
- /// version the head descends from): a mirror a crash cut short, completed. Neither: settings another path wrote since,
- /// an external version.
+ /// copy brought up to them. Those of a version the head descends from, down to the one Main's record says was mirrored
+ /// last (a record whose write failed after project.json 's lags it, so it only bounds the search; an older record
+ /// names none: the last versions): a mirror a crash cut short, completed. Neither: settings another path wrote since,
+ /// merged with the versions no mirror wrote when the record names the one mirrored last (as an index that knows its
+ /// mirror merges them), else an external version.
///
private async Task MeetMainAsync(LeaseContext context, SequenceProject main, ProjectVersion head, FramePhotos photos, CancellationToken cancellationToken)
{
@@ -594,40 +634,69 @@ public sealed class ProjectService
await _db.Projects.SetMirroredAsync(main.Id, head.Id, context.Row.SettingsVersion, cancellationToken).ConfigureAwait(false);
return;
}
+ var recorded = await RecordedMirrorAsync(context, main, head, cancellationToken).ConfigureAwait(false);
if (ProjectContent.SameChoices(head.SettingsJson, shared, photos))
{
+ // The external version of a merge a crash stopped before its merge version (see CatchUpAsync): finished now.
+ if (recorded is not null && head.Kind == ProjectVersionKind.External && head.ParentId is { } pushedId && pushedId != recorded.Id
+ && await _db.Projects.GetVersionAsync(pushedId, cancellationToken).ConfigureAwait(false) is { } pushed && pushed.ProjectId == main.Id)
+ {
+ await MergeIntoMainAsync(context, main, recorded, pushed, head.SettingsJson, head, photos, cancellationToken).ConfigureAwait(false);
+ return;
+ }
if (CurrentPortable(context, photos) is { } copy && ProjectContent.SameChoices(head.SettingsJson, copy, photos))
await _db.Projects.SetMirroredAsync(main.Id, head.Id, context.Row.SettingsVersion, cancellationToken).ConfigureAwait(false);
else
await MirrorAsync(context, main, head, cancellationToken).ConfigureAwait(false);
return;
}
- if (await MirroredBeforeAsync(context, main, head, shared, photos, cancellationToken).ConfigureAwait(false))
+ // A record that names the head as mirrored says project.json held it: whatever it holds now was written since.
+ var headMirrored = context.Reconcile.Live.TryGetValue(main.Id, out var record) && record.Mirrored?.Id == head.Id;
+ if (!headMirrored && await MirroredBeforeAsync(main, head, recorded, shared, photos, cancellationToken).ConfigureAwait(false))
{
await MirrorAsync(context, main, head, cancellationToken).ConfigureAwait(false);
return;
}
+ if (recorded is not null)
+ {
+ await MergeIntoMainAsync(context, main, recorded, head, shared, null, photos, cancellationToken).ConfigureAwait(false);
+ return;
+ }
var external = await AppendDerivedAsync(context, main, head, shared, ProjectVersionKind.External, cancellationToken).ConfigureAwait(false);
main = (await _db.Projects.GetAsync(main.Id, cancellationToken).ConfigureAwait(false))!;
await MirrorAsync(context, main, external, cancellationToken).ConfigureAwait(false);
}
///
- /// Whether holds the choices of an earlier version of Main a mirror wrote: the one Main's record
- /// names as mirrored last, else (an older record) one of the versions the head descends from.
+ /// The version Main's record names as mirrored last, when it is one the head descends from (not the head itself) and of
+ /// a format this Chronos reads; null otherwise (an older record names none).
///
- private async Task MirroredBeforeAsync(LeaseContext context, SequenceProject main, ProjectVersion head, string shared, FramePhotos photos,
+ private async Task RecordedMirrorAsync(LeaseContext context, SequenceProject main, ProjectVersion head, CancellationToken cancellationToken)
+ {
+ if (!context.Reconcile.Live.TryGetValue(main.Id, out var record) || record.Mirrored is not { } recorded || recorded.Number >= head.Number) return null;
+ for (var parent = head.ParentId; parent is { } id;)
+ {
+ if (await _db.Projects.GetVersionAsync(id, cancellationToken).ConfigureAwait(false) is not { } version || version.ProjectId != main.Id
+ || version.Number < recorded.Number) return null;
+ if (version.Id == recorded.Id) return IsNewer(version) ? null : version;
+ parent = version.ParentId;
+ }
+ return null;
+ }
+
+ ///
+ /// Whether holds the choices of an earlier version of Main a mirror wrote: one the head descends
+ /// from, down to (the version Main's record names as mirrored last), else among the last
+ /// .
+ ///
+ private async Task MirroredBeforeAsync(SequenceProject main, ProjectVersion head, ProjectVersion? recorded, string shared, FramePhotos photos,
CancellationToken cancellationToken)
{
- if (context.Reconcile.Live.TryGetValue(main.Id, out var record) && record.Mirrored is { } recorded)
+ var floor = recorded?.Number ?? head.Number - MirrorSearch;
+ for (var parent = head.ParentId; parent is { } id;)
{
- return recorded.Id != head.Id && await _db.Projects.GetVersionAsync(recorded.Id, cancellationToken).ConfigureAwait(false) is { } mirrored
- && mirrored.ProjectId == main.Id && !IsNewer(mirrored) && ProjectContent.SameChoices(mirrored.SettingsJson, shared, photos);
- }
- var parent = head.ParentId;
- for (var step = 0; parent is { } id && step < MirrorSearch; step++)
- {
- if (await _db.Projects.GetVersionAsync(id, cancellationToken).ConfigureAwait(false) is not { } version || version.ProjectId != main.Id) break;
+ if (await _db.Projects.GetVersionAsync(id, cancellationToken).ConfigureAwait(false) is not { } version || version.ProjectId != main.Id
+ || version.Number < floor) break;
if (!IsNewer(version) && ProjectContent.SameChoices(version.SettingsJson, shared, photos)) return true;
parent = version.ParentId;
}
@@ -678,18 +747,9 @@ public sealed class ProjectService
}
try
{
- for (var after = 0; ;)
- {
- var page = await _db.Projects.ListVersionsAfterAsync(row.Id, after, WriteBackPage, cancellationToken).ConfigureAwait(false);
- foreach (var version in page) ProjectSidecars.WriteVersion(context.Folder.VersionPath(row.Id, version.Number, version.Id), version);
- if (page.Count < WriteBackPage) break;
- after = page[^1].Number;
- }
- var mirrored = project.IsMain && project.MirroredVersionId is { } mirroredId
- && await _db.Projects.GetVersionAsync(mirroredId, cancellationToken).ConfigureAwait(false) is { } known
- ? new ProjectHead(known.Id, known.Number)
- : null;
- ProjectSidecars.WriteRecord(context.Folder.ProjectRecordPath(row.Id), ProjectRecord.Of(project, mirrored));
+ await WriteVersionsAsync(context.Folder, row.Id, 0, cancellationToken).ConfigureAwait(false);
+ ProjectSidecars.WriteRecord(context.Folder.ProjectRecordPath(row.Id), ProjectRecord.Of(project, await MirroredHeadAsync(project, null, cancellationToken)
+ .ConfigureAwait(false)));
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
@@ -697,12 +757,86 @@ public sealed class ProjectService
continue;
}
Log.Warning("projects", $"Project {row.Id} of sequence {context.Row.Id} had no folder in the archive; its sidecars are written again from the index");
- if (project == row) continue;
- await _db.Projects.UpdateAsync(project, cancellationToken).ConfigureAwait(false);
- if (promoted is not null) await _db.Projects.UpdateAsync(promoted, cancellationToken).ConfigureAwait(false);
+ try
+ {
+ // Main passes to theirs in one step, this one through a name no project has: never two Mains, nor one name twice.
+ if (promoted is not null) await ProjectIndexer.SwapMainAsync(_db, project, promoted, cancellationToken).ConfigureAwait(false);
+ else if (project != row) await _db.Projects.UpdateAsync(project, cancellationToken).ConfigureAwait(false);
+ }
+ catch (DatabaseException ex) when (ex.IsUniqueViolation || ex.IsForeignKeyViolation)
+ {
+ // The sidecars written are the truth: the next reconcile takes the names and Main from them (ProjectIndexer).
+ Log.Warning("projects", $"The index could not take project {row.Id} as its sidecars now name it; it does next time", ex);
+ }
+ }
+ await HealBehindAsync(context, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// The records the archive has whose head is behind the index's (a projects folder put back from an older backup, a sync
+ /// tool that brought an older record back): the versions they lack and the record written again from the index, which
+ /// holds the newer chain, so the sidecars hold every version again. A record ahead of the index, or naming a head the
+ /// index does not have at its number, is never written over ( ).
+ ///
+ private async Task HealBehindAsync(LeaseContext context, CancellationToken cancellationToken)
+ {
+ foreach (var (id, record) in context.Reconcile.Live)
+ {
+ if (context.Reconcile.HeldBack.Contains(id) || await _db.Projects.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { DeletedAt: null } row
+ || !await BehindAsync(row, record, cancellationToken).ConfigureAwait(false)) continue;
+ try
+ {
+ await HealAsync(context.Folder, row, record, cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
+ {
+ Log.Warning("projects", $"The record of project {id} is behind the index and could not be written again; tried again next time", ex);
+ }
}
}
+ /// Whether 's head is one of the versions the index holds below its head: the record is behind.
+ private async Task BehindAsync(SequenceProject project, ProjectRecord record, CancellationToken cancellationToken)
+ {
+ if (project.HeadVersionId is null) return false;
+ if (record.Head is not { } head) return true;
+ return head.Number < project.HeadNumber && await _db.Projects.GetVersionAsync(head.Id, cancellationToken).ConfigureAwait(false) is { } version
+ && version.ProjectId == project.Id && version.Number == head.Number;
+ }
+
+ ///
+ /// A record behind the index made whole: the version files past its head written from the index (those there are left
+ /// as they are), then the record naming the index's head.
+ ///
+ private async Task HealAsync(SequencePaths folder, SequenceProject project, ProjectRecord record, CancellationToken cancellationToken)
+ {
+ await WriteVersionsAsync(folder, project.Id, record.Head?.Number ?? 0, cancellationToken).ConfigureAwait(false);
+ var healed = ProjectRecord.Of(project with { UpdatedAt = DateTimeOffset.UtcNow }, await MirroredHeadAsync(project, record.Mirrored, cancellationToken)
+ .ConfigureAwait(false));
+ ProjectSidecars.WriteRecord(folder.ProjectRecordPath(project.Id), healed);
+ Log.Warning("projects", $"The record of project {project.Id} named version {record.Head?.Number} as its head, behind the index's {project.HeadNumber}; "
+ + "its versions and record are written again from the index");
+ return healed;
+ }
+
+ /// The version files of a project numbered above written from the index (immutable: one there already is left).
+ private async Task WriteVersionsAsync(SequencePaths folder, Guid projectId, int after, CancellationToken cancellationToken)
+ {
+ while (true)
+ {
+ var page = await _db.Projects.ListVersionsAfterAsync(projectId, after, WriteBackPage, cancellationToken).ConfigureAwait(false);
+ foreach (var version in page) ProjectSidecars.WriteVersion(folder.VersionPath(projectId, version.Number, version.Id), version);
+ if (page.Count < WriteBackPage) return;
+ after = page[^1].Number;
+ }
+ }
+
+ /// The version a Main record names as mirrored: the one this index mirrored when it knows it, else .
+ private async Task MirroredHeadAsync(SequenceProject project, ProjectHead? fallback, CancellationToken cancellationToken) =>
+ project.IsMain && project.MirroredVersionId is { } mirroredId && await _db.Projects.GetVersionAsync(mirroredId, cancellationToken).ConfigureAwait(false) is { } known
+ ? new ProjectHead(known.Id, known.Number)
+ : fallback;
+
///
/// The Main project of a sequence that has none: version 1 from the sequence's settings as its project.json holds
/// them (this index's copy when there is none, else defaults), this index's copy brought up to them. With the archive
@@ -828,15 +962,12 @@ public sealed class ProjectService
///
/// A version appended to a project: its sidecar, the record's head, then the version row and the head in one
- /// transaction. Only onto the head the record names, read again now: a record that cannot be read, or that names another
- /// head than the index has (a version this Chronos cannot read), is never written over and the version is not made.
+ /// transaction. Only onto the head the record names, read again now ( ).
///
- /// The record cannot be read, or its head is not the index's.
+ /// The record cannot be read, or its head is ahead of the index's or not one the index holds.
private async Task AppendAsync(SequencePaths folder, SequenceProject project, ProjectVersion version, CancellationToken cancellationToken)
{
- var record = ReadOwnRecord(folder, project.Id);
- if (record.Head != (project.HeadVersionId is { } headId ? new ProjectHead(headId, project.HeadNumber) : null))
- throw new ProjectsUnreadableException($"The record of project {project.Id} names version {record.Head?.Number} as its head, which the index does not hold.");
+ var record = await WritableRecordAsync(folder, project, cancellationToken).ConfigureAwait(false);
var now = DateTimeOffset.UtcNow;
var advanced = project with { HeadVersionId = version.Id, HeadNumber = version.Number, UpdatedAt = now };
ProjectSidecars.WriteVersion(folder.VersionPath(project.Id, version.Number, version.Id), version);
@@ -849,12 +980,30 @@ public sealed class ProjectService
return advanced;
}
- /// The record of a live project as its folder holds it now, before it is written again: one held back or unreadable is never written over.
- /// The project is held back, or its record cannot be read.
- private static ProjectRecord OwnRecord(LeaseContext context, Guid projectId) =>
- context.Reconcile.HeldBack.Contains(projectId)
- ? throw new ProjectsUnreadableException($"Project {projectId} cannot be read now.")
- : ReadOwnRecord(context.Folder, projectId);
+ ///
+ /// The record of a live project as its folder holds it now, before it is written again, naming the index's head. One
+ /// behind the index (a projects folder put back from an older backup) is made whole first ( ).
+ /// One that cannot be read, or that is ahead of the index or names a head the index does not hold at its number (a
+ /// version this Chronos cannot read), is never written over: nothing is written.
+ ///
+ /// The record cannot be read, or is ahead of the index or apart from it.
+ private async Task WritableRecordAsync(SequencePaths folder, SequenceProject project, CancellationToken cancellationToken)
+ {
+ var record = ReadOwnRecord(folder, project.Id);
+ var head = project.HeadVersionId is { } headId ? new ProjectHead(headId, project.HeadNumber) : null;
+ if (record.Head == head) return record;
+ if (await BehindAsync(project, record, cancellationToken).ConfigureAwait(false)) return await HealAsync(folder, project, record, cancellationToken).ConfigureAwait(false);
+ throw new ProjectsUnreadableException(record.Head is { } named && named.Number > project.HeadNumber
+ ? $"The record of project {project.Id} names version {named.Number} as its head, past the {project.HeadNumber} the index holds."
+ : $"The record of project {project.Id} names version {record.Head?.Number} as its head, which is not the version the index holds at that number.");
+ }
+
+ /// The record of a live project, before it is written again: one held back is never written over ( ).
+ /// The project is held back, or its record cannot be read or is not the index's.
+ private async Task OwnRecordAsync(LeaseContext context, SequenceProject project, CancellationToken cancellationToken) =>
+ context.Reconcile.HeldBack.Contains(project.Id)
+ ? throw new ProjectsUnreadableException($"Project {project.Id} cannot be read now.")
+ : await WritableRecordAsync(context.Folder, project, cancellationToken).ConfigureAwait(false);
private static ProjectRecord ReadOwnRecord(SequencePaths folder, Guid projectId)
{
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs
index 13a769e8..6fa55e04 100644
--- a/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs
@@ -308,6 +308,25 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.Empty(host.Store.List());
}
+ [Test]
+ public async Task ACopyOfAProjectDeletedInTheLibraryReadsGoneAndGoesOnlyWhenDiscarded()
+ {
+ await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
+ var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
+ var vertical = await bed.CheckoutAsync(host, newName: "Vertical");
+ Assert.Equal(WorkspaceState.InSync, (await host.StatusAsync(vertical)).State);
+
+ // Another PC deletes it in the library: never in step, and the copy goes only when its user discards it.
+ await bed.Archives.Projects.DeleteAsync(vertical, bed.Ct);
+ Assert.Equal(WorkspaceState.Gone, (await host.StatusAsync(vertical)).State);
+ Assert.True((await host.PlanRemovalAsync(vertical)).Gone);
+ var refused = await Assert.ThrowsAsync(() => host.RemoveLocalCopyAsync(vertical, discard: false));
+ Assert.Equal(Loc.L("Errors.Workspace.DeletedAtHome"), refused.Message);
+ Assert.NotNull(host.Store.Find(vertical), "nothing was removed");
+ await host.RemoveLocalCopyAsync(vertical, discard: true);
+ Assert.Null(host.Store.Find(vertical));
+ }
+
[Test]
public async Task OlderVersionsArePrunedPastKeptVersionsOnlyOnceTheLibraryHoldsThem()
{
diff --git a/tests/Chronos.Data.Tests/Projects/ProjectMergeTests.cs b/tests/Chronos.Data.Tests/Projects/ProjectMergeTests.cs
index 9ce45bdc..880de7af 100644
--- a/tests/Chronos.Data.Tests/Projects/ProjectMergeTests.cs
+++ b/tests/Chronos.Data.Tests/Projects/ProjectMergeTests.cs
@@ -2,9 +2,11 @@ using System.Globalization;
using System.Text.Json.Nodes;
using Chronos.Core.Model;
using Chronos.Core.Project;
+using Chronos.Data.Archiving;
using Chronos.Data.Projects;
using Chronos.Data.Tests.Archiving;
using Chronos.Data.Tests.Infrastructure;
+using Chronos.Data.Tests.Workspaces;
using Chronos.Testing;
namespace Chronos.Data.Tests.Projects;
@@ -162,6 +164,60 @@ public abstract class MainMergeTests(TestContext context) : DatabaseTest(context
Assert.SequenceEqual([3], settings.ExcludedFrames);
}
+ [Test]
+ public async Task AMergeACrashStopsBetweenItsTwoVersionsIsFinishedNextTime()
+ {
+ foreach (var rebuild in new[] { false, true })
+ {
+ var fx = await FixtureAsync();
+ var (sequence, frames) = await ProjectServiceTests.UploadedAsync(fx, 4);
+ var projects = fx.Service.Projects;
+ var main = await projects.MainAsync(sequence.Id, fx.Ct);
+ var first = await projects.HeadAsync(main.Id, fx.Ct);
+ var pushed = (await projects.PushAsync(main.Id, ProjectServiceTests.Draft(first, new ProjectSettings
+ {
+ Stack = new StackSettings { Mode = StackSetting.Median },
+ Exposure = new ExposureSettings { ExposureOffsetEv = 0.5 },
+ }, frames), fx.Ct)).Version!;
+ var folder = fx.Paths.Sequence(sequence.Folder);
+ var record = ProjectSidecars.ReadRecord(folder.ProjectRecordPath(main.Id));
+ ProjectSidecars.WriteRecord(folder.ProjectRecordPath(main.Id), record with { Mirrored = new ProjectHead(first.Id, 1) });
+
+ // The push's mirror cut short, another path's settings meanwhile, and the catch-up's merge cut after its external version.
+ var reverted = await ProjectServiceTests.WriteSettingsAsync(fx, sequence.Id, new ProjectSettings());
+ await fx.Db.Projects.SetMirroredAsync(main.Id, first.Id, reverted.SettingsVersion, fx.Ct);
+ var theirs = new ProjectSettings { Exposure = new ExposureSettings { ExposureOffsetEv = 1.25 }, ExcludedFrames = [3] };
+ await ProjectServiceTests.WriteSettingsAsync(fx, sequence.Id, theirs);
+ File.WriteAllText(folder.ProjectPath, theirs.ToJson());
+ projects.Cut = step =>
+ {
+ if (step == "catchup.external") throw new CutException(step);
+ };
+ await Assert.ThrowsAsync(() => projects.ListAsync(sequence.Id, fx.Ct));
+ projects.Cut = null;
+ Assert.SequenceEqual([ProjectVersionKind.External, ProjectVersionKind.Commit, ProjectVersionKind.Imported],
+ (await fx.Db.Projects.ListVersionsAsync(main.Id, null, 10, fx.Ct)).Select(v => v.Kind));
+
+ // The next catch-up (by this index, or by one rebuilt from the sidecars) makes the merge version: the push is in force.
+ if (rebuild)
+ {
+ await fx.ReopenWithEmptyIndexAsync();
+ await fx.ScanAsync(ScanMode.Rebuild);
+ }
+ var history = await fx.Service.Projects.HistoryAsync(main.Id, cancellationToken: fx.Ct);
+ Assert.SequenceEqual([ProjectVersionKind.Merge, ProjectVersionKind.External, ProjectVersionKind.Commit, ProjectVersionKind.Imported],
+ history.Select(v => v.Kind));
+ Assert.Equal((history[1].Id, pushed.Id), (history[0].ParentId, history[1].ParentId));
+ foreach (var settings in new[] { ProjectSettings.FromJson((await fx.Db.Sequences.GetAsync(sequence.Id))!.SettingsJson!),
+ ProjectSettings.FromJson(File.ReadAllText(folder.ProjectPath)) })
+ {
+ Assert.Equal((0.5, StackSetting.Median), (settings.Exposure.ExposureOffsetEv, settings.Stack.Mode));
+ Assert.SequenceEqual([3], settings.ExcludedFrames);
+ }
+ Assert.Count(4, await fx.Service.Projects.HistoryAsync(main.Id, cancellationToken: fx.Ct));
+ }
+ }
+
[Test]
public async Task ANewerChronosHeadOfMainIsNotMergedWithSettingsWrittenMeanwhile()
{
diff --git a/tests/Chronos.Data.Tests/Projects/ProjectRecoveryTests.cs b/tests/Chronos.Data.Tests/Projects/ProjectRecoveryTests.cs
index 4bc6ce30..fbc15602 100644
--- a/tests/Chronos.Data.Tests/Projects/ProjectRecoveryTests.cs
+++ b/tests/Chronos.Data.Tests/Projects/ProjectRecoveryTests.cs
@@ -6,6 +6,8 @@ using Chronos.Data.Archiving;
using Chronos.Data.Projects;
using Chronos.Data.Tests.Archiving;
using Chronos.Data.Tests.Infrastructure;
+using Chronos.Data.Tests.Workspaces;
+using Chronos.Data.Workspaces;
using Chronos.Testing;
using static Chronos.Data.Tests.Archiving.ArchiveFixture;
using static Chronos.Data.Tests.Projects.ProjectServiceTests;
@@ -488,6 +490,268 @@ public abstract class ProjectRecoveryTests(TestContext context) : DatabaseTest(c
Assert.FileExists(folder.VersionPath(main.Id, 1, head.Id));
Assert.Equal(PushOutcome.Stored, (await freshHome.PushAsync(main.Id, Draft(head, new ProjectSettings { ExcludedFrames = [0] }, freshFrames), fx.Ct)).Outcome);
}
+
+ [Test]
+ public async Task AnIndexOnlyMainMeetingAMainAnotherIndexMadeIsWrittenBackAsAnotherProject()
+ {
+ var fx = await FixtureAsync();
+ var (fresh, frames) = await UploadedAsync(fx, 2);
+ var projects = fx.Service.Projects;
+ projects.Availability = _ => ArchiveAvailability.ReadOnly;
+ var ours = (await projects.ListAsync(fresh.Id, fx.Ct)).Single();
+
+ // Meanwhile another PC's index makes its own Main into the archive; then this archive takes writes again.
+ var (other, _) = await fx.OtherWriterAsync();
+ var theirs = await other.Projects.MainAsync(fresh.Id, fx.Ct);
+ projects.Availability = ArchiveVolume.Probe;
+
+ // Theirs is Main, ours another project: in the index and in the sidecars alike, and it stays so.
+ foreach (var _ in new[] { 1, 2 })
+ {
+ Assert.SequenceEqual([(theirs.Id, "Main", true), (ours.Id, "Main (2)", false)],
+ (await projects.ListAsync(fresh.Id, fx.Ct)).Select(p => (p.Id, p.Name, p.IsMain)));
+ }
+ var folder = fx.Paths.Sequence(fresh.Folder);
+ Assert.Equal(1, MainRecords(folder));
+ var ourRecord = ProjectSidecars.ReadRecord(folder.ProjectRecordPath(ours.Id));
+ Assert.Equal(("Main (2)", false), (ourRecord.Name, ourRecord.IsMain));
+ Assert.Equal(theirs.Id, (await other.Projects.MainAsync(fresh.Id, fx.Ct)).Id);
+ Assert.SequenceEqual([theirs.Id, ours.Id], (await other.Projects.ListAsync(fresh.Id, fx.Ct)).Select(p => p.Id));
+ Assert.Equal(PushOutcome.Stored,
+ (await projects.PushAsync(theirs.Id, Draft(await projects.HeadAsync(theirs.Id, fx.Ct), new ProjectSettings { ExcludedFrames = [1] }, frames), fx.Ct)).Outcome);
+ Assert.SequenceEqual([1], Settings(fx, fresh).ExcludedFrames);
+ }
+
+ [Test]
+ public async Task AMainAnotherIndexPassedOnIsTakenFromTheRecords()
+ {
+ var fx = await FixtureAsync();
+ var (sequence, _) = await UploadedAsync(fx, 2);
+ var projects = fx.Service.Projects;
+ var main = await projects.MainAsync(sequence.Id, fx.Ct);
+ var second = await projects.CreateAsync(sequence.Id, "Main (2)", cancellationToken: fx.Ct);
+ var folder = fx.Paths.Sequence(sequence.Folder);
+
+ // Another index passed Main on, names and all: the records say the opposite of this index.
+ var mainRecord = ProjectSidecars.ReadRecord(folder.ProjectRecordPath(main.Id));
+ var secondRecord = ProjectSidecars.ReadRecord(folder.ProjectRecordPath(second.Id));
+ ProjectSidecars.WriteRecord(folder.ProjectRecordPath(main.Id), mainRecord with { IsMain = false, Name = "Main (2)", Mirrored = null });
+ ProjectSidecars.WriteRecord(folder.ProjectRecordPath(second.Id), secondRecord with { IsMain = true, Name = "Main" });
+
+ Assert.SequenceEqual([(second.Id, "Main", true), (main.Id, "Main (2)", false)],
+ (await projects.ListAsync(sequence.Id, fx.Ct)).Select(p => (p.Id, p.Name, p.IsMain)));
+ Assert.Equal(second.Id, (await projects.MainAsync(sequence.Id, fx.Ct)).Id);
+ Assert.Count(1, (await fx.Db.Projects.ListBySequenceAsync(sequence.Id, includeDeleted: true, fx.Ct)).Where(p => p.IsMain));
+ Assert.Equal(1, MainRecords(folder));
+ }
+
+ [Test]
+ public async Task AProjectCreationCutBeforeItsRecordHoldsNothingBack()
+ {
+ var fx = await FixtureAsync();
+ var (sequence, frames) = await UploadedAsync(fx, 2);
+ var folder = fx.Paths.Sequence(sequence.Folder);
+
+ // As making Main leaves it when its record cannot be written after its version (a lost disk, a crash): a folder with
+ // version 1 and no record, of a project no index row names.
+ var id = Guid.CreateVersion7();
+ var settings = ProjectContent.ToPortable(new ProjectSettings(), Photos(frames));
+ var now = DateTimeOffset.UtcNow;
+ var cut = new ProjectVersion
+ {
+ Id = Guid.CreateVersion7(),
+ ProjectId = id,
+ Number = 1,
+ Kind = ProjectVersionKind.Imported,
+ ClientName = "cut",
+ SettingsJson = settings,
+ ContentHash = ProjectContent.Hash(settings),
+ SettingsFormat = ProjectContent.FormatOf(settings),
+ FramesVersion = sequence.FramesVersion,
+ CreatedAt = now,
+ StoredAt = now,
+ };
+ ProjectSidecars.WriteVersion(folder.VersionPath(id, 1, cut.Id), cut);
+
+ var main = await fx.Service.Projects.MainAsync(sequence.Id, fx.Ct);
+ Assert.NotEqual(id, main.Id);
+ Assert.SequenceEqual([main.Id], (await new ArchiveProjectHome(fx.Db, fx.Service.Projects, sequence.Id).ListAsync(fx.Ct)).Select(p => p.Id));
+ Assert.FileExists(folder.VersionPath(id, 1, cut.Id));
+ Assert.Null(await fx.Db.Projects.GetAsync(id));
+
+ // Its record there at last (a sync tool bringing another PC's project): indexed as another project, Main stays.
+ ProjectSidecars.WriteRecord(folder.ProjectRecordPath(id), new ProjectRecord(id, sequence.Id, ProjectService.MainName, true, new ProjectHead(cut.Id, 1), now, null, now));
+ Assert.SequenceEqual([(main.Id, true), (id, false)], (await fx.Service.Projects.ListAsync(sequence.Id, fx.Ct)).Select(p => (p.Id, p.IsMain)));
+ }
+
+ [Test]
+ public async Task AProjectsFolderPutBackFromAnOlderBackupIsMadeWholeFromTheIndex()
+ {
+ var fx = await FixtureAsync();
+ var (sequence, frames) = await UploadedAsync(fx, 3);
+ var projects = fx.Service.Projects;
+ var main = await projects.MainAsync(sequence.Id, fx.Ct);
+ var vertical = await projects.CreateAsync(sequence.Id, "Vertical", cancellationToken: fx.Ct);
+ var folder = fx.Paths.Sequence(sequence.Folder);
+ var backup = folder.ProjectsDirectory + "-backup";
+ CopyDirectory(folder.ProjectsDirectory, backup);
+ var v2 = (await projects.PushAsync(vertical.Id, Draft(await projects.HeadAsync(vertical.Id, fx.Ct), new ProjectSettings { ExcludedFrames = [1] }, frames), fx.Ct))
+ .Version!;
+ var m2 = (await projects.PushAsync(main.Id, Draft(await projects.HeadAsync(main.Id, fx.Ct), new ProjectSettings { ExcludedFrames = [2] }, frames), fx.Ct)).Version!;
+
+ // The backup made before those pushes is put back: the records name version 1, the index holds version 2.
+ Directory.Delete(folder.ProjectsDirectory, recursive: true);
+ CopyDirectory(backup, folder.ProjectsDirectory);
+ Assert.Equal(PushOutcome.Stored, (await projects.PushAsync(vertical.Id, Draft(v2, new ProjectSettings { ExcludedFrames = [0] }, frames), fx.Ct)).Outcome);
+ Assert.Equal(PushOutcome.Stored, (await projects.PushAsync(main.Id, Draft(m2, new ProjectSettings { ExcludedFrames = [0] }, frames), fx.Ct)).Outcome);
+ Assert.Equal(3, ProjectSidecars.ReadRecord(folder.ProjectRecordPath(vertical.Id)).Head!.Number);
+ Assert.Equal(v2.ContentHash, ProjectSidecars.ReadVersion(folder.VersionPath(vertical.Id, 2, v2.Id)).ContentHash);
+ Assert.Equal(m2.ContentHash, ProjectSidecars.ReadVersion(folder.VersionPath(main.Id, 2, m2.Id)).ContentHash);
+
+ // The sidecars hold every version again: a rebuilt index has them all, and nothing was added.
+ await fx.ReopenWithEmptyIndexAsync();
+ await fx.ScanAsync(ScanMode.Rebuild);
+ Assert.SequenceEqual([3, 2, 1], (await fx.Service.Projects.HistoryAsync(vertical.Id, cancellationToken: fx.Ct)).Select(v => v.Number));
+ Assert.SequenceEqual([ProjectVersionKind.Commit, ProjectVersionKind.Commit, ProjectVersionKind.Imported],
+ (await fx.Service.Projects.HistoryAsync(main.Id, cancellationToken: fx.Ct)).Select(v => v.Kind));
+ Assert.SequenceEqual([0], Settings(fx, sequence).ExcludedFrames);
+
+ // A read alone makes the records whole too.
+ Directory.Delete(folder.ProjectsDirectory, recursive: true);
+ CopyDirectory(backup, folder.ProjectsDirectory);
+ await fx.Service.Projects.ListAsync(sequence.Id, fx.Ct);
+ Assert.Equal(3, ProjectSidecars.ReadRecord(folder.ProjectRecordPath(vertical.Id)).Head!.Number);
+ Assert.Count(3, ProjectSidecars.ListVersions(folder.ProjectVersionsDirectory(main.Id)));
+ }
+
+ [Test]
+ public async Task AMirrorRecordThatLagsProjectJsonNeverRevertsANewerPush()
+ {
+ var fx = await FixtureAsync();
+ var (sequence, frames) = await UploadedAsync(fx, 3);
+ var projects = fx.Service.Projects;
+ var main = await projects.MainAsync(sequence.Id, fx.Ct);
+ var first = await projects.HeadAsync(main.Id, fx.Ct);
+ var second = (await projects.PushAsync(main.Id, Draft(first, new ProjectSettings { ExcludedFrames = [1] }, frames), fx.Ct)).Version!;
+ var folder = fx.Paths.Sequence(sequence.Folder);
+ var afterSecond = File.ReadAllText(folder.ProjectPath);
+ await projects.PushAsync(main.Id, Draft(second, new ProjectSettings { ExcludedFrames = [2] }, frames), fx.Ct);
+
+ // Version 2's mirror wrote project.json but not the record, and version 3's mirror was cut before project.json.
+ File.WriteAllText(folder.ProjectPath, afterSecond);
+ var record = ProjectSidecars.ReadRecord(folder.ProjectRecordPath(main.Id));
+ ProjectSidecars.WriteRecord(folder.ProjectRecordPath(main.Id), record with { Mirrored = new ProjectHead(first.Id, 1) });
+ await fx.ReopenWithEmptyIndexAsync();
+ await fx.ScanAsync(ScanMode.Rebuild);
+
+ // The mirror completes: no external version brings version 2 back over version 3.
+ Assert.SequenceEqual([3, 2, 1], (await fx.Service.Projects.HistoryAsync(main.Id, cancellationToken: fx.Ct)).Select(v => v.Number));
+ Assert.SequenceEqual([2], Settings(fx, sequence).ExcludedFrames);
+ }
+
+ [Test]
+ public async Task AnIndexMeetingMainMergesSettingsWrittenSinceWithAPushNoMirrorWrote()
+ {
+ var fx = await FixtureAsync();
+ var (sequence, frames) = await UploadedAsync(fx, 3);
+ var projects = fx.Service.Projects;
+ var main = await projects.MainAsync(sequence.Id, fx.Ct);
+ var first = await projects.HeadAsync(main.Id, fx.Ct);
+ var pushed = (await projects.PushAsync(main.Id, Draft(first, new ProjectSettings { Stack = new StackSettings { Mode = StackSetting.Median } }, frames), fx.Ct))
+ .Version!;
+
+ // Version 2's mirror cut short (the record names version 1), and an older Chronos then writes an offset into project.json.
+ var folder = fx.Paths.Sequence(sequence.Folder);
+ File.WriteAllText(folder.ProjectPath, new ProjectSettings { Exposure = new ExposureSettings { ExposureOffsetEv = -1 } }.ToJson());
+ var record = ProjectSidecars.ReadRecord(folder.ProjectRecordPath(main.Id));
+ ProjectSidecars.WriteRecord(folder.ProjectRecordPath(main.Id), record with { Mirrored = new ProjectHead(first.Id, 1) });
+ await fx.ReopenWithEmptyIndexAsync();
+ await fx.ScanAsync(ScanMode.Rebuild);
+
+ // Both are in force, as an index that knew its mirror would have merged them.
+ var history = await fx.Service.Projects.HistoryAsync(main.Id, cancellationToken: fx.Ct);
+ Assert.SequenceEqual([ProjectVersionKind.Merge, ProjectVersionKind.Commit, ProjectVersionKind.Imported], history.Select(v => v.Kind));
+ Assert.Equal(pushed.Id, history[0].ParentId);
+ Assert.Equal((StackSetting.Median, -1.0), (Settings(fx, sequence).Stack.Mode, Settings(fx, sequence).Exposure.ExposureOffsetEv));
+ }
+
+ [Test]
+ public async Task ANewerChronosHeadOverAMirrorCutShortIsLeftAsItIs()
+ {
+ var fx = await FixtureAsync();
+ var (sequence, frames) = await UploadedAsync(fx, 3);
+ var projects = fx.Service.Projects;
+ var main = await projects.MainAsync(sequence.Id, fx.Ct);
+ var first = await projects.HeadAsync(main.Id, fx.Ct);
+ var pushed = (await projects.PushAsync(main.Id, Draft(first, new ProjectSettings { ExcludedFrames = [1] }, frames), fx.Ct)).Version!;
+
+ // Version 2's mirror cut short, nobody writing the settings since; then a newer Chronos pushes version 3.
+ var reverted = await WriteSettingsAsync(fx, sequence.Id, new ProjectSettings());
+ await fx.Db.Projects.SetMirroredAsync(main.Id, first.Id, reverted.SettingsVersion, fx.Ct);
+ var newer = NewerChronos.Push(fx, sequence, pushed);
+
+ Assert.SequenceEqual([main.Id], (await projects.ListAsync(sequence.Id, fx.Ct)).Select(p => p.Id));
+ Assert.Equal(newer.Id, (await projects.HeadAsync(main.Id, fx.Ct)).Id);
+ Assert.Count(3, await projects.HistoryAsync(main.Id, cancellationToken: fx.Ct));
+ Assert.Empty(ProjectSettings.FromJson((await fx.Db.Sequences.GetAsync(sequence.Id))!.SettingsJson!).ExcludedFrames);
+ }
+
+ [Test]
+ public async Task AProjectDeletedAtItsHomeHasNoHeadThere()
+ {
+ var fx = await FixtureAsync();
+ var (sequence, _) = await UploadedAsync(fx, 2);
+ var projects = fx.Service.Projects;
+ var vertical = await projects.CreateAsync(sequence.Id, "Vertical", cancellationToken: fx.Ct);
+ var first = await projects.HeadAsync(vertical.Id, fx.Ct);
+ IProjectHome home = new ArchiveProjectHome(fx.Db, projects, sequence.Id);
+
+ // Deleted (by another PC, say): a workspace asking for its head learns it is gone, never that it is in step.
+ await projects.DeleteAsync(vertical.Id, fx.Ct);
+ Assert.Equal(ProjectError.NotFound, (await Assert.ThrowsAsync(() => home.HeadAsync(vertical.Id, fx.Ct))).Reason);
+ Assert.False(await home.HoldsAsync(vertical.Id, first, fx.Ct));
+ Assert.Equal(first.Id, (await home.HistoryAsync(vertical.Id, null, 10, fx.Ct)).Single().Id);
+ }
+
+ [Test]
+ public async Task AVersionParkingFortyThousandPhotosGoesFromAWorkspaceToTheArchiveAndBack()
+ {
+ var fx = await FixtureAsync();
+ var bed = Own(await WorkspaceFixture.CreateAsync(Context, fx, 3));
+ var vertical = await fx.Service.Projects.CreateAsync(bed.Sequence.Id, "Vertical", cancellationToken: fx.Ct);
+ var (_, sync) = bed.Workspace();
+ var project = await bed.CheckoutAsync(sync, vertical.Id);
+
+ // A long sequence's nights excluded: 40,000 photos parked by a version, past the old 8 MB limit of both files.
+ var pending = Enumerable.Range(0, 40_000).Select(i => new PendingFrame
+ {
+ Sha256 = Convert.ToHexStringLower(SHA256.HashData(BitConverter.GetBytes(i))),
+ Size = 1_000_000 + i,
+ CapturedAt = Start.AddSeconds(i),
+ Excluded = true,
+ }).ToList();
+ var session = await sync.OpenAsync(vertical.Id, fx.Ct);
+ await sync.SaveAsync(vertical.Id, session.Working with { PendingFrames = pending }, fx.Ct);
+ var version = Assert.NotNull(await sync.CommitAsync(vertical.Id, "nights", cancellationToken: fx.Ct));
+ Assert.Greater(new FileInfo(project.VersionPath(version)).Length, 8L << 20);
+ Assert.Equal(1, (await sync.StatusAsync(vertical.Id, bed.Home, fx.Ct)).Ahead);
+ var pushed = await sync.PushAsync(vertical.Id, bed.Home, fx.Ct);
+ Assert.Equal(version.Id, pushed.Pushed.Single().Id);
+ Assert.Equal(WorkspaceState.InSync, pushed.Status.State);
+
+ await fx.ReopenWithEmptyIndexAsync();
+ await fx.ScanAsync(ScanMode.Rebuild);
+ var head = await fx.Service.Projects.HeadAsync(vertical.Id, fx.Ct);
+ Assert.Equal((version.Id, "nights"), (head.Id, head.Note));
+ Assert.Count(40_000, ProjectSettings.FromJson(head.SettingsJson).PendingFrames ?? []);
+ }
+
+ private static void CopyDirectory(string from, string to)
+ {
+ Directory.CreateDirectory(to);
+ foreach (var file in Directory.GetFiles(from)) File.Copy(file, Path.Combine(to, Path.GetFileName(file)));
+ foreach (var directory in Directory.GetDirectories(from)) CopyDirectory(directory, Path.Combine(to, Path.GetFileName(directory)));
+ }
}
public sealed class SqliteProjectRecoveryTests(TestContext context) : ProjectRecoveryTests(context)