using System.Globalization;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Model;
namespace Chronos.Data.Projects;
/// What a reconcile of a sequence's projects met ( ).
/// The sequence has no projects folder: nothing was read, and nothing taken for gone.
/// The projects the archive has a folder for, live or in the projects' trash, whether or not its record read.
/// The live projects the index could not be brought in line with: a record that cannot be read (damaged,
/// of a newer Chronos, a read failure), a head whose version this Chronos cannot read, or a row the index refused. Each stays
/// as the index has it, and nothing is written for it until it reads again.
/// The records of the live projects read, by id (their head as moved forward).
internal sealed record ProjectReconcile(bool Missing, IReadOnlySet Seen, IReadOnlySet HeldBack, IReadOnlyDictionary Live)
{
/// Every live project of the folder was read and indexed: a sequence without a Main may be given one.
public bool Complete => HeldBack.Count == 0;
}
///
/// Brings the index's projects of one sequence in line with their sidecars (owner review 2, R8), which are the truth: a
/// project or version the index lacks is added (an index rebuilt, a sequence restored from the trash), a head the index is
/// behind on moves forward, a name or deletion recorded since is taken, and a row the index marked deleted is listed again
/// when its live record says it is not. Only a record that says so, live or in the projects' trash, deletes a project:
/// never a folder that is not there (moved for a moment, a backup put back, a sync tool) nor a record that cannot be read,
/// whose project stays as the index has it ( ). A version file written past its
/// record's head by a push a crash cut short is adopted when it follows the head (its file is complete: versions are
/// written atomically, then the record); any other file past the head, or a second file of a number the record's chain
/// names another for, is moved aside to versions/.stray , never deleted. Runs under the sequence's lease, or without
/// writing to the archive at all when it is read-only.
///
internal sealed class ProjectIndexer(ChronosDatabase db)
{
private const string StrayFolder = ".stray";
/// Reconciles the projects of in ; the caller holds the sequence's lease.
/// False for a read-only archive: the sidecars are read as they are and only the index is written
/// (a version past its record's head is indexed, not adopted into the record; nothing is moved aside).
public async Task ReconcileAsync(SequencePaths folder, Guid sequenceId, CancellationToken cancellationToken, bool writable = true)
{
var seen = new HashSet();
var heldBack = new HashSet();
var live = new Dictionary();
if (!Directory.Exists(folder.ProjectsDirectory)) return new ProjectReconcile(true, seen, heldBack, live);
foreach (var (directory, trashed) in ProjectFolders(folder))
{
cancellationToken.ThrowIfCancellationRequested();
ProjectRecord record;
try
{
record = ProjectSidecars.ReadRecord(Path.Combine(directory, ArchiveLayout.ProjectFile));
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
// 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)) 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.
if (record.SequenceId != sequenceId || !seen.Add(record.Id)) continue;
if (trashed && record.Deleted is null) record = record with { Deleted = Directory.GetLastWriteTimeUtc(directory) };
if (record.Deleted is null)
{
record = RollForward(folder, record, directory, writable);
live[record.Id] = record;
}
try
{
if (!await IndexAsync(record, directory, trashed, writable, cancellationToken).ConfigureAwait(false)) heldBack.Add(record.Id);
}
catch (DatabaseException ex) when (ex.IsUniqueViolation || ex.IsForeignKeyViolation)
{
// One project the index refuses never stops the others, nor a scan of the archive: it is read again next time.
Log.Warning("projects", $"Project {record.Id} of sequence {sequenceId} could not be indexed", ex);
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.
///
internal static string FreeName(IReadOnlyList live, string name, Guid? projectId)
{
var taken = live.Where(p => p.Id != projectId).Select(p => p.Name).ToHashSet(StringComparer.OrdinalIgnoreCase);
var candidate = name;
for (var n = 2; taken.Contains(candidate); n++)
{
var suffix = $" ({n.ToString(CultureInfo.InvariantCulture)})";
candidate = (name.Length + suffix.Length > ProjectService.MaxNameLength ? name[..(ProjectService.MaxNameLength - suffix.Length)].TrimEnd() : name) + suffix;
}
return candidate;
}
/// The project folders of a sequence: the live ones, then those in the projects' trash (<id>-<time> ).
private static IEnumerable<(string Directory, bool Trashed)> ProjectFolders(SequencePaths folder)
{
foreach (var directory in Directory.EnumerateDirectories(folder.ProjectsDirectory).Order(StringComparer.Ordinal))
{
if (Guid.TryParseExact(Path.GetFileName(directory), "N", out _)) yield return (directory, false);
}
if (!Directory.Exists(folder.ProjectsTrashDirectory)) yield break;
foreach (var directory in Directory.EnumerateDirectories(folder.ProjectsTrashDirectory).Order(StringComparer.Ordinal))
{
if (File.Exists(Path.Combine(directory, ArchiveLayout.ProjectFile))) yield return (directory, true);
}
}
///
/// The record with the version files that follow its head adopted (a push that wrote its version but not the record),
/// and the files past the head that do not follow it moved aside; the record is written again when its head moved. A
/// file past the head that cannot be read proves nothing: then none is moved aside.
///
private static ProjectRecord RollForward(SequencePaths folder, ProjectRecord record, string directory, bool writable)
{
var versions = Path.Combine(directory, ArchiveLayout.ProjectVersionsFolder);
var files = ProjectSidecars.ListVersions(versions);
var head = record.Head;
var moved = false;
var unread = false;
while (true)
{
var next = (head?.Number ?? 0) + 1;
ProjectVersion? follower = null;
foreach (var candidate in files.Where(f => f.Number == next))
{
try
{
var version = ProjectSidecars.ReadVersion(candidate.Path);
if (version.ProjectId == record.Id && version.Id == candidate.Id && version.ParentId == head?.Id)
{
follower = version;
break;
}
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("projects", $"Version file {candidate.Path} cannot be read", ex);
unread = true;
}
}
if (follower is null) break;
head = new ProjectHead(follower.Id, follower.Number);
moved = true;
}
if (writable && !unread)
{
foreach (var stray in files.Where(f => f.Number > (head?.Number ?? 0)))
SetAside(versions, stray.Path, $"does not follow the head of project {record.Id}");
}
if (!moved) return record;
var rolled = record with { Head = head, Updated = DateTimeOffset.UtcNow };
if (!writable) return rolled;
try
{
ProjectSidecars.WriteRecord(folder.ProjectRecordPath(record.Id), rolled);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// The index takes the versions all the same; the record is written with them before anything else is (ProjectService).
Log.Warning("projects", $"The record of project {record.Id} could not be moved forward to version {head!.Number}", ex);
}
return rolled;
}
/// A version file moved aside into versions/.stray (kept, never deleted).
private static void SetAside(string versions, string path, string why)
{
try
{
var aside = Path.Combine(versions, StrayFolder);
Directory.CreateDirectory(aside);
File.Move(path, Path.Combine(aside, Path.GetFileName(path) + "." + DateTime.UtcNow.ToString("yyyyMMddHHmmssfff", CultureInfo.InvariantCulture)));
Log.Warning("projects", $"Version file {path} {why}; moved aside");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("projects", $"Version file {path} could not be moved aside", ex);
}
}
///
/// Writes what the index lacks of one project's record and versions. False when its head could not be reached: the
/// record names a version this Chronos cannot read (damaged, of a newer Chronos), and the index's head stays on the
/// newest one it holds below it.
///
private async Task IndexAsync(ProjectRecord record, string directory, bool trashed, bool writable, CancellationToken cancellationToken)
{
var row = await db.Projects.GetAsync(record.Id, cancellationToken).ConfigureAwait(false);
if (row is null)
{
var project = record.ToProject();
if (project.DeletedAt is null)
{
var live = await db.Projects.ListBySequenceAsync(record.SequenceId, includeDeleted: false, cancellationToken).ConfigureAwait(false);
if (project.IsMain && live.Any(p => p.IsMain))
{
Log.Warning("projects", $"Project {record.Id} says it is Main, but sequence {record.SequenceId} has one; indexed as another project");
project = project with { IsMain = false };
}
project = project with { Name = FreeName(live, project.Name, project.Id) };
}
// The head follows its versions below, so a version the index cannot take never leaves a head without its row.
row = project with { HeadVersionId = null, HeadNumber = 0 };
await db.Projects.InsertAsync(row, cancellationToken).ConfigureAwait(false);
}
await IndexVersionsAsync(record, directory, writable, cancellationToken).ConfigureAwait(false);
var (headId, headNumber) = (row.HeadVersionId, row.HeadNumber);
var reached = true;
if (record.Head is { } head && (head.Number > headNumber || (head.Number == headNumber && head.Id != headId)))
{
if (await db.Projects.GetVersionAsync(head.Id, cancellationToken).ConfigureAwait(false) is { } indexed && indexed.ProjectId == record.Id
&& indexed.Number == head.Number)
{
(headId, headNumber) = (head.Id, head.Number);
}
else
{
reached = false;
Log.Warning("projects", $"The newest version of project {record.Id} ({head.Number}) cannot be read; the project is shown as far as it can be, and not changed");
var below = await db.Projects.ListVersionsAsync(record.Id, head.Number, 1, cancellationToken).ConfigureAwait(false);
if (below.Count > 0 && below[0].Number > headNumber) (headId, headNumber) = (below[0].Id, below[0].Number);
}
}
var updated = row with { HeadVersionId = headId, HeadNumber = headNumber };
if (record.Deleted is not null || trashed)
{
updated = updated with { DeletedAt = row.DeletedAt ?? record.Deleted };
}
else if (row.DeletedAt is not null || row.Name != record.Name)
{
var others = (await db.Projects.ListBySequenceAsync(record.SequenceId, includeDeleted: false, cancellationToken).ConfigureAwait(false))
.Where(p => p.Id != record.Id).ToList();
if (row.DeletedAt is not null)
{
// Its live record says it is not deleted: listed again, Main again unless the sequence has another.
Log.Warning("projects", $"Project {record.Id} of sequence {record.SequenceId} is live in its sidecars; it is listed again");
updated = updated with { DeletedAt = null, IsMain = row.IsMain && !others.Any(p => p.IsMain) };
}
// The record's name, else (another project has it) the name the index has, else one free.
updated = updated with
{
Name = FreeName(others, record.Name, record.Id) == record.Name ? record.Name
: FreeName(others, row.Name, record.Id) == row.Name ? row.Name
: FreeName(others, record.Name, record.Id),
};
}
if (updated != row) await db.Projects.UpdateAsync(updated, cancellationToken).ConfigureAwait(false);
return reached || record.Deleted is not null || trashed;
}
///
/// The version files up to the record's head the index lacks, taken in. Of several files of one number, the one the
/// record's chain names is taken and the others are moved aside; when the chain cannot tell (a version on it cannot be
/// read), none is taken.
///
private async Task IndexVersionsAsync(ProjectRecord record, string directory, bool writable, CancellationToken cancellationToken)
{
var versions = Path.Combine(directory, ArchiveLayout.ProjectVersionsFolder);
var files = ProjectSidecars.ListVersions(versions);
var limit = record.Head?.Number ?? 0;
var indexed = new Dictionary(await db.Projects.ListVersionIdsAsync(record.Id, cancellationToken).ConfigureAwait(false));
Dictionary? chain = null;
foreach (var number in files.Where(f => f.Number <= limit && !indexed.ContainsKey(f.Number)).GroupBy(f => f.Number))
{
var candidates = number.ToList();
if (candidates.Count > 1)
{
chain ??= Chain(record, files);
var named = candidates.Where(c => chain.TryGetValue(c.Number, out var id) && id == c.Id).ToList();
if (named.Count == 0)
{
Log.Warning("projects", $"Project {record.Id} has {candidates.Count} version files numbered {number.Key} and its record's chain names none; none is indexed");
continue;
}
if (writable)
{
foreach (var other in candidates.Where(c => c.Id != named[0].Id))
SetAside(versions, other.Path, $"has the number of another version of project {record.Id}");
}
candidates = named;
}
foreach (var file in candidates)
{
ProjectVersion version;
try
{
version = ProjectSidecars.ReadVersion(file.Path);
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("projects", $"Version file {file.Path} cannot be read; it is not indexed", ex);
continue;
}
if (version.ProjectId != record.Id || version.Number != file.Number || version.Id != file.Id) continue;
if (await db.Projects.GetVersionAsync(version.Id, cancellationToken).ConfigureAwait(false) is not null)
{
Log.Warning("projects", $"Version file {file.Path} holds a version the index has under another number; it is not indexed");
continue;
}
await db.Projects.InsertVersionAsync(version, cancellationToken).ConfigureAwait(false);
indexed[version.Number] = version.Id;
}
}
}
/// The version ids by number along the record's chain, from its head back through each parent, as far as their files read.
private static Dictionary Chain(ProjectRecord record, IReadOnlyList<(int Number, Guid Id, string Path)> files)
{
var chain = new Dictionary();
var byId = files.GroupBy(f => f.Id).ToDictionary(g => g.Key, g => g.First());
for (var id = record.Head?.Id; id is { } current && byId.TryGetValue(current, out var file) && !chain.ContainsKey(file.Number);)
{
chain[file.Number] = file.Id;
try
{
id = ProjectSidecars.ReadVersion(file.Path).ParentId;
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("projects", $"Version file {file.Path} cannot be read", ex);
break;
}
}
return chain;
}
}