Files
Chronos/src/Chronos.Core/Model/Entities.cs
T
Alby96andClaude Opus 5.5 ee9505df22 feat(jobs): progress detail contract and a 2/s publish throttle
Mass passes need to say what they do now (photo x of y, sequence n of m) without
slowing down. This adds the contract and the engine side; handlers and displays
follow in their own parcels.

- Core: JobDetail (step, item, item x of y, part n of m with unit), JobStep and
  JobPartUnit appended-only and stored by kebab name; Job.Detail.
- Protocol: JobDetailDto, appended as JobDto.Detail, JobProgressEvent.Detail and
  NodeProgress.Detail, so older peers ignore it and newer ones fall back.
- Data: JobContext keeps a detail across reports (ReportAsync with a detail,
  ReportItemAsync without allocating, CheckpointAsync with a detail) and publishes
  at most once per ProgressInterval (500 ms on the engine's TimeProvider), at once
  for the first report, a new step or a completed count; a dropped report costs no
  allocation or lock, and the persist that falls due publishes what it saves.
  Persist stays at most every 5 s. JobWire maps steps, units and details; an
  unknown name reads as none.
- Migration 0011 adds jobs.progress_detail (nullable JSON text); an unreadable
  cell reads as no detail. Lists return it.
- Server: ProgressGate (500 ms per job, step-change and completion bypass)
  shared by the engine host and render nodes; node details are stored and
  broadcast, an older node without one still works.

Refs #65

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

528 lines
22 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 Chronos.Core.Imaging;
namespace Chronos.Core.Model;
/// <summary>A rooted folder tree that holds originals, sidecars, proxies and exports (BRIEF §7).</summary>
public sealed record Archive
{
public required Guid Id { get; init; }
public required string Name { get; init; }
public required string RootPath { get; init; }
public string FolderTemplate { get; init; } = Naming.TemplateDefaults.Folder;
public string FileTemplate { get; init; } = Naming.TemplateDefaults.File;
public int SchemaVersion { get; init; } = 1;
public DateTimeOffset Created { get; init; }
/// <summary>Proxy long edge in pixels; 0 = full size, -1 = proxies disabled.</summary>
public int ProxyLongEdge { get; init; } = 1920;
}
/// <summary>
/// The tombstone of a photo removed from a sequence (owner review 2, R6): its SHA-256, the replacement's when it was
/// replaced by a converted file, why and when. Kept in the sidecar (<c>removed</c>) and the index (<c>frame_removals</c>), so
/// sync never offers the photo back and an upload of that content into the sequence is answered as already there.
/// </summary>
public sealed record FrameRemoval(Guid SequenceId, string Sha256, string? ReplacementSha256, RemovalReason Reason, DateTimeOffset RemovedAt);
/// <summary>One shoot: a folder of frames that becomes one project (BRIEF §5).</summary>
public sealed record Sequence
{
public required Guid Id { get; init; }
public required Guid ArchiveId { get; init; }
public string? Title { get; init; }
/// <summary>Folder relative to the archive root, forward slashes.</summary>
public required string Folder { get; init; }
public string? CameraMake { get; init; }
public string? CameraModel { get; init; }
public string? CameraSerial { get; init; }
public string? Lens { get; init; }
public DateTime? FirstCapture { get; init; }
public DateTime? LastCapture { get; init; }
public int FrameCount { get; init; }
/// <summary>Median capture interval in seconds.</summary>
public double? MedianInterval { get; init; }
public long TotalBytes { get; init; }
public SequenceStatus Status { get; init; }
public int RenderedCount { get; init; }
public DateTimeOffset? VerifiedAt { get; init; }
public Guid? HeroFrameId { get; init; }
public IReadOnlyList<string> Tags { get; init; } = [];
public int Rating { get; init; }
public string? Notes { get; init; }
/// <summary>Render settings ("project") as JSON.</summary>
public string? SettingsJson { get; init; }
/// <summary>Compact analysis summary as JSON; the full report lives in <c>.chronos/analysis.json</c>.</summary>
public string? AnalysisJson { get; init; }
public SequenceOrigin Origin { get; init; }
public SyncState SyncState { get; init; }
public int SettingsVersion { get; init; }
public int FramesVersion { get; init; }
public Guid? OwnerUserId { get; init; }
public int WarningCount { get; init; }
/// <summary>Frames that decode only through their embedded preview (<see cref="FrameFlags.PreviewOnly"/>, BRIEF §8.2).</summary>
public int PreviewOnlyCount { get; init; }
public DateTimeOffset UpdatedAt { get; init; }
/// <summary>The title, else capture date and camera, else the folder name (never empty).</summary>
public string DisplayTitle
{
get
{
if (!string.IsNullOrWhiteSpace(Title)) return Title;
var described = $"{FirstCapture:yyyy-MM-dd} {CameraModel}".Trim();
if (described.Length > 0) return described;
var folder = Folder.TrimEnd('/');
return folder.Length > 0 ? folder[(folder.LastIndexOf('/') + 1)..] : Id.ToString("N")[..8];
}
}
}
/// <summary>One photo of a sequence.</summary>
public sealed record Frame
{
public required Guid Id { get; init; }
public required Guid SequenceId { get; init; }
public required int Index { get; init; }
/// <summary>Path relative to the archive root, forward slashes.</summary>
public required string RelativePath { get; init; }
public required string FileName { get; init; }
public string? OriginalFileName { get; init; }
public long Size { get; init; }
/// <summary>Lower-case hex SHA-256 of the original file.</summary>
public string? Sha256 { get; init; }
/// <summary>Camera wall-clock time including sub-seconds (unspecified kind).</summary>
public DateTime? CapturedAt { get; init; }
/// <summary>UTC offset of <see cref="CapturedAt"/> when known, in minutes.</summary>
public int? UtcOffsetMinutes { get; init; }
public TimestampSource TimestampSource { get; init; }
public double? ExposureTime { get; init; }
public double? FNumber { get; init; }
public int? Iso { get; init; }
public double? FocalLength { get; init; }
public double? ExposureBias { get; init; }
public int? WhiteBalance { get; init; }
public int Orientation { get; init; } = 1;
public int Width { get; init; }
public int Height { get; init; }
public ImageFileFormat Format { get; init; }
public long? PreviewOffset { get; init; }
public long? PreviewLength { get; init; }
/// <summary>Size of the largest embedded preview like <see cref="Width"/> and <see cref="Height"/> (before orientation);
/// 0 when there is none or it is not known.</summary>
public int PreviewWidth { get; init; }
public int PreviewHeight { get; init; }
/// <summary>Mean log2 luminance once analysed.</summary>
public double? MeanLogLuminance { get; init; }
public double? ClipLow { get; init; }
public double? ClipHigh { get; init; }
public FrameFlags Flags { get; init; }
/// <summary>Exposure value at ISO 100: log2(N²/t) − log2(ISO/100).</summary>
public double? ExposureValue => ExposureTime is > 0 && FNumber is > 0
? Math.Log2(FNumber.Value * FNumber.Value / ExposureTime.Value) - Math.Log2((Iso ?? 100) / 100.0)
: null;
}
/// <summary>An exported video or image sequence.</summary>
public sealed record Render
{
public required Guid Id { get; init; }
public required Guid SequenceId { get; init; }
public required string PresetName { get; init; }
public string? SettingsJson { get; init; }
public required string OutputPath { get; init; }
public string? Codec { get; init; }
public int Width { get; init; }
public int Height { get; init; }
public double Fps { get; init; }
public double DurationSeconds { get; init; }
public long Bytes { get; init; }
public DateTimeOffset Created { get; init; }
public string? ProducedBy { get; init; }
/// <summary>The project whose version was rendered (owner review 2, R8); null for a render of the sequence's settings.</summary>
public Guid? ProjectId { get; init; }
/// <summary>The project version rendered; null for a render of the sequence's settings.</summary>
public Guid? ProjectVersionId { get; init; }
/// <summary>
/// Lower-case hex SHA-256 of a single-file render (owner review 1, R9), hashed when it is recorded; null for an image
/// sequence's folder (verified file by file when copied) and for a render recorded before migration 0010, hashed the
/// first time it is copied, deleted or restored.
/// </summary>
public string? Sha256 { get; init; }
/// <summary>
/// What the render is beyond its codec (<see cref="RenderKind"/>): null for a video or an image sequence (told apart by
/// <see cref="Codec"/>), <see cref="RenderKind.Still"/> for one frame saved as an image. A text, so a newer Chronos can add
/// kinds.
/// </summary>
public string? Kind { get; init; }
}
/// <summary>The values of <see cref="Render.Kind"/> and of the videos library's kinds (owner review 1, R9).</summary>
public static class RenderKind
{
/// <summary>A video file (MP4, AVI, GIF, APNG): <see cref="Render.Kind"/> null and a video codec.</summary>
public const string Video = "video";
/// <summary>A folder of numbered images: <see cref="Render.Kind"/> null and an image-sequence codec.</summary>
public const string Sequence = "sequence";
/// <summary>One frame saved as one image ("Save frame"): fps 0 and duration 0.</summary>
public const string Still = "still";
/// <summary>
/// The library kind of a render: its <see cref="Render.Kind"/> when set (a kind of a newer Chronos as it is), else
/// <see cref="Sequence"/> for an image-sequence codec and <see cref="Video"/> otherwise.
/// </summary>
public static string Of(string? kind, string? codec) =>
kind is { Length: > 0 } ? kind
: codec is { } c && c.EndsWith("sequence", StringComparison.OrdinalIgnoreCase) ? Sequence
: Video;
/// <summary>
/// <see cref="Of(string?, string?)"/>, telling a still apart when its kind was lost (one uploaded to a server of before
/// phase 5, which does not record it): an image-sequence codec with fps 0 and duration 0, which every still records and
/// no image sequence has.
/// </summary>
public static string Of(string? kind, string? codec, double fps, double durationSeconds)
{
var of = Of(kind, codec);
return of == Sequence && fps <= 0 && durationSeconds <= 0 ? Still : of;
}
/// <inheritdoc cref="Of(string?, string?, double, double)"/>
public static string Of(Render render)
{
ArgumentNullException.ThrowIfNull(render);
return Of(render.Kind, render.Codec, render.Fps, render.DurationSeconds);
}
}
/// <summary>
/// A verified copy of a render in a videos folder (owner review 1, R9; <c>render_copies</c>): recorded once the copy matched
/// its render. There is no link to <c>renders</c>, so the copy of a server render downloaded to a PC is recorded too, and a
/// copy outlives its render's deletion (copies are the user's files; Chronos never deletes them).
/// </summary>
public sealed record RenderCopy
{
public required Guid Id { get; init; }
/// <summary>The render copied (of this index, or of the server it was downloaded from).</summary>
public required Guid RenderId { get; init; }
/// <summary>Absolute path of the copy (a file, or a folder for an image sequence).</summary>
public required string Path { get; init; }
/// <summary>Lower-case hex SHA-256 the copy was verified against; null for an image sequence's folder (verified per file).</summary>
public string? Sha256 { get; init; }
public long Bytes { get; init; }
public DateTimeOffset CopiedAt { get; init; }
/// <summary>The user (server) or the PC (desktop) that copied it.</summary>
public string? CopiedBy { get; init; }
}
/// <summary>
/// A project of a sequence (owner review 2, R8): a named set of render settings ("4K landscape", "Vertical social") with a
/// linear history of versions. Every sequence has one Main project, whose head is the sequence's own settings
/// (<see cref="Sequence.SettingsJson"/>). Its sidecar (<c>.chronos/projects/&lt;id&gt;/project.json</c>) is the truth; the
/// index row is derived.
/// </summary>
public sealed record SequenceProject
{
public required Guid Id { get; init; }
public required Guid SequenceId { get; init; }
public required string Name { get; init; }
/// <summary>The sequence's Main project: its head is mirrored into the sequence's settings and drives its hero frame.</summary>
public bool IsMain { get; init; }
/// <summary>The newest version; null before the first.</summary>
public Guid? HeadVersionId { get; init; }
/// <summary>The newest version's number (1, 2, …); 0 before the first.</summary>
public int HeadNumber { get; init; }
/// <summary>Main only: the sequence's settings version its head was last mirrored to or taken from.</summary>
public int? MirroredSettingsVersion { get; init; }
/// <summary>
/// Main only: the version last mirrored to or taken from the sequence's settings; another than the head while a mirror
/// is to complete (a push a crash cut short), null when unknown (an index rebuilt from the sidecars).
/// </summary>
public Guid? MirroredVersionId { get; init; }
public string? CreatedBy { get; init; }
public DateTimeOffset CreatedAt { get; init; }
public DateTimeOffset UpdatedAt { get; init; }
/// <summary>When the project was deleted (its folder moved to <c>.chronos/projects/.trash</c>); null while it exists.</summary>
public DateTimeOffset? DeletedAt { get; init; }
}
/// <summary>How a project version came to be (stored as its wire name, <see cref="ProjectVersionKinds"/>).</summary>
public enum ProjectVersionKind
{
/// <summary>Saved by a user in a workspace.</summary>
Commit,
/// <summary>A working state merged with versions stored meanwhile.</summary>
Merge,
/// <summary>An earlier version brought back (<see cref="ProjectVersion.RestoredFrom"/>).</summary>
Restore,
/// <summary>The first version of a project made from settings that were there (Main from the sequence's settings, a copy of another project).</summary>
Imported,
/// <summary>Main only: settings written by a path outside the projects (an analysis, the server's API, an older Chronos).</summary>
External,
}
/// <summary>Wire names of <see cref="ProjectVersionKind"/>: <c>commit</c>, <c>merge</c>, <c>restore</c>, <c>imported</c>, <c>external</c>.</summary>
public static class ProjectVersionKinds
{
public static string Name(ProjectVersionKind kind) => kind.ToString().ToLowerInvariant();
/// <summary>The kind a wire name stands for; <see cref="ProjectVersionKind.Commit"/> for one this build does not know.</summary>
public static ProjectVersionKind Parse(string? name)
{
foreach (var kind in Enum.GetValues<ProjectVersionKind>())
{
if (string.Equals(Name(kind), name, StringComparison.OrdinalIgnoreCase)) return kind;
}
return ProjectVersionKind.Commit;
}
}
/// <summary>
/// One version of a project (owner review 2, R8): immutable once stored. <see cref="SettingsJson"/> is the portable form
/// of the settings (frame positions parked by photo, <c>ProjectContent</c>) and <see cref="ContentHash"/> the SHA-256 of
/// its UTF-8 bytes, checked wherever it is stored or read.
/// </summary>
public sealed record ProjectVersion
{
public required Guid Id { get; init; }
public required Guid ProjectId { get; init; }
/// <summary>The version it was made from; null for a project's first.</summary>
public Guid? ParentId { get; init; }
/// <summary>1 for the first version of a project, then one more for each.</summary>
public required int Number { get; init; }
public ProjectVersionKind Kind { get; init; }
public string? Author { get; init; }
/// <summary>The PC it was made on ("STUDIO-PC" from a workspace; the archive's own versions carry its lease owner, "chronos@STUDIO-PC").</summary>
public string? ClientName { get; init; }
public string? Note { get; init; }
public required string SettingsJson { get; init; }
public required string ContentHash { get; init; }
/// <summary>The settings format (<c>ProjectSettings.Version</c>) of <see cref="SettingsJson"/>; a newer one opens read-only.</summary>
public int SettingsFormat { get; init; } = 1;
/// <summary>The frames version of the sequence the settings were made against.</summary>
public int FramesVersion { get; init; }
/// <summary>For a <see cref="ProjectVersionKind.Restore"/>: the version brought back.</summary>
public Guid? RestoredFrom { get; init; }
/// <summary>When it was made (in a workspace).</summary>
public DateTimeOffset CreatedAt { get; init; }
/// <summary>When its home stored it; null for a workspace's version not pushed yet.</summary>
public DateTimeOffset? StoredAt { get; init; }
}
/// <summary>Any long operation: resumable, cancellable, logged (BRIEF §5, §14.6).</summary>
public sealed record Job
{
public required Guid Id { get; init; }
public required JobKind Kind { get; init; }
public IReadOnlyList<Guid> TargetIds { get; init; } = [];
/// <summary>Human-readable target ("Harbour sunset", "Archive · 2024").</summary>
public string? TargetLabel { get; init; }
public string? ParametersJson { get; init; }
public JobState State { get; init; }
public JobPriority Priority { get; init; } = JobPriority.Normal;
public long ProgressDone { get; init; }
public long ProgressTotal { get; init; }
public double? ItemsPerSecond { get; init; }
public TimeSpan? Eta { get; init; }
/// <summary>Opaque resume cursor written at checkpoints.</summary>
public string? Checkpoint { get; init; }
public string? LogTail { get; init; }
public Guid? CreatedBy { get; init; }
public string? NodeId { get; init; }
public int Attempts { get; init; }
public string? Error { get; init; }
public DateTimeOffset Created { get; init; }
public DateTimeOffset? Started { get; init; }
public DateTimeOffset? Finished { get; init; }
/// <summary>The schedule that queued this job; null for jobs queued by a user or by other jobs (owner review 2, R10).</summary>
public Guid? ScheduleId { get; init; }
/// <summary>
/// What the job did when its progress was last saved (step, item, photo x of y, part n of m); null when its handler
/// reports none or the job never ran. Kept when the job stops, so a paused or failed one tells where it stopped.
/// </summary>
public JobDetail? Detail { get; init; }
}
/// <summary>
/// A recurring job (owner review 2, R10): an action (scan, verify, backup, …) with its parameters, run on a recurrence
/// in the host's time zone. System schedules (<see cref="SystemKey"/> set) stand for the timers a host used to run out of
/// sight; they are seeded once, can be edited and reset, never deleted.
/// </summary>
public sealed record Schedule
{
public required Guid Id { get; init; }
/// <summary>Stable key of a host's system schedule (<c>archive-scan</c>); null for schedules a user created.</summary>
public string? SystemKey { get; init; }
public required string Name { get; init; }
/// <summary>Wire name of the action (<c>scan</c>, <c>verify</c>, <c>backup</c>…).</summary>
public required string Action { get; init; }
/// <summary>What the action works on: <c>current</c>, the host's archive.</summary>
public string Target { get; init; } = "current";
/// <summary>The action's parameters as JSON (camelCase, only the fields the action reads).</summary>
public string? ParametersJson { get; init; }
/// <summary>The recurrence in its text form (<c>every:10m</c>, <c>daily:03:00</c>, <c>weekly:mon,thu@02:30</c>, <c>monthly:1@04:00</c>).</summary>
public required string Recurrence { get; init; }
/// <summary>A run missed while the host was off happens once when it comes back; otherwise it is skipped.</summary>
public bool CatchUp { get; init; } = true;
/// <summary>Priority of the jobs it queues.</summary>
public JobPriority Priority { get; init; } = JobPriority.Background;
public bool Enabled { get; init; } = true;
/// <summary>When it fires next (UTC); null while disabled or not computed yet.</summary>
public DateTimeOffset? NextRun { get; init; }
public DateTimeOffset? LastRun { get; init; }
/// <summary>The first job the last run queued.</summary>
public Guid? LastJobId { get; init; }
/// <summary>What the last run did: <c>queued</c>, <c>skipped-pending</c>, <c>skipped-offline</c>, <c>skipped-nothing</c>,
/// <c>unavailable</c> or <c>failed:&lt;reason&gt;</c>.</summary>
public string? LastOutcome { get; init; }
public Guid? CreatedBy { get; init; }
public DateTimeOffset Created { get; init; }
public DateTimeOffset Updated { get; init; }
/// <summary>True for a host's system schedule.</summary>
public bool IsSystem => SystemKey is not null;
}
/// <summary>A memory card known to this client (BRIEF §13).</summary>
public sealed record MediaCard
{
public required Guid Id { get; init; }
/// <summary><c>{volumeSerial}-{label}-{capacity}</c>.</summary>
public required string Identity { get; init; }
public uint VolumeSerial { get; init; }
public string? Label { get; init; }
public long Capacity { get; init; }
public string? Nickname { get; init; }
public string? CameraMake { get; init; }
public string? CameraModel { get; init; }
public string? CameraSerial { get; init; }
public string? ProfileJson { get; init; }
public bool AutoImport { get; init; }
public DateTimeOffset FirstSeen { get; init; }
public DateTimeOffset LastSeen { get; init; }
}
public sealed record User
{
public required Guid Id { get; init; }
public required string Username { get; init; }
public string? DisplayName { get; init; }
public required string PasswordHash { get; init; }
public UserRole Role { get; init; }
public Permissions Permissions { get; init; }
public long QuotaBytes { get; init; }
public long UsedBytes { get; init; }
public bool Disabled { get; init; }
public bool MustChangePassword { get; init; }
public DateTimeOffset Created { get; init; }
public DateTimeOffset? LastLogin { get; init; }
}
public sealed record SessionToken
{
public required string TokenHash { get; init; }
public required Guid UserId { get; init; }
public string? ClientName { get; init; }
public DateTimeOffset Created { get; init; }
public DateTimeOffset Expires { get; init; }
public DateTimeOffset LastUsed { get; init; }
public bool Revoked { get; init; }
}
public sealed record RenderNode
{
public required Guid Id { get; init; }
public required Guid UserId { get; init; }
public required string ClientName { get; init; }
public string? CapabilitiesJson { get; init; }
public DateTimeOffset LastHeartbeat { get; init; }
public string State { get; init; } = "idle";
}
public sealed record AuditEntry
{
public required Guid Id { get; init; }
public DateTimeOffset At { get; init; }
public Guid? UserId { get; init; }
public string? Username { get; init; }
public required string Action { get; init; }
public string? TargetKind { get; init; }
public string? TargetId { get; init; }
public string? Details { get; init; }
public string? RemoteAddress { get; init; }
}