Files
Chronos/src/Chronos.Data/Repositories/RenderRepository.cs
T
Alby96 03d32f18d3 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)
2026-10-27 22:51:32 +01:00

115 lines
6.8 KiB
C#

using Chronos.Core.Model;
namespace Chronos.Data.Repositories;
/// <summary>Exports of sequences; keeps <c>sequences.rendered_count</c> in step.</summary>
public sealed class RenderRepository
{
private const string Columns =
"id, sequence_id, preset_name, settings_json, output_path, codec, width, height, fps, duration_seconds, bytes, created, produced_by, project_id, " +
"project_version_id";
private const string RecountSql =
"UPDATE sequences SET rendered_count = (SELECT count(*) FROM renders WHERE sequence_id = $1) WHERE id = $1";
private readonly DbAccess _db;
internal RenderRepository(DbAccess db) => _db = db;
public Task InsertAsync(Render render, CancellationToken cancellationToken = default) =>
_db.InTransactionAsync(async session =>
{
await LockSequenceAsync(session, render.SequenceId, cancellationToken).ConfigureAwait(false);
await session.ExecuteAsync($"INSERT INTO renders ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)",
[
render.Id, render.SequenceId, render.PresetName, DbParam.Json(render.SettingsJson), render.OutputPath, render.Codec,
render.Width, render.Height, render.Fps, render.DurationSeconds, render.Bytes, render.Created, render.ProducedBy, render.ProjectId,
render.ProjectVersionId,
], cancellationToken).ConfigureAwait(false);
return await session.ExecuteAsync(RecountSql, [render.SequenceId], cancellationToken).ConfigureAwait(false);
}, cancellationToken);
public Task<Render?> GetAsync(Guid id, CancellationToken cancellationToken = default) =>
_db.SingleAsync($"SELECT {Columns} FROM renders WHERE id = $1", [id], Map, cancellationToken);
/// <summary>Renders of a sequence, newest first.</summary>
public Task<IReadOnlyList<Render>> ListBySequenceAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
_db.ListAsync($"SELECT {Columns} FROM renders WHERE sequence_id = $1 ORDER BY created DESC, id DESC", [sequenceId], Map, cancellationToken);
public Task<bool> DeleteAsync(Guid id, CancellationToken cancellationToken = default) =>
_db.InTransactionAsync(async session =>
{
var sequenceId = await session.ScalarAsync<Guid?>("SELECT sequence_id FROM renders WHERE id = $1", [id], cancellationToken).ConfigureAwait(false);
if (sequenceId is null) return false;
await LockSequenceAsync(session, sequenceId.Value, cancellationToken).ConfigureAwait(false);
if (await session.ExecuteAsync("DELETE FROM renders WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) == 0) return false;
await session.ExecuteAsync(RecountSql, [sequenceId], cancellationToken).ConfigureAwait(false);
return true;
}, cancellationToken);
/// <summary>
/// Rewrites the archive-relative output paths of an archive's renders after the folder of sequence
/// <paramref name="sequenceId"/> moved (a Reorganize, or a move another index of the archive or the user made, which a
/// scan finds): an export inside the folder moved with it. Each render under the old folder whose file
/// <paramref name="follows"/> the folder takes the new path: the caller tells the sequence's own exports there (which
/// follow unless their file stayed behind) from an export of another sequence saved inside it through the Export
/// folder picker (which follows only when its file moved with the folder: a sequence that took the old folder since, by
/// a later Reorganize another index made, keeps its own). An export of the sequence whose path an export of another
/// sequence names follows without asking: that path is the other sequence's now, which brought an export of that name
/// into the old folder. Outputs elsewhere (absolute paths, other folders) stay as they are.
/// </summary>
/// <param name="follows">Whether the render at the first archive-relative path follows to the second one; the third
/// argument is the sequence it is an export of.</param>
/// <remarks>Only paths still under <paramref name="oldFolder"/> change, so repeating it after a crash is harmless.</remarks>
public async Task<int> RebaseFolderAsync(Guid archiveId, Guid sequenceId, string oldFolder, string newFolder, Func<string, string, Guid, bool> follows,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(follows);
// The archive root never moves, and its prefix ("/") would match absolute paths outside the archive.
if (oldFolder.Length == 0) return 0;
// substr counts characters (code points) on both dialects.
var prefix = oldFolder + "/";
var under = await _db.ListAsync(
"SELECT r.id, r.sequence_id, r.output_path FROM renders r JOIN sequences s ON s.id = r.sequence_id WHERE s.archive_id = $1 AND substr(r.output_path, 1, $2) = $3",
[archiveId, prefix.EnumerateRunes().Count(), prefix], r => (Id: r.GetGuid(0), SequenceId: r.GetGuid(1), Path: r.GetString(2)), cancellationToken)
.ConfigureAwait(false);
var rebased = 0;
foreach (var (id, owner, path) in under)
{
var to = newFolder.Length == 0 ? path[prefix.Length..] : newFolder + path[oldFolder.Length..];
var taken = owner == sequenceId && under.Any(o => o.SequenceId != sequenceId && string.Equals(o.Path, path, StringComparison.Ordinal));
if (!taken && !follows(path, to, owner)) continue;
rebased += await _db.ExecuteAsync("UPDATE renders SET output_path = $2 WHERE id = $1", [id, to], cancellationToken).ConfigureAwait(false);
}
return rebased;
}
/// <summary>
/// Serialises render changes per sequence on PostgreSQL, so the recount (a new statement, hence a new snapshot)
/// sees every committed render; SQLite's write lock already does this.
/// </summary>
private async Task LockSequenceAsync(IDbSession session, Guid sequenceId, CancellationToken cancellationToken)
{
if (_db.Sql.IsPostgres) await SequenceRepository.LockAsync(session, sequenceId, cancellationToken).ConfigureAwait(false);
}
private static Render Map(DbRow r) => new()
{
Id = r.GetGuid(0),
SequenceId = r.GetGuid(1),
PresetName = r.GetString(2),
SettingsJson = r.GetStringOrNull(3),
OutputPath = r.GetString(4),
Codec = r.GetStringOrNull(5),
Width = r.GetInt32(6),
Height = r.GetInt32(7),
Fps = r.GetDouble(8),
DurationSeconds = r.GetDouble(9),
Bytes = r.GetInt64(10),
Created = r.GetDateTimeOffset(11),
ProducedBy = r.GetStringOrNull(12),
ProjectId = r.GetGuidOrNull(13),
ProjectVersionId = r.GetGuidOrNull(14),
};
}