using Chronos.Core.Archiving;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
namespace Chronos.Data.Projects;
/// A project's home cannot be reached now (its archive offline or busy, its server out of reach): try again later.
public sealed class HomeUnavailableException(string message, Exception? inner = null) : IOException(message, inner);
/// The sequence a home keeps projects for, as a workspace's project file names it.
public sealed record HomeSequence(BundleArchive Archive, BundleSequence Sequence, BundleHome Home);
///
/// Where a sequence's projects live (owner review 2, R8): the side a workspace pushes to and pulls from, "like git". This
/// PC's archive is one (); a server is the other (, phase
/// 5b). Every call may throw when the home cannot be reached, and
/// when it refuses.
///
public interface IProjectHome
{
/// Gives a project another name (1–60 characters, unique among the sequence's live projects whatever the case).
/// Unknown project, or the name is invalid or taken.
Task RenameAsync(Guid projectId, string name, CancellationToken cancellationToken) =>
throw new NotSupportedException("This home does not rename projects.");
/// Deletes a project (never Main) into the home's project trash, with all its versions, which stay readable there.
/// Unknown project, or the Main project.
Task DeleteAsync(Guid projectId, CancellationToken cancellationToken) => throw new NotSupportedException("This home does not delete projects.");
/// The sequence and where it is.
Task SequenceAsync(CancellationToken cancellationToken);
/// The sequence's live projects, Main first (made when the sequence had none).
Task> ListAsync(CancellationToken cancellationToken);
/// 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; 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.
Task GetVersionAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken);
///
/// Whether the home holds durably, read back from where it keeps it and matching its content
/// hash: what a workspace asks before it drops its own copy. A home that keeps no other copy answers from
/// .
///
async Task HoldsAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(version);
return await GetVersionAsync(projectId, version.Id, cancellationToken).ConfigureAwait(false) is { } held
&& string.Equals(held.ContentHash, version.ContentHash, StringComparison.OrdinalIgnoreCase) && ProjectContent.Verifies(held.SettingsJson, held.ContentHash);
}
/// The versions numbered above , oldest first, at most .
Task> VersionsAfterAsync(Guid projectId, int afterNumber, int limit, CancellationToken cancellationToken);
/// One page of the history, newest first: the versions numbered below (from the head when null).
Task> HistoryAsync(Guid projectId, int? beforeNumber, int limit, CancellationToken cancellationToken);
/// Stores a version made from the head ().
Task PushAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken);
/// The sequence's frames as the home holds them now.
Task FramesAsync(CancellationToken cancellationToken);
///
/// A cheap stamp of what answers: another value whenever the frames, how their photos are
/// named (a hash learnt) or the encodings conversions joined may have changed, so a workspace reads the frames again only
/// then. Null from a home that keeps none: the frames are read every time.
///
Task FramesStampAsync(CancellationToken cancellationToken) => Task.FromResult(null);
///
/// The highest project settings format the home stores and renders (owner review 1, phase 4); a version of a higher one
/// is not pushed to it (an older server refuses it, 422 newer_format). This PC's archive reads what this Chronos does.
///
int SettingsFormat => ProjectSettings.CurrentVersion;
}
/// A sequence of this PC's archive as its projects' home: the archive's .
public sealed class ArchiveProjectHome(ChronosDatabase db, ProjectService projects, Guid sequenceId) : IProjectHome
{
public Guid SequenceId => sequenceId;
public async Task SequenceAsync(CancellationToken cancellationToken)
{
var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {sequenceId} is not in the index.");
var archive = await db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false);
return new HomeSequence(new BundleArchive(sequence.ArchiveId, archive?.Name ?? string.Empty, archive?.RootPath),
new BundleSequence(sequence.Id, sequence.Folder, sequence.DisplayTitle, sequence.FrameCount),
new BundleHome(BundleHome.ArchiveKind, sequence.Id, sequence.ArchiveId));
}
public Task> ListAsync(CancellationToken cancellationToken) =>
Reach(async () =>
{
// Made at once when the sequence has none, so every list has a Main.
await projects.MainAsync(sequenceId, cancellationToken).ConfigureAwait(false);
return await projects.ListAsync(sequenceId, cancellationToken).ConfigureAwait(false);
});
public Task CreateAsync(string name, Guid? fromVersionId, string? author, CancellationToken cancellationToken) =>
Reach(() => projects.CreateAsync(sequenceId, name, fromVersionId, author, cancellationToken));
public Task HeadAsync(Guid projectId, CancellationToken cancellationToken) =>
Reach(async () =>
{
await Own(projectId, cancellationToken).ConfigureAwait(false);
return await projects.HeadAsync(projectId, cancellationToken).ConfigureAwait(false);
});
public Task GetVersionAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken) =>
Reach(async () =>
{
if (await projects.GetVersionAsync(versionId, cancellationToken).ConfigureAwait(false) is not { } version)
{
// A version the index does not know yet may be in the sequence's sidecars (see Own): they are read first.
await projects.ListAsync(sequenceId, cancellationToken).ConfigureAwait(false);
version = await projects.GetVersionAsync(versionId, cancellationToken).ConfigureAwait(false);
}
return version is not null && version.ProjectId == projectId ? version : null;
});
/// Read back from the version's file in the archive, never from the index's row ().
public Task HoldsAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken) =>
Reach(async () =>
{
ArgumentNullException.ThrowIfNull(version);
var project = await Own(projectId, cancellationToken).ConfigureAwait(false);
return project.DeletedAt is null && ProjectContent.Verifies(version.SettingsJson, version.ContentHash)
&& await projects.StoredAsync(projectId, version, cancellationToken).ConfigureAwait(false);
});
public Task> VersionsAfterAsync(Guid projectId, int afterNumber, int limit, CancellationToken cancellationToken) =>
Reach(async () =>
{
await Own(projectId, cancellationToken).ConfigureAwait(false);
return await projects.VersionsAfterAsync(projectId, afterNumber, limit, cancellationToken).ConfigureAwait(false);
});
public Task> HistoryAsync(Guid projectId, int? beforeNumber, int limit, CancellationToken cancellationToken) =>
Reach(async () =>
{
await Own(projectId, cancellationToken).ConfigureAwait(false);
return await projects.HistoryAsync(projectId, beforeNumber, limit, cancellationToken).ConfigureAwait(false);
});
public Task PushAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken) =>
Reach(async () =>
{
await Own(projectId, cancellationToken).ConfigureAwait(false);
return await projects.PushAsync(projectId, version, cancellationToken).ConfigureAwait(false);
});
public Task FramesAsync(CancellationToken cancellationToken) => projects.FramesAsync(sequenceId, cancellationToken);
public Task RenameAsync(Guid projectId, string name, CancellationToken cancellationToken) =>
Reach(async () =>
{
await Own(projectId, cancellationToken).ConfigureAwait(false);
return await projects.RenameAsync(projectId, name, cancellationToken).ConfigureAwait(false);
});
public Task DeleteAsync(Guid projectId, CancellationToken cancellationToken) =>
Reach(async () =>
{
await Own(projectId, cancellationToken).ConfigureAwait(false);
await projects.DeleteAsync(projectId, cancellationToken).ConfigureAwait(false);
return true;
});
///
/// The sequence's frames version (frames added, removed, converted or renamed), with how many of its photos the index has
/// hashed and a checksum of those hashes (a Verify hashes them, or finds other bytes, without another frames version)
/// and how many removals it keeps (a conversion's links).
///
public async Task FramesStampAsync(CancellationToken cancellationToken) =>
await StampOfAsync(db, sequenceId, cancellationToken).ConfigureAwait(false);
///
/// The stamp of a sequence's frames as an index holds them (): what a server answers for
/// its sequences too (GET …/projects/frames/stamp).
///
/// The sequence is not in the index.
public static async Task StampOfAsync(ChronosDatabase db, Guid sequenceId, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(db);
var row = await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {sequenceId} is not in the index.");
var (hashed, checksum, removals) = await db.Frames.CountNamedAsync(sequenceId, cancellationToken).ConfigureAwait(false);
return string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{row.FramesVersion}:{hashed}:{checksum}:{removals}");
}
///
/// The project is one of this sequence's. One the index does not know yet (an index taken back from an older backup, a
/// sequence back from the trash, a project another program sharing the archive made) is looked for in the sequence's
/// sidecars first, which every listing brings into the index.
///
private async Task Own(Guid projectId, CancellationToken cancellationToken)
{
if (await projects.GetAsync(projectId, cancellationToken).ConfigureAwait(false) is not { } project)
{
await projects.ListAsync(sequenceId, cancellationToken).ConfigureAwait(false);
project = await projects.GetAsync(projectId, cancellationToken).ConfigureAwait(false);
}
return project is not null && project.SequenceId == sequenceId
? project
: throw new ProjectException(ProjectError.NotFound, $"Project {projectId} is not a project of sequence {sequenceId}.");
}
/// An archive offline, read-only or busy is a home out of reach for now.
private static async Task Reach(Func> call)
{
try
{
return await call().ConfigureAwait(false);
}
catch (ArchiveOfflineException ex)
{
throw new HomeUnavailableException(ex.Message, ex);
}
catch (LeaseUnavailableException ex)
{
throw new HomeUnavailableException(ex.Message, ex);
}
catch (SequenceFolderMovedException ex)
{
// Another index of the archive moved the sequence: this one finds it at its next scan.
throw new HomeUnavailableException(ex.Message, ex);
}
catch (ProjectsUnreadableException ex)
{
// A record or a version this Chronos cannot read now (damaged, held open, of a newer Chronos): nothing was written.
throw new HomeUnavailableException(ex.Message, ex);
}
}
}