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:
Alby96 committed 2026-10-27 22:51:32 +01:00
1 parent e3cbe30b29
commit 03d32f18d3
51 files changed
+4917 -108

No files matched your search

@@ -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>;
}