using System.Globalization;
using System.Text;
using Chronos.Core.Model;
namespace Chronos.Data.Jobs;
/// How much a kind of job counts in the priority queue ().
public enum JobKindPriority
{
Low,
Normal,
High,
}
///
/// The priority queue of Settings (owner review 1, R2). Jobs always run one at a time. Off, they run in claim order
/// (priority, then age) and a running job is never interrupted: the user pauses it to let the next one start. On, a kind
/// of a higher runs first, and a queued job of a higher level that the engine can run makes
/// the running job of a lower level yield without asking: it goes back to the queue with its checkpoint and resumes by
/// itself once nothing above it waits. Kinds of the same level never interrupt each other.
///
public sealed record JobPriorityQueue
{
///
/// The levels a kind has unless the user changed it: renders, imports and downloads first, and the copy of a project's
/// media into the workspace, which Edit waits for (owner review 2, R8), a workspace's local render and the move of the
/// workspace folder, which Edit is held for (phase 5c), and the copy of videos into the videos folder, a transfer the user
/// waits for like a download (owner review 1, R9); a local render's sending home at the normal level; the long
/// passes that resume anywhere, and the housekeeping of the schedules (backups, clean-ups), last.
///
public static IReadOnlyDictionary DefaultLevels { get; } = new Dictionary
{
[JobKind.Render] = JobKindPriority.High,
[JobKind.Import] = JobKindPriority.High,
[JobKind.Download] = JobKindPriority.High,
[JobKind.WorkspaceCopy] = JobKindPriority.High,
[JobKind.WorkspaceRender] = JobKindPriority.High,
[JobKind.WorkspaceSend] = JobKindPriority.Normal,
[JobKind.WorkspaceMove] = JobKindPriority.High,
[JobKind.VideoCopy] = JobKindPriority.High,
[JobKind.Verify] = JobKindPriority.Low,
[JobKind.Proxies] = JobKindPriority.Low,
[JobKind.Backup] = JobKindPriority.Low,
[JobKind.Cleanup] = JobKindPriority.Low,
};
/// The strict queue: no levels, no interruptions.
public static JobPriorityQueue Off { get; } = new();
/// Whether levels order the queue and interrupt lower jobs.
public bool Enabled { get; init; }
/// Levels the user set; a kind not listed has its level, else normal.
public IReadOnlyDictionary Levels { get; init; } = new Dictionary();
/// The level of .
public JobKindPriority LevelOf(JobKind kind) =>
Levels.TryGetValue(kind, out var level) || DefaultLevels.TryGetValue(kind, out level) ? level : JobKindPriority.Normal;
/// Whether a queued job of interrupts a running job of .
public bool Interrupts(JobKind challenger, JobKind running) => Enabled && LevelOf(challenger) > LevelOf(running);
///
/// Whether is claimed before : the higher level first while the queue is on,
/// then the higher priority, the older job and the lower id ().
///
public bool ClaimsBefore(Job a, Job b)
{
ArgumentNullException.ThrowIfNull(a);
ArgumentNullException.ThrowIfNull(b);
if (Enabled && LevelOf(a.Kind) != LevelOf(b.Kind)) return LevelOf(a.Kind) > LevelOf(b.Kind);
return a.Priority != b.Priority ? a.Priority > b.Priority : a.Created != b.Created ? a.Created < b.Created : a.Id.CompareTo(b.Id) < 0;
}
///
/// The SQL ordering of the queue (before priority, age and id): the levels of , highest first, as
/// a CASE over the kind column; empty while the queue is off or every kind has the same level.
///
internal string OrderSql(IEnumerable kinds)
{
if (!Enabled) return string.Empty;
var levels = kinds.Distinct().GroupBy(LevelOf).Where(g => g.Key != JobKindPriority.Normal).ToList();
if (levels.Count == 0) return string.Empty;
var sql = new StringBuilder("CASE");
foreach (var level in levels)
{
sql.Append(" WHEN kind IN (").AppendJoin(", ", level.Select(k => ((int)k).ToString(CultureInfo.InvariantCulture))).Append(") THEN ")
.Append(((int)level.Key).ToString(CultureInfo.InvariantCulture));
}
return sql.Append(" ELSE ").Append(((int)JobKindPriority.Normal).ToString(CultureInfo.InvariantCulture)).Append(" END DESC, ").ToString();
}
/// Wire name of a level in API v1 and settings files: high, normal, low.
public static string Wire(JobKindPriority level) => level.ToString().ToLowerInvariant();
/// The level named (, any case); false for anything else.
public static bool TryParse(string? text, out JobKindPriority level)
{
foreach (var candidate in Enum.GetValues())
{
if (!string.Equals(text, Wire(candidate), StringComparison.OrdinalIgnoreCase)) continue;
level = candidate;
return true;
}
level = JobKindPriority.Normal;
return false;
}
///
/// The queue from settings: maps kind names ( or the enum name) to
/// level names; unknown kinds and levels are skipped, so a settings file written by a newer build still loads.
///
public static JobPriorityQueue From(bool enabled, IReadOnlyDictionary? levels)
{
var parsed = new Dictionary();
foreach (var (name, value) in levels ?? new Dictionary())
{
if ((JobWire.TryParseKind(name, out var kind) || Enum.TryParse(name, ignoreCase: true, out kind)) && Enum.IsDefined(kind) && TryParse(value, out var level))
parsed[kind] = level;
}
return new JobPriorityQueue { Enabled = enabled, Levels = parsed };
}
/// The levels that differ from , by wire kind name: what settings store.
public static Dictionary Changed(IReadOnlyDictionary levels)
{
var defaults = new JobPriorityQueue();
return levels.Where(l => defaults.LevelOf(l.Key) != l.Value).OrderBy(l => l.Key)
.ToDictionary(l => JobWire.Kind(l.Key), l => Wire(l.Value), StringComparer.Ordinal);
}
}