feat(projects): workspace projects with linear versions, the local archive as their home
Owner review 2, phase 5a (R8): editing moves out of the library into a workspace on a fast disk, and a sequence gets several projects, each with a linear version history pushed and pulled like git. - Core: ProjectSettings keeps members a newer Chronos wrote (Extra) and reads a newer settings format read-only; ProjectContent is the portable form of a version (every frame position parked by photo, canonical text, SHA-256 content hash); ProjectBundle format 2 adds the workspace section, and a file without it is still written as format 1. JobKind.WorkspaceCopy = 20 (19 kept for Convert). - Data: migration 0009 (projects, project_versions, the render's project columns); ProjectService on ArchiveService.Projects keeps projects as sidecars first (.chronos/projects/<id>/), then the index, under the sequence lease: create, rename, delete into the projects' trash, history, push with fast-forward, idempotent repeat, divergence and hash checks. Main is made from the sequence's settings and mirrored both ways, so every older code path keeps working; outside writes become "external" versions, a mirror a crash cut short is completed or merged. Full scans and rebuilds take the projects back from their sidecars. - ProjectMerge moves from the App to Data/Projects, merges pending frames photo by photo and replays unpushed commits on a moved head. - Workspaces: WorkspaceStore, WorkspaceSync (checkout, save, commit, push, pull with replay and merge, conflicts settled by keep mine / take server / save both, restore, status) and the WorkspaceCopy job (proxies copied hash-verified and resumable; originals refused until phase 5c). - Renders of a project version place its positions on the frames and record the project and version. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit c4c1802884e403db8759ed0501f770a67a047f20)
This commit is contained in:
1 parent
e3cbe30b29
commit
03d32f18d3
51 files changed
+4917
-108
No files matched your search
@@ -0,0 +1,276 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
|
||||
namespace Chronos.Data.Projects;
|
||||
|
||||
/// <summary>The newest version of a project as its record names it: id and number.</summary>
|
||||
public sealed record ProjectHead(Guid Id, int Number);
|
||||
|
||||
/// <summary>
|
||||
/// The record of a project in its folder (<c>.chronos/projects/<id>/project.json</c>): what the index row is rebuilt
|
||||
/// from. <see cref="Deleted"/> is set when the project was deleted, before its folder moves to the projects' trash.
|
||||
/// </summary>
|
||||
public sealed record ProjectRecord(Guid Id, Guid SequenceId, string Name, bool IsMain, ProjectHead? Head, DateTimeOffset Created, string? CreatedBy,
|
||||
DateTimeOffset Updated, DateTimeOffset? Deleted = null)
|
||||
{
|
||||
/// <summary>The record of an index row.</summary>
|
||||
public static ProjectRecord Of(SequenceProject project)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
return new ProjectRecord(project.Id, project.SequenceId, project.Name, project.IsMain,
|
||||
project.HeadVersionId is { } head ? new ProjectHead(head, project.HeadNumber) : null, project.CreatedAt, project.CreatedBy, project.UpdatedAt,
|
||||
project.DeletedAt);
|
||||
}
|
||||
|
||||
/// <summary>The index row of this record (nothing mirrored known yet).</summary>
|
||||
public SequenceProject ToProject() => new()
|
||||
{
|
||||
Id = Id,
|
||||
SequenceId = SequenceId,
|
||||
Name = Name,
|
||||
IsMain = IsMain,
|
||||
HeadVersionId = Head?.Id,
|
||||
HeadNumber = Head?.Number ?? 0,
|
||||
CreatedBy = CreatedBy,
|
||||
CreatedAt = Created,
|
||||
UpdatedAt = Updated,
|
||||
DeletedAt = Deleted,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The files of projects (owner review 2, R8), the same in an archive and in a workspace: the record of a project
|
||||
/// (<see cref="ProjectRecord"/>) and one file per version, immutable once written:
|
||||
/// <code>{ "format": "chronos-project-version", "formatVersion": 1, "id", "projectId", "parentId", "number", "kind",
|
||||
/// "author", "clientName", "note", "settingsFormat", "framesVersion", "contentHash", "restoredFrom", "created",
|
||||
/// "stored", "settings": "<the portable settings as text>" }</code>
|
||||
/// The settings are a JSON string, so the bytes the content hash covers come back exactly; a version whose text does not
|
||||
/// match its hash is refused as damaged. Writes are atomic (temp, flush, rename).
|
||||
/// </summary>
|
||||
public static class ProjectSidecars
|
||||
{
|
||||
public const string RecordFormat = "chronos-project-record";
|
||||
public const string VersionFormat = "chronos-project-version";
|
||||
public const int FormatVersion = 1;
|
||||
|
||||
/// <summary>A version file is a few kilobytes; a larger one is not read.</summary>
|
||||
public const int MaxVersionBytes = 8 << 20;
|
||||
|
||||
private static readonly JsonWriterOptions Indented = new() { Indented = true };
|
||||
|
||||
/// <summary>
|
||||
/// Writes a version file. A version is immutable: an existing file is left when it holds the same version (same id
|
||||
/// and content hash) and refused otherwise, unless <paramref name="replace"/> (a workspace's own copy of a version,
|
||||
/// stored at its home since).
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">Another version is at that path.</exception>
|
||||
public static void WriteVersion(string path, ProjectVersion version, bool replace = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(version);
|
||||
if (!replace && File.Exists(path))
|
||||
{
|
||||
ProjectVersion existing;
|
||||
try
|
||||
{
|
||||
existing = ReadVersion(path);
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
// A damaged file is never overwritten: it is moved aside, kept.
|
||||
File.Move(path, path + ".damaged-" + DateTime.UtcNow.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture));
|
||||
existing = null!;
|
||||
}
|
||||
if (existing is not null)
|
||||
{
|
||||
if (existing.Id == version.Id && string.Equals(existing.ContentHash, version.ContentHash, StringComparison.OrdinalIgnoreCase)) return;
|
||||
throw new IOException($"{path} holds another version ({existing.Id}).");
|
||||
}
|
||||
}
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
AtomicFile.WriteAllText(path, VersionJson(version));
|
||||
}
|
||||
|
||||
/// <summary>Reads a version file and checks its content hash.</summary>
|
||||
/// <exception cref="InvalidDataException">Not a version file, damaged, newer, or its settings do not match their hash.</exception>
|
||||
/// <exception cref="IOException">The file cannot be read.</exception>
|
||||
public static ProjectVersion ReadVersion(string path)
|
||||
{
|
||||
if (new FileInfo(path).Length > MaxVersionBytes) throw new InvalidDataException($"{path} is too large to be a project version.");
|
||||
return ParseVersion(AtomicFile.ReadAllText(path), path);
|
||||
}
|
||||
|
||||
/// <summary>The text of a version file.</summary>
|
||||
public static string VersionJson(ProjectVersion version)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(version);
|
||||
using var buffer = new MemoryStream();
|
||||
using (var w = new Utf8JsonWriter(buffer, Indented))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("format", VersionFormat);
|
||||
w.WriteNumber("formatVersion", FormatVersion);
|
||||
w.WriteString("id", version.Id);
|
||||
w.WriteString("projectId", version.ProjectId);
|
||||
if (version.ParentId is { } parent) w.WriteString("parentId", parent);
|
||||
w.WriteNumber("number", version.Number);
|
||||
w.WriteString("kind", ProjectVersionKinds.Name(version.Kind));
|
||||
if (version.Author is { } author) w.WriteString("author", author);
|
||||
if (version.ClientName is { } client) w.WriteString("clientName", client);
|
||||
if (version.Note is { } note) w.WriteString("note", note);
|
||||
w.WriteNumber("settingsFormat", version.SettingsFormat);
|
||||
w.WriteNumber("framesVersion", version.FramesVersion);
|
||||
w.WriteString("contentHash", version.ContentHash.ToLowerInvariant());
|
||||
if (version.RestoredFrom is { } restored) w.WriteString("restoredFrom", restored);
|
||||
w.WriteString("created", version.CreatedAt);
|
||||
if (version.StoredAt is { } stored) w.WriteString("stored", stored);
|
||||
w.WriteString("settings", version.SettingsJson);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
return Encoding.UTF8.GetString(buffer.GetBuffer(), 0, (int)buffer.Length);
|
||||
}
|
||||
|
||||
/// <summary>Reads a version file's text (<paramref name="source"/> names it in errors) and checks its content hash.</summary>
|
||||
/// <exception cref="InvalidDataException">Not a version file, damaged, newer, or its settings do not match their hash.</exception>
|
||||
public static ProjectVersion ParseVersion(string json, string source)
|
||||
{
|
||||
using var document = Parse(json, source);
|
||||
var root = document.RootElement;
|
||||
Check(root, VersionFormat, source);
|
||||
var settings = Text(root, "settings") ?? throw new InvalidDataException($"{source} holds no settings.");
|
||||
var hash = Text(root, "contentHash") ?? throw new InvalidDataException($"{source} has no content hash.");
|
||||
if (!ProjectContent.Verifies(settings, hash)) throw new InvalidDataException($"The settings in {source} do not match their content hash.");
|
||||
return new ProjectVersion
|
||||
{
|
||||
Id = Id(root, "id") ?? throw new InvalidDataException($"{source} has no version id."),
|
||||
ProjectId = Id(root, "projectId") ?? throw new InvalidDataException($"{source} names no project."),
|
||||
ParentId = Id(root, "parentId"),
|
||||
Number = Int(root, "number") is { } number and > 0 ? number : throw new InvalidDataException($"{source} has no version number."),
|
||||
Kind = ProjectVersionKinds.Parse(Text(root, "kind")),
|
||||
Author = Text(root, "author"),
|
||||
ClientName = Text(root, "clientName"),
|
||||
Note = Text(root, "note"),
|
||||
SettingsJson = settings,
|
||||
ContentHash = hash.ToLowerInvariant(),
|
||||
SettingsFormat = Int(root, "settingsFormat") ?? ProjectContent.FormatOf(settings),
|
||||
FramesVersion = Int(root, "framesVersion") ?? 0,
|
||||
RestoredFrom = Id(root, "restoredFrom"),
|
||||
CreatedAt = Time(root, "created") ?? default,
|
||||
StoredAt = Time(root, "stored"),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Writes a project's record atomically.</summary>
|
||||
public static void WriteRecord(string path, ProjectRecord record)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(record);
|
||||
using var buffer = new MemoryStream();
|
||||
using (var w = new Utf8JsonWriter(buffer, Indented))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("format", RecordFormat);
|
||||
w.WriteNumber("formatVersion", FormatVersion);
|
||||
w.WriteString("id", record.Id);
|
||||
w.WriteString("sequenceId", record.SequenceId);
|
||||
w.WriteString("name", record.Name);
|
||||
w.WriteBoolean("isMain", record.IsMain);
|
||||
if (record.Head is { } head)
|
||||
{
|
||||
w.WriteStartObject("head");
|
||||
w.WriteString("id", head.Id);
|
||||
w.WriteNumber("number", head.Number);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteString("created", record.Created);
|
||||
if (record.CreatedBy is { } by) w.WriteString("createdBy", by);
|
||||
w.WriteString("updated", record.Updated);
|
||||
if (record.Deleted is { } deleted) w.WriteString("deleted", deleted);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
AtomicFile.WriteAllBytes(path, buffer.GetBuffer().AsSpan(0, (int)buffer.Length));
|
||||
}
|
||||
|
||||
/// <summary>Reads a project's record.</summary>
|
||||
/// <exception cref="InvalidDataException">Not a project record, damaged or newer.</exception>
|
||||
/// <exception cref="IOException">The file cannot be read.</exception>
|
||||
public static ProjectRecord ReadRecord(string path)
|
||||
{
|
||||
using var document = Parse(AtomicFile.ReadAllText(path), path);
|
||||
var root = document.RootElement;
|
||||
Check(root, RecordFormat, path);
|
||||
ProjectHead? head = null;
|
||||
if (root.TryGetProperty("head", out var h) && h.ValueKind == JsonValueKind.Object && Id(h, "id") is { } headId && Int(h, "number") is { } number and > 0)
|
||||
head = new ProjectHead(headId, number);
|
||||
var name = Text(root, "name");
|
||||
return new ProjectRecord(
|
||||
Id(root, "id") ?? throw new InvalidDataException($"{path} has no project id."),
|
||||
Id(root, "sequenceId") ?? throw new InvalidDataException($"{path} names no sequence."),
|
||||
string.IsNullOrWhiteSpace(name) ? throw new InvalidDataException($"{path} has no name.") : name,
|
||||
root.TryGetProperty("isMain", out var main) && main.ValueKind == JsonValueKind.True,
|
||||
head,
|
||||
Time(root, "created") ?? default,
|
||||
Text(root, "createdBy"),
|
||||
Time(root, "updated") ?? Time(root, "created") ?? default,
|
||||
Time(root, "deleted"));
|
||||
}
|
||||
|
||||
/// <summary>The version files of a folder by number and id (<c>000001-<id>.json</c>), in number order; other files are not listed.</summary>
|
||||
public static IReadOnlyList<(int Number, Guid Id, string Path)> ListVersions(string directory)
|
||||
{
|
||||
if (!Directory.Exists(directory)) return [];
|
||||
var found = new List<(int, Guid, string)>();
|
||||
foreach (var path in Directory.EnumerateFiles(directory, "*.json"))
|
||||
{
|
||||
if (TryParseName(Path.GetFileName(path), out var number, out var id)) found.Add((number, id, path));
|
||||
}
|
||||
return [.. found.OrderBy(f => f.Item1).ThenBy(f => f.Item2)];
|
||||
}
|
||||
|
||||
/// <summary>The number and id a version file name carries (<see cref="ArchiveLayout.ProjectVersionFileName"/>).</summary>
|
||||
public static bool TryParseName(string fileName, out int number, out Guid id)
|
||||
{
|
||||
number = 0;
|
||||
id = Guid.Empty;
|
||||
var name = Path.GetFileNameWithoutExtension(fileName);
|
||||
var dash = name.IndexOf('-', StringComparison.Ordinal);
|
||||
return dash > 0 && Path.GetExtension(fileName).Equals(".json", StringComparison.OrdinalIgnoreCase)
|
||||
&& int.TryParse(name.AsSpan(0, dash), NumberStyles.None, CultureInfo.InvariantCulture, out number) && number > 0
|
||||
&& Guid.TryParseExact(name.AsSpan(dash + 1), "N", out id);
|
||||
}
|
||||
|
||||
private static JsonDocument Parse(string json, string source)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 64 });
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException($"{source} is not valid JSON.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Check(JsonElement root, string format, string source)
|
||||
{
|
||||
if (root.ValueKind != JsonValueKind.Object || Text(root, "format") != format) throw new InvalidDataException($"{source} is not a {format} file.");
|
||||
if (Int(root, "formatVersion") is not { } version || version < 1) throw new InvalidDataException($"{source} has no valid format version.");
|
||||
if (version > FormatVersion) throw new InvalidDataException($"{source} uses format {version}, newer than this Chronos ({FormatVersion}).");
|
||||
}
|
||||
|
||||
private static string? Text(JsonElement element, string name) =>
|
||||
element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
|
||||
|
||||
private static int? Int(JsonElement element, string name) =>
|
||||
element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.Number && value.TryGetInt32(out var number) ? number : null;
|
||||
|
||||
private static Guid? Id(JsonElement element, string name) =>
|
||||
element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String && value.TryGetGuid(out var id) && id != Guid.Empty ? id : null;
|
||||
|
||||
private static DateTimeOffset? Time(JsonElement element, string name) =>
|
||||
element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String && value.TryGetDateTimeOffset(out var time) ? time : null;
|
||||
}
|
||||
Reference in new issue
Block a user