wip(processing): analysis and render job handlers, render node client (interrupted)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
30 files changed
+2262
-21
No files matched your search
@@ -0,0 +1,53 @@
|
||||
using System.Globalization;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Jobs;
|
||||
|
||||
namespace Titano.Data.Processing.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.LightAnalyse"/> and <see cref="JobKind.DeepAnalyse"/> over the target sequences, one after the
|
||||
/// other. Progress counts sequences (light) or frames (deep); checkpoint: the number of sequences done. A deep pass
|
||||
/// interrupted inside a sequence resumes from that sequence's <c>analysis.partial</c>.
|
||||
/// </summary>
|
||||
internal sealed class AnalyseJobHandler(TitanoDatabase db, SequenceAnalyser analyser, JobKind kind) : IJobHandler
|
||||
{
|
||||
public JobKind Kind => kind;
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
var deep = kind == JobKind.DeepAnalyse;
|
||||
var targets = context.Job.TargetIds;
|
||||
var first = int.TryParse(context.Checkpoint, NumberStyles.None, CultureInfo.InvariantCulture, out var next) ? next : 0;
|
||||
// Deep progress is in frames across all targets, so the bar and the ETA cover the whole job.
|
||||
var frames = new long[targets.Count];
|
||||
if (deep)
|
||||
{
|
||||
for (var i = 0; i < targets.Count; i++)
|
||||
frames[i] = (await db.Sequences.GetAsync(targets[i], context.Cancellation).ConfigureAwait(false))?.FrameCount ?? 0;
|
||||
}
|
||||
var total = deep ? frames.Sum() : targets.Count;
|
||||
for (var i = first; i < targets.Count; i++)
|
||||
{
|
||||
context.Cancellation.ThrowIfCancellationRequested();
|
||||
var before = deep ? frames[..i].Sum() : i;
|
||||
var chain = new ProgressChain(context.ReportAsync);
|
||||
var progress = deep ? chain.For<AnalysisProgress>(p => (before + p.Done, total, null)) : null;
|
||||
var outcome = await analyser.AnalyseAsync(targets[i], deep, progress, context.Cancellation).ConfigureAwait(false);
|
||||
await chain.FlushAsync().ConfigureAwait(false);
|
||||
if (outcome is null) context.Log(Loc.L("Archive.Log.SequenceMissing", targets[i]));
|
||||
else Report(context, outcome, deep);
|
||||
await context.CheckpointAsync((i + 1).ToString(CultureInfo.InvariantCulture), deep ? before + frames[i] : i + 1, total).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Report(JobContext context, AnalysisOutcome outcome, bool deep)
|
||||
{
|
||||
var title = outcome.Sequence.DisplayTitle;
|
||||
context.Log(Loc.L(deep ? "Advisor.Log.DeepDone" : "Advisor.Log.LightDone", title, outcome.Frames, outcome.Warnings));
|
||||
if (outcome.SettingsChanged) context.Log(Loc.L("Advisor.Log.AutoUpdated", title));
|
||||
if (outcome.SettingsUnreadable) context.Log(Loc.L("Advisor.Log.ProjectUnreadable", title));
|
||||
if (outcome.Presets.Count > 0) context.Log(Loc.L("Advisor.Log.Presets", string.Join(" · ", outcome.Presets.Select(p => p.DisplayName()))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Export;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Render;
|
||||
using Titano.Data.Jobs;
|
||||
|
||||
namespace Titano.Data.Processing.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Render"/> on this machine (BRIEF §11.5): target = the sequence; parameters = Protocol
|
||||
/// <c>RenderJobParameters</c> whose preset JSON is the export section of a project (preset, overrides, name template,
|
||||
/// folder, batch). The project is the embedded one or the sequence's own; frames flagged missing, corrupt, excluded or
|
||||
/// undecodable are left out. The preset and every batch preset render after one preparation pass into the sequence's
|
||||
/// <c>exports/</c> (or the export folder), named by the template, and each finished output is recorded at once.
|
||||
/// Checkpoint: the batch entries recorded and the output being written, so a crashed attempt's leftovers are removed and
|
||||
/// only unfinished entries render again. A failed entry fails the job after the others ran; retrying renders it alone.
|
||||
/// </summary>
|
||||
internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions options) : IJobHandler
|
||||
{
|
||||
public JobKind Kind => JobKind.Render;
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
var cancellation = context.Cancellation;
|
||||
var (parameters, export) = ProcessingJobs.ReadRender(context.Job.ParametersJson);
|
||||
if (context.Job.TargetIds is not [var sequenceId] || await db.Sequences.GetAsync(sequenceId, cancellation).ConfigureAwait(false) is not { } sequence
|
||||
|| await db.Archives.GetAsync(sequence.ArchiveId, cancellation).ConfigureAwait(false) is not { } archive)
|
||||
throw new InvalidOperationException(Loc.L("Errors.Render.Sequence"));
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
var folder = paths.Sequence(sequence.Folder);
|
||||
var project = (parameters.SettingsJson is { } embedded ? ProjectStore.Parse(embedded) : ProjectStore.Read(sequence, folder)) with { Export = export };
|
||||
var settingsJson = project.ToJson();
|
||||
|
||||
var resume = RenderCheckpoint.Parse(context.Checkpoint);
|
||||
var done = resume.Done.ToList();
|
||||
if (resume is { Pending: { } pending, PendingOutput: { } output })
|
||||
{
|
||||
// A crash after the render row was written but before the checkpoint: that entry is finished.
|
||||
var recorded = await db.Renders.ListBySequenceAsync(sequence.Id, cancellation).ConfigureAwait(false);
|
||||
if (recorded.Any(r => r.OutputPath == Stored(paths, output))) done.Add(pending);
|
||||
else Discard(output);
|
||||
}
|
||||
var targets = Targets(export, parameters.PresetName).Select((t, i) => (i, t)).Where(t => !done.Contains(t.i)).ToList();
|
||||
if (targets.Count == 0) return;
|
||||
|
||||
var frames = await SequenceFrames.LoadAsync(db, archive, sequence, parameters.UseProxies, cancellation).ConfigureAwait(false);
|
||||
IReadOnlyList<TargetOutcome> outcomes;
|
||||
await using (var render = new SequenceRender(frames, project, SequenceAnalyser.ReadReport(folder, frames.Count), options))
|
||||
{
|
||||
outcomes = await render.RenderAllAsync(
|
||||
targets,
|
||||
(target, setup) => ExportNaming.OutputPath(project.Export, folder.Exports, SequenceRender.NameContext(sequence, target, setup)),
|
||||
(index, path) => context.CheckpointAsync(new RenderCheckpoint(done, index, path).ToJson(), context.Done, context.Total),
|
||||
async (index, target, result) =>
|
||||
{
|
||||
// The output is complete: record it even if the job is being cancelled, so it is never orphaned.
|
||||
var entity = result.ToEntity(sequence.Id, target.PresetName, settingsJson, options.ProducedBy) with { OutputPath = Stored(paths, result.OutputPath) };
|
||||
await db.Renders.InsertAsync(entity, CancellationToken.None).ConfigureAwait(false);
|
||||
done.Add(index);
|
||||
await context.CheckpointAsync(new RenderCheckpoint(done, null, null).ToJson(), context.Done, context.Total).ConfigureAwait(false);
|
||||
context.Log(Loc.L("Export.Log.Rendered", target.PresetName, Path.GetFileName(result.OutputPath)));
|
||||
foreach (var remark in SequenceRender.Remarks(result)) context.Log(remark);
|
||||
},
|
||||
context.ReportAsync,
|
||||
cancellation).ConfigureAwait(false);
|
||||
}
|
||||
var failed = outcomes.Where(o => o.Error is not null).ToList();
|
||||
foreach (var outcome in failed) context.Log(Loc.L("Export.Log.Failed", outcome.Target.PresetName, outcome.Error));
|
||||
if (failed.Count > 0)
|
||||
throw new InvalidOperationException(failed.Count == 1 ? failed[0].Error : Loc.L("Errors.Render.Failed", failed.Count, outcomes.Count));
|
||||
}
|
||||
|
||||
/// <summary>The job's preset, then every other preset of the batch with its own values.</summary>
|
||||
internal static List<ExportTarget> Targets(ExportSettings export, string presetName)
|
||||
{
|
||||
var main = ExportResolver.Resolve(export);
|
||||
var targets = new List<ExportTarget> { new(main, presetName) };
|
||||
foreach (var id in export.Batch.Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
if (id.Equals(main.BasePresetId, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
var resolved = ExportResolver.Resolve(new ExportSettings { Preset = new Auto<string>().WithManual(id) });
|
||||
targets.Add(new ExportTarget(resolved, ProcessingJobs.PresetName(resolved)));
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
/// <summary>Archive-relative for outputs inside the archive (like the server's renders), absolute otherwise.</summary>
|
||||
private static string Stored(ArchivePaths paths, string output)
|
||||
{
|
||||
var relative = paths.ToRelative(output);
|
||||
return relative.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(relative) ? output : relative;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes what an interrupted attempt left of <paramref name="output"/>: the encoder's hidden temporary file or
|
||||
/// folder, and an output that was completed but never recorded (it renders again under the same name).
|
||||
/// </summary>
|
||||
private static void Discard(string output)
|
||||
{
|
||||
var parent = Path.GetDirectoryName(output);
|
||||
if (parent is null || !Directory.Exists(parent)) return;
|
||||
foreach (var leftover in Directory.EnumerateFileSystemEntries(parent, "." + Path.GetFileName(output) + ".*.tmp").Append(output))
|
||||
{
|
||||
if (Directory.Exists(leftover)) Directory.Delete(leftover, recursive: true);
|
||||
else if (File.Exists(leftover)) File.Delete(leftover);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user