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;
/// The manifest of a workspace folder (workspace.json).
public sealed record WorkspaceManifest(string Format, int FormatVersion, Guid Id, DateTimeOffset Created);
///
/// A workspace's sync state of one project besides its versions (sync.json): a restore to record, a conflict to
/// settle, and the journal of a replay or a save-both under way, which the next sync finishes or undoes after a crash.
///
/// The version a restore brought back; the next commit is a "restore" of it.
/// The conflict a pull or push stopped at, until the user settles it.
/// A replay (or a base moved onto local commits the home holds) written in steps; null when none is under way.
/// A save-both that made its copy at the home and has not finished; null when none is under way.
public sealed record WorkspaceSyncState(Guid? RestoredFrom, WorkspaceConflict? Conflict, WorkspaceReplay? Replay = null, WorkspaceSaveBoth? SaveBoth = null)
{
public static WorkspaceSyncState None { get; } = new(null, null);
/// Nothing to keep: the file can go.
[JsonIgnore]
public bool IsEmpty => RestoredFrom is null && Conflict is null && Replay is null && SaveBoth is null;
}
///
/// The journal of a replay (): the base it moves the project onto, the local versions it
/// replaces, the replayed ones it writes and the local versions the home already holds (their answer lost), whose files
/// take the home's copy. The bundle's base is the commit point: once it is the replay is finished
/// (the replaced set aside, the held ones adopted), before it the replayed ones are set aside and nothing else moved.
///
public sealed record WorkspaceReplay(Guid OntoBase, IReadOnlyList Replaced, IReadOnlyList Replayed, IReadOnlyList Adopted);
///
/// A save-both under way (): the copy made at the home and its first version (the base the
/// local versions are sent on top of), the base this project had when it started, and the id each local version is sent
/// under, so a retry sends to the same copy what it lacks and the home answers "already stored" for the rest.
///
public sealed record WorkspaceSaveBoth(Guid CopyId, Guid CopyBaseId, int CopyBaseNumber, Guid? FromBase, IReadOnlyList Moves);
/// A local version () and the id it is sent under to a save-both's copy.
public sealed record WorkspaceMove(Guid LocalId, Guid CopyVersionId);
/// A version file of a workspace that cannot be read (): the number and id its name carries, and why.
public sealed record UnreadableVersion(int Number, Guid Id, string Path, string Reason);
///
/// 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 ().
///
public sealed record WorkspaceConflict(Guid TheirsVersionId, int TheirsNumber, Guid BaseVersionId, IReadOnlyList Mine,
IReadOnlyList Differences, DateTimeOffset Found)
{
///
/// The home's head holds settings of a newer Chronos (a difference at ): nothing of
/// this workspace's is merged into them. Only Save both settles it (this workspace's versions go to a new project in this
/// Chronos's format), or a Chronos that reads them; keeping mine or taking the server's is refused.
///
[JsonIgnore]
public bool NewerFormat => Differences.Any(d => d.Path == ProjectMerge.FormatPath);
}
///
/// Parameters of a job: target = the home's sequence; the workspace folder, the
/// project whose media to copy and what to copy (; originals in phase 5c).
///
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;
///
/// The workspace of this PC (owner review 2, R8): a folder on a fast disk where projects are edited, never inside the
/// library. <root>/workspace.json names it; each project has a folder named by its id
/// (). There is no index: the store lists the folders holding a project.chronos. The
/// desktop puts it in %LOCALAPPDATA%\Chronos\workspace unless set otherwise; the store takes any folder.
///
public sealed class WorkspaceStore
{
public const string ManifestFile = "workspace.json";
public const string FormatName = "chronos-workspace";
public const int FormatVersion = 1;
/// The folder name of the workspace inside the program's data folder.
public const string DefaultFolderName = "workspace";
///
/// Opens the workspace at , making the folder and its manifest when there is none. The manifest
/// is written whole to a temporary file and moved into place, so a crash never leaves half of one; a manifest left
/// empty, or unreadable in a folder that holds no project yet (an earlier build's interrupted first write), is made again.
///
/// The folder's workspace.json is not a workspace manifest, or a newer one.
/// The folder cannot be made or read.
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)) Create(path, replace: false);
else if (Unfinished(path)) Create(path, replace: true);
Manifest = Read(path);
}
public string Root { get; }
public WorkspaceManifest Manifest { get; }
public Guid Id => Manifest.Id;
/// The folder of a project, whether it exists or not.
public WorkspaceProject Project(Guid projectId) => new(this, projectId);
/// The project's folder when it holds a working state; null otherwise.
public WorkspaceProject? Find(Guid projectId)
{
var project = Project(projectId);
return project.Exists ? project : null;
}
/// The projects of the workspace: every folder named by a project id that holds a project.chronos.
public IReadOnlyList List()
{
var found = new List();
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;
}
/// The working states of the workspace's projects (one unreadable is left out, and logged).
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;
}
///
/// Writes a new manifest. Without another program opening the same folder at the same moment
/// may have made one first: that one wins (the move never replaces a file).
///
private static void Create(string path, bool replace)
{
var manifest = new WorkspaceManifest(FormatName, FormatVersion, Guid.CreateVersion7(), DateTimeOffset.UtcNow);
var text = JsonSerializer.Serialize(manifest, WorkspaceJson.Default.WorkspaceManifest);
if (replace)
{
Log.Warning("workspace", $"{path} was left unfinished; a new manifest is written");
AtomicFile.WriteAllText(path, text);
return;
}
var temp = AtomicFile.TempPathFor(path);
try
{
using (var stream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
stream.Write(System.Text.Encoding.UTF8.GetBytes(text));
stream.Flush(flushToDisk: true);
}
try
{
File.Move(temp, path, overwrite: false);
}
catch (IOException) when (File.Exists(path))
{
// Another program's manifest came first.
}
}
finally
{
if (File.Exists(temp)) File.Delete(temp);
}
}
///
/// A manifest an interrupted first write left (an earlier build wrote it in place): empty, or not JSON in a folder that
/// holds no project yet. A readable manifest, or any in a folder with projects, is never written over.
///
private bool Unfinished(string path)
{
string text;
try
{
text = AtomicFile.ReadAllText(path);
}
catch (IOException)
{
return false;
}
if (string.IsNullOrWhiteSpace(text.Trim('\0'))) return true;
try
{
using var _ = JsonDocument.Parse(text);
return false;
}
catch (JsonException)
{
return List().Count == 0;
}
}
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;
}
}
///
/// One project in the workspace (owner review 2, R8): <root>/<project id>/ with
/// project.chronos (the working state: a project file of format 2, its settings placed on the media's frames),
/// media/media.json with media/proxies/<frame id>.jpg (originals later) and media/analysis.json
/// (the home's deep report), versions/<number>-<id>.json (commits not pushed yet, and the versions pulled),
/// sync.json, exports/ and the lease .lock.lease that one writer at a time holds.
///
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";
/// Old local commits replaced by their replay on top of the home's head: kept, never erased by Chronos.
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);
/// The file a frame's proxy is copied to, relative to .
public static string ProxyName(Guid frameId) => ProxiesFolder + "/" + ProxyCache.FileName(frameId);
/// The absolute path of a file named relative to .
public string MediaFile(string relative) => LongPath.FromPortableRelative(MediaDirectory, relative);
/// Holds the project for one writer (this program's sync, a copy job) until disposed.
/// Another writer kept it for longer than .
public async Task LockAsync(TimeSpan wait, CancellationToken cancellationToken = default)
{
Directory.CreateDirectory(Folder);
return await LeaseFile.AcquireAsync(Folder, LeaseName, "workspace@" + Environment.MachineName, wait, cancellationToken: cancellationToken).ConfigureAwait(false);
}
/// Not a project file of a workspace, damaged or newer.
/// The file cannot be read.
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);
}
/// The media index; null while the media were never copied, or were removed.
/// The index is damaged or newer.
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));
}
///
/// The versions this workspace holds, oldest first. One that cannot be read is left out here, logged, and listed by
/// : the sync treats one above the base as a gap in the chain of versions to send, never
/// as a version that is not there ().
///
public IReadOnlyList Versions() => ReadVersions(log: true).Versions;
///
/// The version files of the workspace that cannot be read now (damaged, held open, over the size a version may be, of
/// a newer Chronos), by the number and id their names carry, oldest first.
///
public IReadOnlyList UnreadableVersions() => ReadVersions(log: false).Unreadable;
private (List Versions, List Unreadable) ReadVersions(bool log)
{
var versions = new List();
var unreadable = new List();
foreach (var (number, id, 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)
{
// Said once per file as it is now: every sync step lists the versions again.
if (log && (!Reported.TryGetValue(path, out var said) || said != ex.Message))
{
Reported[path] = ex.Message;
Log.Warning("workspace", $"Version file {path} cannot be read", ex);
}
unreadable.Add(new UnreadableVersion(number, id, path, ex.Message));
}
}
return (versions, unreadable);
}
/// The version files whose read failure was logged, with why (logged again when the reason changes).
private static readonly System.Collections.Concurrent.ConcurrentDictionary Reported = new(StringComparer.Ordinal);
/// The path of a version in .
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);
///
/// Moves a version file aside into versions/.replaced (a local commit replayed under another id), trying again
/// for a moment while another program (an indexer, an antivirus) holds it open.
///
internal void SetAside(ProjectVersion version) => SetAside(VersionPath(version));
/// Moves the version file at aside into versions/.replaced (see ).
internal void SetAside(string path)
{
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);
for (var attempt = 1; ; attempt++)
{
try
{
File.Move(path, target);
return;
}
catch (IOException) when (attempt < SetAsideAttempts && File.Exists(path) && !File.Exists(target))
{
Thread.Sleep(10 * attempt);
}
}
}
///
/// Writes a version straight into versions/.replaced: kept, never part of the chain of versions to send (the
/// working state a take of the server's values replaced).
///
internal void WriteAside(ProjectVersion version)
{
ArgumentNullException.ThrowIfNull(version);
ProjectSidecars.WriteVersion(Path.Combine(VersionsDirectory, ReplacedFolder, Path.GetFileName(VersionPath(version))), version);
}
/// Moves tried, some 1 s in all, before a version file held open fails to move aside.
private const int SetAsideAttempts = 15;
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)
{
ArgumentNullException.ThrowIfNull(state);
if (state.IsEmpty)
{
if (File.Exists(SyncPath)) File.Delete(SyncPath);
return;
}
Directory.CreateDirectory(Folder);
AtomicFile.WriteAllText(SyncPath, JsonSerializer.Serialize(state, WorkspaceJson.Default.WorkspaceSyncState));
}
}