feat(projects): workspace projects with linear versions, the local archive as their home
Owner review 2, phase 5a (R8): editing moves out of the library into a workspace on a fast disk, and a sequence gets several projects, each with a linear version history pushed and pulled like git. - Core: ProjectSettings keeps members a newer Chronos wrote (Extra) and reads a newer settings format read-only; ProjectContent is the portable form of a version (every frame position parked by photo, canonical text, SHA-256 content hash); ProjectBundle format 2 adds the workspace section, and a file without it is still written as format 1. JobKind.WorkspaceCopy = 20 (19 kept for Convert). - Data: migration 0009 (projects, project_versions, the render's project columns); ProjectService on ArchiveService.Projects keeps projects as sidecars first (.chronos/projects/<id>/), then the index, under the sequence lease: create, rename, delete into the projects' trash, history, push with fast-forward, idempotent repeat, divergence and hash checks. Main is made from the sequence's settings and mirrored both ways, so every older code path keeps working; outside writes become "external" versions, a mirror a crash cut short is completed or merged. Full scans and rebuilds take the projects back from their sidecars. - ProjectMerge moves from the App to Data/Projects, merges pending frames photo by photo and replays unpushed commits on a moved head. - Workspaces: WorkspaceStore, WorkspaceSync (checkout, save, commit, push, pull with replay and merge, conflicts settled by keep mine / take server / save both, restore, status) and the WorkspaceCopy job (proxies copied hash-verified and resumable; originals refused until phase 5c). - Renders of a project version place its positions on the frames and record the project and version. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit c4c1802884e403db8759ed0501f770a67a047f20)
This commit is contained in:
1 parent
e3cbe30b29
commit
03d32f18d3
51 files changed
+4917
-108
No files matched your search
@@ -2,6 +2,7 @@ using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
@@ -37,11 +38,13 @@ public sealed class ArchiveIndexer
|
||||
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly SequenceWriter _writer;
|
||||
private readonly ProjectIndexer _projects;
|
||||
|
||||
internal ArchiveIndexer(ChronosDatabase db, SequenceWriter writer)
|
||||
{
|
||||
_db = db;
|
||||
_writer = writer;
|
||||
_projects = new ProjectIndexer(db);
|
||||
}
|
||||
|
||||
/// <param name="resumeAfter">Last folder completed by an interrupted run (job checkpoint), or null.</param>
|
||||
@@ -78,6 +81,8 @@ public sealed class ArchiveIndexer
|
||||
{
|
||||
var reconcile = mode == ScanMode.Full || (state is not null && state.Photos != folder.Photos);
|
||||
var (id, bytes) = await IndexFolderAsync(archive, paths, folder, reconcile, snapshot, locations, cancellationToken).ConfigureAwait(false);
|
||||
// A full scan or a rebuild takes the projects' sidecars back too (owner review 2, R8).
|
||||
if (mode != ScanMode.Incremental) await ReconcileProjectsAsync(paths, id, cancellationToken).ConfigureAwait(false);
|
||||
if (snapshotWriter is not null)
|
||||
{
|
||||
// Bytes go under the stamp they were read at (the listed one for the bytes indexed, else one taken before
|
||||
@@ -339,6 +344,21 @@ public sealed class ArchiveIndexer
|
||||
/// </summary>
|
||||
private SequenceStatus Uncovered => _writer.Options.ImagesAfterScan ? CoveringStatus : SequenceStatus.None;
|
||||
|
||||
/// <summary>
|
||||
/// The projects of a sequence brought in line with their sidecars (<see cref="ProjectIndexer"/>), under its lease; nothing
|
||||
/// for a sequence without a projects folder (its Main is made when a project is first asked for).
|
||||
/// </summary>
|
||||
private async Task ReconcileProjectsAsync(ArchivePaths paths, Guid sequenceId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) is not { } row
|
||||
|| !Directory.Exists(paths.Sequence(row.Folder).ProjectsDirectory)) return;
|
||||
await using (await _writer.LockAsync(paths, sequenceId, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var folder = await SequenceWriter.FolderAsync(_db, paths, row, cancellationToken).ConfigureAwait(false);
|
||||
await _projects.ReconcileAsync(folder, sequenceId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Indexes one folder; returns its sequence and the sidecar bytes when they were read and not rewritten since (for the snapshot).</summary>
|
||||
private async Task<(Guid Id, byte[]? Bytes)> IndexFolderAsync(Archive archive, ArchivePaths paths, SequenceFolder folder, bool reconcile, IndexSnapshot? snapshot,
|
||||
Locations locations, CancellationToken cancellationToken)
|
||||
|
||||
@@ -9,6 +9,7 @@ using Chronos.Core.Naming;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
@@ -44,6 +45,7 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
Trash = new SequenceTrash(db, _writer, Indexer);
|
||||
FrameTrash = new FrameTrash(db, _writer, Indexer, Ingest, Trash);
|
||||
Converter = new MassConverter(db, _writer, Ingest, FrameTrash, Trash, this);
|
||||
Projects = new ProjectService(db, _writer);
|
||||
var shared = Housekeeping.CleanupSteps.Shared(Trash);
|
||||
CleanupSteps = [.. shared, .. _writer.Options.CleanupSteps.Where(s => !shared.Any(o => o.Name == s.Name))];
|
||||
}
|
||||
@@ -68,6 +70,12 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
/// <summary>Converts sequences to JPEG, TIFF-16 or linear DNG, replacing their frames or into new sequences (owner review 2, R7).</summary>
|
||||
public MassConverter Converter { get; }
|
||||
|
||||
/// <summary>The projects of the sequences and their versions: this PC's archive as a project's home (owner review 2, R8).</summary>
|
||||
public ProjectService Projects { get; }
|
||||
|
||||
/// <summary>The decoders of this engine's image passes (thumbnails, proxies).</summary>
|
||||
public Core.Imaging.ImageDecoder Decoder => _writer.Options.Decoder;
|
||||
|
||||
/// <summary>
|
||||
/// The steps this host's <see cref="JobKind.Cleanup"/> jobs can run: the shared ones (<see cref="Housekeeping.CleanupSteps.Shared"/>),
|
||||
/// then the host's (<see cref="ArchiveServiceOptions.CleanupSteps"/>). A schedule host lists their names.
|
||||
|
||||
@@ -90,14 +90,30 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options)
|
||||
public ArchiveServiceOptions Options => options;
|
||||
|
||||
/// <summary>Holds the sequence exclusively until disposed.</summary>
|
||||
public async Task<IAsyncDisposable> LockAsync(ArchivePaths archive, Guid sequenceId, CancellationToken cancellationToken)
|
||||
public Task<IAsyncDisposable> LockAsync(ArchivePaths archive, Guid sequenceId, CancellationToken cancellationToken) =>
|
||||
LockAsync(archive, sequenceId, null, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Holds the sequence exclusively until disposed, waiting at most <paramref name="wait"/> for this process's other writers
|
||||
/// and for the lease (the options' lease wait when null).
|
||||
/// </summary>
|
||||
/// <exception cref="LeaseUnavailableException">Another writer kept the sequence for longer than the wait.</exception>
|
||||
public async Task<IAsyncDisposable> LockAsync(ArchivePaths archive, Guid sequenceId, TimeSpan? wait, CancellationToken cancellationToken)
|
||||
{
|
||||
var name = $"seq-{sequenceId:N}";
|
||||
var gate = _gates.GetOrAdd(sequenceId, _ => new SemaphoreSlim(1, 1));
|
||||
await gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (wait is { } limit)
|
||||
{
|
||||
if (!await gate.WaitAsync(limit, cancellationToken).ConfigureAwait(false)) throw new LeaseUnavailableException(name, null);
|
||||
}
|
||||
else
|
||||
{
|
||||
await gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
try
|
||||
{
|
||||
var lease = await LeaseFile.AcquireAsync(archive.LocksDirectory, $"seq-{sequenceId:N}", options.Owner, options.LeaseWait,
|
||||
options.LeaseDuration, cancellationToken).ConfigureAwait(false);
|
||||
var lease = await LeaseFile.AcquireAsync(archive.LocksDirectory, name, options.Owner, wait ?? options.LeaseWait, options.LeaseDuration,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return new Held(gate, lease);
|
||||
}
|
||||
catch
|
||||
|
||||
@@ -24,6 +24,7 @@ public abstract class ChronosRepositories
|
||||
Uploads = new UploadRepository(access);
|
||||
Schedules = new ScheduleRepository(access);
|
||||
FrameRemovals = new FrameRemovalRepository(access);
|
||||
Projects = new ProjectRepository(access);
|
||||
}
|
||||
|
||||
public ArchiveRepository Archives { get; }
|
||||
@@ -45,6 +46,9 @@ public abstract class ChronosRepositories
|
||||
|
||||
/// <summary>Tombstones of the photos removed from sequences (owner review 2, R6).</summary>
|
||||
public FrameRemovalRepository FrameRemovals { get; }
|
||||
|
||||
/// <summary>Projects of sequences and their versions (owner review 2, R8).</summary>
|
||||
public ProjectRepository Projects { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
-- Projects of sequences (owner review 2, R8): named sets of render settings ("4K landscape", "Vertical social"), each
|
||||
-- with a linear history of immutable versions. The sidecars in <sequence>/.chronos/projects/ are the truth; these rows
|
||||
-- are derived and rebuilt from them. Every sequence has one Main project, whose head is mirrored into
|
||||
-- sequences.settings_json: mirrored_version_id and mirrored_settings_version are the version and the settings version of
|
||||
-- the last mirror, so settings another path wrote are caught up as an "external" version, and a mirror a crash cut short
|
||||
-- is completed. A version's settings are text, not jsonb, so the bytes its content hash covers stay exact. Renders
|
||||
-- remember the project version they rendered. Mirrors sqlite/0009_projects.sql.
|
||||
|
||||
CREATE TABLE projects (
|
||||
id uuid NOT NULL PRIMARY KEY,
|
||||
sequence_id uuid NOT NULL REFERENCES sequences (id) ON DELETE CASCADE,
|
||||
name text NOT NULL,
|
||||
is_main boolean NOT NULL DEFAULT FALSE,
|
||||
head_version_id uuid,
|
||||
head_number integer NOT NULL DEFAULT 0,
|
||||
mirrored_settings_version integer,
|
||||
mirrored_version_id uuid,
|
||||
created_by text,
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL,
|
||||
deleted_at timestamptz
|
||||
);
|
||||
CREATE UNIQUE INDEX ux_projects_name ON projects (sequence_id, name) WHERE deleted_at IS NULL;
|
||||
CREATE UNIQUE INDEX ux_projects_main ON projects (sequence_id) WHERE is_main AND deleted_at IS NULL;
|
||||
|
||||
CREATE TABLE project_versions (
|
||||
id uuid NOT NULL PRIMARY KEY,
|
||||
project_id uuid NOT NULL REFERENCES projects (id) ON DELETE CASCADE,
|
||||
parent_id uuid,
|
||||
number integer NOT NULL,
|
||||
kind text NOT NULL,
|
||||
author text,
|
||||
client_name text,
|
||||
note text,
|
||||
settings_json text NOT NULL,
|
||||
content_hash text NOT NULL,
|
||||
settings_format integer NOT NULL,
|
||||
frames_version integer NOT NULL,
|
||||
restored_from uuid,
|
||||
created_at timestamptz NOT NULL,
|
||||
stored_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE UNIQUE INDEX ux_project_versions_number ON project_versions (project_id, number);
|
||||
|
||||
ALTER TABLE renders ADD COLUMN project_id uuid;
|
||||
ALTER TABLE renders ADD COLUMN project_version_id uuid;
|
||||
@@ -0,0 +1,46 @@
|
||||
-- Projects of sequences (owner review 2, R8): named sets of render settings ("4K landscape", "Vertical social"), each
|
||||
-- with a linear history of immutable versions. The sidecars in <sequence>/.chronos/projects/ are the truth; these rows
|
||||
-- are derived and rebuilt from them. Every sequence has one Main project, whose head is mirrored into
|
||||
-- sequences.settings_json: mirrored_version_id and mirrored_settings_version are the version and the settings version of
|
||||
-- the last mirror, so settings another path wrote are caught up as an "external" version, and a mirror a crash cut short
|
||||
-- is completed. A version's settings are text, never re-encoded, so the bytes its content hash covers stay exact.
|
||||
-- Renders remember the project version they rendered. Mirrors postgres/0009_projects.sql.
|
||||
|
||||
CREATE TABLE projects (
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
sequence_id TEXT NOT NULL REFERENCES sequences (id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
is_main INTEGER NOT NULL DEFAULT 0,
|
||||
head_version_id TEXT,
|
||||
head_number INTEGER NOT NULL DEFAULT 0,
|
||||
mirrored_settings_version INTEGER,
|
||||
mirrored_version_id TEXT,
|
||||
created_by TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
deleted_at TEXT
|
||||
);
|
||||
CREATE UNIQUE INDEX ux_projects_name ON projects (sequence_id, name) WHERE deleted_at IS NULL;
|
||||
CREATE UNIQUE INDEX ux_projects_main ON projects (sequence_id) WHERE is_main = 1 AND deleted_at IS NULL;
|
||||
|
||||
CREATE TABLE project_versions (
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
project_id TEXT NOT NULL REFERENCES projects (id) ON DELETE CASCADE,
|
||||
parent_id TEXT,
|
||||
number INTEGER NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
author TEXT,
|
||||
client_name TEXT,
|
||||
note TEXT,
|
||||
settings_json TEXT NOT NULL,
|
||||
content_hash TEXT NOT NULL,
|
||||
settings_format INTEGER NOT NULL,
|
||||
frames_version INTEGER NOT NULL,
|
||||
restored_from TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
stored_at TEXT NOT NULL
|
||||
);
|
||||
CREATE UNIQUE INDEX ux_project_versions_number ON project_versions (project_id, number);
|
||||
|
||||
ALTER TABLE renders ADD COLUMN project_id TEXT;
|
||||
ALTER TABLE renders ADD COLUMN project_version_id TEXT;
|
||||
@@ -48,7 +48,9 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt
|
||||
if (!SequenceFolders.Holds(folder, sequence.Id)) throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved"));
|
||||
// A server writes only inside its archive (BRIEF §14.2): an export folder chosen on a client means nothing there.
|
||||
if (options.Host == EncoderHost.Server) export = export with { Folder = null };
|
||||
var project = (parameters.SettingsJson is { } embedded ? ProjectStore.Parse(embedded) : ProjectStore.Read(sequence, folder)) with { Export = export };
|
||||
var embedded = parameters.SettingsJson ?? await VersionSettingsAsync(parameters, sequence, cancellation).ConfigureAwait(false);
|
||||
var frames = await SequenceFrames.LoadAsync(db, archive, sequence, parameters.UseProxies, options.Archive.Decoder, cancellation).ConfigureAwait(false);
|
||||
var project = (embedded is not null ? ProjectStore.Parse(Placed(embedded, frames)) : ProjectStore.Read(sequence, folder)) with { Export = export };
|
||||
var settingsJson = project.ToJson();
|
||||
|
||||
using var names = new OutputNames();
|
||||
@@ -71,7 +73,6 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt
|
||||
var targets = all.Select((t, i) => (i, t)).Where(t => !done.Contains(t.i)).Select(t => (t.i, adapt(t.t))).ToList();
|
||||
if (targets.Count == 0) return;
|
||||
|
||||
var frames = await SequenceFrames.LoadAsync(db, archive, sequence, parameters.UseProxies, options.Archive.Decoder, cancellation).ConfigureAwait(false);
|
||||
var companions = await GprCompanions.FindAsync(db, archive, frames.Frames, cancellation).ConfigureAwait(false);
|
||||
IReadOnlyList<TargetOutcome> outcomes;
|
||||
await using (var render = new SequenceRender(frames, project, SequenceAnalyser.ReadReport(folder, frames), options, originals: !parameters.UseProxies,
|
||||
@@ -88,6 +89,8 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt
|
||||
{
|
||||
Id = RenderId(context.Job.Id, index),
|
||||
OutputPath = Stored(paths, result.OutputPath),
|
||||
ProjectId = parameters.ProjectId,
|
||||
ProjectVersionId = parameters.ProjectVersionId,
|
||||
};
|
||||
await db.Renders.InsertAsync(entity, CancellationToken.None).ConfigureAwait(false);
|
||||
done.Add(index);
|
||||
@@ -120,6 +123,37 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt
|
||||
throw new InvalidOperationException(failed.Count == 1 ? failed[0].Error : Loc.L("Errors.Render.Failed", failed.Count, outcomes.Count));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The settings of the project version a job names without embedding them (owner review 2, R8); null when it names none.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">The version is not one of the sequence's projects'.</exception>
|
||||
private async Task<string?> VersionSettingsAsync(Protocol.RenderJobParameters parameters, Sequence sequence, CancellationToken cancellationToken)
|
||||
{
|
||||
if (parameters.ProjectVersionId is not { } versionId) return null;
|
||||
return await db.Projects.GetVersionAsync(versionId, cancellationToken).ConfigureAwait(false) is { } version
|
||||
&& await db.Projects.GetAsync(version.ProjectId, cancellationToken).ConfigureAwait(false) is { } owner && owner.SequenceId == sequence.Id
|
||||
? version.SettingsJson
|
||||
: throw new InvalidOperationException(Loc.L("Errors.Render.ProjectVersion"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settings whose positions wait for their photos (a project version's portable form, settings synced from another copy)
|
||||
/// with them placed on the frames rendered; others as they are.
|
||||
/// </summary>
|
||||
internal static string Placed(string settingsJson, SequenceFrames frames)
|
||||
{
|
||||
if (!settingsJson.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase)) return settingsJson;
|
||||
try
|
||||
{
|
||||
return ProjectContent.Place(settingsJson, new FramePhotos(frames.Frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, f.CapturedAt)))));
|
||||
}
|
||||
catch (System.Text.Json.JsonException)
|
||||
{
|
||||
// Not a project: reading it says so.
|
||||
return settingsJson;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The job's preset, then every other preset of the batch with its own values.</summary>
|
||||
internal static List<ExportTarget> Targets(ExportSettings export, string presetName) =>
|
||||
[
|
||||
|
||||
@@ -41,6 +41,35 @@ public static class ProcessingJobs
|
||||
JsonSerializer.Serialize(parameters, ProtocolJson.Default.RenderJobParameters), JobPriority.User);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Render"/> of a project version (owner review 2, R8) on the sequence's home: the version's portable
|
||||
/// settings, placed on the sequence's frames by the render, with <paramref name="export"/> as their export section; the
|
||||
/// render records the project and the version. One job per preset, as <see cref="RenderEach"/>.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<ArchiveJobRequest> RenderVersion(Sequence sequence, ProjectVersion version, ExportSettings export, int sourceWidth, int sourceHeight,
|
||||
bool useProxies = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sequence);
|
||||
ArgumentNullException.ThrowIfNull(version);
|
||||
ArgumentNullException.ThrowIfNull(export);
|
||||
return
|
||||
[
|
||||
VersionJob(sequence, version, export with { Batch = [] }, sourceWidth, sourceHeight, useProxies),
|
||||
.. BatchPresets(export).Select(id => VersionJob(sequence, version, BatchExport(export, id), sourceWidth, sourceHeight, useProxies)),
|
||||
];
|
||||
}
|
||||
|
||||
private static ArchiveJobRequest VersionJob(Sequence sequence, ProjectVersion version, ExportSettings export, int sourceWidth, int sourceHeight, bool useProxies)
|
||||
{
|
||||
var parameters = Parameters(export, sourceWidth, sourceHeight, version.SettingsJson, useProxies) with
|
||||
{
|
||||
ProjectId = version.ProjectId,
|
||||
ProjectVersionId = version.Id,
|
||||
};
|
||||
return new ArchiveJobRequest(JobKind.Render, [sequence.Id], RenderLabel(sequence.DisplayTitle, parameters.PresetName),
|
||||
JsonSerializer.Serialize(parameters, ProtocolJson.Default.RenderJobParameters), JobPriority.User);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The label of a render job, "Harbour sunset → 4K HEVC". It is stored as written, in the language of the moment like
|
||||
/// the preset name: its arrow points from the sequence to the preset in that language's reading direction.
|
||||
@@ -64,7 +93,11 @@ public static class ProcessingJobs
|
||||
return
|
||||
[
|
||||
parameters with { PresetJson = JsonSerializer.Serialize(export with { Batch = [] }, ProcessingJson.Default.ExportSettings) },
|
||||
.. batch.Select(id => Parameters(BatchExport(export, id), sourceWidth, sourceHeight, parameters.SettingsJson, parameters.UseProxies)),
|
||||
.. batch.Select(id => Parameters(BatchExport(export, id), sourceWidth, sourceHeight, parameters.SettingsJson, parameters.UseProxies) with
|
||||
{
|
||||
ProjectId = parameters.ProjectId,
|
||||
ProjectVersionId = parameters.ProjectVersionId,
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
|
||||
namespace Chronos.Data.Projects;
|
||||
|
||||
/// <summary>A project's home cannot be reached now (its archive offline or busy, its server out of reach): try again later.</summary>
|
||||
public sealed class HomeUnavailableException(string message, Exception? inner = null) : IOException(message, inner);
|
||||
|
||||
/// <summary>The sequence a home keeps projects for, as a workspace's project file names it.</summary>
|
||||
public sealed record HomeSequence(BundleArchive Archive, BundleSequence Sequence, BundleHome Home);
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<see cref="ArchiveProjectHome"/>); a server is the other (phase 5b). Every call may throw
|
||||
/// <see cref="HomeUnavailableException"/> when the home cannot be reached, and <see cref="ProjectException"/> when it refuses.
|
||||
/// </summary>
|
||||
public interface IProjectHome
|
||||
{
|
||||
/// <summary>The sequence and where it is.</summary>
|
||||
Task<HomeSequence> SequenceAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The sequence's live projects, Main first (made when the sequence had none).</summary>
|
||||
Task<IReadOnlyList<SequenceProject>> ListAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>A new project named <paramref name="name"/> from <paramref name="fromVersionId"/> (a version of any project of the sequence), or from Main's head.</summary>
|
||||
Task<SequenceProject> CreateAsync(string name, Guid? fromVersionId, string? author, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The project's newest version.</summary>
|
||||
Task<ProjectVersion> HeadAsync(Guid projectId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>A version of the project by id; null when the home has none.</summary>
|
||||
Task<ProjectVersion?> GetVersionAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The versions numbered above <paramref name="afterNumber"/>, oldest first, at most <paramref name="limit"/>.</summary>
|
||||
Task<IReadOnlyList<ProjectVersion>> VersionsAfterAsync(Guid projectId, int afterNumber, int limit, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>One page of the history, newest first: the versions numbered below <paramref name="beforeNumber"/> (from the head when null).</summary>
|
||||
Task<IReadOnlyList<ProjectVersion>> HistoryAsync(Guid projectId, int? beforeNumber, int limit, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Stores a version made from the head (<see cref="ProjectService.PushAsync"/>).</summary>
|
||||
Task<PushResult> PushAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The sequence's frames as the home holds them now.</summary>
|
||||
Task<HomeFrames> FramesAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>A sequence of this PC's archive as its projects' home: the archive's <see cref="ProjectService"/>.</summary>
|
||||
public sealed class ArchiveProjectHome(ChronosDatabase db, ProjectService projects, Guid sequenceId) : IProjectHome
|
||||
{
|
||||
public Guid SequenceId => sequenceId;
|
||||
|
||||
public async Task<HomeSequence> 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<IReadOnlyList<SequenceProject>> 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<SequenceProject> CreateAsync(string name, Guid? fromVersionId, string? author, CancellationToken cancellationToken) =>
|
||||
Reach(() => projects.CreateAsync(sequenceId, name, fromVersionId, author, cancellationToken));
|
||||
|
||||
public Task<ProjectVersion> HeadAsync(Guid projectId, CancellationToken cancellationToken) =>
|
||||
Reach(async () =>
|
||||
{
|
||||
await Own(projectId, cancellationToken).ConfigureAwait(false);
|
||||
return await projects.HeadAsync(projectId, cancellationToken).ConfigureAwait(false);
|
||||
});
|
||||
|
||||
public async Task<ProjectVersion?> GetVersionAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken) =>
|
||||
await projects.GetVersionAsync(versionId, cancellationToken).ConfigureAwait(false) is { } version && version.ProjectId == projectId ? version : null;
|
||||
|
||||
public Task<IReadOnlyList<ProjectVersion>> 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<IReadOnlyList<ProjectVersion>> 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<PushResult> 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<HomeFrames> FramesAsync(CancellationToken cancellationToken) => projects.FramesAsync(sequenceId, cancellationToken);
|
||||
|
||||
/// <summary>The project is one of this sequence's.</summary>
|
||||
private async Task<SequenceProject> Own(Guid projectId, CancellationToken cancellationToken) =>
|
||||
await projects.GetAsync(projectId, cancellationToken).ConfigureAwait(false) is { } project && project.SequenceId == sequenceId
|
||||
? project
|
||||
: throw new ProjectException(ProjectError.NotFound, $"Project {projectId} is not a project of sequence {sequenceId}.");
|
||||
|
||||
/// <summary>An archive offline, read-only or busy is a home out of reach for now.</summary>
|
||||
private static async Task<T> Reach<T>(Func<Task<T>> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Data.Projects;
|
||||
|
||||
/// <summary>
|
||||
/// 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, Main flag or deletion recorded since is taken, and a live index row whose folder is gone
|
||||
/// is marked deleted. 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 is moved aside to <c>versions/.stray</c>, never deleted. Runs under the sequence's lease.
|
||||
/// </summary>
|
||||
internal sealed class ProjectIndexer(ChronosDatabase db)
|
||||
{
|
||||
private const string StrayFolder = ".stray";
|
||||
|
||||
/// <summary>Reconciles the projects of <paramref name="sequenceId"/> in <paramref name="folder"/>; the caller holds the sequence's lease.</summary>
|
||||
public async Task ReconcileAsync(SequencePaths folder, Guid sequenceId, CancellationToken cancellationToken)
|
||||
{
|
||||
var seen = new HashSet<Guid>();
|
||||
if (Directory.Exists(folder.ProjectsDirectory))
|
||||
{
|
||||
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)
|
||||
{
|
||||
Log.Warning("projects", $"The project in {directory} cannot be read", ex);
|
||||
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);
|
||||
await IndexAsync(record, directory, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
foreach (var gone in await db.Projects.ListBySequenceAsync(sequenceId, includeDeleted: false, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (seen.Contains(gone.Id)) continue;
|
||||
Log.Warning("projects", $"Project {gone.Id} of sequence {sequenceId} has no folder any more; it is marked deleted");
|
||||
await db.Projects.UpdateAsync(gone with { DeletedAt = DateTimeOffset.UtcNow, UpdatedAt = DateTimeOffset.UtcNow }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The project folders of a sequence: the live ones, then those in the projects' trash (<c><id>-<time></c>).</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static ProjectRecord RollForward(SequencePaths folder, ProjectRecord record, string directory)
|
||||
{
|
||||
var versions = Path.Combine(directory, ArchiveLayout.ProjectVersionsFolder);
|
||||
var files = ProjectSidecars.ListVersions(versions);
|
||||
var head = record.Head;
|
||||
var moved = false;
|
||||
while (true)
|
||||
{
|
||||
var next = (head?.Number ?? 0) + 1;
|
||||
var candidates = files.Where(f => f.Number == next).ToList();
|
||||
ProjectVersion? follower = null;
|
||||
foreach (var candidate in candidates)
|
||||
{
|
||||
try
|
||||
{
|
||||
var version = ProjectSidecars.ReadVersion(candidate.Path);
|
||||
if (version.ProjectId == record.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);
|
||||
}
|
||||
}
|
||||
if (follower is null) break;
|
||||
head = new ProjectHead(follower.Id, follower.Number);
|
||||
moved = true;
|
||||
}
|
||||
foreach (var stray in files.Where(f => f.Number > (head?.Number ?? 0)))
|
||||
{
|
||||
try
|
||||
{
|
||||
var aside = Path.Combine(versions, StrayFolder);
|
||||
Directory.CreateDirectory(aside);
|
||||
File.Move(stray.Path, Path.Combine(aside, Path.GetFileName(stray.Path) + "." + DateTime.UtcNow.ToString("yyyyMMddHHmmssfff", CultureInfo.InvariantCulture)));
|
||||
Log.Warning("projects", $"Version file {stray.Path} does not follow the head of project {record.Id}; moved aside");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("projects", $"Version file {stray.Path} could not be moved aside", ex);
|
||||
}
|
||||
}
|
||||
if (!moved) return record;
|
||||
var rolled = record with { Head = head, Updated = DateTimeOffset.UtcNow };
|
||||
ProjectSidecars.WriteRecord(folder.ProjectRecordPath(record.Id), rolled);
|
||||
return rolled;
|
||||
}
|
||||
|
||||
/// <summary>Writes what the index lacks of one project's record and versions.</summary>
|
||||
private async Task IndexAsync(ProjectRecord record, string directory, CancellationToken cancellationToken)
|
||||
{
|
||||
var row = await db.Projects.GetAsync(record.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (row is null)
|
||||
{
|
||||
var project = record.ToProject();
|
||||
var live = await db.Projects.ListBySequenceAsync(record.SequenceId, includeDeleted: false, cancellationToken).ConfigureAwait(false);
|
||||
if (project.DeletedAt is null && 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 };
|
||||
}
|
||||
if (project.DeletedAt is null && live.Any(p => string.Equals(p.Name, project.Name, StringComparison.OrdinalIgnoreCase)))
|
||||
project = project with { Name = project.Name + " (" + project.Id.ToString("N")[..6] + ")" };
|
||||
// The head follows its versions below, so a version the index cannot take never leaves a head without its row.
|
||||
await db.Projects.InsertAsync(project with { HeadVersionId = null, HeadNumber = 0 }, cancellationToken).ConfigureAwait(false);
|
||||
row = project with { HeadVersionId = null, HeadNumber = 0 };
|
||||
}
|
||||
var indexed = await db.Projects.ListVersionIdsAsync(record.Id, cancellationToken).ConfigureAwait(false);
|
||||
var headNumber = row.HeadNumber;
|
||||
Guid? headId = row.HeadVersionId;
|
||||
var limit = record.Head?.Number ?? 0;
|
||||
foreach (var file in ProjectSidecars.ListVersions(Path.Combine(directory, ArchiveLayout.ProjectVersionsFolder)))
|
||||
{
|
||||
if (file.Number > limit || indexed.ContainsKey(file.Number)) continue;
|
||||
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) continue;
|
||||
await db.Projects.InsertVersionAsync(version, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
if (record.Head is { } head && head.Number > headNumber && await db.Projects.GetVersionAsync(head.Id, cancellationToken).ConfigureAwait(false) is not null)
|
||||
(headId, headNumber) = (head.Id, head.Number);
|
||||
var updated = row with
|
||||
{
|
||||
Name = row.DeletedAt is null && record.Deleted is null && row.Name != record.Name && !await NameTakenAsync(record, cancellationToken).ConfigureAwait(false)
|
||||
? record.Name
|
||||
: row.Name,
|
||||
HeadVersionId = headId,
|
||||
HeadNumber = headNumber,
|
||||
DeletedAt = row.DeletedAt ?? record.Deleted,
|
||||
};
|
||||
if (updated != row) await db.Projects.UpdateAsync(updated, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<bool> NameTakenAsync(ProjectRecord record, CancellationToken cancellationToken) =>
|
||||
(await db.Projects.ListBySequenceAsync(record.SequenceId, includeDeleted: false, cancellationToken).ConfigureAwait(false))
|
||||
.Any(p => p.Id != record.Id && string.Equals(p.Name, record.Name, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Sync;
|
||||
|
||||
namespace Chronos.Data.Projects;
|
||||
|
||||
/// <summary>The result of a three-way merge of projects: the merged settings and the members both sides changed to different values.</summary>
|
||||
/// <param name="Conflicts">Each settled for the side asked (<c>takeTheirs</c>), else for ours; empty when the merge needed nobody.</param>
|
||||
public sealed record ProjectMergeResult(ProjectSettings Merged, IReadOnlyList<SettingsDifference> Conflicts)
|
||||
{
|
||||
public bool HasConflicts => Conflicts.Count > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Commits not stored at their home yet, replayed on top of the version stored there meanwhile (owner review 2, R8): one
|
||||
/// project per commit, in order, and the conflicts of the last one (the net change of all of them against theirs).
|
||||
/// </summary>
|
||||
public sealed record ProjectReplay(IReadOnlyList<ProjectSettings> Commits, IReadOnlyList<SettingsDifference> Conflicts)
|
||||
{
|
||||
public bool HasConflicts => Conflicts.Count > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Three-way merge of projects: the editor's edit (<c>ours</c>) and a change stored meanwhile by someone else
|
||||
/// (<c>theirs</c>: an analysis filling Auto values, another client through the server, another workspace through a
|
||||
/// project's home), both made from <c>basis</c>. Values are compared member by member down the JSON tree; a member only
|
||||
/// one side changed takes that side's value, a member both changed takes the editor's (the user is looking at it) unless
|
||||
/// its path is among those asked to take theirs. <see cref="Conflicts"/> lists those members for a source that asks the
|
||||
/// user instead (a server sequence, BRIEF §14.5; a workspace project, owner review 2, R8). Pending frames (frame
|
||||
/// positions parked by photo, the portable form of <see cref="ProjectContent"/>) merge photo by photo and flag by flag, so
|
||||
/// two people excluding different photos never conflict; two heroes chosen on both sides do (path <see cref="HeroPath"/>).
|
||||
/// Members this Chronos does not know merge like the others and are kept.
|
||||
/// </summary>
|
||||
public static class ProjectMerge
|
||||
{
|
||||
/// <summary>The path of the conflict of two heroes chosen among pending frames on both sides.</summary>
|
||||
public const string HeroPath = "hero";
|
||||
|
||||
private const string PendingPath = "pendingFrames";
|
||||
|
||||
public static ProjectSettings Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs) =>
|
||||
MergeWithConflicts(basis, ours, theirs).Merged;
|
||||
|
||||
/// <summary>
|
||||
/// The merge of <paramref name="ours"/> and <paramref name="theirs"/> made from <paramref name="basis"/>, and its
|
||||
/// conflicts. A conflict whose path is in <paramref name="takeTheirs"/> takes theirs (the user chose "take server"
|
||||
/// there), every other one ours.
|
||||
/// </summary>
|
||||
public static ProjectMergeResult MergeWithConflicts(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs, IReadOnlySet<string>? takeTheirs = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(basis);
|
||||
ArgumentNullException.ThrowIfNull(ours);
|
||||
ArgumentNullException.ThrowIfNull(theirs);
|
||||
var conflicts = new List<SettingsDifference>();
|
||||
var choice = takeTheirs ?? EmptySet;
|
||||
var (b, o, t) = (Keyed(basis), Keyed(ours), Keyed(theirs));
|
||||
var merged = MergeNode(b, o, t, string.Empty, conflicts, choice) as JsonObject ?? new JsonObject();
|
||||
OneHero(merged, o, t, conflicts, choice);
|
||||
return new ProjectMergeResult(FromKeyed(merged), conflicts);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The members both sides changed to different values, in document order: the path below the project
|
||||
/// ("exposure.deflickerWindow.manual"; "pendingFrames.<photo>.excluded" for a pending frame), the editor's value and
|
||||
/// theirs as JSON (null when absent).
|
||||
/// </summary>
|
||||
public static IReadOnlyList<SettingsDifference> Conflicts(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs) =>
|
||||
MergeWithConflicts(basis, ours, theirs).Conflicts;
|
||||
|
||||
/// <summary>
|
||||
/// Replays commits made from <paramref name="basis"/> (<paramref name="mine"/>, oldest first, each including the ones
|
||||
/// before it) on top of <paramref name="theirs"/>: each becomes theirs with that commit's changes since the basis, so the
|
||||
/// history stays linear and the last one holds the net change. Conflicts are those of the last commit; their paths in
|
||||
/// <paramref name="takeTheirs"/> take theirs in every commit.
|
||||
/// </summary>
|
||||
public static ProjectReplay Replay(ProjectSettings basis, IReadOnlyList<ProjectSettings> mine, ProjectSettings theirs, IReadOnlySet<string>? takeTheirs = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(mine);
|
||||
var commits = new List<ProjectSettings>(mine.Count);
|
||||
IReadOnlyList<SettingsDifference> conflicts = [];
|
||||
foreach (var commit in mine)
|
||||
{
|
||||
var result = MergeWithConflicts(basis, commit, theirs, takeTheirs);
|
||||
commits.Add(result.Merged);
|
||||
conflicts = result.Conflicts;
|
||||
}
|
||||
return new ProjectReplay(commits, conflicts);
|
||||
}
|
||||
|
||||
/// <summary>True when both projects store the same values.</summary>
|
||||
public static bool SameValues(ProjectSettings a, ProjectSettings b) => a.ToJson() == b.ToJson();
|
||||
|
||||
private static readonly IReadOnlySet<string> EmptySet = new HashSet<string>();
|
||||
|
||||
private static JsonNode? MergeNode(JsonNode? basis, JsonNode? ours, JsonNode? theirs, string path, List<SettingsDifference> conflicts,
|
||||
IReadOnlySet<string> takeTheirs)
|
||||
{
|
||||
if (JsonNode.DeepEquals(ours, basis)) return theirs?.DeepClone();
|
||||
if (JsonNode.DeepEquals(theirs, basis) || JsonNode.DeepEquals(theirs, ours)) return ours?.DeepClone();
|
||||
if (path == PendingPath && ours is JsonObject or null && theirs is JsonObject or null)
|
||||
return MergePending(basis as JsonObject, ours as JsonObject, theirs as JsonObject, conflicts, takeTheirs);
|
||||
if (ours is JsonObject mine && theirs is JsonObject other)
|
||||
{
|
||||
var common = basis as JsonObject;
|
||||
var merged = new JsonObject();
|
||||
foreach (var name in mine.Select(p => p.Key).Union(other.Select(p => p.Key)))
|
||||
{
|
||||
var child = path.Length == 0 ? name : path + "." + name;
|
||||
var value = MergeNode(common?[name], mine[name], other[name], child, conflicts, takeTheirs);
|
||||
if (value is not null || (takeTheirs.Contains(child) ? other.ContainsKey(name) : mine.ContainsKey(name))) merged[name] = value;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
var at = path.Length == 0 ? "settings" : path;
|
||||
conflicts.Add(new SettingsDifference(at, ours?.ToJsonString(), theirs?.ToJsonString()));
|
||||
return takeTheirs.Contains(at) ? theirs?.DeepClone() : ours?.DeepClone();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pending frames keyed by photo, merged entry by entry: an entry one side lacks counts as the photo with no position on
|
||||
/// it, so excluding one photo here and another there both stay, and a flag both changed alike is no conflict.
|
||||
/// </summary>
|
||||
private static JsonObject MergePending(JsonObject? basis, JsonObject? ours, JsonObject? theirs, List<SettingsDifference> conflicts,
|
||||
IReadOnlySet<string> takeTheirs)
|
||||
{
|
||||
var merged = new JsonObject();
|
||||
var keys = (ours?.Select(p => p.Key) ?? []).Union(theirs?.Select(p => p.Key) ?? []).Union(basis?.Select(p => p.Key) ?? []).ToList();
|
||||
foreach (var key in keys)
|
||||
{
|
||||
var template = ours?[key] ?? theirs?[key] ?? basis?[key];
|
||||
var value = MergeNode(basis?[key] ?? Unplaced(template), ours?[key] ?? Unplaced(template), theirs?[key] ?? Unplaced(template),
|
||||
PendingPath + "." + key, conflicts, takeTheirs);
|
||||
if (value is not null) merged[key] = value;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Two heroes after a merge (each side chose one among photos that wait): one conflict, settled for ours or, when asked,
|
||||
/// theirs; the other entry no longer holds the hero.
|
||||
/// </summary>
|
||||
private static void OneHero(JsonObject merged, JsonObject ours, JsonObject theirs, List<SettingsDifference> conflicts, IReadOnlySet<string> takeTheirs)
|
||||
{
|
||||
if (merged[PendingPath] is not JsonObject pending) return;
|
||||
var heroes = pending.Where(p => p.Value is JsonObject entry && Flag(entry, "hero")).Select(p => p.Key).ToList();
|
||||
if (heroes.Count < 2) return;
|
||||
var mine = HeroOf(ours);
|
||||
var other = HeroOf(theirs);
|
||||
var keep = takeTheirs.Contains(HeroPath) ? other ?? heroes[0] : mine ?? heroes[0];
|
||||
foreach (var key in heroes.Where(k => k != keep)) pending[key]!["hero"] = false;
|
||||
conflicts.Add(new SettingsDifference(HeroPath, mine is null ? null : (ours[PendingPath] as JsonObject)?[mine]?.ToJsonString(),
|
||||
other is null ? null : (theirs[PendingPath] as JsonObject)?[other]?.ToJsonString()));
|
||||
}
|
||||
|
||||
private static string? HeroOf(JsonObject project) =>
|
||||
project[PendingPath] is JsonObject pending ? pending.FirstOrDefault(p => p.Value is JsonObject entry && Flag(entry, "hero")).Key : null;
|
||||
|
||||
/// <summary>The project as JSON with its pending frames as an object keyed by photo (<see cref="KeyOf"/>).</summary>
|
||||
private static JsonObject Keyed(ProjectSettings settings)
|
||||
{
|
||||
var project = JsonNode.Parse(settings.ToJson())!.AsObject();
|
||||
if (project[PendingPath] is JsonArray pending)
|
||||
{
|
||||
var keyed = new JsonObject();
|
||||
foreach (var entry in pending) keyed[KeyOf(entry)] = entry?.DeepClone();
|
||||
project[PendingPath] = keyed;
|
||||
}
|
||||
return project;
|
||||
}
|
||||
|
||||
/// <summary>A keyed project back as settings: pending frames as a list again, without those that no longer hold a position.</summary>
|
||||
private static ProjectSettings FromKeyed(JsonObject project)
|
||||
{
|
||||
if (project[PendingPath] is JsonObject keyed)
|
||||
{
|
||||
var list = new JsonArray();
|
||||
foreach (var (_, entry) in keyed)
|
||||
{
|
||||
if (entry is JsonObject e && !Waits(e)) continue;
|
||||
list.Add(entry?.DeepClone());
|
||||
}
|
||||
if (list.Count == 0) project.Remove(PendingPath);
|
||||
else project[PendingPath] = list;
|
||||
}
|
||||
return ProjectSettings.FromJson(project.ToJsonString(), allowNewer: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The key of a pending entry: its photo and which copy of it ("sha:…#0", or "photo:size@ticks#0" for a photo not hashed),
|
||||
/// or its JSON for an entry naming no photo.
|
||||
/// </summary>
|
||||
private static string KeyOf(JsonNode? entry)
|
||||
{
|
||||
if (entry is JsonObject e)
|
||||
{
|
||||
var occurrence = e["occurrence"] is JsonValue o && o.TryGetValue<int>(out var n) ? n : 0;
|
||||
if (e["sha256"] is JsonValue s && s.TryGetValue<string>(out var sha) && sha.Length > 0)
|
||||
return string.Create(CultureInfo.InvariantCulture, $"sha:{sha.ToLowerInvariant()}#{occurrence}");
|
||||
var size = e["size"] is JsonValue z && z.TryGetValue<long>(out var bytes) ? bytes : 0;
|
||||
if (e["capturedAt"] is JsonValue c && c.TryGetValue<DateTime>(out var at))
|
||||
return string.Create(CultureInfo.InvariantCulture, $"photo:{size}@{at.Ticks}#{occurrence}");
|
||||
}
|
||||
return "raw:" + (entry?.ToJsonString() ?? "null");
|
||||
}
|
||||
|
||||
/// <summary>The entry of the photo of <paramref name="template"/> holding no position; null for an entry naming no photo.</summary>
|
||||
private static JsonNode? Unplaced(JsonNode? template)
|
||||
{
|
||||
if (template is not JsonObject entry || KeyOf(entry).StartsWith("raw:", StringComparison.Ordinal)) return null;
|
||||
var empty = new JsonObject();
|
||||
foreach (var name in new[] { "sha256", "size", "capturedAt", "occurrence" })
|
||||
{
|
||||
if (entry[name] is { } value) empty[name] = value.DeepClone();
|
||||
}
|
||||
empty["excluded"] = false;
|
||||
empty["hero"] = false;
|
||||
empty["keyframes"] = new JsonArray();
|
||||
return empty;
|
||||
}
|
||||
|
||||
private static bool Flag(JsonObject entry, string name) => entry[name] is JsonValue value && value.TryGetValue<bool>(out var set) && set;
|
||||
|
||||
/// <summary>A pending entry still holds a position (its unknown members count too: they are not this Chronos's to drop).</summary>
|
||||
private static bool Waits(JsonObject entry) =>
|
||||
Flag(entry, "excluded") || Flag(entry, "hero") || entry["keyframes"] is JsonArray { Count: > 0 }
|
||||
|| entry.Any(p => p.Key is not ("sha256" or "size" or "capturedAt" or "occurrence" or "excluded" or "hero" or "keyframes"));
|
||||
|
||||
/// <summary>One outside change (<paramref name="basis"/> → <paramref name="theirs"/>) applied to any number of projects made from the basis.</summary>
|
||||
public sealed class Rebase(ProjectSettings basis, ProjectSettings theirs)
|
||||
{
|
||||
public ProjectSettings Apply(ProjectSettings ours)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ours);
|
||||
return Merge(basis, ours, theirs);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A project's JSON text as settings, a newer Chronos's too (read-only there).</summary>
|
||||
/// <exception cref="InvalidDataException">The text is not a project.</exception>
|
||||
internal static ProjectSettings Read(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ProjectSettings.FromJson(json, allowNewer: true);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException(ex.Message, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,588 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.Data.Projects;
|
||||
|
||||
/// <summary>Why a project operation was refused (<see cref="ProjectException.Reason"/>).</summary>
|
||||
public enum ProjectError
|
||||
{
|
||||
/// <summary>The sequence is not in the index.</summary>
|
||||
SequenceNotFound,
|
||||
|
||||
/// <summary>The project (or the version named) does not exist, or was deleted.</summary>
|
||||
NotFound,
|
||||
|
||||
/// <summary>The name is blank or longer than <see cref="ProjectService.MaxNameLength"/>.</summary>
|
||||
InvalidName,
|
||||
|
||||
/// <summary>Another project of the sequence has that name (case does not count).</summary>
|
||||
NameTaken,
|
||||
|
||||
/// <summary>The Main project cannot be deleted: it holds the sequence's own settings.</summary>
|
||||
MainCannotBeDeleted,
|
||||
}
|
||||
|
||||
/// <summary>A project operation was refused; nothing was written.</summary>
|
||||
public sealed class ProjectException(ProjectError reason, string message) : InvalidOperationException(message)
|
||||
{
|
||||
public ProjectError Reason { get; } = reason;
|
||||
}
|
||||
|
||||
/// <summary>What became of a version pushed to its home (<see cref="ProjectService.PushAsync"/>).</summary>
|
||||
public enum PushOutcome
|
||||
{
|
||||
/// <summary>Stored as the project's new head (its parent was the head: a fast-forward).</summary>
|
||||
Stored,
|
||||
|
||||
/// <summary>A version with that id is stored already (a push repeated after its answer was lost): nothing changed.</summary>
|
||||
AlreadyStored,
|
||||
|
||||
/// <summary>The head moved since the version's parent: pull the head, replay the version on it and push again.</summary>
|
||||
Diverged,
|
||||
|
||||
/// <summary>The settings do not match the content hash sent with them: nothing was stored.</summary>
|
||||
HashMismatch,
|
||||
|
||||
/// <summary>The settings are of a newer format than this home reads: nothing was stored.</summary>
|
||||
NewerFormat,
|
||||
|
||||
/// <summary>Not a version of this project: settings that are not portable (they name frames by position), or an id another project holds.</summary>
|
||||
Invalid,
|
||||
}
|
||||
|
||||
/// <summary>The answer to a push: the outcome, the version as stored (<see cref="PushOutcome.Stored"/>, <see cref="PushOutcome.AlreadyStored"/>) and the project's head.</summary>
|
||||
public sealed record PushResult(PushOutcome Outcome, ProjectVersion? Version, ProjectVersion? Head);
|
||||
|
||||
/// <summary>
|
||||
/// The frames of a sequence at its home, as project settings name them: their frames version, rows in index order and
|
||||
/// photos (<see cref="FramePhotos"/>, for <see cref="ProjectContent"/>).
|
||||
/// </summary>
|
||||
public sealed record HomeFrames(int FramesVersion, IReadOnlyList<Frame> Frames, FramePhotos Photos);
|
||||
|
||||
/// <summary>
|
||||
/// The projects of the sequences of this PC's archives (owner review 2, R8): the home side of a workspace's push and pull.
|
||||
/// Every operation runs under the sequence's lease and first catches up: the sidecars into the index
|
||||
/// (<see cref="ProjectIndexer"/>), the Main project made when the sequence has none (version 1, "imported" from the
|
||||
/// sequence's settings), and settings another path wrote into the sequence since the last mirror appended to Main as an
|
||||
/// "external" version (or merged with a push whose mirror a crash cut short). A version is written as a sidecar first
|
||||
/// (immutable), then the project's record, then the index; a push to Main is also mirrored into the sequence's
|
||||
/// <c>project.json</c> and settings (positions placed on its frames, through the settings version check), so the code
|
||||
/// paths that read the sequence's settings keep working and only Main drives the hero frame the Library shows. Other
|
||||
/// projects stay on this home: copies of a sequence linked to a server sync only its settings, i.e. Main.
|
||||
/// </summary>
|
||||
public sealed class ProjectService
|
||||
{
|
||||
/// <summary>The name of the project made for every sequence (the desktop shows it in the UI language).</summary>
|
||||
public const string MainName = "Main";
|
||||
|
||||
public const int MaxNameLength = 60;
|
||||
|
||||
/// <summary>Frames read at once when a sequence's photos are gathered.</summary>
|
||||
private const int PageSize = 1000;
|
||||
|
||||
/// <summary>How long a read waits for a sequence another writer holds before it answers from the index alone.</summary>
|
||||
private static readonly TimeSpan ReadWait = TimeSpan.FromSeconds(3);
|
||||
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly SequenceWriter _writer;
|
||||
private readonly ProjectIndexer _indexer;
|
||||
|
||||
internal ProjectService(ChronosDatabase db, SequenceWriter writer)
|
||||
{
|
||||
_db = db;
|
||||
_writer = writer;
|
||||
_indexer = new ProjectIndexer(db);
|
||||
}
|
||||
|
||||
/// <summary>The client name versions made here carry (the archive engine's lease owner).</summary>
|
||||
public string ClientName => _writer.Options.Owner;
|
||||
|
||||
/// <summary>The live projects of a sequence, Main first; read from the index alone while the archive is offline.</summary>
|
||||
/// <exception cref="ProjectException">The sequence is not in the index.</exception>
|
||||
public async Task<IReadOnlyList<SequenceProject>> ListAsync(Guid sequenceId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await ReadAsync(sequenceId, cancellationToken).ConfigureAwait(false);
|
||||
return await _db.Projects.ListBySequenceAsync(sequenceId, includeDeleted: false, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The sequence's Main project, made now (from its settings) when it has none.</summary>
|
||||
/// <exception cref="ProjectException">The sequence is not in the index.</exception>
|
||||
/// <exception cref="ArchiveOfflineException">The archive is offline and the index has no Main project yet.</exception>
|
||||
public async Task<SequenceProject> MainAsync(Guid sequenceId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await ReadAsync(sequenceId, cancellationToken).ConfigureAwait(false);
|
||||
if (await _db.Projects.GetMainAsync(sequenceId, cancellationToken).ConfigureAwait(false) is { } main) return main;
|
||||
// The catch-up could not run (the archive offline, the sequence busy): it runs now, or says why it cannot.
|
||||
return await UnderLeaseAsync(sequenceId, async (_, ct) => (await _db.Projects.GetMainAsync(sequenceId, ct).ConfigureAwait(false))!, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public Task<SequenceProject?> GetAsync(Guid projectId, CancellationToken cancellationToken = default) => _db.Projects.GetAsync(projectId, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// A new project of the sequence named <paramref name="name"/>, whose first version (kind "imported") holds the settings of
|
||||
/// <paramref name="fromVersionId"/> (a version of any project of the sequence), or of Main's head.
|
||||
/// </summary>
|
||||
/// <exception cref="ProjectException">Unknown sequence or version, or the name is invalid or taken.</exception>
|
||||
public Task<SequenceProject> CreateAsync(Guid sequenceId, string name, Guid? fromVersionId = null, string? author = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var trimmed = ValidName(name);
|
||||
return UnderLeaseAsync(sequenceId, async (context, ct) =>
|
||||
{
|
||||
await EnsureNameFreeAsync(sequenceId, null, trimmed, ct).ConfigureAwait(false);
|
||||
ProjectVersion source;
|
||||
if (fromVersionId is { } from)
|
||||
{
|
||||
source = await _db.Projects.GetVersionAsync(from, ct).ConfigureAwait(false) is { } version
|
||||
&& await _db.Projects.GetAsync(version.ProjectId, ct).ConfigureAwait(false) is { SequenceId: var owner } && owner == sequenceId
|
||||
? version
|
||||
: throw new ProjectException(ProjectError.NotFound, $"Version {from} is not a version of sequence {sequenceId}.");
|
||||
}
|
||||
else
|
||||
{
|
||||
var main = (await _db.Projects.GetMainAsync(sequenceId, ct).ConfigureAwait(false))!;
|
||||
source = (await _db.Projects.GetVersionAsync(main.HeadVersionId!.Value, ct).ConfigureAwait(false))!;
|
||||
}
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var project = new SequenceProject
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
SequenceId = sequenceId,
|
||||
Name = trimmed,
|
||||
CreatedBy = author,
|
||||
CreatedAt = now,
|
||||
UpdatedAt = now,
|
||||
};
|
||||
var first = new ProjectVersion
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ProjectId = project.Id,
|
||||
Number = 1,
|
||||
Kind = ProjectVersionKind.Imported,
|
||||
Author = author,
|
||||
ClientName = ClientName,
|
||||
SettingsJson = source.SettingsJson,
|
||||
ContentHash = source.ContentHash,
|
||||
SettingsFormat = source.SettingsFormat,
|
||||
FramesVersion = source.FramesVersion,
|
||||
CreatedAt = now,
|
||||
StoredAt = now,
|
||||
};
|
||||
return await AddProjectAsync(context.Folder, project, first, ct).ConfigureAwait(false);
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Gives a project another name.</summary>
|
||||
/// <exception cref="ProjectException">Unknown project, or the name is invalid or taken.</exception>
|
||||
public async Task<SequenceProject> RenameAsync(Guid projectId, string name, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var trimmed = ValidName(name);
|
||||
var project = await LiveAsync(projectId, cancellationToken).ConfigureAwait(false);
|
||||
return await UnderLeaseAsync(project.SequenceId, async (context, ct) =>
|
||||
{
|
||||
var current = await LiveAsync(projectId, ct).ConfigureAwait(false);
|
||||
if (current.Name == trimmed) return current;
|
||||
await EnsureNameFreeAsync(current.SequenceId, projectId, trimmed, ct).ConfigureAwait(false);
|
||||
var renamed = current with { Name = trimmed, UpdatedAt = DateTimeOffset.UtcNow };
|
||||
ProjectSidecars.WriteRecord(context.Folder.ProjectRecordPath(projectId), ProjectRecord.Of(renamed));
|
||||
await _db.Projects.UpdateAsync(renamed, ct).ConfigureAwait(false);
|
||||
return renamed;
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a project: its record says so, its folder moves to <c>.chronos/projects/.trash</c> (kept, never erased by
|
||||
/// Chronos) and it leaves the listing.
|
||||
/// </summary>
|
||||
/// <exception cref="ProjectException">Unknown project, or the Main project.</exception>
|
||||
public async Task DeleteAsync(Guid projectId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var project = await LiveAsync(projectId, cancellationToken).ConfigureAwait(false);
|
||||
if (project.IsMain) throw new ProjectException(ProjectError.MainCannotBeDeleted, "The Main project cannot be deleted.");
|
||||
await UnderLeaseAsync(project.SequenceId, async (context, ct) =>
|
||||
{
|
||||
var current = await LiveAsync(projectId, ct).ConfigureAwait(false);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var deleted = current with { DeletedAt = now, UpdatedAt = now };
|
||||
ProjectSidecars.WriteRecord(context.Folder.ProjectRecordPath(projectId), ProjectRecord.Of(deleted));
|
||||
Directory.CreateDirectory(context.Folder.ProjectsTrashDirectory);
|
||||
Directory.Move(context.Folder.ProjectDirectory(projectId),
|
||||
Path.Combine(context.Folder.ProjectsTrashDirectory, projectId.ToString("N") + "-" + now.UtcTicks.ToString(System.Globalization.CultureInfo.InvariantCulture)));
|
||||
await _db.Projects.UpdateAsync(deleted, ct).ConfigureAwait(false);
|
||||
return true;
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>One page of a project's history, newest first: the versions numbered below <paramref name="beforeNumber"/> (from the head when null).</summary>
|
||||
/// <exception cref="ProjectException">Unknown project.</exception>
|
||||
public async Task<IReadOnlyList<ProjectVersion>> HistoryAsync(Guid projectId, int? beforeNumber = null, int limit = 50, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var project = await KnownAsync(projectId, cancellationToken).ConfigureAwait(false);
|
||||
await ReadAsync(project.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
return await _db.Projects.ListVersionsAsync(projectId, beforeNumber, limit, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The versions numbered above <paramref name="afterNumber"/>, oldest first: what a workspace pulls.</summary>
|
||||
/// <exception cref="ProjectException">Unknown project.</exception>
|
||||
public async Task<IReadOnlyList<ProjectVersion>> VersionsAfterAsync(Guid projectId, int afterNumber, int limit = 100, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var project = await KnownAsync(projectId, cancellationToken).ConfigureAwait(false);
|
||||
await ReadAsync(project.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
return await _db.Projects.ListVersionsAfterAsync(projectId, afterNumber, limit, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>A version by id; null when the index has none.</summary>
|
||||
public Task<ProjectVersion?> GetVersionAsync(Guid versionId, CancellationToken cancellationToken = default) =>
|
||||
_db.Projects.GetVersionAsync(versionId, cancellationToken);
|
||||
|
||||
/// <summary>The newest version of a project, after catching up.</summary>
|
||||
/// <exception cref="ProjectException">Unknown project.</exception>
|
||||
public async Task<ProjectVersion> 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);
|
||||
return await _db.Projects.GetVersionAsync(project.HeadVersionId ?? Guid.Empty, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ProjectException(ProjectError.NotFound, $"Project {projectId} has no version.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores <paramref name="version"/> (made in a workspace from its <see cref="ProjectVersion.ParentId"/>) as the
|
||||
/// project's new head when its parent is the head: its number is the head's plus one, whatever it says. Repeated with
|
||||
/// the id of a stored version, it answers as the first time. Its settings must be portable (positions parked by photo)
|
||||
/// and match their content hash. A version of Main is mirrored into the sequence's settings.
|
||||
/// </summary>
|
||||
/// <exception cref="ProjectException">Unknown project.</exception>
|
||||
public async Task<PushResult> PushAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(version);
|
||||
var project = await LiveAsync(projectId, cancellationToken).ConfigureAwait(false);
|
||||
return await UnderLeaseAsync(project.SequenceId, async (context, ct) =>
|
||||
{
|
||||
var current = await LiveAsync(projectId, ct).ConfigureAwait(false);
|
||||
var head = await _db.Projects.GetVersionAsync(current.HeadVersionId ?? Guid.Empty, ct).ConfigureAwait(false);
|
||||
if (await _db.Projects.GetVersionAsync(version.Id, ct).ConfigureAwait(false) is { } existing)
|
||||
{
|
||||
return existing.ProjectId == projectId && string.Equals(existing.ContentHash, version.ContentHash, StringComparison.OrdinalIgnoreCase)
|
||||
? new PushResult(PushOutcome.AlreadyStored, existing, head)
|
||||
: new PushResult(PushOutcome.Invalid, null, head);
|
||||
}
|
||||
if (!ProjectContent.Verifies(version.SettingsJson, version.ContentHash)) return new PushResult(PushOutcome.HashMismatch, null, head);
|
||||
var format = ProjectContent.FormatOf(version.SettingsJson);
|
||||
if (format > ProjectSettings.CurrentVersion) return new PushResult(PushOutcome.NewerFormat, null, head);
|
||||
if (!IsPortable(version.SettingsJson)) return new PushResult(PushOutcome.Invalid, null, head);
|
||||
if (version.ParentId != current.HeadVersionId) return new PushResult(PushOutcome.Diverged, null, head);
|
||||
var stored = version with
|
||||
{
|
||||
ProjectId = projectId,
|
||||
Number = current.HeadNumber + 1,
|
||||
ContentHash = version.ContentHash.ToLowerInvariant(),
|
||||
SettingsFormat = format,
|
||||
StoredAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
current = await AppendAsync(context.Folder, current, stored, ct).ConfigureAwait(false);
|
||||
if (current.IsMain) await MirrorAsync(context, current, stored, ct).ConfigureAwait(false);
|
||||
return new PushResult(PushOutcome.Stored, stored, stored);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The frames of a sequence as they are indexed now, with its frames version.</summary>
|
||||
/// <exception cref="ProjectException">The sequence is not in the index.</exception>
|
||||
public async Task<HomeFrames> FramesAsync(Guid sequenceId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
var before = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? throw SequenceMissing(sequenceId);
|
||||
var frames = await LoadFramesAsync(sequenceId, cancellationToken).ConfigureAwait(false);
|
||||
var after = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? throw SequenceMissing(sequenceId);
|
||||
if (after.FramesVersion == before.FramesVersion || attempt == 2) return new HomeFrames(after.FramesVersion, frames.Frames, frames.Photos);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Catches the sequence's projects up under its lease (see the class remarks) before a read; the index alone answers while
|
||||
/// the archive is offline or the sequence busy for longer than the lease wait.
|
||||
/// </summary>
|
||||
private async Task ReadAsync(Guid sequenceId, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await UnderLeaseAsync(sequenceId, (_, _) => Task.FromResult(true), cancellationToken, ReadWait).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is ArchiveOfflineException or LeaseUnavailableException)
|
||||
{
|
||||
Log.Info("projects", $"The projects of sequence {sequenceId} are read from the index: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Runs <paramref name="work"/> under the sequence's lease, after catching its projects up.</summary>
|
||||
private async Task<T> UnderLeaseAsync<T>(Guid sequenceId, Func<LeaseContext, CancellationToken, Task<T>> work, CancellationToken cancellationToken,
|
||||
TimeSpan? wait = null)
|
||||
{
|
||||
var sequence = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? throw SequenceMissing(sequenceId);
|
||||
var archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false) ?? throw SequenceMissing(sequenceId);
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
await using (await _writer.LockAsync(paths, sequenceId, wait, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var row = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? throw SequenceMissing(sequenceId);
|
||||
var context = new LeaseContext(paths.Sequence(row.Folder), row);
|
||||
await CatchUpAsync(context, cancellationToken).ConfigureAwait(false);
|
||||
return await work(context, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The sidecars into the index, the Main project made, and Main in step with the sequence's settings.</summary>
|
||||
private async Task CatchUpAsync(LeaseContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
await _indexer.ReconcileAsync(context.Folder, context.Row.Id, cancellationToken).ConfigureAwait(false);
|
||||
var main = await _db.Projects.GetMainAsync(context.Row.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (main?.HeadVersionId is null)
|
||||
{
|
||||
await MakeMainAsync(context, main, cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
if (main.MirroredVersionId == main.HeadVersionId && main.MirroredSettingsVersion == context.Row.SettingsVersion) return;
|
||||
var head = (await _db.Projects.GetVersionAsync(main.HeadVersionId.Value, cancellationToken).ConfigureAwait(false))!;
|
||||
var frames = await LoadFramesAsync(context.Row.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (CurrentPortable(context, frames.Photos) is not { } current)
|
||||
{
|
||||
// Settings no Chronos can read (or of a newer one): left as they are, recorded as seen.
|
||||
await _db.Projects.SetMirroredAsync(main.Id, main.HeadVersionId, context.Row.SettingsVersion, cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
var sameAsHead = ProjectContent.Hash(current) == head.ContentHash;
|
||||
if (main.MirroredVersionId == main.HeadVersionId || main.MirroredVersionId is null)
|
||||
{
|
||||
// Only the sequence's settings version moved (settings another path wrote, or only its title or tags), or the index
|
||||
// was rebuilt and knows no mirror: settings that differ from the head are its newest state.
|
||||
var latest = sameAsHead ? head : await AppendDerivedAsync(context, main, head, current, ProjectVersionKind.External, cancellationToken).ConfigureAwait(false);
|
||||
await _db.Projects.SetMirroredAsync(main.Id, latest.Id, context.Row.SettingsVersion, cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
// The head is newer than the mirror: a push whose mirror a crash (or a settings edit at the same moment) cut short.
|
||||
if (sameAsHead)
|
||||
{
|
||||
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.Hash(current) == mirrored.ContentHash)
|
||||
{
|
||||
// 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).
|
||||
var merged = ProjectMerge.Merge(ProjectMerge.Read(mirrored.SettingsJson), ProjectMerge.Read(head.SettingsJson), ProjectMerge.Read(current));
|
||||
var version = await AppendDerivedAsync(context, main, head, ProjectContent.Canonical(merged.ToJson()), ProjectVersionKind.Merge, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
main = (await _db.Projects.GetAsync(main.Id, cancellationToken).ConfigureAwait(false))!;
|
||||
await MirrorAsync(context, main, version, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The Main project of a sequence that has none (or one without versions): version 1 from the sequence's settings.</summary>
|
||||
private async Task MakeMainAsync(LeaseContext context, SequenceProject? existing, CancellationToken cancellationToken)
|
||||
{
|
||||
var frames = await LoadFramesAsync(context.Row.Id, cancellationToken).ConfigureAwait(false);
|
||||
var portable = CurrentPortable(context, frames.Photos) ?? ProjectContent.ToPortable(new ProjectSettings(), frames.Photos);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var project = existing ?? new SequenceProject
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
SequenceId = context.Row.Id,
|
||||
Name = await FreeMainNameAsync(context.Row.Id, cancellationToken).ConfigureAwait(false),
|
||||
IsMain = true,
|
||||
CreatedAt = now,
|
||||
UpdatedAt = now,
|
||||
};
|
||||
var first = NewVersion(project.Id, null, project.HeadNumber + 1, ProjectVersionKind.Imported, portable, context.Row.FramesVersion, now);
|
||||
if (existing is null)
|
||||
{
|
||||
await AddProjectAsync(context.Folder, project with { MirroredSettingsVersion = context.Row.SettingsVersion, MirroredVersionId = first.Id }, first,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
var updated = await AppendAsync(context.Folder, existing, first, cancellationToken).ConfigureAwait(false);
|
||||
await _db.Projects.SetMirroredAsync(updated.Id, first.Id, context.Row.SettingsVersion, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"Main", or "Main (2)"… when a project of that name exists already (one made before the sequence had its Main).</summary>
|
||||
private async Task<string> FreeMainNameAsync(Guid sequenceId, CancellationToken cancellationToken)
|
||||
{
|
||||
var names = (await _db.Projects.ListBySequenceAsync(sequenceId, includeDeleted: false, cancellationToken).ConfigureAwait(false))
|
||||
.Select(p => p.Name).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var name = MainName;
|
||||
for (var n = 2; names.Contains(name); n++) name = $"{MainName} ({n})";
|
||||
return name;
|
||||
}
|
||||
|
||||
/// <summary>The portable form of the sequence's settings in force (index, else <c>project.json</c>, else defaults); null when unreadable or newer.</summary>
|
||||
private static string? CurrentPortable(LeaseContext context, FramePhotos photos)
|
||||
{
|
||||
var json = context.Row.SettingsJson ?? (File.Exists(context.Folder.ProjectPath) ? AtomicFile.ReadAllText(context.Folder.ProjectPath) : null)
|
||||
?? new ProjectSettings().ToJson();
|
||||
try
|
||||
{
|
||||
if (ProjectContent.FormatOf(json) > ProjectSettings.CurrentVersion) return null;
|
||||
return ProjectContent.ToPortable(json, photos);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
Log.Warning("projects", $"The settings of sequence {context.Row.Id} cannot be read", ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A version made here (catch-up or merge) appended to Main.</summary>
|
||||
private async Task<ProjectVersion> AppendDerivedAsync(LeaseContext context, SequenceProject main, ProjectVersion head, string portable, ProjectVersionKind kind,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var version = NewVersion(main.Id, head.Id, main.HeadNumber + 1, kind, portable, context.Row.FramesVersion, DateTimeOffset.UtcNow);
|
||||
await AppendAsync(context.Folder, main, version, cancellationToken).ConfigureAwait(false);
|
||||
return version;
|
||||
}
|
||||
|
||||
private ProjectVersion NewVersion(Guid projectId, Guid? parentId, int number, ProjectVersionKind kind, string portable, int framesVersion, DateTimeOffset now) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ProjectId = projectId,
|
||||
ParentId = parentId,
|
||||
Number = number,
|
||||
Kind = kind,
|
||||
ClientName = ClientName,
|
||||
SettingsJson = portable,
|
||||
ContentHash = ProjectContent.Hash(portable),
|
||||
SettingsFormat = ProjectContent.FormatOf(portable),
|
||||
FramesVersion = framesVersion,
|
||||
CreatedAt = now,
|
||||
StoredAt = now,
|
||||
};
|
||||
|
||||
/// <summary>A new project with its first version: sidecars (version, then record), then both rows in one transaction.</summary>
|
||||
private async Task<SequenceProject> AddProjectAsync(SequencePaths folder, SequenceProject project, ProjectVersion first, CancellationToken cancellationToken)
|
||||
{
|
||||
var withHead = project with { HeadVersionId = first.Id, HeadNumber = first.Number };
|
||||
ProjectSidecars.WriteVersion(folder.VersionPath(project.Id, first.Number, first.Id), first);
|
||||
ProjectSidecars.WriteRecord(folder.ProjectRecordPath(project.Id), ProjectRecord.Of(withHead));
|
||||
await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
await tx.Projects.InsertAsync(withHead with { HeadVersionId = null, HeadNumber = 0 }, cancellationToken).ConfigureAwait(false);
|
||||
await tx.Projects.InsertVersionAsync(first, cancellationToken).ConfigureAwait(false);
|
||||
await tx.Projects.UpdateAsync(withHead, cancellationToken).ConfigureAwait(false);
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return withHead;
|
||||
}
|
||||
|
||||
/// <summary>A version appended to a project: its sidecar, the record's head, then the version row and the head in one transaction.</summary>
|
||||
private async Task<SequenceProject> AppendAsync(SequencePaths folder, SequenceProject project, ProjectVersion version, CancellationToken cancellationToken)
|
||||
{
|
||||
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);
|
||||
ProjectSidecars.WriteRecord(folder.ProjectRecordPath(project.Id), ProjectRecord.Of(advanced));
|
||||
await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
await tx.Projects.InsertVersionAsync(version, cancellationToken).ConfigureAwait(false);
|
||||
if (!await tx.Projects.AdvanceHeadAsync(project.Id, project.HeadNumber, version.Id, version.Number, now, cancellationToken).ConfigureAwait(false))
|
||||
throw new IOException($"The head of project {project.Id} moved in the index while its lease was held.");
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return advanced;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes Main's <paramref name="version"/> into the sequence: its positions placed on the sequence's frames, then
|
||||
/// <c>project.json</c> and the index's settings (and hero frame) with the settings version as the check. Recorded as
|
||||
/// mirrored when the index took it; a settings edit that won the race is caught up by the next operation (merged).
|
||||
/// </summary>
|
||||
private async Task MirrorAsync(LeaseContext context, SequenceProject main, ProjectVersion version, CancellationToken cancellationToken)
|
||||
{
|
||||
var frames = await LoadFramesAsync(context.Row.Id, cancellationToken).ConfigureAwait(false);
|
||||
var placed = ProjectSettings.FromJson(ProjectContent.Place(version.SettingsJson, frames.Photos));
|
||||
var json = placed.ToJson();
|
||||
Directory.CreateDirectory(context.Folder.MetaDirectory);
|
||||
AtomicFile.WriteAllText(context.Folder.ProjectPath, json);
|
||||
var hero = placed.HeroFrame is { } index && (uint)index < (uint)frames.Frames.Count ? frames.Frames[index].Id : Guid.Empty;
|
||||
var result = await _db.Sequences.EditAsync(context.Row.Id, new SequenceEdit { SettingsJson = json, HeroFrameId = hero }, context.Row.SettingsVersion,
|
||||
context.Row.FramesVersion, cancellationToken).ConfigureAwait(false);
|
||||
if (result is { Outcome: SequenceEditOutcome.Updated, Sequence: { } updated })
|
||||
{
|
||||
context.Row = updated;
|
||||
await _db.Projects.SetMirroredAsync(main.Id, version.Id, updated.SettingsVersion, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
Log.Info("projects", $"The settings of sequence {context.Row.Id} changed while version {version.Number} of Main was mirrored; merged next time");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Whether settings name no frame by position (every position parked by photo).</summary>
|
||||
private static bool IsPortable(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonNode.Parse(json, new JsonNodeOptions { PropertyNameCaseInsensitive = true }) is JsonObject project
|
||||
&& project["excludedFrames"] is null or JsonArray { Count: 0 }
|
||||
&& project["heroFrame"] is null
|
||||
&& (project["camera"] is not JsonObject camera || camera["keyframes"] is null or JsonArray { Count: 0 });
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or ArgumentException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<(IReadOnlyList<Frame> Frames, FramePhotos Photos)> LoadFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
|
||||
{
|
||||
var frames = new List<Frame>();
|
||||
for (var after = -1; ;)
|
||||
{
|
||||
var page = await _db.Frames.ListBySequenceAsync(sequenceId, after, PageSize, cancellationToken).ConfigureAwait(false);
|
||||
frames.AddRange(page);
|
||||
if (page.Count < PageSize) break;
|
||||
after = page[^1].Index;
|
||||
}
|
||||
return (frames, new FramePhotos(frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, f.CapturedAt)))));
|
||||
}
|
||||
|
||||
private async Task EnsureNameFreeAsync(Guid sequenceId, Guid? projectId, string name, CancellationToken cancellationToken)
|
||||
{
|
||||
var projects = await _db.Projects.ListBySequenceAsync(sequenceId, includeDeleted: false, cancellationToken).ConfigureAwait(false);
|
||||
if (projects.Any(p => p.Id != projectId && string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase)))
|
||||
throw new ProjectException(ProjectError.NameTaken, $"Sequence {sequenceId} has a project named '{name}'.");
|
||||
}
|
||||
|
||||
private static string ValidName(string name)
|
||||
{
|
||||
var trimmed = name?.Trim() ?? string.Empty;
|
||||
return trimmed.Length is > 0 and <= MaxNameLength && !trimmed.Any(char.IsControl)
|
||||
? trimmed
|
||||
: throw new ProjectException(ProjectError.InvalidName, "A project name has 1 to 60 characters.");
|
||||
}
|
||||
|
||||
private async Task<SequenceProject> KnownAsync(Guid projectId, CancellationToken cancellationToken) =>
|
||||
await _db.Projects.GetAsync(projectId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ProjectException(ProjectError.NotFound, $"Project {projectId} does not exist.");
|
||||
|
||||
private async Task<SequenceProject> LiveAsync(Guid projectId, CancellationToken cancellationToken) =>
|
||||
await KnownAsync(projectId, cancellationToken).ConfigureAwait(false) is { DeletedAt: null } project
|
||||
? project
|
||||
: throw new ProjectException(ProjectError.NotFound, $"Project {projectId} was deleted.");
|
||||
|
||||
private static ProjectException SequenceMissing(Guid sequenceId) => new(ProjectError.SequenceNotFound, $"Sequence {sequenceId} is not in the index.");
|
||||
|
||||
/// <summary>The sequence as read under its lease (the mirror moves its settings version) and its folder.</summary>
|
||||
private sealed class LeaseContext(SequencePaths folder, Sequence row)
|
||||
{
|
||||
public SequencePaths Folder { get; } = folder;
|
||||
public Sequence Row { get; set; } = row;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
|
||||
namespace Chronos.Data.Projects;
|
||||
|
||||
/// <summary>The newest version of a project as its record names it: id and number.</summary>
|
||||
public sealed record ProjectHead(Guid Id, int Number);
|
||||
|
||||
/// <summary>
|
||||
/// The record of a project in its folder (<c>.chronos/projects/<id>/project.json</c>): what the index row is rebuilt
|
||||
/// from. <see cref="Deleted"/> is set when the project was deleted, before its folder moves to the projects' trash.
|
||||
/// </summary>
|
||||
public sealed record ProjectRecord(Guid Id, Guid SequenceId, string Name, bool IsMain, ProjectHead? Head, DateTimeOffset Created, string? CreatedBy,
|
||||
DateTimeOffset Updated, DateTimeOffset? Deleted = null)
|
||||
{
|
||||
/// <summary>The record of an index row.</summary>
|
||||
public static ProjectRecord Of(SequenceProject project)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
return new ProjectRecord(project.Id, project.SequenceId, project.Name, project.IsMain,
|
||||
project.HeadVersionId is { } head ? new ProjectHead(head, project.HeadNumber) : null, project.CreatedAt, project.CreatedBy, project.UpdatedAt,
|
||||
project.DeletedAt);
|
||||
}
|
||||
|
||||
/// <summary>The index row of this record (nothing mirrored known yet).</summary>
|
||||
public SequenceProject ToProject() => new()
|
||||
{
|
||||
Id = Id,
|
||||
SequenceId = SequenceId,
|
||||
Name = Name,
|
||||
IsMain = IsMain,
|
||||
HeadVersionId = Head?.Id,
|
||||
HeadNumber = Head?.Number ?? 0,
|
||||
CreatedBy = CreatedBy,
|
||||
CreatedAt = Created,
|
||||
UpdatedAt = Updated,
|
||||
DeletedAt = Deleted,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The files of projects (owner review 2, R8), the same in an archive and in a workspace: the record of a project
|
||||
/// (<see cref="ProjectRecord"/>) and one file per version, immutable once written:
|
||||
/// <code>{ "format": "chronos-project-version", "formatVersion": 1, "id", "projectId", "parentId", "number", "kind",
|
||||
/// "author", "clientName", "note", "settingsFormat", "framesVersion", "contentHash", "restoredFrom", "created",
|
||||
/// "stored", "settings": "<the portable settings as text>" }</code>
|
||||
/// The settings are a JSON string, so the bytes the content hash covers come back exactly; a version whose text does not
|
||||
/// match its hash is refused as damaged. Writes are atomic (temp, flush, rename).
|
||||
/// </summary>
|
||||
public static class ProjectSidecars
|
||||
{
|
||||
public const string RecordFormat = "chronos-project-record";
|
||||
public const string VersionFormat = "chronos-project-version";
|
||||
public const int FormatVersion = 1;
|
||||
|
||||
/// <summary>A version file is a few kilobytes; a larger one is not read.</summary>
|
||||
public const int MaxVersionBytes = 8 << 20;
|
||||
|
||||
private static readonly JsonWriterOptions Indented = new() { Indented = true };
|
||||
|
||||
/// <summary>
|
||||
/// Writes a version file. A version is immutable: an existing file is left when it holds the same version (same id
|
||||
/// and content hash) and refused otherwise, unless <paramref name="replace"/> (a workspace's own copy of a version,
|
||||
/// stored at its home since).
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">Another version is at that path.</exception>
|
||||
public static void WriteVersion(string path, ProjectVersion version, bool replace = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(version);
|
||||
if (!replace && File.Exists(path))
|
||||
{
|
||||
ProjectVersion existing;
|
||||
try
|
||||
{
|
||||
existing = ReadVersion(path);
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
// A damaged file is never overwritten: it is moved aside, kept.
|
||||
File.Move(path, path + ".damaged-" + DateTime.UtcNow.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture));
|
||||
existing = null!;
|
||||
}
|
||||
if (existing is not null)
|
||||
{
|
||||
if (existing.Id == version.Id && string.Equals(existing.ContentHash, version.ContentHash, StringComparison.OrdinalIgnoreCase)) return;
|
||||
throw new IOException($"{path} holds another version ({existing.Id}).");
|
||||
}
|
||||
}
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
AtomicFile.WriteAllText(path, VersionJson(version));
|
||||
}
|
||||
|
||||
/// <summary>Reads a version file and checks its content hash.</summary>
|
||||
/// <exception cref="InvalidDataException">Not a version file, damaged, newer, or its settings do not match their hash.</exception>
|
||||
/// <exception cref="IOException">The file cannot be read.</exception>
|
||||
public static ProjectVersion ReadVersion(string path)
|
||||
{
|
||||
if (new FileInfo(path).Length > MaxVersionBytes) throw new InvalidDataException($"{path} is too large to be a project version.");
|
||||
return ParseVersion(AtomicFile.ReadAllText(path), path);
|
||||
}
|
||||
|
||||
/// <summary>The text of a version file.</summary>
|
||||
public static string VersionJson(ProjectVersion version)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(version);
|
||||
using var buffer = new MemoryStream();
|
||||
using (var w = new Utf8JsonWriter(buffer, Indented))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("format", VersionFormat);
|
||||
w.WriteNumber("formatVersion", FormatVersion);
|
||||
w.WriteString("id", version.Id);
|
||||
w.WriteString("projectId", version.ProjectId);
|
||||
if (version.ParentId is { } parent) w.WriteString("parentId", parent);
|
||||
w.WriteNumber("number", version.Number);
|
||||
w.WriteString("kind", ProjectVersionKinds.Name(version.Kind));
|
||||
if (version.Author is { } author) w.WriteString("author", author);
|
||||
if (version.ClientName is { } client) w.WriteString("clientName", client);
|
||||
if (version.Note is { } note) w.WriteString("note", note);
|
||||
w.WriteNumber("settingsFormat", version.SettingsFormat);
|
||||
w.WriteNumber("framesVersion", version.FramesVersion);
|
||||
w.WriteString("contentHash", version.ContentHash.ToLowerInvariant());
|
||||
if (version.RestoredFrom is { } restored) w.WriteString("restoredFrom", restored);
|
||||
w.WriteString("created", version.CreatedAt);
|
||||
if (version.StoredAt is { } stored) w.WriteString("stored", stored);
|
||||
w.WriteString("settings", version.SettingsJson);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
return Encoding.UTF8.GetString(buffer.GetBuffer(), 0, (int)buffer.Length);
|
||||
}
|
||||
|
||||
/// <summary>Reads a version file's text (<paramref name="source"/> names it in errors) and checks its content hash.</summary>
|
||||
/// <exception cref="InvalidDataException">Not a version file, damaged, newer, or its settings do not match their hash.</exception>
|
||||
public static ProjectVersion ParseVersion(string json, string source)
|
||||
{
|
||||
using var document = Parse(json, source);
|
||||
var root = document.RootElement;
|
||||
Check(root, VersionFormat, source);
|
||||
var settings = Text(root, "settings") ?? throw new InvalidDataException($"{source} holds no settings.");
|
||||
var hash = Text(root, "contentHash") ?? throw new InvalidDataException($"{source} has no content hash.");
|
||||
if (!ProjectContent.Verifies(settings, hash)) throw new InvalidDataException($"The settings in {source} do not match their content hash.");
|
||||
return new ProjectVersion
|
||||
{
|
||||
Id = Id(root, "id") ?? throw new InvalidDataException($"{source} has no version id."),
|
||||
ProjectId = Id(root, "projectId") ?? throw new InvalidDataException($"{source} names no project."),
|
||||
ParentId = Id(root, "parentId"),
|
||||
Number = Int(root, "number") is { } number and > 0 ? number : throw new InvalidDataException($"{source} has no version number."),
|
||||
Kind = ProjectVersionKinds.Parse(Text(root, "kind")),
|
||||
Author = Text(root, "author"),
|
||||
ClientName = Text(root, "clientName"),
|
||||
Note = Text(root, "note"),
|
||||
SettingsJson = settings,
|
||||
ContentHash = hash.ToLowerInvariant(),
|
||||
SettingsFormat = Int(root, "settingsFormat") ?? ProjectContent.FormatOf(settings),
|
||||
FramesVersion = Int(root, "framesVersion") ?? 0,
|
||||
RestoredFrom = Id(root, "restoredFrom"),
|
||||
CreatedAt = Time(root, "created") ?? default,
|
||||
StoredAt = Time(root, "stored"),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Writes a project's record atomically.</summary>
|
||||
public static void WriteRecord(string path, ProjectRecord record)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(record);
|
||||
using var buffer = new MemoryStream();
|
||||
using (var w = new Utf8JsonWriter(buffer, Indented))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("format", RecordFormat);
|
||||
w.WriteNumber("formatVersion", FormatVersion);
|
||||
w.WriteString("id", record.Id);
|
||||
w.WriteString("sequenceId", record.SequenceId);
|
||||
w.WriteString("name", record.Name);
|
||||
w.WriteBoolean("isMain", record.IsMain);
|
||||
if (record.Head is { } head)
|
||||
{
|
||||
w.WriteStartObject("head");
|
||||
w.WriteString("id", head.Id);
|
||||
w.WriteNumber("number", head.Number);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteString("created", record.Created);
|
||||
if (record.CreatedBy is { } by) w.WriteString("createdBy", by);
|
||||
w.WriteString("updated", record.Updated);
|
||||
if (record.Deleted is { } deleted) w.WriteString("deleted", deleted);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
AtomicFile.WriteAllBytes(path, buffer.GetBuffer().AsSpan(0, (int)buffer.Length));
|
||||
}
|
||||
|
||||
/// <summary>Reads a project's record.</summary>
|
||||
/// <exception cref="InvalidDataException">Not a project record, damaged or newer.</exception>
|
||||
/// <exception cref="IOException">The file cannot be read.</exception>
|
||||
public static ProjectRecord ReadRecord(string path)
|
||||
{
|
||||
using var document = Parse(AtomicFile.ReadAllText(path), path);
|
||||
var root = document.RootElement;
|
||||
Check(root, RecordFormat, path);
|
||||
ProjectHead? head = null;
|
||||
if (root.TryGetProperty("head", out var h) && h.ValueKind == JsonValueKind.Object && Id(h, "id") is { } headId && Int(h, "number") is { } number and > 0)
|
||||
head = new ProjectHead(headId, number);
|
||||
var name = Text(root, "name");
|
||||
return new ProjectRecord(
|
||||
Id(root, "id") ?? throw new InvalidDataException($"{path} has no project id."),
|
||||
Id(root, "sequenceId") ?? throw new InvalidDataException($"{path} names no sequence."),
|
||||
string.IsNullOrWhiteSpace(name) ? throw new InvalidDataException($"{path} has no name.") : name,
|
||||
root.TryGetProperty("isMain", out var main) && main.ValueKind == JsonValueKind.True,
|
||||
head,
|
||||
Time(root, "created") ?? default,
|
||||
Text(root, "createdBy"),
|
||||
Time(root, "updated") ?? Time(root, "created") ?? default,
|
||||
Time(root, "deleted"));
|
||||
}
|
||||
|
||||
/// <summary>The version files of a folder by number and id (<c>000001-<id>.json</c>), in number order; other files are not listed.</summary>
|
||||
public static IReadOnlyList<(int Number, Guid Id, string Path)> ListVersions(string directory)
|
||||
{
|
||||
if (!Directory.Exists(directory)) return [];
|
||||
var found = new List<(int, Guid, string)>();
|
||||
foreach (var path in Directory.EnumerateFiles(directory, "*.json"))
|
||||
{
|
||||
if (TryParseName(Path.GetFileName(path), out var number, out var id)) found.Add((number, id, path));
|
||||
}
|
||||
return [.. found.OrderBy(f => f.Item1).ThenBy(f => f.Item2)];
|
||||
}
|
||||
|
||||
/// <summary>The number and id a version file name carries (<see cref="ArchiveLayout.ProjectVersionFileName"/>).</summary>
|
||||
public static bool TryParseName(string fileName, out int number, out Guid id)
|
||||
{
|
||||
number = 0;
|
||||
id = Guid.Empty;
|
||||
var name = Path.GetFileNameWithoutExtension(fileName);
|
||||
var dash = name.IndexOf('-', StringComparison.Ordinal);
|
||||
return dash > 0 && Path.GetExtension(fileName).Equals(".json", StringComparison.OrdinalIgnoreCase)
|
||||
&& int.TryParse(name.AsSpan(0, dash), NumberStyles.None, CultureInfo.InvariantCulture, out number) && number > 0
|
||||
&& Guid.TryParseExact(name.AsSpan(dash + 1), "N", out id);
|
||||
}
|
||||
|
||||
private static JsonDocument Parse(string json, string source)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 64 });
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException($"{source} is not valid JSON.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Check(JsonElement root, string format, string source)
|
||||
{
|
||||
if (root.ValueKind != JsonValueKind.Object || Text(root, "format") != format) throw new InvalidDataException($"{source} is not a {format} file.");
|
||||
if (Int(root, "formatVersion") is not { } version || version < 1) throw new InvalidDataException($"{source} has no valid format version.");
|
||||
if (version > FormatVersion) throw new InvalidDataException($"{source} uses format {version}, newer than this Chronos ({FormatVersion}).");
|
||||
}
|
||||
|
||||
private static string? Text(JsonElement element, string name) =>
|
||||
element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
|
||||
|
||||
private static int? Int(JsonElement element, string name) =>
|
||||
element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.Number && value.TryGetInt32(out var number) ? number : null;
|
||||
|
||||
private static Guid? Id(JsonElement element, string name) =>
|
||||
element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String && value.TryGetGuid(out var id) && id != Guid.Empty ? id : null;
|
||||
|
||||
private static DateTimeOffset? Time(JsonElement element, string name) =>
|
||||
element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String && value.TryGetDateTimeOffset(out var time) ? time : null;
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Data.Repositories;
|
||||
|
||||
/// <summary>
|
||||
/// Projects of sequences and their versions (owner review 2, R8; <c>projects</c>, <c>project_versions</c>). The sidecars
|
||||
/// in <c>.chronos/projects/</c> are the truth and are written first (<c>Projects.ProjectService</c>); these rows are
|
||||
/// derived, rebuilt from the sidecars, and go with the sequence's row.
|
||||
/// </summary>
|
||||
public sealed class ProjectRepository
|
||||
{
|
||||
private const string Columns =
|
||||
"id, sequence_id, name, is_main, head_version_id, head_number, mirrored_settings_version, mirrored_version_id, created_by, created_at, " +
|
||||
"updated_at, deleted_at";
|
||||
|
||||
private const string VersionColumns =
|
||||
"id, project_id, parent_id, number, kind, author, client_name, note, settings_json, content_hash, settings_format, frames_version, " +
|
||||
"restored_from, created_at, stored_at";
|
||||
|
||||
private readonly DbAccess _db;
|
||||
|
||||
internal ProjectRepository(DbAccess db) => _db = db;
|
||||
|
||||
/// <summary>The projects of a sequence: Main first, then the others oldest first; deleted ones only when asked.</summary>
|
||||
public Task<IReadOnlyList<SequenceProject>> ListBySequenceAsync(Guid sequenceId, bool includeDeleted = false, CancellationToken cancellationToken = default) =>
|
||||
_db.ListAsync($"SELECT {Columns} FROM projects WHERE sequence_id = $1{(includeDeleted ? string.Empty : " AND deleted_at IS NULL")} " +
|
||||
"ORDER BY is_main DESC, created_at, id", [sequenceId], Map, cancellationToken);
|
||||
|
||||
public Task<SequenceProject?> GetAsync(Guid id, CancellationToken cancellationToken = default) =>
|
||||
_db.SingleAsync($"SELECT {Columns} FROM projects WHERE id = $1", [id], Map, cancellationToken);
|
||||
|
||||
/// <summary>The Main project of a sequence; null until it is made.</summary>
|
||||
public Task<SequenceProject?> GetMainAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
|
||||
_db.SingleAsync($"SELECT {Columns} FROM projects WHERE sequence_id = $1 AND is_main = $2 AND deleted_at IS NULL", [sequenceId, true], Map,
|
||||
cancellationToken);
|
||||
|
||||
/// <summary>Adds a project; a name or a Main another live project of the sequence has already fails (unique).</summary>
|
||||
public Task InsertAsync(SequenceProject project, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
return _db.ExecuteAsync($"INSERT INTO projects ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)",
|
||||
[
|
||||
project.Id, project.SequenceId, project.Name, project.IsMain, project.HeadVersionId, project.HeadNumber, project.MirroredSettingsVersion,
|
||||
project.MirroredVersionId, project.CreatedBy, project.CreatedAt, project.UpdatedAt, project.DeletedAt,
|
||||
], cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Stores every field of <paramref name="project"/> but its id, sequence and creation; false when it is gone.</summary>
|
||||
public async Task<bool> UpdateAsync(SequenceProject project, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
return await _db.ExecuteAsync(
|
||||
"UPDATE projects SET name = $2, is_main = $3, head_version_id = $4, head_number = $5, mirrored_settings_version = $6, mirrored_version_id = $7, " +
|
||||
"updated_at = $8, deleted_at = $9 WHERE id = $1",
|
||||
[
|
||||
project.Id, project.Name, project.IsMain, project.HeadVersionId, project.HeadNumber, project.MirroredSettingsVersion,
|
||||
project.MirroredVersionId, project.UpdatedAt, project.DeletedAt,
|
||||
], cancellationToken).ConfigureAwait(false) > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves the head to <paramref name="headId"/> (number <paramref name="headNumber"/>) only while it is still at
|
||||
/// <paramref name="expectedNumber"/>: two writers never both advance it from the same head. False when it moved.
|
||||
/// </summary>
|
||||
public async Task<bool> AdvanceHeadAsync(Guid projectId, int expectedNumber, Guid headId, int headNumber, DateTimeOffset at,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await _db.ExecuteAsync("UPDATE projects SET head_version_id = $2, head_number = $3, updated_at = $4 WHERE id = $1 AND head_number = $5",
|
||||
[projectId, headId, headNumber, at, expectedNumber], cancellationToken).ConfigureAwait(false) > 0;
|
||||
|
||||
/// <summary>Records the version and the sequence's settings version a Main project's head was last mirrored with.</summary>
|
||||
public async Task<bool> SetMirroredAsync(Guid projectId, Guid? versionId, int settingsVersion, CancellationToken cancellationToken = default) =>
|
||||
await _db.ExecuteAsync("UPDATE projects SET mirrored_version_id = $2, mirrored_settings_version = $3 WHERE id = $1",
|
||||
[projectId, versionId, settingsVersion], cancellationToken).ConfigureAwait(false) > 0;
|
||||
|
||||
/// <summary>Adds a version; a number or id the project has already fails (unique).</summary>
|
||||
public Task InsertVersionAsync(ProjectVersion version, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(version);
|
||||
return _db.ExecuteAsync($"INSERT INTO project_versions ({VersionColumns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)",
|
||||
[
|
||||
version.Id, version.ProjectId, version.ParentId, version.Number, ProjectVersionKinds.Name(version.Kind), version.Author, version.ClientName,
|
||||
version.Note, DbParam.Text(version.SettingsJson), version.ContentHash, version.SettingsFormat, version.FramesVersion, version.RestoredFrom,
|
||||
version.CreatedAt, version.StoredAt ?? version.CreatedAt,
|
||||
], cancellationToken);
|
||||
}
|
||||
|
||||
public Task<ProjectVersion?> GetVersionAsync(Guid id, CancellationToken cancellationToken = default) =>
|
||||
_db.SingleAsync($"SELECT {VersionColumns} FROM project_versions WHERE id = $1", [id], MapVersion, cancellationToken);
|
||||
|
||||
public Task<ProjectVersion?> GetVersionByNumberAsync(Guid projectId, int number, CancellationToken cancellationToken = default) =>
|
||||
_db.SingleAsync($"SELECT {VersionColumns} FROM project_versions WHERE project_id = $1 AND number = $2", [projectId, number], MapVersion,
|
||||
cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// One page of a project's history, newest first: the versions numbered below <paramref name="beforeNumber"/> (all
|
||||
/// when null), at most <paramref name="limit"/> (1–1000).
|
||||
/// </summary>
|
||||
public Task<IReadOnlyList<ProjectVersion>> ListVersionsAsync(Guid projectId, int? beforeNumber, int limit, CancellationToken cancellationToken = default) =>
|
||||
_db.ListAsync($"SELECT {VersionColumns} FROM project_versions WHERE project_id = $1 AND number < $2 ORDER BY number DESC LIMIT $3",
|
||||
[projectId, beforeNumber ?? int.MaxValue, Cursor.ClampLimit(limit)], MapVersion, cancellationToken);
|
||||
|
||||
/// <summary>The versions numbered above <paramref name="afterNumber"/>, oldest first, at most <paramref name="limit"/> (1–1000): what a pull takes.</summary>
|
||||
public Task<IReadOnlyList<ProjectVersion>> ListVersionsAfterAsync(Guid projectId, int afterNumber, int limit, CancellationToken cancellationToken = default) =>
|
||||
_db.ListAsync($"SELECT {VersionColumns} FROM project_versions WHERE project_id = $1 AND number > $2 ORDER BY number LIMIT $3",
|
||||
[projectId, afterNumber, Cursor.ClampLimit(limit)], MapVersion, cancellationToken);
|
||||
|
||||
/// <summary>The id of each version of a project by number (the index's side of a comparison with the sidecars).</summary>
|
||||
public async Task<IReadOnlyDictionary<int, Guid>> ListVersionIdsAsync(Guid projectId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var rows = await _db.ListAsync("SELECT number, id FROM project_versions WHERE project_id = $1", [projectId], r => (r.GetInt32(0), r.GetGuid(1)),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return rows.ToDictionary(r => r.Item1, r => r.Item2);
|
||||
}
|
||||
|
||||
private static SequenceProject Map(DbRow r) => new()
|
||||
{
|
||||
Id = r.GetGuid(0),
|
||||
SequenceId = r.GetGuid(1),
|
||||
Name = r.GetString(2),
|
||||
IsMain = r.GetBool(3),
|
||||
HeadVersionId = r.GetGuidOrNull(4),
|
||||
HeadNumber = r.GetInt32(5),
|
||||
MirroredSettingsVersion = r.GetInt32OrNull(6),
|
||||
MirroredVersionId = r.GetGuidOrNull(7),
|
||||
CreatedBy = r.GetStringOrNull(8),
|
||||
CreatedAt = r.GetDateTimeOffset(9),
|
||||
UpdatedAt = r.GetDateTimeOffset(10),
|
||||
DeletedAt = r.GetDateTimeOffsetOrNull(11),
|
||||
};
|
||||
|
||||
private static ProjectVersion MapVersion(DbRow r) => new()
|
||||
{
|
||||
Id = r.GetGuid(0),
|
||||
ProjectId = r.GetGuid(1),
|
||||
ParentId = r.GetGuidOrNull(2),
|
||||
Number = r.GetInt32(3),
|
||||
Kind = ProjectVersionKinds.Parse(r.GetStringOrNull(4)),
|
||||
Author = r.GetStringOrNull(5),
|
||||
ClientName = r.GetStringOrNull(6),
|
||||
Note = r.GetStringOrNull(7),
|
||||
SettingsJson = r.GetString(8),
|
||||
ContentHash = r.GetString(9),
|
||||
SettingsFormat = r.GetInt32(10),
|
||||
FramesVersion = r.GetInt32(11),
|
||||
RestoredFrom = r.GetGuidOrNull(12),
|
||||
CreatedAt = r.GetDateTimeOffset(13),
|
||||
StoredAt = r.GetDateTimeOffset(14),
|
||||
};
|
||||
}
|
||||
@@ -6,7 +6,8 @@ namespace Chronos.Data.Repositories;
|
||||
public sealed class RenderRepository
|
||||
{
|
||||
private const string Columns =
|
||||
"id, sequence_id, preset_name, settings_json, output_path, codec, width, height, fps, duration_seconds, bytes, created, produced_by";
|
||||
"id, sequence_id, preset_name, settings_json, output_path, codec, width, height, fps, duration_seconds, bytes, created, produced_by, project_id, " +
|
||||
"project_version_id";
|
||||
|
||||
private const string RecountSql =
|
||||
"UPDATE sequences SET rendered_count = (SELECT count(*) FROM renders WHERE sequence_id = $1) WHERE id = $1";
|
||||
@@ -19,10 +20,11 @@ public sealed class RenderRepository
|
||||
_db.InTransactionAsync(async session =>
|
||||
{
|
||||
await LockSequenceAsync(session, render.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
await session.ExecuteAsync($"INSERT INTO renders ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)",
|
||||
await session.ExecuteAsync($"INSERT INTO renders ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)",
|
||||
[
|
||||
render.Id, render.SequenceId, render.PresetName, DbParam.Json(render.SettingsJson), render.OutputPath, render.Codec,
|
||||
render.Width, render.Height, render.Fps, render.DurationSeconds, render.Bytes, render.Created, render.ProducedBy,
|
||||
render.Width, render.Height, render.Fps, render.DurationSeconds, render.Bytes, render.Created, render.ProducedBy, render.ProjectId,
|
||||
render.ProjectVersionId,
|
||||
], cancellationToken).ConfigureAwait(false);
|
||||
return await session.ExecuteAsync(RecountSql, [render.SequenceId], cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken);
|
||||
@@ -106,5 +108,7 @@ public sealed class RenderRepository
|
||||
Bytes = r.GetInt64(10),
|
||||
Created = r.GetDateTimeOffset(11),
|
||||
ProducedBy = r.GetStringOrNull(12),
|
||||
ProjectId = r.GetGuidOrNull(13),
|
||||
ProjectVersionId = r.GetGuidOrNull(14),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
|
||||
namespace Chronos.Data.Workspaces;
|
||||
|
||||
/// <summary>Builds the jobs of the workspace (owner review 2, R8), and their handlers for the desktop's engine.</summary>
|
||||
public static class WorkspaceJobs
|
||||
{
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.WorkspaceCopy"/>: the media of workspace project <paramref name="projectId"/> (checked out first,
|
||||
/// <see cref="WorkspaceSync.CheckoutAsync"/>) copied from its home, the sequence of this PC's archive.
|
||||
/// </summary>
|
||||
public static ArchiveJobRequest Copy(Sequence sequence, string workspaceRoot, Guid projectId, string media = BundleMedia.Proxies)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sequence);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(workspaceRoot);
|
||||
return new ArchiveJobRequest(JobKind.WorkspaceCopy, [sequence.Id], sequence.DisplayTitle,
|
||||
JsonSerializer.Serialize(new WorkspaceCopyParameters(workspaceRoot, projectId, media), WorkspaceJson.Default.WorkspaceCopyParameters), JobPriority.User);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The handlers of the workspace's jobs for a desktop's engine (never a server's: the job writes into a folder its
|
||||
/// parameters name).
|
||||
/// </summary>
|
||||
public static IReadOnlyList<IJobHandler> CreateHandlers(ChronosDatabase db, ArchiveService archives) => [new WorkspaceCopyJobHandler(db, archives)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.WorkspaceCopy"/> for a sequence of this PC's archive (owner review 2, R8): its proxies into the
|
||||
/// workspace project's <c>media/proxies/<frame id>.jpg</c>, the archive's own when current, the missing ones made
|
||||
/// first by the archive's proxy pass (made here from the original when the archive makes none), each written atomically
|
||||
/// and read back to check its SHA-256; then the deep report (<c>media/analysis.json</c>) and, last, <c>media/media.json</c>.
|
||||
/// Frames changed at the home during the copy make it start again (three times at most). The working state's positions
|
||||
/// follow the new frames by photo. Checkpoint: <c>proxies:<frame></c> during the archive's pass, then
|
||||
/// <c>copy:<frame></c>. Originals come in phase 5c: asked for, the job fails saying so.
|
||||
/// </summary>
|
||||
internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService archives) : IJobHandler
|
||||
{
|
||||
private const int PageSize = 1000;
|
||||
private const int Passes = 3;
|
||||
private static readonly TimeSpan LockWait = TimeSpan.FromMinutes(2);
|
||||
private static readonly TimeSpan CheckpointEvery = TimeSpan.FromSeconds(5);
|
||||
|
||||
public JobKind Kind => JobKind.WorkspaceCopy;
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
var ct = context.Cancellation;
|
||||
var parameters = Parameters(context.Job);
|
||||
if (parameters.Media == BundleMedia.Originals) throw new NotSupportedException(Loc.L("Errors.Workspace.OriginalsLater"));
|
||||
if (parameters.Media != BundleMedia.Proxies) throw new InvalidDataException(Loc.L("Errors.Workspace.Parameters"));
|
||||
if (context.Job.TargetIds is not [var sequenceId] || await db.Sequences.GetAsync(sequenceId, ct).ConfigureAwait(false) is not { } sequence
|
||||
|| await db.Archives.GetAsync(sequence.ArchiveId, ct).ConfigureAwait(false) is not { } archive)
|
||||
throw new InvalidOperationException(Loc.L("Archive.Log.SequenceMissing", context.Job.TargetIds.FirstOrDefault()));
|
||||
var store = new WorkspaceStore(parameters.WorkspaceRoot);
|
||||
var project = store.Find(parameters.ProjectId) ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.NotCheckedOut"));
|
||||
if (project.ReadBundle().Workspace is not { Home: { IsArchive: true } home } || home.SequenceId != sequenceId)
|
||||
throw new InvalidOperationException(Loc.L("Errors.Workspace.OtherHome"));
|
||||
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var (stage, next) = Parse(context.Checkpoint);
|
||||
for (var pass = 1; ; pass++)
|
||||
{
|
||||
var (row, frames) = await FramesAsync(sequenceId, ct).ConfigureAwait(false);
|
||||
var policy = ManifestStore.ReadArchive(paths.ManifestPath).ProxyPolicy;
|
||||
var makesProxies = policy.LongEdge != ProxyPolicy.Disabled && ArchiveVolume.Probe(paths) == ArchiveAvailability.Online;
|
||||
var total = (long)frames.Count * (makesProxies ? 2 : 1);
|
||||
long offset = 0;
|
||||
if (makesProxies)
|
||||
{
|
||||
if (stage == Stage.Proxies && (row.Status & SequenceStatus.ProxiesBuilt) == 0)
|
||||
{
|
||||
var result = await archives.Images.BuildProxiesAsync(archive, row, force: false, next,
|
||||
(frame, _) => context.CheckpointAsync(Checkpoint(Stage.Proxies, frame), frame, total), ct).ConfigureAwait(false);
|
||||
context.Log(Loc.L("Archive.Log.ProxiesDone", row.DisplayTitle, result.Built, result.Reused, result.Undecodable, result.Waiting));
|
||||
next = 0;
|
||||
}
|
||||
offset = frames.Count;
|
||||
}
|
||||
// Frames before a copy checkpoint were copied by an earlier run.
|
||||
var copied = stage == Stage.Copy ? next : 0;
|
||||
(stage, next) = (Stage.Copy, 0);
|
||||
var folder = paths.Sequence(row.Folder);
|
||||
var tally = new Tally();
|
||||
var entries = new WorkspaceFrame[frames.Count];
|
||||
Directory.CreateDirectory(project.ProxiesDirectory);
|
||||
var clock = System.Diagnostics.Stopwatch.StartNew();
|
||||
for (var i = 0; i < frames.Count; i++)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
entries[i] = Copy(project, folder, paths, frames[i], policy, done: i < copied, tally, ct);
|
||||
if (clock.Elapsed >= CheckpointEvery)
|
||||
{
|
||||
await context.CheckpointAsync(Checkpoint(Stage.Copy, i + 1), offset + i + 1, total).ConfigureAwait(false);
|
||||
clock.Restart();
|
||||
}
|
||||
else
|
||||
{
|
||||
await context.ReportAsync(offset + i + 1, total).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
var analysis = CopyAnalysis(folder, project, frames.Count);
|
||||
var after = await db.Sequences.GetAsync(sequenceId, ct).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException(Loc.L("Archive.Log.SequenceMissing", sequenceId));
|
||||
if (after.FramesVersion != row.FramesVersion && pass < Passes)
|
||||
{
|
||||
context.Log(Loc.L("Archive.Log.WorkspaceFramesChanged", row.DisplayTitle));
|
||||
(stage, next) = (Stage.Proxies, 0);
|
||||
continue;
|
||||
}
|
||||
var media = new WorkspaceMedia(WorkspaceMedia.FormatName, WorkspaceMedia.CurrentFormatVersion, BundleMedia.Proxies, sequenceId, row.FramesVersion, entries,
|
||||
DateTimeOffset.UtcNow, analysis);
|
||||
// The working state is the editor's meanwhile: it is held only while the media index and the positions move.
|
||||
using (await project.LockAsync(LockWait, ct).ConfigureAwait(false))
|
||||
{
|
||||
Commit(project, project.ReadBundle(), media, row);
|
||||
RemoveStale(project, media);
|
||||
}
|
||||
context.Log(Loc.L("Archive.Log.WorkspaceCopied", row.DisplayTitle, tally.Copied, tally.Made, tally.Kept, tally.Missing));
|
||||
await context.CheckpointAsync(Checkpoint(Stage.Done, frames.Count), total, total).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The frame's file in the workspace: kept when an earlier run copied it (before the checkpoint, or the same bytes as the
|
||||
/// archive's proxy), else the archive's current proxy, else one made from the original; none for a frame without either.
|
||||
/// </summary>
|
||||
private WorkspaceFrame Copy(WorkspaceProject project, SequencePaths folder, ArchivePaths paths, Frame frame, ProxyPolicy policy, bool done, Tally tally,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var name = WorkspaceProject.ProxyName(frame.Id);
|
||||
var target = project.MediaFile(name);
|
||||
if (done && File.Exists(target))
|
||||
{
|
||||
tally.Kept++;
|
||||
var kept = AtomicFile.ReadAllBytes(target);
|
||||
return WorkspaceFrame.Of(frame, name, Sha(kept), kept.Length);
|
||||
}
|
||||
var source = folder.Proxy(frame.Index);
|
||||
byte[]? bytes = null;
|
||||
if (File.Exists(source) && ArchiveImages.IsProxyOf(source, frame.CapturedAt, frame.Width, frame.Height, null)) bytes = AtomicFile.ReadAllBytes(source);
|
||||
var made = false;
|
||||
if (bytes is null && (frame.Flags & FrameFlags.Missing) == 0)
|
||||
{
|
||||
var original = paths.FromRelative(frame.RelativePath);
|
||||
try
|
||||
{
|
||||
var edge = policy.LongEdge == ProxyPolicy.Disabled ? new ProxyPolicy().LongEdge : policy.LongEdge;
|
||||
bytes = File.Exists(original) ? ArchiveImages.MakeProxy(archives.Decoder, original, frame, null, edge, policy.Quality, cancellationToken) : null;
|
||||
made = bytes is not null;
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
Log.Warning("workspace", $"No proxy of {original} could be made", ex);
|
||||
}
|
||||
}
|
||||
if (bytes is null)
|
||||
{
|
||||
tally.Missing++;
|
||||
return WorkspaceFrame.Of(frame, null, null, 0);
|
||||
}
|
||||
var sha = Sha(bytes);
|
||||
if (File.Exists(target) && Sha(AtomicFile.ReadAllBytes(target)) == sha)
|
||||
{
|
||||
tally.Kept++;
|
||||
return WorkspaceFrame.Of(frame, name, sha, bytes.Length);
|
||||
}
|
||||
WriteVerified(target, bytes, sha);
|
||||
if (made) tally.Made++;
|
||||
else tally.Copied++;
|
||||
return WorkspaceFrame.Of(frame, name, sha, bytes.Length);
|
||||
}
|
||||
|
||||
/// <summary>Writes atomically and reads back: a file that does not hash as its source is written again once, then refused.</summary>
|
||||
private static void WriteVerified(string path, byte[] bytes, string sha)
|
||||
{
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
AtomicFile.WriteAllBytes(path, bytes);
|
||||
if (Sha(AtomicFile.ReadAllBytes(path)) == sha) return;
|
||||
if (attempt == 2) throw new IOException(Loc.L("Errors.Workspace.CopyMismatch", path));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The home's deep report into the media folder when it describes these frames; its SHA-256, or null without one.</summary>
|
||||
private static string? CopyAnalysis(SequencePaths folder, WorkspaceProject project, int frameCount)
|
||||
{
|
||||
if (!File.Exists(folder.AnalysisPath))
|
||||
{
|
||||
if (File.Exists(project.AnalysisPath)) File.Delete(project.AnalysisPath);
|
||||
return null;
|
||||
}
|
||||
var bytes = AtomicFile.ReadAllBytes(folder.AnalysisPath);
|
||||
try
|
||||
{
|
||||
if (Core.Analysis.Deep.DeepAnalysisReport.FromJson(System.Text.Encoding.UTF8.GetString(bytes)).FrameCount != frameCount) return null;
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidDataException or JsonException or IOException)
|
||||
{
|
||||
Log.Warning("workspace", $"{folder.AnalysisPath} cannot be read; the workspace takes no deep report", ex);
|
||||
return null;
|
||||
}
|
||||
var sha = Sha(bytes);
|
||||
WriteVerified(project.AnalysisPath, bytes, sha);
|
||||
return sha;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The media index and the working state moved onto it: first the working state with every position parked by photo
|
||||
/// (valid whatever the frames), then the index, then the working state placed on the new frames. A crash in between
|
||||
/// leaves positions that wait for their photos, which the next open places.
|
||||
/// </summary>
|
||||
private static void Commit(WorkspaceProject project, ProjectBundle bundle, WorkspaceMedia media, Sequence row)
|
||||
{
|
||||
var old = TryReadMedia(project);
|
||||
var workspace = bundle.Workspace! with { Media = new BundleMedia(BundleMedia.Proxies, media.FramesVersion) };
|
||||
var sequence = bundle.Sequence with { Folder = row.Folder, Title = row.DisplayTitle, Frames = media.Frames.Count };
|
||||
var working = bundle.Project;
|
||||
// Without the media index the positions were made against, they are taken as naming these frames.
|
||||
if (!working.IsNewerFormat && old is not null)
|
||||
{
|
||||
var portable = ProjectSettings.FromJson(ProjectContent.ToPortable(working, old.Photos), allowNewer: true);
|
||||
project.WriteBundle(bundle with { Project = portable, Workspace = workspace, Sequence = sequence });
|
||||
project.WriteMedia(media);
|
||||
working = ProjectSettings.FromJson(ProjectContent.Place(portable.ToJson(), media.Photos), allowNewer: true);
|
||||
}
|
||||
else
|
||||
{
|
||||
project.WriteMedia(media);
|
||||
}
|
||||
project.WriteBundle(bundle with { Project = working, Workspace = workspace, Sequence = sequence, Saved = DateTimeOffset.UtcNow });
|
||||
}
|
||||
|
||||
/// <summary>Proxies of frames the sequence no longer has: regenerable copies, removed so the media folder holds the frames listed.</summary>
|
||||
private static void RemoveStale(WorkspaceProject project, WorkspaceMedia media)
|
||||
{
|
||||
var listed = media.Frames.Where(f => f.File is not null).Select(f => Path.GetFileName(f.File!)).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var file in Directory.EnumerateFiles(project.ProxiesDirectory, "*.jpg"))
|
||||
{
|
||||
if (listed.Contains(Path.GetFileName(file))) continue;
|
||||
try
|
||||
{
|
||||
File.Delete(file);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("workspace", $"{file} could not be removed", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static WorkspaceMedia? TryReadMedia(WorkspaceProject project)
|
||||
{
|
||||
try
|
||||
{
|
||||
return project.ReadMedia();
|
||||
}
|
||||
catch (InvalidDataException ex)
|
||||
{
|
||||
Log.Warning("workspace", $"The media index of {project.Folder} cannot be read; positions are taken as they are", ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The sequence row with its frames as one state (listed between two reads of the row at the same frames version).</summary>
|
||||
private async Task<(Sequence Row, List<Frame> Frames)> FramesAsync(Guid sequenceId, CancellationToken cancellationToken)
|
||||
{
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
var before = await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException(Loc.L("Archive.Log.SequenceMissing", sequenceId));
|
||||
var frames = new List<Frame>();
|
||||
for (var after = -1; ;)
|
||||
{
|
||||
var page = await db.Frames.ListBySequenceAsync(sequenceId, after, PageSize, cancellationToken).ConfigureAwait(false);
|
||||
frames.AddRange(page);
|
||||
if (page.Count < PageSize) break;
|
||||
after = page[^1].Index;
|
||||
}
|
||||
var now = await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? before;
|
||||
if (now.FramesVersion == before.FramesVersion || attempt == 2) return (now, frames);
|
||||
}
|
||||
}
|
||||
|
||||
private static WorkspaceCopyParameters Parameters(Job job)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (job.ParametersJson is { Length: > 0 } json
|
||||
&& JsonSerializer.Deserialize(json, WorkspaceJson.Default.WorkspaceCopyParameters) is { WorkspaceRoot.Length: > 0 } parameters
|
||||
&& parameters.ProjectId != Guid.Empty)
|
||||
return parameters with { Media = parameters.Media ?? BundleMedia.Proxies };
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException(Loc.L("Errors.Workspace.Parameters"), ex);
|
||||
}
|
||||
throw new InvalidDataException(Loc.L("Errors.Workspace.Parameters"));
|
||||
}
|
||||
|
||||
private static string Sha(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
|
||||
|
||||
private enum Stage
|
||||
{
|
||||
Proxies,
|
||||
Copy,
|
||||
Done,
|
||||
}
|
||||
|
||||
private static string Checkpoint(Stage stage, int frame) =>
|
||||
string.Create(CultureInfo.InvariantCulture, $"{stage.ToString().ToLowerInvariant()}:{frame}");
|
||||
|
||||
private static (Stage Stage, int Next) Parse(string? checkpoint)
|
||||
{
|
||||
var parts = checkpoint?.Split(':');
|
||||
return parts is [var name, var number] && Enum.TryParse<Stage>(name, ignoreCase: true, out var stage)
|
||||
&& int.TryParse(number, NumberStyles.None, CultureInfo.InvariantCulture, out var next)
|
||||
? (stage == Stage.Done ? Stage.Copy : stage, stage == Stage.Done ? 0 : next)
|
||||
: (Stage.Proxies, 0);
|
||||
}
|
||||
|
||||
private sealed class Tally
|
||||
{
|
||||
public int Copied { get; set; }
|
||||
public int Made { get; set; }
|
||||
public int Kept { get; set; }
|
||||
public int Missing { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Render;
|
||||
using Chronos.Data.Processing;
|
||||
|
||||
namespace Chronos.Data.Workspaces;
|
||||
|
||||
/// <summary>
|
||||
/// One frame of a workspace's media (<c>media/media.json</c>): the frame's record at its home (what analyses and the
|
||||
/// editor read) and the file the workspace holds for it, with its SHA-256 and size as copied.
|
||||
/// </summary>
|
||||
/// <param name="File">The file relative to the media folder ("proxies/<frame id>.jpg"); null when the workspace holds none.</param>
|
||||
public sealed record WorkspaceFrame(
|
||||
Guid Id,
|
||||
int Index,
|
||||
string FileName,
|
||||
string? OriginalFileName,
|
||||
long Size,
|
||||
string? Sha256,
|
||||
DateTime? CapturedAt,
|
||||
int? UtcOffsetMinutes,
|
||||
TimestampSource TimestampSource,
|
||||
double? ExposureTime,
|
||||
double? FNumber,
|
||||
int? Iso,
|
||||
double? FocalLength,
|
||||
double? ExposureBias,
|
||||
int? WhiteBalance,
|
||||
int Orientation,
|
||||
int Width,
|
||||
int Height,
|
||||
ImageFileFormat Format,
|
||||
int PreviewWidth,
|
||||
int PreviewHeight,
|
||||
double? MeanLogLuminance,
|
||||
double? ClipLow,
|
||||
double? ClipHigh,
|
||||
FrameFlags Flags,
|
||||
string? File,
|
||||
string? FileSha256,
|
||||
long FileBytes)
|
||||
{
|
||||
/// <summary>The record of a home's frame, with the file the workspace holds for it.</summary>
|
||||
public static WorkspaceFrame Of(Frame frame, string? file, string? fileSha256, long fileBytes)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(frame);
|
||||
return new WorkspaceFrame(frame.Id, frame.Index, frame.FileName, frame.OriginalFileName, frame.Size, frame.Sha256, frame.CapturedAt, frame.UtcOffsetMinutes,
|
||||
frame.TimestampSource, frame.ExposureTime, frame.FNumber, frame.Iso, frame.FocalLength, frame.ExposureBias, frame.WhiteBalance, frame.Orientation,
|
||||
frame.Width, frame.Height, frame.Format, frame.PreviewWidth, frame.PreviewHeight, frame.MeanLogLuminance, frame.ClipLow, frame.ClipHigh, frame.Flags,
|
||||
file, fileSha256, fileBytes);
|
||||
}
|
||||
|
||||
/// <summary>The frame as the processing engine reads it; flagged missing while the workspace holds no file for it.</summary>
|
||||
public Frame ToFrame(Guid sequenceId) => new()
|
||||
{
|
||||
Id = Id,
|
||||
SequenceId = sequenceId,
|
||||
Index = Index,
|
||||
RelativePath = File ?? FileName,
|
||||
FileName = FileName,
|
||||
OriginalFileName = OriginalFileName,
|
||||
Size = Size,
|
||||
Sha256 = Sha256,
|
||||
CapturedAt = CapturedAt,
|
||||
UtcOffsetMinutes = UtcOffsetMinutes,
|
||||
TimestampSource = TimestampSource,
|
||||
ExposureTime = ExposureTime,
|
||||
FNumber = FNumber,
|
||||
Iso = Iso,
|
||||
FocalLength = FocalLength,
|
||||
ExposureBias = ExposureBias,
|
||||
WhiteBalance = WhiteBalance,
|
||||
Orientation = Orientation,
|
||||
Width = Width,
|
||||
Height = Height,
|
||||
Format = Format,
|
||||
PreviewWidth = PreviewWidth,
|
||||
PreviewHeight = PreviewHeight,
|
||||
MeanLogLuminance = MeanLogLuminance,
|
||||
ClipLow = ClipLow,
|
||||
ClipHigh = ClipHigh,
|
||||
Flags = File is null ? Flags | FrameFlags.Missing : Flags,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a workspace project holds of its sequence's photos (<c>media/media.json</c>, owner review 2, R8): the kind
|
||||
/// (<see cref="BundleMedia.Proxies"/>; originals in phase 5c), the sequence and its frames version at the home when they
|
||||
/// were copied, and every frame in index order. Written last by a copy, so a copy cut short leaves the previous index.
|
||||
/// </summary>
|
||||
public sealed record WorkspaceMedia(string Format, int FormatVersion, string Kind, Guid SequenceId, int FramesVersion, IReadOnlyList<WorkspaceFrame> Frames,
|
||||
DateTimeOffset Copied, string? AnalysisSha256 = null)
|
||||
{
|
||||
public const string FormatName = "chronos-workspace-media";
|
||||
public const int CurrentFormatVersion = 1;
|
||||
|
||||
/// <summary>The frames' photos in index order, as project positions name them.</summary>
|
||||
[JsonIgnore]
|
||||
public FramePhotos Photos => new(Frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
|
||||
|
||||
/// <summary>The frames held, as the processing engine reads them.</summary>
|
||||
public IReadOnlyList<Frame> ToFrames() => [.. Frames.Select(f => f.ToFrame(SequenceId))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A workspace project's sequence opened for editing (like a server sequence opened with proxies): the home's sequence
|
||||
/// row, the frames as the workspace holds them and the absolute path of each frame's file (null, and the frame flagged
|
||||
/// missing, when it holds none).
|
||||
/// </summary>
|
||||
public sealed class WorkspaceSequence
|
||||
{
|
||||
public WorkspaceSequence(Sequence sequence, IReadOnlyList<Frame> frames, IReadOnlyList<string?> files)
|
||||
{
|
||||
if (files.Count != frames.Count) throw new ArgumentException("One file entry per frame is required.", nameof(files));
|
||||
Sequence = sequence;
|
||||
Frames = frames;
|
||||
Files = files;
|
||||
}
|
||||
|
||||
public Sequence Sequence { get; }
|
||||
|
||||
public IReadOnlyList<Frame> Frames { get; }
|
||||
|
||||
public IReadOnlyList<string?> Files { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The editor's frame source over the workspace's files, through the same read-ahead window as archive renders; it also
|
||||
/// implements <see cref="Core.Analysis.Deep.IFrameSource"/> and <see cref="IAsyncDisposable"/> (dispose it when done).
|
||||
/// </summary>
|
||||
public IRenderFrameSource OpenFrames(ImageDecoder decoder, FrameWindowOptions? window = null)
|
||||
{
|
||||
var frames = new SequenceFrames(Sequence, Frames, Files);
|
||||
return new SequenceFrameSource(frames, frames.LightFrames(), decoder, window);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Sync;
|
||||
|
||||
namespace Chronos.Data.Workspaces;
|
||||
|
||||
/// <summary>The manifest of a workspace folder (<c>workspace.json</c>).</summary>
|
||||
public sealed record WorkspaceManifest(string Format, int FormatVersion, Guid Id, DateTimeOffset Created);
|
||||
|
||||
/// <summary>A workspace's sync state of one project besides its versions (<c>sync.json</c>): a restore to record, a conflict to settle.</summary>
|
||||
/// <param name="RestoredFrom">The version a restore brought back; the next commit is a "restore" of it.</param>
|
||||
/// <param name="Conflict">The conflict a pull or push stopped at, until the user settles it.</param>
|
||||
public sealed record WorkspaceSyncState(Guid? RestoredFrom, WorkspaceConflict? Conflict)
|
||||
{
|
||||
public static WorkspaceSyncState None { get; } = new(null, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A pull or push that met real conflicts (owner review 2, R8): the home's head it met, the version the local commits were
|
||||
/// made from, the local commits (oldest first) and the members both sides changed (mine, theirs). Settled by keeping mine,
|
||||
/// taking the server's (each member or all), or saving both (<see cref="WorkspaceSync.ResolveAsync"/>).
|
||||
/// </summary>
|
||||
public sealed record WorkspaceConflict(Guid TheirsVersionId, int TheirsNumber, Guid BaseVersionId, IReadOnlyList<Guid> Mine,
|
||||
IReadOnlyList<SettingsDifference> Differences, DateTimeOffset Found);
|
||||
|
||||
/// <summary>
|
||||
/// Parameters of a <see cref="JobKind.WorkspaceCopy"/> job: target = the home's sequence; the workspace folder, the
|
||||
/// project whose media to copy and what to copy (<see cref="BundleMedia.Proxies"/>; originals in phase 5c).
|
||||
/// </summary>
|
||||
public sealed record WorkspaceCopyParameters(string WorkspaceRoot, Guid ProjectId, string Media);
|
||||
|
||||
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
UseStringEnumConverter = true, WriteIndented = true)]
|
||||
[JsonSerializable(typeof(WorkspaceManifest))]
|
||||
[JsonSerializable(typeof(WorkspaceMedia))]
|
||||
[JsonSerializable(typeof(WorkspaceSyncState))]
|
||||
[JsonSerializable(typeof(WorkspaceCopyParameters))]
|
||||
internal sealed partial class WorkspaceJson : JsonSerializerContext;
|
||||
|
||||
/// <summary>
|
||||
/// The workspace of this PC (owner review 2, R8): a folder on a fast disk where projects are edited, never inside the
|
||||
/// library. <c><root>/workspace.json</c> names it; each project has a folder named by its id
|
||||
/// (<see cref="WorkspaceProject"/>). There is no index: the store lists the folders holding a <c>project.chronos</c>. The
|
||||
/// desktop puts it in <c>%LOCALAPPDATA%\Chronos\workspace</c> unless set otherwise; the store takes any folder.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceStore
|
||||
{
|
||||
public const string ManifestFile = "workspace.json";
|
||||
public const string FormatName = "chronos-workspace";
|
||||
public const int FormatVersion = 1;
|
||||
|
||||
/// <summary>The folder name of the workspace inside the program's data folder.</summary>
|
||||
public const string DefaultFolderName = "workspace";
|
||||
|
||||
/// <summary>Opens the workspace at <paramref name="root"/>, making the folder and its manifest when there is none.</summary>
|
||||
/// <exception cref="InvalidDataException">The folder's <c>workspace.json</c> is not a workspace manifest, or a newer one.</exception>
|
||||
/// <exception cref="IOException">The folder cannot be made or read.</exception>
|
||||
public WorkspaceStore(string root)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(root);
|
||||
Root = LongPath.Normalize(Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)));
|
||||
Directory.CreateDirectory(Root);
|
||||
var path = Path.Combine(Root, ManifestFile);
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
var manifest = new WorkspaceManifest(FormatName, FormatVersion, Guid.CreateVersion7(), DateTimeOffset.UtcNow);
|
||||
// Another program opening the same folder at the same moment: the first manifest wins.
|
||||
try
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None);
|
||||
JsonSerializer.Serialize(stream, manifest, WorkspaceJson.Default.WorkspaceManifest);
|
||||
stream.Flush(flushToDisk: true);
|
||||
}
|
||||
catch (IOException) when (File.Exists(path))
|
||||
{
|
||||
}
|
||||
}
|
||||
Manifest = Read(path);
|
||||
}
|
||||
|
||||
public string Root { get; }
|
||||
|
||||
public WorkspaceManifest Manifest { get; }
|
||||
|
||||
public Guid Id => Manifest.Id;
|
||||
|
||||
/// <summary>The folder of a project, whether it exists or not.</summary>
|
||||
public WorkspaceProject Project(Guid projectId) => new(this, projectId);
|
||||
|
||||
/// <summary>The project's folder when it holds a working state; null otherwise.</summary>
|
||||
public WorkspaceProject? Find(Guid projectId)
|
||||
{
|
||||
var project = Project(projectId);
|
||||
return project.Exists ? project : null;
|
||||
}
|
||||
|
||||
/// <summary>The projects of the workspace: every folder named by a project id that holds a <c>project.chronos</c>.</summary>
|
||||
public IReadOnlyList<WorkspaceProject> List()
|
||||
{
|
||||
var found = new List<WorkspaceProject>();
|
||||
foreach (var directory in Directory.EnumerateDirectories(Root).Order(StringComparer.Ordinal))
|
||||
{
|
||||
if (Guid.TryParseExact(Path.GetFileName(directory), "N", out var id) && File.Exists(Path.Combine(directory, WorkspaceProject.BundleFile)))
|
||||
found.Add(Project(id));
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/// <summary>The working states of the workspace's projects (one unreadable is left out, and logged).</summary>
|
||||
public IReadOnlyList<(WorkspaceProject Project, ProjectBundle Bundle)> ListBundles()
|
||||
{
|
||||
var bundles = new List<(WorkspaceProject, ProjectBundle)>();
|
||||
foreach (var project in List())
|
||||
{
|
||||
try
|
||||
{
|
||||
bundles.Add((project, project.ReadBundle()));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("workspace", $"The project in {project.Folder} cannot be read", ex);
|
||||
}
|
||||
}
|
||||
return bundles;
|
||||
}
|
||||
|
||||
private static WorkspaceManifest Read(string path)
|
||||
{
|
||||
WorkspaceManifest? manifest;
|
||||
try
|
||||
{
|
||||
manifest = JsonSerializer.Deserialize(AtomicFile.ReadAllText(path), WorkspaceJson.Default.WorkspaceManifest);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException($"{path} is not a workspace manifest.", ex);
|
||||
}
|
||||
if (manifest is null || manifest.Format != FormatName || manifest.Id == Guid.Empty) throw new InvalidDataException($"{path} is not a workspace manifest.");
|
||||
if (manifest.FormatVersion > FormatVersion)
|
||||
throw new InvalidDataException($"{path} uses format {manifest.FormatVersion}, newer than this Chronos ({FormatVersion}).");
|
||||
return manifest;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One project in the workspace (owner review 2, R8): <c><root>/<project id>/</c> with
|
||||
/// <c>project.chronos</c> (the working state: a project file of format 2, its settings placed on the media's frames),
|
||||
/// <c>media/media.json</c> with <c>media/proxies/<frame id>.jpg</c> (originals later) and <c>media/analysis.json</c>
|
||||
/// (the home's deep report), <c>versions/<number>-<id>.json</c> (commits not pushed yet, and the versions pulled),
|
||||
/// <c>sync.json</c>, <c>exports/</c> and the lease <c>.lock.lease</c> that one writer at a time holds.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceProject
|
||||
{
|
||||
public const string BundleFile = "project.chronos";
|
||||
public const string MediaFolder = "media";
|
||||
public const string MediaIndexFile = "media.json";
|
||||
public const string ProxiesFolder = "proxies";
|
||||
public const string OriginalsFolder = "originals";
|
||||
public const string VersionsFolder = "versions";
|
||||
public const string ExportsFolder = "exports";
|
||||
public const string SyncFile = "sync.json";
|
||||
|
||||
/// <summary>Old local commits replaced by their replay on top of the home's head: kept, never erased by Chronos.</summary>
|
||||
public const string ReplacedFolder = ".replaced";
|
||||
|
||||
private const string LeaseName = ".lock";
|
||||
|
||||
internal WorkspaceProject(WorkspaceStore store, Guid projectId)
|
||||
{
|
||||
Store = store;
|
||||
ProjectId = projectId;
|
||||
Folder = Path.Combine(store.Root, projectId.ToString("N"));
|
||||
}
|
||||
|
||||
public WorkspaceStore Store { get; }
|
||||
public Guid ProjectId { get; }
|
||||
public string Folder { get; }
|
||||
public string BundlePath => Path.Combine(Folder, BundleFile);
|
||||
public string MediaDirectory => Path.Combine(Folder, MediaFolder);
|
||||
public string MediaIndexPath => Path.Combine(MediaDirectory, MediaIndexFile);
|
||||
public string ProxiesDirectory => Path.Combine(MediaDirectory, ProxiesFolder);
|
||||
public string OriginalsDirectory => Path.Combine(MediaDirectory, OriginalsFolder);
|
||||
public string AnalysisPath => Path.Combine(MediaDirectory, ArchiveLayout.AnalysisFile);
|
||||
public string VersionsDirectory => Path.Combine(Folder, VersionsFolder);
|
||||
public string ExportsDirectory => Path.Combine(Folder, ExportsFolder);
|
||||
public string SyncPath => Path.Combine(Folder, SyncFile);
|
||||
|
||||
public bool Exists => File.Exists(BundlePath);
|
||||
|
||||
/// <summary>The file a frame's proxy is copied to, relative to <see cref="MediaDirectory"/>.</summary>
|
||||
public static string ProxyName(Guid frameId) => ProxiesFolder + "/" + ProxyCache.FileName(frameId);
|
||||
|
||||
/// <summary>The absolute path of a file named relative to <see cref="MediaDirectory"/>.</summary>
|
||||
public string MediaFile(string relative) => LongPath.FromPortableRelative(MediaDirectory, relative);
|
||||
|
||||
/// <summary>Holds the project for one writer (this program's sync, a copy job) until disposed.</summary>
|
||||
/// <exception cref="LeaseUnavailableException">Another writer kept it for longer than <paramref name="wait"/>.</exception>
|
||||
public async Task<IDisposable> LockAsync(TimeSpan wait, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Directory.CreateDirectory(Folder);
|
||||
return await LeaseFile.AcquireAsync(Folder, LeaseName, "workspace@" + Environment.MachineName, wait, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <exception cref="InvalidDataException">Not a project file of a workspace, damaged or newer.</exception>
|
||||
/// <exception cref="IOException">The file cannot be read.</exception>
|
||||
public ProjectBundle ReadBundle()
|
||||
{
|
||||
var bundle = ProjectBundle.Load(BundlePath);
|
||||
if (bundle.Workspace is not { } workspace || workspace.ProjectId != ProjectId)
|
||||
throw new InvalidDataException($"{BundlePath} is not the working state of project {ProjectId}.");
|
||||
return bundle;
|
||||
}
|
||||
|
||||
public void WriteBundle(ProjectBundle bundle)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(bundle);
|
||||
if (bundle.Workspace?.ProjectId != ProjectId) throw new ArgumentException("The project file is another project's.", nameof(bundle));
|
||||
Directory.CreateDirectory(Folder);
|
||||
bundle.Save(BundlePath);
|
||||
}
|
||||
|
||||
/// <summary>The media index; null while the media were never copied, or were removed.</summary>
|
||||
/// <exception cref="InvalidDataException">The index is damaged or newer.</exception>
|
||||
public WorkspaceMedia? ReadMedia()
|
||||
{
|
||||
if (!File.Exists(MediaIndexPath)) return null;
|
||||
WorkspaceMedia? media;
|
||||
try
|
||||
{
|
||||
media = JsonSerializer.Deserialize(AtomicFile.ReadAllText(MediaIndexPath), WorkspaceJson.Default.WorkspaceMedia);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException($"{MediaIndexPath} cannot be read.", ex);
|
||||
}
|
||||
if (media is null || media.Format != WorkspaceMedia.FormatName) throw new InvalidDataException($"{MediaIndexPath} is not a media index.");
|
||||
if (media.FormatVersion > WorkspaceMedia.CurrentFormatVersion) throw new InvalidDataException($"{MediaIndexPath} is newer than this Chronos.");
|
||||
return media;
|
||||
}
|
||||
|
||||
internal void WriteMedia(WorkspaceMedia media)
|
||||
{
|
||||
Directory.CreateDirectory(MediaDirectory);
|
||||
AtomicFile.WriteAllText(MediaIndexPath, JsonSerializer.Serialize(media, WorkspaceJson.Default.WorkspaceMedia));
|
||||
}
|
||||
|
||||
/// <summary>The versions this workspace holds, oldest first; one that cannot be read is left out (and logged).</summary>
|
||||
public IReadOnlyList<ProjectVersion> Versions()
|
||||
{
|
||||
var versions = new List<ProjectVersion>();
|
||||
foreach (var (_, _, path) in ProjectSidecars.ListVersions(VersionsDirectory))
|
||||
{
|
||||
try
|
||||
{
|
||||
var version = ProjectSidecars.ReadVersion(path);
|
||||
if (version.ProjectId == ProjectId) versions.Add(version);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("workspace", $"Version file {path} cannot be read", ex);
|
||||
}
|
||||
}
|
||||
return versions;
|
||||
}
|
||||
|
||||
/// <summary>The path of a version in <see cref="VersionsDirectory"/>.</summary>
|
||||
public string VersionPath(ProjectVersion version) => Path.Combine(VersionsDirectory, ArchiveLayout.ProjectVersionFileName(version.Number, version.Id));
|
||||
|
||||
internal void WriteVersion(ProjectVersion version, bool replace = false) => ProjectSidecars.WriteVersion(VersionPath(version), version, replace);
|
||||
|
||||
/// <summary>Moves a version file aside into <c>versions/.replaced</c> (a local commit replayed under another id).</summary>
|
||||
internal void SetAside(ProjectVersion version)
|
||||
{
|
||||
var path = VersionPath(version);
|
||||
if (!File.Exists(path)) return;
|
||||
var aside = Path.Combine(VersionsDirectory, ReplacedFolder);
|
||||
Directory.CreateDirectory(aside);
|
||||
var target = Path.Combine(aside, Path.GetFileName(path));
|
||||
if (File.Exists(target)) target += "." + DateTime.UtcNow.Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
File.Move(path, target);
|
||||
}
|
||||
|
||||
public WorkspaceSyncState ReadSync()
|
||||
{
|
||||
if (!File.Exists(SyncPath)) return WorkspaceSyncState.None;
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize(AtomicFile.ReadAllText(SyncPath), WorkspaceJson.Default.WorkspaceSyncState) ?? WorkspaceSyncState.None;
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException($"{SyncPath} cannot be read.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
internal void WriteSync(WorkspaceSyncState state)
|
||||
{
|
||||
if (state == WorkspaceSyncState.None || state is { RestoredFrom: null, Conflict: null })
|
||||
{
|
||||
if (File.Exists(SyncPath)) File.Delete(SyncPath);
|
||||
return;
|
||||
}
|
||||
Directory.CreateDirectory(Folder);
|
||||
AtomicFile.WriteAllText(SyncPath, JsonSerializer.Serialize(state, WorkspaceJson.Default.WorkspaceSyncState));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,625 @@
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Sync;
|
||||
|
||||
namespace Chronos.Data.Workspaces;
|
||||
|
||||
/// <summary>Where a workspace project stands against its home (<see cref="WorkspaceStatus.State"/>), the most pressing first.</summary>
|
||||
public enum WorkspaceState
|
||||
{
|
||||
/// <summary>Nothing to save, push or pull.</summary>
|
||||
InSync,
|
||||
|
||||
/// <summary>The working state has changes no version holds yet (save a version).</summary>
|
||||
Modified,
|
||||
|
||||
/// <summary>Versions saved here wait to be pushed (<see cref="WorkspaceStatus.Ahead"/>).</summary>
|
||||
Ahead,
|
||||
|
||||
/// <summary>The home has versions this workspace has not pulled (<see cref="WorkspaceStatus.Behind"/>).</summary>
|
||||
Behind,
|
||||
|
||||
/// <summary>A pull or push met changes both sides made to the same settings: keep mine, take the server's or save both.</summary>
|
||||
Conflict,
|
||||
|
||||
/// <summary>The home cannot be reached now; work goes on here and syncs later.</summary>
|
||||
Offline,
|
||||
|
||||
/// <summary>The workspace holds no media for the project (never copied, or removed): copy them again to edit.</summary>
|
||||
MediaRemoved,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A workspace project's state (owner review 2, R8): the leading <see cref="State"/> and every fact behind it. Without a
|
||||
/// home to ask, <see cref="Behind"/> is 0 and <see cref="Offline"/> false.
|
||||
/// </summary>
|
||||
/// <param name="Base">The home's version the project was last in step with.</param>
|
||||
/// <param name="HomeHead">The home's newest version, when it was asked.</param>
|
||||
public sealed record WorkspaceStatus(WorkspaceState State, bool Modified, int Ahead, int Behind, bool Offline, bool MediaRemoved, bool ReadOnly,
|
||||
WorkspaceConflict? Conflict, BundleBase? Base, ProjectVersion? HomeHead);
|
||||
|
||||
/// <summary>What a push, pull or resolve did: the versions it stored at the home and those it took from there, and where it left the project.</summary>
|
||||
/// <param name="SavedAs">After <see cref="ConflictChoice.SaveBoth"/>: the new project at the home holding this workspace's versions.</param>
|
||||
public sealed record WorkspaceSyncResult(WorkspaceStatus Status, IReadOnlyList<ProjectVersion> Pushed, IReadOnlyList<ProjectVersion> Pulled,
|
||||
SequenceProject? SavedAs = null);
|
||||
|
||||
/// <summary>How a conflict is settled (owner review 2, R8: only on real conflicts).</summary>
|
||||
public enum ConflictChoice
|
||||
{
|
||||
/// <summary>This workspace's values where both changed (each member listed in <c>takeServer</c> takes the server's instead).</summary>
|
||||
KeepMine,
|
||||
|
||||
/// <summary>The server's values wherever both changed.</summary>
|
||||
TakeServer,
|
||||
|
||||
/// <summary>Both kept: this workspace's versions go to a new project at the home, and this project takes the server's.</summary>
|
||||
SaveBoth,
|
||||
}
|
||||
|
||||
/// <summary>The working state of a workspace project opened for editing.</summary>
|
||||
/// <param name="Working">The settings, their positions placed on the media's frames.</param>
|
||||
/// <param name="Sequence">The sequence over the media's files; null while the workspace holds no media.</param>
|
||||
public sealed record WorkspaceSession(WorkspaceProject Project, ProjectBundle Bundle, ProjectSettings Working, WorkspaceMedia? Media, WorkspaceSequence? Sequence)
|
||||
{
|
||||
/// <summary>The settings come from a newer Chronos: shown, never saved.</summary>
|
||||
public bool IsReadOnly => Bundle.IsReadOnly;
|
||||
}
|
||||
|
||||
/// <summary>A push the home refused for good (not a divergence: settings damaged on the way, of a newer format, or not this project's).</summary>
|
||||
public sealed class WorkspaceSyncException(PushOutcome outcome, string message) : IOException(message)
|
||||
{
|
||||
public PushOutcome Outcome { get; } = outcome;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sync of workspace projects with their homes, "like git" with one linear history and no branches (owner review 2, R8).
|
||||
/// A workspace edits the working state (<see cref="SaveAsync"/>), saves versions of it locally (<see cref="CommitAsync"/>,
|
||||
/// parent = the last one), pushes them in order (<see cref="PushAsync"/>) and pulls the home's (<see cref="PullAsync"/>).
|
||||
/// When the home moved meanwhile, its new versions are pulled and each local commit is replayed on top of them
|
||||
/// (<see cref="ProjectMerge.Replay"/>, new ids, the old files kept in <c>versions/.replaced</c>), and the working state is
|
||||
/// merged too (<see cref="ProjectMerge.MergeWithConflicts"/>); settings both sides changed to different values stop
|
||||
/// there as a conflict (<see cref="WorkspaceConflict"/>) for the user to settle (<see cref="ResolveAsync"/>). Versions
|
||||
/// travel in the portable form (<see cref="ProjectContent"/>), so frames inserted at the home never move a position. Every
|
||||
/// operation holds the project's lease; nothing is ever deleted: a restore or save-both first saves uncommitted changes
|
||||
/// as a version.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
{
|
||||
/// <summary>Versions asked for at once when pulling.</summary>
|
||||
private const int PullPage = 100;
|
||||
|
||||
/// <summary>Times a push pulls and replays when the home keeps moving under it.</summary>
|
||||
private const int PushAttempts = 3;
|
||||
|
||||
private static readonly FramePhotos NoFrames = new([]);
|
||||
|
||||
public WorkspaceStore Store => store;
|
||||
|
||||
/// <summary>How long an operation waits for the project's lease (another program working on it).</summary>
|
||||
public TimeSpan LockWait { get; init; } = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>
|
||||
/// The project <paramref name="projectId"/> of <paramref name="home"/> brought into the workspace: its folder, the home's
|
||||
/// head as the base and the working state (positions waiting for the media, which a
|
||||
/// <see cref="JobKind.WorkspaceCopy"/> job copies: <see cref="WorkspaceJobs.Copy"/>). A project already here is left as
|
||||
/// it is.
|
||||
/// </summary>
|
||||
/// <exception cref="ProjectException">The home has no such project.</exception>
|
||||
/// <exception cref="InvalidOperationException">A project of that id from another home is in the workspace.</exception>
|
||||
public async Task<WorkspaceProject> CheckoutAsync(IProjectHome home, Guid projectId, string media = BundleMedia.Proxies, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(home);
|
||||
var project = store.Project(projectId);
|
||||
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var sequence = await home.SequenceAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (project.Exists)
|
||||
{
|
||||
var existing = project.ReadBundle();
|
||||
if (existing.Workspace!.Home.SequenceId != sequence.Home.SequenceId)
|
||||
throw new InvalidOperationException($"Project {projectId} in the workspace belongs to another sequence.");
|
||||
return project;
|
||||
}
|
||||
var listed = (await home.ListAsync(cancellationToken).ConfigureAwait(false)).FirstOrDefault(p => p.Id == projectId)
|
||||
?? throw new ProjectException(ProjectError.NotFound, $"The home has no project {projectId}.");
|
||||
var head = await home.HeadAsync(projectId, cancellationToken).ConfigureAwait(false);
|
||||
Verify(head);
|
||||
project.WriteVersion(head, replace: true);
|
||||
Directory.CreateDirectory(project.ExportsDirectory);
|
||||
var bundle = new ProjectBundle(sequence.Archive, sequence.Sequence, ProjectSettings.FromJson(head.SettingsJson, allowNewer: true), DateTimeOffset.UtcNow)
|
||||
{
|
||||
Workspace = new BundleWorkspace(projectId, listed.Name, listed.IsMain, sequence.Home, Base(head), new BundleMedia(media, 0)),
|
||||
};
|
||||
project.WriteBundle(bundle);
|
||||
return project;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The working state for the editor: its settings placed on the media's frames, and the media's sequence.</summary>
|
||||
/// <exception cref="InvalidOperationException">The project is not in the workspace.</exception>
|
||||
public Task<WorkspaceSession> OpenAsync(Guid projectId, CancellationToken cancellationToken = default) =>
|
||||
Task.Run(() =>
|
||||
{
|
||||
var project = Existing(projectId);
|
||||
var bundle = project.ReadBundle();
|
||||
var media = project.ReadMedia();
|
||||
var working = bundle.Project;
|
||||
if (media is not null && !working.IsNewerFormat)
|
||||
working = ProjectSettings.FromJson(ProjectContent.Place(working.ToJson(), media.Photos), allowNewer: true);
|
||||
return new WorkspaceSession(project, bundle, working, media, media is null ? null : SequenceOf(project, bundle, media));
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>Stores the working state (the editor's settings, positions on the media's frames); no version is made.</summary>
|
||||
/// <exception cref="InvalidOperationException">The project is read-only (a newer Chronos's settings) or not in the workspace.</exception>
|
||||
public async Task SaveAsync(Guid projectId, ProjectSettings working, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(working);
|
||||
var project = Existing(projectId);
|
||||
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var bundle = project.ReadBundle();
|
||||
if (bundle.IsReadOnly || working.IsNewerFormat) throw ReadOnly(projectId);
|
||||
project.WriteBundle(bundle with { Project = working, Saved = DateTimeOffset.UtcNow });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves the working state as a new local version (parent = the last one), unless it is the last one's already: null
|
||||
/// then. The version waits here until pushed. After a restore it is a "restore" of the version brought back.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">The project is read-only, has a conflict to settle, or is not in the workspace.</exception>
|
||||
public async Task<ProjectVersion?> CommitAsync(Guid projectId, string? note = null, string? author = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var project = Existing(projectId);
|
||||
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (project.ReadSync().Conflict is not null) throw new InvalidOperationException($"Project {projectId} has a conflict to settle first.");
|
||||
return CommitLocked(project, project.ReadBundle(), note, author);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pushes the local versions in order. When the home moved meanwhile, its versions are pulled and the local ones
|
||||
/// replayed on top of them first; a real conflict stops the push (<see cref="WorkspaceState.Conflict"/>).
|
||||
/// </summary>
|
||||
/// <exception cref="HomeUnavailableException">The home cannot be reached; nothing was lost, push again later.</exception>
|
||||
/// <exception cref="WorkspaceSyncException">The home refused a version for good.</exception>
|
||||
public async Task<WorkspaceSyncResult> PushAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(home);
|
||||
var project = Existing(projectId);
|
||||
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var pushed = new List<ProjectVersion>();
|
||||
var pulled = new List<ProjectVersion>();
|
||||
for (var attempt = 0; attempt < PushAttempts; attempt++)
|
||||
{
|
||||
var bundle = project.ReadBundle();
|
||||
if (project.ReadSync().Conflict is not null) break;
|
||||
var diverged = false;
|
||||
foreach (var local in Unpushed(project, bundle))
|
||||
{
|
||||
var result = await home.PushAsync(projectId, local, cancellationToken).ConfigureAwait(false);
|
||||
switch (result.Outcome)
|
||||
{
|
||||
case PushOutcome.Stored or PushOutcome.AlreadyStored when result.Version is { } stored:
|
||||
Verify(stored);
|
||||
if (stored.Number != local.Number) project.SetAside(local);
|
||||
project.WriteVersion(stored, replace: true);
|
||||
bundle = WithBase(bundle, stored);
|
||||
project.WriteBundle(bundle);
|
||||
pushed.Add(stored);
|
||||
continue;
|
||||
case PushOutcome.Diverged:
|
||||
diverged = true;
|
||||
break;
|
||||
default:
|
||||
throw new WorkspaceSyncException(result.Outcome, $"The home refused version {local.Number} of project {projectId}: {result.Outcome}.");
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (!diverged) break;
|
||||
var (_, conflict, taken) = await ReplayAsync(project, bundle, home, null, cancellationToken).ConfigureAwait(false);
|
||||
pulled.AddRange(taken);
|
||||
if (conflict is not null) break;
|
||||
}
|
||||
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), pushed, pulled);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes the home's versions newer than the base: the working state (and any local versions, replayed) moves onto the
|
||||
/// home's head; a real conflict stops it (<see cref="WorkspaceState.Conflict"/>).
|
||||
/// </summary>
|
||||
/// <exception cref="HomeUnavailableException">The home cannot be reached.</exception>
|
||||
public async Task<WorkspaceSyncResult> PullAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(home);
|
||||
var project = Existing(projectId);
|
||||
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
IReadOnlyList<ProjectVersion> pulled = [];
|
||||
if (project.ReadSync().Conflict is null)
|
||||
{
|
||||
var bundle = project.ReadBundle();
|
||||
var head = await home.HeadAsync(projectId, cancellationToken).ConfigureAwait(false);
|
||||
if (head.Id != bundle.Workspace!.Base?.VersionId) (_, _, pulled) = await ReplayAsync(project, bundle, home, null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], pulled);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settles the conflict a pull or push stopped at. <see cref="ConflictChoice.KeepMine"/> keeps this workspace's values
|
||||
/// (but for the members in <paramref name="takeServer"/>), <see cref="ConflictChoice.TakeServer"/> takes the server's
|
||||
/// wherever both changed; either way the local versions are replayed on the home's head and wait to be pushed.
|
||||
/// <see cref="ConflictChoice.SaveBoth"/> saves the working state as a version, sends this workspace's versions to a new
|
||||
/// project at the home (<paramref name="saveBothName"/>, else this project's name with a number) made from the base,
|
||||
/// and moves this project onto the home's head.
|
||||
/// </summary>
|
||||
/// <exception cref="HomeUnavailableException">The home cannot be reached; the conflict stays.</exception>
|
||||
public async Task<WorkspaceSyncResult> ResolveAsync(Guid projectId, IProjectHome home, ConflictChoice choice, IReadOnlySet<string>? takeServer = null,
|
||||
string? saveBothName = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(home);
|
||||
var project = Existing(projectId);
|
||||
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var bundle = project.ReadBundle();
|
||||
var sync = project.ReadSync();
|
||||
if (sync.Conflict is null) return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], []);
|
||||
if (choice == ConflictChoice.SaveBoth)
|
||||
return await SaveBothAsync(project, bundle, home, saveBothName, cancellationToken).ConfigureAwait(false);
|
||||
IReadOnlySet<string> takeTheirs = choice == ConflictChoice.TakeServer ? AllPaths : takeServer ?? new HashSet<string>();
|
||||
var (_, conflict, pulled) = await ReplayAsync(project, bundle, home, takeTheirs, cancellationToken).ConfigureAwait(false);
|
||||
if (conflict is null) project.WriteSync(project.ReadSync() with { Conflict = null });
|
||||
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], pulled);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Brings version <paramref name="versionId"/> back as the working state (from this workspace, else from
|
||||
/// <paramref name="home"/>); the next version saved is a "restore" of it. Uncommitted changes are saved as a version
|
||||
/// first, so a restore loses nothing.
|
||||
/// </summary>
|
||||
/// <exception cref="ProjectException">Neither this workspace nor the home has the version.</exception>
|
||||
public async Task<ProjectSettings> RestoreAsync(Guid projectId, Guid versionId, IProjectHome? home = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var project = Existing(projectId);
|
||||
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var version = project.Versions().FirstOrDefault(v => v.Id == versionId);
|
||||
if (version is null && home is not null && await home.GetVersionAsync(projectId, versionId, cancellationToken).ConfigureAwait(false) is { } fetched)
|
||||
{
|
||||
Verify(fetched);
|
||||
project.WriteVersion(fetched, replace: true);
|
||||
version = fetched;
|
||||
}
|
||||
if (version is null) throw new ProjectException(ProjectError.NotFound, $"Version {versionId} of project {projectId} is not known here.");
|
||||
var bundle = project.ReadBundle();
|
||||
if (bundle.IsReadOnly) throw ReadOnly(projectId);
|
||||
if (project.ReadSync().Conflict is null) CommitLocked(project, bundle, null, null);
|
||||
var media = project.ReadMedia();
|
||||
var working = ProjectSettings.FromJson(ProjectContent.Place(version.SettingsJson, media?.Photos ?? NoFrames), allowNewer: true);
|
||||
project.WriteBundle(project.ReadBundle() with { Project = working, Saved = DateTimeOffset.UtcNow });
|
||||
project.WriteSync(project.ReadSync() with { RestoredFrom = versionId });
|
||||
return working;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Where the project stands; with a <paramref name="home"/>, against the home's head too (offline when it cannot be reached).</summary>
|
||||
public async Task<WorkspaceStatus> StatusAsync(Guid projectId, IProjectHome? home = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var project = Existing(projectId);
|
||||
return await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The versions this workspace saved and has not pushed yet, oldest first.</summary>
|
||||
public IReadOnlyList<ProjectVersion> Unpushed(Guid projectId)
|
||||
{
|
||||
var project = Existing(projectId);
|
||||
return Unpushed(project, project.ReadBundle());
|
||||
}
|
||||
|
||||
private static readonly IReadOnlySet<string> AllPaths = new EveryPath();
|
||||
|
||||
/// <summary>
|
||||
/// Pulls the home's versions after the base and replays the local ones and the working state on its head. With
|
||||
/// <paramref name="takeTheirs"/> null a conflict is recorded and nothing else moves (the versions pulled are kept as
|
||||
/// files); with a choice the conflicts are settled by it.
|
||||
/// </summary>
|
||||
private async Task<(ProjectBundle Bundle, WorkspaceConflict? Conflict, IReadOnlyList<ProjectVersion> Pulled)> ReplayAsync(WorkspaceProject project,
|
||||
ProjectBundle bundle, IProjectHome home, IReadOnlySet<string>? takeTheirs, CancellationToken cancellationToken)
|
||||
{
|
||||
var basis = await BaseVersionAsync(project, bundle, home, cancellationToken).ConfigureAwait(false);
|
||||
// Read before the home's versions are written over them: a local commit the home stored although its answer was lost
|
||||
// comes back among them, and the commits after it were made on it.
|
||||
var locals = Unpushed(project, bundle);
|
||||
var theirs = new List<ProjectVersion>();
|
||||
for (var after = basis?.Number ?? 0; ;)
|
||||
{
|
||||
var page = await home.VersionsAfterAsync(project.ProjectId, after, PullPage, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var version in page)
|
||||
{
|
||||
Verify(version);
|
||||
project.WriteVersion(version, replace: true);
|
||||
}
|
||||
theirs.AddRange(page);
|
||||
if (page.Count < PullPage) break;
|
||||
after = page[^1].Number;
|
||||
}
|
||||
if (theirs.Count == 0) return (bundle, null, theirs);
|
||||
var head = theirs[^1];
|
||||
var atHome = theirs.Select(v => v.Id).ToHashSet();
|
||||
var ours = locals.TakeWhile(v => atHome.Contains(v.Id)).ToList();
|
||||
var tipVersion = locals.Count > 0 ? locals[^1] : basis;
|
||||
if (ours.Count > 0) basis = theirs.First(v => v.Id == ours[^1].Id);
|
||||
locals = [.. locals.Skip(ours.Count)];
|
||||
var media = project.ReadMedia();
|
||||
var photos = media?.Photos ?? NoFrames;
|
||||
var basisSettings = basis is null ? new ProjectSettings() : ProjectMerge.Read(basis.SettingsJson);
|
||||
var headSettings = ProjectMerge.Read(head.SettingsJson);
|
||||
var tip = tipVersion is null ? basisSettings : ProjectMerge.Read(tipVersion.SettingsJson);
|
||||
var working = ProjectMerge.Read(Portable(bundle.Project, media) ?? throw MediaMissing(project.ProjectId));
|
||||
// "Take the server's" everywhere: the paths are those the merge finds, so it runs once to find them.
|
||||
var choice = takeTheirs is EveryPath ? null : takeTheirs;
|
||||
List<ProjectSettings> mine = [.. locals.Select(v => ProjectMerge.Read(v.SettingsJson))];
|
||||
var replay = ProjectMerge.Replay(basisSettings, mine, headSettings, choice);
|
||||
if (takeTheirs is EveryPath) replay = ProjectMerge.Replay(basisSettings, mine, headSettings, Paths(replay.Conflicts));
|
||||
var newTip = replay.Commits.Count > 0 ? replay.Commits[^1] : headSettings;
|
||||
var merge = ProjectMerge.MergeWithConflicts(tip, working, newTip, choice);
|
||||
if (takeTheirs is EveryPath) merge = ProjectMerge.MergeWithConflicts(tip, working, newTip, Paths(merge.Conflicts));
|
||||
var differences = replay.Conflicts.Concat(merge.Conflicts).DistinctBy(d => d.Path).ToList();
|
||||
if (differences.Count > 0 && takeTheirs is null)
|
||||
{
|
||||
var conflict = new WorkspaceConflict(head.Id, head.Number, basis?.Id ?? Guid.Empty, [.. locals.Select(v => v.Id)], differences, DateTimeOffset.UtcNow);
|
||||
project.WriteSync(project.ReadSync() with { Conflict = conflict });
|
||||
return (bundle, conflict, theirs);
|
||||
}
|
||||
var parent = head;
|
||||
for (var i = 0; i < locals.Count; i++)
|
||||
{
|
||||
var local = locals[i];
|
||||
var portable = ProjectContent.Canonical(replay.Commits[i].ToJson());
|
||||
var rebased = local with
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ParentId = parent.Id,
|
||||
Number = parent.Number + 1,
|
||||
Kind = i == locals.Count - 1 && differences.Count > 0 ? ProjectVersionKind.Merge : local.Kind,
|
||||
SettingsJson = portable,
|
||||
ContentHash = ProjectContent.Hash(portable),
|
||||
SettingsFormat = ProjectContent.FormatOf(portable),
|
||||
StoredAt = null,
|
||||
};
|
||||
project.SetAside(local);
|
||||
project.WriteVersion(rebased);
|
||||
parent = rebased;
|
||||
}
|
||||
var placed = ProjectSettings.FromJson(ProjectContent.Place(ProjectContent.Canonical(merge.Merged.ToJson()), photos), allowNewer: true);
|
||||
var moved = WithBase(bundle, head) with { Project = placed, Saved = DateTimeOffset.UtcNow };
|
||||
project.WriteBundle(moved);
|
||||
return (moved, null, theirs);
|
||||
}
|
||||
|
||||
/// <summary>Both sides kept: this workspace's versions to a new project at the home, this project onto the home's head.</summary>
|
||||
private async Task<WorkspaceSyncResult> SaveBothAsync(WorkspaceProject project, ProjectBundle bundle, IProjectHome home, string? name, CancellationToken cancellationToken)
|
||||
{
|
||||
var workspace = bundle.Workspace!;
|
||||
if (!bundle.IsReadOnly) CommitLocked(project, bundle, null, null);
|
||||
bundle = project.ReadBundle();
|
||||
var locals = Unpushed(project, bundle);
|
||||
var basis = await BaseVersionAsync(project, bundle, home, cancellationToken).ConfigureAwait(false);
|
||||
SequenceProject? copy = null;
|
||||
var pushed = new List<ProjectVersion>();
|
||||
if (locals.Count > 0)
|
||||
{
|
||||
copy = await CreateNamedAsync(home, name, workspace.Name, basis?.Id, cancellationToken).ConfigureAwait(false);
|
||||
var parent = await home.HeadAsync(copy.Id, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var local in locals)
|
||||
{
|
||||
var moved = local with { Id = Guid.CreateVersion7(), ProjectId = copy.Id, ParentId = parent.Id, Number = parent.Number + 1, StoredAt = null };
|
||||
var result = await home.PushAsync(copy.Id, moved, cancellationToken).ConfigureAwait(false);
|
||||
if (result is not { Outcome: PushOutcome.Stored or PushOutcome.AlreadyStored, Version: { } stored })
|
||||
throw new WorkspaceSyncException(result.Outcome, $"The home refused version {local.Number} saved as project '{copy.Name}': {result.Outcome}.");
|
||||
pushed.Add(stored);
|
||||
parent = stored;
|
||||
}
|
||||
}
|
||||
// This project takes the home's head: the local versions now live in the copy (and their files in versions/.replaced).
|
||||
var head = await home.HeadAsync(project.ProjectId, cancellationToken).ConfigureAwait(false);
|
||||
Verify(head);
|
||||
project.WriteVersion(head, replace: true);
|
||||
foreach (var local in locals) project.SetAside(local);
|
||||
var media = project.ReadMedia();
|
||||
var working = ProjectSettings.FromJson(ProjectContent.Place(head.SettingsJson, media?.Photos ?? NoFrames), allowNewer: true);
|
||||
project.WriteBundle(WithBase(bundle, head) with { Project = working, Saved = DateTimeOffset.UtcNow });
|
||||
project.WriteSync(WorkspaceSyncState.None);
|
||||
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), pushed, [head], copy);
|
||||
}
|
||||
|
||||
/// <summary>A new project at the home named <paramref name="name"/>, else "<paramref name="source"/> (2)", "(3)"… whichever is free.</summary>
|
||||
private static async Task<SequenceProject> CreateNamedAsync(IProjectHome home, string? name, string source, Guid? from, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(name)) return await home.CreateAsync(name, from, null, cancellationToken).ConfigureAwait(false);
|
||||
for (var n = 2; ; n++)
|
||||
{
|
||||
var candidate = $"{source} ({n})";
|
||||
if (candidate.Length > ProjectService.MaxNameLength) candidate = $"{source[..(ProjectService.MaxNameLength - 6)]} ({n})";
|
||||
try
|
||||
{
|
||||
return await home.CreateAsync(candidate, from, null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (ProjectException ex) when (ex.Reason == ProjectError.NameTaken && n < 100)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ProjectVersion? CommitLocked(WorkspaceProject project, ProjectBundle bundle, string? note, string? author)
|
||||
{
|
||||
if (bundle.IsReadOnly) throw ReadOnly(project.ProjectId);
|
||||
var workspace = bundle.Workspace!;
|
||||
var media = project.ReadMedia();
|
||||
var portable = Portable(bundle.Project, media) ?? throw MediaMissing(project.ProjectId);
|
||||
var hash = ProjectContent.Hash(portable);
|
||||
var locals = Unpushed(project, bundle);
|
||||
var (tipId, tipNumber, tipHash) = locals.Count > 0
|
||||
? (locals[^1].Id, locals[^1].Number, locals[^1].ContentHash)
|
||||
: (workspace.Base?.VersionId, workspace.Base?.Number ?? 0, workspace.Base?.ContentHash);
|
||||
if (hash == tipHash) return null;
|
||||
var sync = project.ReadSync();
|
||||
var version = new ProjectVersion
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ProjectId = project.ProjectId,
|
||||
ParentId = tipId,
|
||||
Number = tipNumber + 1,
|
||||
Kind = sync.RestoredFrom is null ? ProjectVersionKind.Commit : ProjectVersionKind.Restore,
|
||||
Author = author,
|
||||
ClientName = clientName,
|
||||
Note = string.IsNullOrWhiteSpace(note) ? null : note.Trim(),
|
||||
SettingsJson = portable,
|
||||
ContentHash = hash,
|
||||
SettingsFormat = ProjectContent.FormatOf(portable),
|
||||
FramesVersion = media?.FramesVersion ?? workspace.Media.FramesVersion,
|
||||
RestoredFrom = sync.RestoredFrom,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
project.WriteVersion(version);
|
||||
if (sync.RestoredFrom is not null) project.WriteSync(sync with { RestoredFrom = null });
|
||||
return version;
|
||||
}
|
||||
|
||||
private async Task<WorkspaceStatus> StatusLockedAsync(WorkspaceProject project, IProjectHome? home, CancellationToken cancellationToken)
|
||||
{
|
||||
var bundle = project.ReadBundle();
|
||||
var workspace = bundle.Workspace!;
|
||||
WorkspaceMedia? media;
|
||||
try
|
||||
{
|
||||
media = project.ReadMedia();
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
media = null;
|
||||
}
|
||||
var conflict = project.ReadSync().Conflict;
|
||||
var locals = Unpushed(project, bundle);
|
||||
var tipHash = locals.Count > 0 ? locals[^1].ContentHash : workspace.Base?.ContentHash;
|
||||
var modified = !bundle.IsReadOnly && (Portable(bundle.Project, media) is not { } portable || ProjectContent.Hash(portable) != tipHash);
|
||||
ProjectVersion? head = null;
|
||||
var offline = false;
|
||||
if (home is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
head = await home.HeadAsync(project.ProjectId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (HomeUnavailableException)
|
||||
{
|
||||
offline = true;
|
||||
}
|
||||
}
|
||||
var behind = head is not null && head.Id != workspace.Base?.VersionId ? Math.Max(1, head.Number - (workspace.Base?.Number ?? 0)) : 0;
|
||||
// A local commit the home stored although its answer was lost reads as behind by the commits it holds: they are ours.
|
||||
if (head is not null && locals.Any(v => v.Id == head.Id)) behind = 0;
|
||||
var state = media is null ? WorkspaceState.MediaRemoved
|
||||
: conflict is not null ? WorkspaceState.Conflict
|
||||
: offline ? WorkspaceState.Offline
|
||||
: behind > 0 ? WorkspaceState.Behind
|
||||
: locals.Count > 0 ? WorkspaceState.Ahead
|
||||
: modified ? WorkspaceState.Modified
|
||||
: WorkspaceState.InSync;
|
||||
return new WorkspaceStatus(state, modified, locals.Count, behind, offline, media is null, bundle.IsReadOnly, conflict, workspace.Base, head);
|
||||
}
|
||||
|
||||
/// <summary>The local versions after the base, oldest first, each the child of the one before (the base's for the first).</summary>
|
||||
private static List<ProjectVersion> Unpushed(WorkspaceProject project, ProjectBundle bundle)
|
||||
{
|
||||
var basis = bundle.Workspace!.Base;
|
||||
var candidates = project.Versions().Where(v => v.StoredAt is null && v.Number > (basis?.Number ?? 0)).ToList();
|
||||
var chain = new List<ProjectVersion>();
|
||||
var parent = basis?.VersionId;
|
||||
while (candidates.FirstOrDefault(v => v.ParentId == parent) is { } next)
|
||||
{
|
||||
chain.Add(next);
|
||||
candidates.Remove(next);
|
||||
parent = next.Id;
|
||||
}
|
||||
return chain;
|
||||
}
|
||||
|
||||
/// <summary>The base version's content: this workspace's file, else the home's (kept as a file).</summary>
|
||||
private static async Task<ProjectVersion?> BaseVersionAsync(WorkspaceProject project, ProjectBundle bundle, IProjectHome home, CancellationToken cancellationToken)
|
||||
{
|
||||
if (bundle.Workspace!.Base is not { } basis) return null;
|
||||
if (project.Versions().FirstOrDefault(v => v.Id == basis.VersionId) is { } local) return local;
|
||||
var fetched = await home.GetVersionAsync(project.ProjectId, basis.VersionId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ProjectException(ProjectError.NotFound, $"The home no longer has version {basis.Number} of project {project.ProjectId}.");
|
||||
Verify(fetched);
|
||||
project.WriteVersion(fetched, replace: true);
|
||||
return fetched;
|
||||
}
|
||||
|
||||
private static ProjectBundle WithBase(ProjectBundle bundle, ProjectVersion version) =>
|
||||
bundle with { Workspace = bundle.Workspace! with { Base = Base(version) } };
|
||||
|
||||
private static BundleBase Base(ProjectVersion version) => new(version.Id, version.Number, version.ContentHash);
|
||||
|
||||
/// <summary>A version as a home handed it: its settings match its hash.</summary>
|
||||
private static void Verify(ProjectVersion version)
|
||||
{
|
||||
if (!ProjectContent.Verifies(version.SettingsJson, version.ContentHash))
|
||||
throw new InvalidDataException($"Version {version.Number} of project {version.ProjectId} does not match its content hash.");
|
||||
}
|
||||
|
||||
private static HashSet<string> Paths(IEnumerable<SettingsDifference> differences) => [.. differences.Select(d => d.Path)];
|
||||
|
||||
/// <summary>
|
||||
/// The portable form of a working state, whose positions name the frames of <paramref name="media"/>; null when the
|
||||
/// workspace holds no media and the working state names frames by position (which frames, only the media say).
|
||||
/// </summary>
|
||||
private static string? Portable(ProjectSettings working, WorkspaceMedia? media)
|
||||
{
|
||||
if (media is not null) return ProjectContent.ToPortable(working, media.Photos);
|
||||
var positions = working.ExcludedFrames.Count > 0 || working.HeroFrame is not null || working.Camera.Keyframes.Count > 0;
|
||||
return positions ? null : ProjectContent.ToPortable(working, NoFrames);
|
||||
}
|
||||
|
||||
private static InvalidOperationException MediaMissing(Guid projectId) =>
|
||||
new($"Project {projectId} names frames the workspace holds no media of: copy the media again first.");
|
||||
|
||||
private WorkspaceProject Existing(Guid projectId) =>
|
||||
store.Find(projectId) ?? throw new InvalidOperationException($"Project {projectId} is not in the workspace.");
|
||||
|
||||
private static InvalidOperationException ReadOnly(Guid projectId) =>
|
||||
new($"Project {projectId} holds settings of a newer Chronos: it opens read-only.");
|
||||
|
||||
/// <summary>The sequence of a workspace project over its media, for the editor.</summary>
|
||||
private static WorkspaceSequence SequenceOf(WorkspaceProject project, ProjectBundle bundle, WorkspaceMedia media)
|
||||
{
|
||||
var frames = media.ToFrames();
|
||||
var files = media.Frames.Select(f => f.File is { } file && File.Exists(project.MediaFile(file)) ? project.MediaFile(file) : null).ToList();
|
||||
var times = frames.Where(f => f.CapturedAt is not null).Select(f => f.CapturedAt!.Value).Order().ToList();
|
||||
var sequence = new Sequence
|
||||
{
|
||||
Id = bundle.Workspace!.Home.SequenceId,
|
||||
ArchiveId = bundle.Archive.Id,
|
||||
Title = bundle.Sequence.Title,
|
||||
Folder = bundle.Sequence.Folder,
|
||||
FrameCount = frames.Count,
|
||||
FirstCapture = times.Count > 0 ? times[0] : null,
|
||||
LastCapture = times.Count > 0 ? times[^1] : null,
|
||||
FramesVersion = media.FramesVersion,
|
||||
SettingsJson = bundle.Project.ToJson(),
|
||||
Origin = bundle.Workspace.Home.IsArchive ? SequenceOrigin.Local : SequenceOrigin.Server,
|
||||
};
|
||||
return new WorkspaceSequence(sequence, frames, files.Select((f, i) => frames[i].Flags.HasFlag(FrameFlags.Missing) ? null : f).ToList());
|
||||
}
|
||||
|
||||
/// <summary>The choice "take the server's wherever both changed": its paths are only known once the merge ran.</summary>
|
||||
private sealed class EveryPath : HashSet<string>;
|
||||
}
|
||||
Reference in new issue
Block a user