Files
Chronos/src/Chronos.App/Workspace/WorkspaceHost.cs
T
Alby96andClaude Opus 5.5 a368dc8bf0 fix(projects): phase 5a fix round 2 of the projects engine
The sidecars stay the truth of a sequence's projects in the cases round 1's
checkers found still open, and no version or setting is lost on the way:

- An index-only Main meeting a Main another index made is written back as
  another project, and Main passes to theirs in one transaction through a
  free temporary name, so ux_projects_name and ux_projects_main never fail
  (the SqliteException used to escape ListAsync and leave the index and the
  sidecars disagreeing). A refusal is logged; the next reconcile settles it.
- The reconcile takes Main from the records, in step with the index, when
  another index passed it on: exactly one Main per sequence, names from the
  records where free.
- A project folder with versions and no record, of a project no index row
  names (a creation cut before its record), no longer holds the sequence
  back forever: it is left as it is and indexed once its record arrives.
- A record behind the index (a projects folder put back from an older
  backup) is made whole from the index: its missing versions and the record
  are written again, at every catch-up and before any append, rename or
  delete. Only a record ahead of the index or naming another version is
  refused, with a message that says so.
- An index meeting Main walks the chain down to the version the record names
  as mirrored (a bound, since that record write may lag project.json), so a
  lagging record never makes an External that reverts a newer push. When the
  record names a mirrored ancestor, settings written since merge with the
  unmirrored versions, as for an index that knows its mirror.
- The catch-up merge's External + Merge pair is resumable: an External head
  whose parent is a push no mirror wrote is finished into its Merge version
  next time, by this index or one rebuilt from the sidecars.
- A project deleted at the home has no head there, so a workspace copy of it
  reads Gone, never In sync; Remove local copy without discard says the
  project was deleted in the library.
- DatabaseExceptions are contained per sequence in the archive scan's project
  reconcile and in ProjectService reads.

Tests: SQLite (PostgreSQL-ready) for each scenario, including a cut between
the two catch-up versions, a 40,000-exclusion version through save, push and
rebuild, and the App's Remove local copy of a project deleted at home.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 11:24:15 +01:00

734 lines
44 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.IO;
using Chronos.App.Infrastructure;
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;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
namespace Chronos.App.Workspace;
/// <summary>A workspace operation was refused for a reason the user can act on; the message is one localized sentence.</summary>
public sealed class WorkspaceException(string message, Exception? inner = null) : InvalidOperationException(message, inner);
/// <summary>A project of this PC's workspace, as Edit's picker and the editor list it.</summary>
/// <param name="HasMedia">The workspace holds the project's media (a copy that ended); without them it cannot open.</param>
/// <param name="Saved">When its working state was last written.</param>
public sealed record WorkspaceEntry(Guid ProjectId, Guid SequenceId, string Name, bool IsMain, BundleHome Home, string SequenceTitle, bool HasMedia,
DateTimeOffset Saved);
/// <summary>A project brought into the workspace and the copy of its media that was queued.</summary>
public sealed record WorkspaceCheckout(SequenceProject Project, Job Copy);
/// <summary>What Save version did: the version (null when nothing changed), its sync when Sync automatically is on, where the project stands.</summary>
/// <param name="SyncError">Why the sync after it did not happen (the home out of reach, the project busy); the version waits here.</param>
public sealed record WorkspaceSaveResult(ProjectVersion? Version, WorkspaceSyncResult? Synced, WorkspaceStatus Status, Exception? SyncError);
/// <summary>A project's history as the History flyout lists it: newest first, the versions not sent yet on top.</summary>
/// <param name="Unsent">The ids among <paramref name="Versions"/> that wait to be sent to the home.</param>
/// <param name="Offline">The home could not be asked: only the versions this workspace keeps are listed.</param>
public sealed record WorkspaceHistory(IReadOnlyList<ProjectVersion> Versions, IReadOnlySet<Guid> Unsent, bool Offline);
/// <summary>
/// The plan of "Remove local copy": what the project's folder holds (files and bytes) and what would not be at the home
/// after it (versions not sent, changes not saved as a version, a conflict to settle).
/// </summary>
/// <param name="Gone">
/// The home answered it no longer has the project or its sequence: nothing can be sent or checked there, so the copy can
/// only go with its work kept aside (Discard).
/// </param>
public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files, long Bytes, int Unsent, bool Modified, bool Conflict, bool Offline, bool Gone = false)
{
/// <summary>Everything the copy holds is at the home: it can go without discarding anything.</summary>
public bool IsSafe => Unsent == 0 && !Modified && !Conflict;
}
/// <summary>
/// The workspace of this PC (owner review 2, R8), composed for the desktop: its folder (Settings › Workspace, else
/// <c>workspace</c> under the data folder: <c>%LOCALAPPDATA%\Chronos\workspace</c>, <c>.\data\workspace</c> for a portable
/// copy), the <see cref="WorkspaceStore"/> and <see cref="WorkspaceSync"/> over it, and this PC's archive as the home of
/// its projects (<see cref="ArchiveProjectHome"/>; a server home comes in phase 5b). Every operation runs off the UI thread
/// and returns where the project stands. Nothing a workspace holds is lost: a version is sent before its copy goes, a copy
/// is removed only once the home verifiably holds its head, the work a user chose to discard is kept in
/// <c>&lt;workspace&gt;/.trash</c>, and versions the home holds are pruned past Settings › Workspace › Kept versions only
/// after the home was asked for each. A capture (sample data, no engine) has no workspace: Edit opens the library there.
/// </summary>
public sealed class WorkspaceHost
{
/// <summary>Where discarded work of removed local copies is kept (the store lists only folders named by a project id).</summary>
public const string TrashFolder = ".trash";
private readonly AppEnvironment _environment;
private readonly AppSettings _settings;
private readonly Action _savePreferences;
private readonly Func<ChronosDatabase?> _db;
private readonly Func<ArchiveService?> _archives;
private readonly Func<JobEngine?> _engine;
private readonly Lock _gate = new();
private readonly Dictionary<Guid, Guid> _copies = [];
private OpenWorkspace? _open;
public WorkspaceHost(AppEnvironment environment, AppSettings settings, Action savePreferences, Func<ChronosDatabase?> db, Func<ArchiveService?> archives,
Func<JobEngine?> engine)
{
_environment = environment;
_settings = settings;
_savePreferences = savePreferences;
_db = db;
_archives = archives;
_engine = engine;
}
/// <summary>
/// The PC versions made here carry ("STUDIO-PC"): data, shown as it is by History (no words of the UI in it, so every
/// language reads it alike).
/// </summary>
public static string ClientName { get; } = Environment.MachineName;
/// <summary>How long an operation waits for a project another writer holds (a copy job writing its media index).</summary>
public TimeSpan LockWait { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>The workspace folder of a data folder: <c>workspace</c> beside the index.</summary>
public static string DefaultRoot(AppEnvironment environment)
{
ArgumentNullException.ThrowIfNull(environment);
return Path.Combine(environment.DataDirectory, WorkspaceStore.DefaultFolderName);
}
/// <summary>The folder in use: Settings › Workspace › Folder, else <see cref="DefaultRoot"/>.</summary>
public string Root => _settings.WorkspaceFolder is { Length: > 0 } folder ? Path.GetFullPath(folder) : DefaultRoot(_environment);
/// <summary>Edit opens workspace projects (false in a capture, whose sample library has no engine to copy media).</summary>
public bool IsEnabled => !_environment.IsCapture;
/// <summary>The workspace can be used now: enabled, with the index and the archive engine open.</summary>
public bool IsAvailable => IsEnabled && _db() is not null && _archives() is not null;
public AppSettings Settings => _settings;
/// <summary>The sync over the workspace folder in use (made, with the folder and its manifest, at first use).</summary>
/// <exception cref="IOException">The folder cannot be made or read.</exception>
/// <exception cref="InvalidDataException">The folder holds another program's or a newer workspace manifest.</exception>
public WorkspaceSync Sync
{
get
{
var root = Root;
lock (_gate)
{
if (_open is not { } open || !string.Equals(open.Root, root, StringComparison.OrdinalIgnoreCase))
{
var store = new WorkspaceStore(root);
_open = open = new OpenWorkspace(root, new WorkspaceSync(store, ClientName) { LockWait = LockWait });
}
return open.Sync;
}
}
}
public WorkspaceStore Store => Sync.Store;
/// <summary>The home of a workspace project; null for a home this PC cannot reach in this phase (a server, phase 5b).</summary>
public IProjectHome? HomeOf(BundleHome home)
{
ArgumentNullException.ThrowIfNull(home);
return home.IsArchive && _db() is { } db && _archives() is { } archives ? new ArchiveProjectHome(db, archives.Projects, home.SequenceId) : null;
}
/// <summary>The home of a sequence of this PC's archive.</summary>
/// <exception cref="WorkspaceException">The index or the archive engine is not open.</exception>
public IProjectHome HomeOfSequence(Guid sequenceId) =>
HomeOf(new BundleHome(BundleHome.ArchiveKind, sequenceId)) ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
/// <summary>
/// The projects of the workspace (one whose working state cannot be read is left out, and logged). A workspace folder
/// not made yet that lies inside a library is not made by listing it: it lists nothing.
/// </summary>
public Task<IReadOnlyList<WorkspaceEntry>> ListAsync(CancellationToken cancellationToken = default) => Task.Run(async () =>
{
if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return [];
return (IReadOnlyList<WorkspaceEntry>)[.. Store.ListBundles().Select(b => Entry(b.Project, b.Bundle))];
}, cancellationToken);
/// <summary>The workspace projects of one sequence.</summary>
public async Task<IReadOnlyList<WorkspaceEntry>> ProjectsOfAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
[.. (await ListAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.SequenceId == sequenceId)];
/// <summary>A workspace project by id; null when the workspace has none (or it cannot be read).</summary>
public Task<WorkspaceEntry?> FindAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return null;
if (Store.Find(projectId) is not { } project) return null;
try
{
return Entry(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 null;
}
}, cancellationToken);
/// <summary>The project of <paramref name="sequenceId"/> opened last here, else the one saved last; null when the workspace has none.</summary>
public async Task<WorkspaceEntry?> LastUsedAsync(Guid sequenceId, CancellationToken cancellationToken = default)
{
var projects = await ProjectsOfAsync(sequenceId, cancellationToken).ConfigureAwait(false);
if (_settings.WorkspaceRecent.TryGetValue(sequenceId, out var last) && projects.FirstOrDefault(p => p.ProjectId == last) is { } recent) return recent;
return projects.OrderByDescending(p => p.Saved).FirstOrDefault();
}
/// <summary>Remembers <paramref name="projectId"/> as the project of <paramref name="sequenceId"/> to open next time.</summary>
public void Remember(Guid sequenceId, Guid projectId)
{
if (_settings.WorkspaceRecent.TryGetValue(sequenceId, out var known) && known == projectId) return;
_settings.WorkspaceRecent[sequenceId] = projectId;
_savePreferences();
}
/// <summary>The home's live projects of a sequence, Main first (made from the sequence's settings when it has none yet).</summary>
public Task<IReadOnlyList<SequenceProject>> HomeProjectsAsync(Guid sequenceId, CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
return Task.Run(() => home.ListAsync(cancellationToken), cancellationToken);
}
/// <summary>
/// Brings a project of <paramref name="sequenceId"/> into the workspace and queues the copy of its media: the project
/// <paramref name="projectId"/>, else a new one named <paramref name="newName"/> (from Main's head), else Main. A
/// project already here keeps its working state; only its media are copied again.
/// </summary>
/// <exception cref="ProjectException">The home has no such project, or the name is invalid or taken.</exception>
/// <exception cref="HomeUnavailableException">The archive is offline or busy.</exception>
/// <exception cref="WorkspaceException">The workspace folder lies inside a library: nothing was written, here or at the home.</exception>
public async Task<WorkspaceCheckout> CheckoutAsync(Guid sequenceId, Guid? projectId, string? newName, string media = BundleMedia.Proxies,
CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
var checkout = await Task.Run(async () =>
{
// Refused before anything is written: the copy job would refuse such a folder after the checkout filled it.
if (await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) throw new WorkspaceException(Loc.L("Errors.Workspace.InsideLibraryEdit", Root));
SequenceProject project;
if (newName is not null)
{
project = await home.CreateAsync(newName, null, null, cancellationToken).ConfigureAwait(false);
}
else
{
var listed = await home.ListAsync(cancellationToken).ConfigureAwait(false);
project = projectId is { } id
? listed.FirstOrDefault(p => p.Id == id) ?? throw new ProjectException(ProjectError.NotFound, $"The home has no project {id}.")
: listed.First(p => p.IsMain);
}
await Sync.CheckoutAsync(home, project.Id, media, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {project.Id} ('{project.Name}') of sequence {sequenceId} checked out into {Store.Root}");
return new WorkspaceCheckout(project, await QueueCopyCoreAsync(sequenceId, project.Id, media, cancellationToken).ConfigureAwait(false));
}, cancellationToken);
// Back on the caller's thread (the UI's): the settings are written there.
Remember(sequenceId, checkout.Project.Id);
return checkout;
}
/// <summary>
/// Queues the copy of a workspace project's media again ("Update media": the home's frames changed), unless one is
/// waiting or running already: that one is returned.
/// </summary>
public Task<Job> QueueCopyAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var bundle = Existing(projectId).ReadBundle();
return await QueueCopyCoreAsync(bundle.Workspace!.Home.SequenceId, projectId, bundle.Workspace.Media.Kind, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
/// <summary>
/// Where a project stands. With <paramref name="askHome"/>, against its home's head too: a home that cannot be reached
/// reads as offline; one that answers it no longer has the project or its sequence (the sequence left the index) reads
/// as <see cref="WorkspaceState.Gone"/>, whose local copy can then only be removed (nothing is removed by itself).
/// </summary>
public Task<WorkspaceStatus> StatusAsync(Guid projectId, bool askHome = true, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
var home = askHome ? HomeOf(project.ReadBundle().Workspace!.Home) : null;
try
{
return await Sync.StatusAsync(projectId, home, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (home is not null && ex is ProjectException or DatabaseException or IOException)
{
var gone = ex is ProjectException { Reason: ProjectError.SequenceNotFound or ProjectError.NotFound };
Log.Info("workspace", gone ? $"The home no longer has project {projectId}: {ex.Message}" : $"The home of project {projectId} could not be asked: {ex.Message}");
var local = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
return local with
{
Offline = true,
State = local.State is WorkspaceState.MediaRemoved or WorkspaceState.Conflict && !gone ? local.State
: gone ? WorkspaceState.Gone
: WorkspaceState.Offline,
};
}
}, cancellationToken);
/// <summary>
/// "Save version": the working state as a new local version with <paramref name="note"/> (none when nothing changed
/// since the last), then, with Settings › Workspace › Sync automatically, the sync with the home
/// (<see cref="SyncAsync"/>); a home out of reach leaves the version waiting here.
/// </summary>
/// <exception cref="InvalidOperationException">The project is read-only, has a conflict to settle, or names frames the workspace has no media of.</exception>
public async Task<WorkspaceSaveResult> SaveVersionAsync(Guid projectId, string? note, CancellationToken cancellationToken = default)
{
var version = await Task.Run(async () =>
{
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
return await Sync.CommitAsync(projectId, note, null, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
if (version is not null) Log.Info("workspace", $"Version {version.Number} of project {projectId} saved");
if (!_settings.WorkspaceAutoSync) return new WorkspaceSaveResult(version, null, await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false), null);
try
{
var synced = await SyncAsync(projectId, cancellationToken).ConfigureAwait(false);
return new WorkspaceSaveResult(version, synced, synced.Status, null);
}
catch (Exception ex) when (ex is HomeUnavailableException or LeaseUnavailableException or WorkspaceSyncException or WorkspaceException or ProjectException
or DatabaseException)
{
// The version is saved here all the same: it waits for the next sync.
Log.Info("workspace", $"Version of project {projectId} not sent yet: {ex.Message}");
return new WorkspaceSaveResult(version, null, await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false), ex);
}
}
/// <summary>The working state as a new local version without a note and without sending it; null when nothing changed.</summary>
public Task<ProjectVersion?> CommitAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
return await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
/// <summary>
/// "Sync": the home's new versions taken (the working state and the local versions moved onto them), then the local
/// versions sent in order, then the versions past Kept versions pruned. A real conflict stops it before anything is
/// sent (<see cref="WorkspaceState.Conflict"/>).
/// </summary>
/// <exception cref="HomeUnavailableException">The home cannot be reached; nothing was lost.</exception>
/// <exception cref="WorkspaceSyncException">The home refused a version for good.</exception>
public Task<WorkspaceSyncResult> SyncAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var home = HomeOfProject(projectId);
var pulled = await Sync.PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
if (pulled.Status.State == WorkspaceState.Conflict) return pulled;
var pushed = await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
await PruneQuietlyAsync(projectId, home, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {projectId} synced: {pushed.Pushed.Count} sent, {pulled.Pulled.Count + pushed.Pulled.Count} taken, {pushed.Status.State}");
return new WorkspaceSyncResult(pushed.Status, pushed.Pushed, [.. pulled.Pulled, .. pushed.Pulled]);
}, cancellationToken);
/// <summary>
/// Settles the conflict a sync stopped at, as <paramref name="shown"/> listed it to the user (else as recorded), then
/// sends what waits. When what differs now is not what was shown, nothing is settled: the conflict found now comes back
/// (<see cref="WorkspaceState.Conflict"/>) to be asked again. <see cref="ConflictChoice.SaveBoth"/> sends this
/// workspace's versions to a sibling project named "&lt;name&gt; (&lt;this PC&gt;)" (a number added when that name is taken).
/// </summary>
public Task<WorkspaceSyncResult> ResolveAsync(Guid projectId, ConflictChoice choice, IReadOnlySet<string>? takeServer = null,
WorkspaceConflict? shown = null, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var home = HomeOfProject(projectId);
WorkspaceSyncResult resolved;
if (choice == ConflictChoice.SaveBoth)
{
var name = SiblingName(Existing(projectId).ReadBundle().Workspace!.Name);
try
{
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, name, shown, cancellationToken).ConfigureAwait(false);
}
catch (ProjectException ex) when (ex.Reason is ProjectError.NameTaken or ProjectError.InvalidName)
{
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false);
}
}
else
{
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false);
}
if (resolved.Status.State == WorkspaceState.Conflict)
{
Log.Info("workspace", $"Conflict of project {projectId} not settled ({choice}): what differs changed since it was shown");
return resolved;
}
Log.Info("workspace", $"Conflict of project {projectId} settled: {choice}{(resolved.SavedAs is { } copy ? $", saved as '{copy.Name}'" : string.Empty)}");
var pushed = await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
return new WorkspaceSyncResult(pushed.Status, [.. resolved.Pushed, .. pushed.Pushed], [.. resolved.Pulled, .. pushed.Pulled], resolved.SavedAs)
{
Kept = resolved.Kept,
};
}, cancellationToken);
/// <summary>"<paramref name="name"/> (<c>PC</c>)", within the 60 characters of a project name.</summary>
public static string SiblingName(string name)
{
ArgumentNullException.ThrowIfNull(name);
var suffix = " (" + Environment.MachineName + ")";
if (suffix.Length >= ProjectService.MaxNameLength) suffix = suffix[..(ProjectService.MaxNameLength / 2)] + ")";
var room = ProjectService.MaxNameLength - suffix.Length;
return (name.Length > room ? name[..room].TrimEnd() : name) + suffix;
}
/// <summary>
/// Brings version <paramref name="versionId"/> back as the working state (uncommitted changes saved as a version first);
/// returns it, its positions on the media's frames.
/// </summary>
public Task<ProjectSettings> RestoreAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
if (status.ReadOnly) throw new WorkspaceException(Loc.L("Errors.Workspace.ReadOnly"));
if (status.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing"));
var home = HomeOf(Existing(projectId).ReadBundle().Workspace!.Home);
var restored = await Sync.RestoreAsync(projectId, versionId, home, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Version {versionId} of project {projectId} restored as the working state");
return restored;
}, cancellationToken);
/// <summary>The project's history, newest first: the versions not sent yet, then the home's (this workspace's own while the home is out of reach).</summary>
public Task<WorkspaceHistory> HistoryAsync(Guid projectId, int limit = 50, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
var unsent = Sync.Unpushed(projectId);
var home = HomeOf(project.ReadBundle().Workspace!.Home);
IReadOnlyList<ProjectVersion> stored;
var offline = false;
try
{
stored = home is null
? throw new HomeUnavailableException("The project's home cannot be reached from this PC.")
: await home.HistoryAsync(projectId, null, limit, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException)
{
Log.Info("workspace", $"The history of project {projectId} is read from the workspace: {ex.Message}");
offline = true;
stored = [.. project.Versions().Where(v => v.StoredAt is not null).OrderByDescending(v => v.Number).Take(limit)];
}
var ids = unsent.Select(v => v.Id).ToHashSet();
return new WorkspaceHistory([.. unsent.Reverse(), .. stored.Where(v => !ids.Contains(v.Id))], ids, offline);
}, cancellationToken);
/// <summary>A new project of the sequence named <paramref name="name"/> from <paramref name="fromVersionId"/> (a version the home holds), else from Main's head.</summary>
/// <exception cref="ProjectException">The name is invalid or taken.</exception>
public Task<SequenceProject> CreateProjectAsync(Guid sequenceId, string name, Guid? fromVersionId, CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
return Task.Run(async () =>
{
var created = await home.CreateAsync(name, fromVersionId, null, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project '{created.Name}' ({created.Id}) made for sequence {sequenceId}");
return created;
}, cancellationToken);
}
/// <summary>Renames a project at its home, then its working state here.</summary>
/// <exception cref="ProjectException">The name is invalid or taken, or the project is gone.</exception>
public Task<string> RenameAsync(Guid projectId, string name, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
var renamed = await ArchiveProjects(project).RenameAsync(projectId, name, cancellationToken).ConfigureAwait(false);
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
var bundle = project.ReadBundle();
project.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Name = renamed.Name } });
}
Log.Info("workspace", $"Project {projectId} renamed '{renamed.Name}'");
return renamed.Name;
}, cancellationToken);
/// <summary>
/// Deletes a project (never Main): the working state saved and sent first, so its home's trash
/// (<c>.chronos/projects/.trash</c>) holds every version; then the local copy goes.
/// </summary>
/// <returns>
/// False when the home deleted the project but its local copy could not be removed (a file in use): the copy stays,
/// and Remove local copy takes it later.
/// </returns>
/// <exception cref="WorkspaceException">Something could not be sent (the home out of reach, a conflict): nothing was deleted.</exception>
/// <exception cref="ProjectException">Main, or the project is gone.</exception>
public async Task<bool> DeleteProjectAsync(Guid projectId, CancellationToken cancellationToken = default)
{
var (sequenceId, removed) = await Task.Run(async () =>
{
var project = Existing(projectId);
var workspace = project.ReadBundle().Workspace!;
if (workspace.IsMain) throw new ProjectException(ProjectError.MainCannotBeDeleted, "The Main project cannot be deleted.");
var home = HomeOfProject(projectId);
var local = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
if (local.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
if (!local.ReadOnly) await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
var status = (await SendAsync(projectId, home, cancellationToken).ConfigureAwait(false)).Status;
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
await ArchiveProjects(project).DeleteAsync(projectId, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {projectId} ('{workspace.Name}') deleted at its home");
try
{
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
return (workspace.Home.SequenceId, true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or LeaseUnavailableException)
{
// The home's delete stands (its trash holds every version); the copy, all of it sent, waits for Remove local copy.
Log.Warning("workspace", $"Project {projectId} was deleted at its home, but its local copy stays", ex);
return (workspace.Home.SequenceId, false);
}
}, cancellationToken);
Forget(sequenceId, projectId);
return removed;
}
/// <summary>
/// "Send first" for a project not open in the editor (the picker's Remove local copy): its working state saved as a
/// version when it can be, then the sync.
/// </summary>
/// <exception cref="WorkspaceException">A conflict waits (open the project and Sync to settle it), or something is still not at the home.</exception>
public async Task SendAllAsync(Guid projectId, CancellationToken cancellationToken = default)
{
var local = await Task.Run(() => Sync.StatusAsync(projectId, null, cancellationToken), cancellationToken).ConfigureAwait(false);
if (local is { Conflict: null, ReadOnly: false, MediaRemoved: false }) await CommitAsync(projectId, cancellationToken).ConfigureAwait(false);
var status = (await SyncAsync(projectId, cancellationToken).ConfigureAwait(false)).Status;
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
}
/// <summary>The plan of "Remove local copy": the folder's files and size, and what would not be at the home after it.</summary>
public Task<WorkspaceRemovalPlan> PlanRemovalAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
var name = project.ReadBundle().Workspace!.Name;
var status = await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false);
var (files, bytes) = Measure(project.Folder);
return new WorkspaceRemovalPlan(projectId, name, files, bytes, status.Ahead, status.Modified, status.Conflict is not null, status.Offline,
status.State == WorkspaceState.Gone);
}, cancellationToken);
/// <summary>
/// Removes a project's local copy. Without <paramref name="discard"/> it is refused while anything is not at the home,
/// and the home's head and the base this copy was made from are read back and checked against their hashes first.
/// With <paramref name="discard"/> (the user's explicit word) the versions not sent and the working state are moved to
/// <c>&lt;workspace&gt;/.trash</c> rather than erased. The media (copies the home can make again) are deleted.
/// </summary>
/// <exception cref="WorkspaceException">Something is not at the home yet, or the home's copy does not check out.</exception>
public async Task RemoveLocalCopyAsync(Guid projectId, bool discard, CancellationToken cancellationToken = default)
{
var sequenceId = await Task.Run(async () =>
{
var project = Existing(projectId);
var workspace = project.ReadBundle().Workspace!;
if (!discard)
{
var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly) || status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
await VerifyHomeAsync(projectId, workspace, cancellationToken).ConfigureAwait(false);
}
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Local copy of project {projectId} ('{workspace.Name}') removed{(discard ? ", its unsent work kept in " + TrashFolder : string.Empty)}");
return workspace.Home.SequenceId;
}, cancellationToken);
Forget(sequenceId, projectId);
}
/// <summary>
/// Drops the oldest versions this workspace took from the home, keeping Settings › Workspace › Kept versions of them
/// (the base among them), the versions not sent and the set-aside ones; a version goes only once the home was asked
/// and holds it with the same content.
/// </summary>
public async Task<int> PruneAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(home);
var project = Existing(projectId);
var keep = Math.Max(1, _settings.WorkspaceKeptVersions);
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
var basis = project.ReadBundle().Workspace!.Base;
var stored = project.Versions().Where(v => v.StoredAt is not null).OrderByDescending(v => v.Number).ToList();
var kept = stored.Where(v => v.Id != basis?.VersionId).Take(keep - (basis is null ? 0 : 1)).Select(v => v.Id).ToHashSet();
var removed = 0;
foreach (var version in stored.Where(v => v.Id != basis?.VersionId && !kept.Contains(v.Id)))
{
// Read back from where the home keeps it, not from an index of it.
if (!await home.HoldsAsync(projectId, version, cancellationToken).ConfigureAwait(false)) continue;
File.Delete(project.VersionPath(version));
removed++;
}
return removed;
}
}
private async Task PruneQuietlyAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken)
{
try
{
var removed = await PruneAsync(projectId, home, cancellationToken).ConfigureAwait(false);
if (removed > 0) Log.Info("workspace", $"{removed} older version(s) of project {projectId} dropped from the workspace (kept at the home)");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or ProjectException)
{
Log.Warning("workspace", $"Older versions of project {projectId} could not be pruned", ex);
}
}
/// <summary>The local versions sent (after the home's new ones were taken), as one sync without the pruning.</summary>
private async Task<WorkspaceSyncResult> SendAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken)
{
var pulled = await Sync.PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
return pulled.Status.State == WorkspaceState.Conflict ? pulled : await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
}
/// <summary>The home holds this copy's work: its head and the base this copy was last in step with read back, each matching its hash.</summary>
private async Task VerifyHomeAsync(Guid projectId, BundleWorkspace workspace, CancellationToken cancellationToken)
{
var home = HomeOf(workspace.Home) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"));
ProjectVersion head;
ProjectVersion? basis;
bool held;
try
{
head = await home.HeadAsync(projectId, cancellationToken).ConfigureAwait(false);
basis = workspace.Base is { } b ? await home.GetVersionAsync(projectId, b.VersionId, cancellationToken).ConfigureAwait(false) : head;
// Read back from where the home keeps them, not from an index of them.
held = basis is not null && await home.HoldsAsync(projectId, head, cancellationToken).ConfigureAwait(false)
&& (basis.Id == head.Id || await home.HoldsAsync(projectId, basis, cancellationToken).ConfigureAwait(false));
}
catch (ProjectException ex) when (ex.Reason is ProjectError.NotFound or ProjectError.SequenceNotFound)
{
// Deleted at the home (its trash keeps every version sent): this copy goes only when its user discards it.
throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"), ex);
}
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException)
{
throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"), ex);
}
if (!held || !ProjectContent.Verifies(head.SettingsJson, head.ContentHash) || basis is null || !ProjectContent.Verifies(basis.SettingsJson, basis.ContentHash)
|| (workspace.Base is { } known && !string.Equals(known.ContentHash, basis.ContentHash, StringComparison.OrdinalIgnoreCase)))
throw new WorkspaceException(Loc.L("Errors.Workspace.HomeCheck"));
}
/// <summary>
/// The project's folder taken out of the workspace under its lease: the working state, the versions, the sync state and
/// the exports moved to <c>.trash/&lt;id&gt;-&lt;time&gt;</c> (kept: nothing a user made is erased), the media deleted; the
/// emptied folder goes once the lease is released.
/// </summary>
private async Task RemoveFolderAsync(WorkspaceProject project, CancellationToken cancellationToken)
{
// A copy of its media still under way would write them again behind the removal.
Guid copy;
lock (_gate) _copies.Remove(project.ProjectId, out copy);
if (copy != Guid.Empty && _engine() is { } engine && _db() is { } db && await db.Jobs.GetAsync(copy, cancellationToken).ConfigureAwait(false) is
{ State: JobState.Queued or JobState.Running or JobState.Paused })
await engine.CancelAsync(copy, cancellationToken).ConfigureAwait(false);
var aside = Path.Combine(Store.Root, TrashFolder, project.ProjectId.ToString("N") + "-" + DateTime.UtcNow.Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture));
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
Directory.CreateDirectory(aside);
// The working state first: without it the folder is no project any more, whatever happens after.
File.Move(project.BundlePath, Path.Combine(aside, WorkspaceProject.BundleFile));
if (File.Exists(project.SyncPath)) File.Move(project.SyncPath, Path.Combine(aside, WorkspaceProject.SyncFile));
if (Directory.Exists(project.VersionsDirectory)) Directory.Move(project.VersionsDirectory, Path.Combine(aside, WorkspaceProject.VersionsFolder));
if (Directory.Exists(project.ExportsDirectory) && Directory.EnumerateFileSystemEntries(project.ExportsDirectory).Any())
Directory.Move(project.ExportsDirectory, Path.Combine(aside, WorkspaceProject.ExportsFolder));
if (Directory.Exists(project.MediaDirectory)) Directory.Delete(project.MediaDirectory, recursive: true);
}
try
{
Directory.Delete(project.Folder, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Info("workspace", $"The emptied folder {project.Folder} stays: {ex.Message}");
}
}
/// <summary>A version can be saved: no conflict waits, the settings are this Chronos's, the media are here.</summary>
/// <exception cref="WorkspaceException">Why not.</exception>
private static void EnsureWritable(WorkspaceStatus status)
{
if (status.ReadOnly) throw new WorkspaceException(Loc.L("Errors.Workspace.ReadOnly"));
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
if (status.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing"));
}
/// <summary>
/// The workspace folder lies inside a library this index knows (a portable copy's <c>data</c> folder under a library
/// at a drive's root): editing happens outside every library, so nothing is checked out or copied there.
/// </summary>
private async Task<bool> InsideALibraryAsync(CancellationToken cancellationToken)
{
if (_db() is not { } db) return false;
var root = Plain(Path.GetFullPath(Root));
foreach (var archive in await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (DataLocation.IsUnder(root, Plain(Path.GetFullPath(archive.RootPath)))) return true;
}
return false;
// Without the long-path prefix, which only one of the two may carry.
static string Plain(string path) =>
path.StartsWith(@"\\?\UNC\", StringComparison.Ordinal) ? @"\\" + path[8..]
: path.StartsWith(@"\\?\", StringComparison.Ordinal) ? path[4..]
: path;
}
private void Forget(Guid sequenceId, Guid projectId)
{
if (!_settings.WorkspaceRecent.TryGetValue(sequenceId, out var known) || known != projectId) return;
_settings.WorkspaceRecent.Remove(sequenceId);
_savePreferences();
}
private async Task<Job> QueueCopyCoreAsync(Guid sequenceId, Guid projectId, string media, CancellationToken cancellationToken)
{
var engine = _engine() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var db = _db() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
Guid known;
lock (_gate) _copies.TryGetValue(projectId, out known);
if (known != Guid.Empty && await db.Jobs.GetAsync(known, cancellationToken).ConfigureAwait(false) is { State: JobState.Queued or JobState.Running } running) return running;
var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {sequenceId} is not in the index.");
var job = await engine.EnqueueAsync(WorkspaceJobs.Copy(sequence, Store.Root, projectId, media), cancellationToken: cancellationToken).ConfigureAwait(false);
lock (_gate) _copies[projectId] = job.Id;
return job;
}
private IProjectHome HomeOfProject(Guid projectId) =>
HomeOf(Existing(projectId).ReadBundle().Workspace!.Home) ?? throw new HomeUnavailableException("The project's home cannot be reached from this PC.");
private ProjectService ArchiveProjects(WorkspaceProject project) =>
project.ReadBundle().Workspace!.Home.IsArchive && _archives() is { } archives ? archives.Projects : throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"));
private WorkspaceProject Existing(Guid projectId) => Store.Find(projectId) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.NotCheckedOut"));
private static WorkspaceEntry Entry(WorkspaceProject project, ProjectBundle bundle)
{
var workspace = bundle.Workspace!;
return new WorkspaceEntry(project.ProjectId, workspace.Home.SequenceId, workspace.Name, workspace.IsMain, workspace.Home,
bundle.Sequence.Title is { Length: > 0 } title ? title : bundle.Sequence.Folder, File.Exists(project.MediaIndexPath), bundle.Saved);
}
/// <summary>Files and bytes under <paramref name="folder"/>, the lease left out.</summary>
private static (int Files, long Bytes) Measure(string folder)
{
var (files, bytes) = (0, 0L);
if (!Directory.Exists(folder)) return (files, bytes);
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", SearchOption.AllDirectories))
{
if (file.Name.EndsWith(".lease", StringComparison.OrdinalIgnoreCase)) continue;
files++;
bytes += file.Length;
}
return (files, bytes);
}
private sealed record OpenWorkspace(string Root, WorkspaceSync Sync);
}