merge: phase 5 parcel P3
This commit is contained in:
commit
8ea75b4b02
17 files changed
+875
-13
No files matched your search
@@ -24,7 +24,7 @@ public static class Dto
|
||||
f.FocalLength, f.Orientation, f.Width, f.Height, f.Format.ToString().ToLowerInvariant(), (long)f.Flags, f.PreviewWidth, f.PreviewHeight);
|
||||
|
||||
public static RenderDto Render(Render r) => new(r.Id, r.PresetName, r.Codec, r.Width, r.Height, r.Fps, r.DurationSeconds, r.Bytes, r.Created, r.ProducedBy,
|
||||
r.ProjectId, r.ProjectVersionId);
|
||||
r.ProjectId, r.ProjectVersionId, r.Sha256, r.Kind);
|
||||
|
||||
public static JobDto Job(Job j) => new(
|
||||
j.Id, JobWire.Kind(j.Kind), j.TargetIds, j.TargetLabel, JobWire.State(j.State), JobWire.Priority(j.Priority), j.ProgressDone,
|
||||
|
||||
@@ -107,7 +107,7 @@ public sealed class ServerState
|
||||
public string Database { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>What this server offers clients (<see cref="ServerInfo.Capabilities"/>; <see cref="ServerCapabilities"/> names those clients act on).</summary>
|
||||
public List<string> Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events", ServerCapabilities.Projects];
|
||||
public List<string> Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events", ServerCapabilities.Projects, ServerCapabilities.Videos];
|
||||
|
||||
public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow;
|
||||
}
|
||||
@@ -5,6 +5,7 @@ using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Videos;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Events;
|
||||
using Chronos.Server.Jobs;
|
||||
@@ -15,7 +16,7 @@ namespace Chronos.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/v1/archive/trash</c> (owner review 2, R6; administrators of the archive): the entries of the archive's trash —
|
||||
/// deleted sequences and photos deleted from sequences —, restoring one, and emptying it: a dry run that measures the
|
||||
/// deleted sequences, photos deleted from sequences and deleted videos (owner review 1, R9) —, restoring one, and emptying it: a dry run that measures the
|
||||
/// entries and fingerprints them, then an <c>empty-trash</c> job that erases exactly those entries and refuses when the
|
||||
/// trash changed since (BRIEF §0.2 rule 8: the only erase of user files, always an explicit, confirmed action).
|
||||
/// </summary>
|
||||
@@ -29,8 +30,11 @@ public static partial class TrashEndpoints
|
||||
trash.MapPost("/empty", EmptyAsync);
|
||||
}
|
||||
|
||||
/// <summary>Whether <paramref name="name"/> has the shape of an entry name (a sequence id, a time, <c>photos-</c>): never a path.</summary>
|
||||
public static bool IsEntryName(string? name) => name is not null && EntryName().IsMatch(name);
|
||||
/// <summary>
|
||||
/// Whether <paramref name="name"/> has the shape of an entry name (a sequence id, a time, <c>photos-</c>, or a videos entry
|
||||
/// <c>videos-<render id>-<ticks></c>, owner review 1, R9): never a path.
|
||||
/// </summary>
|
||||
public static bool IsEntryName(string? name) => name is not null && (EntryName().IsMatch(name) || VideoTrashNames.IsEntryName(name));
|
||||
|
||||
public static TrashEntryDto Entry(TrashEntry e) =>
|
||||
new(e.Name, e.Kind.ToString().ToLowerInvariant(), e.SequenceId, e.Title, e.Folder, e.Frames, e.Files, e.Bytes, e.DeletedBy, e.DeletedAt, e.ConversionDeleted);
|
||||
@@ -55,9 +59,11 @@ public static partial class TrashEndpoints
|
||||
/// a sequence, <c>frames</c> for photos.
|
||||
/// </summary>
|
||||
private static async Task<IResult> RestoreAsync(HttpContext context, Caller caller, string name, ChronosDatabase db, ServerArchive archive,
|
||||
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
|
||||
[FromServices] ArchiveService? archives, [FromServices] IVideoLibrary? videos, JobEngineHost host, AuditLog audit, EventHub events,
|
||||
IHostApplicationLifetime lifetime)
|
||||
{
|
||||
if (!IsEntryName(name)) return ApiErrors.NotFound(context, "trash_entry");
|
||||
if (VideoTrashNames.IsEntryName(name)) return await RestoreVideoAsync(context, caller, name, db, archive, VideoEndpoints.Library(videos, archives, db), audit, events, lifetime);
|
||||
TrashRestoreResult result;
|
||||
try
|
||||
{
|
||||
@@ -107,6 +113,49 @@ public static partial class TrashEndpoints
|
||||
result.Kept.Count == 0 ? null : string.Join(" ", KeptPhoto.Sentences(result.Kept, culture))), ProtocolJson.Default.TrashRestoreDto);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Brings a deleted video back (owner review 1, R9, decision 18): the trashed file re-hashed against its record, moved back
|
||||
/// into its sequence's folder (a free name when its own is taken) and its entry recorded again with the same render id.
|
||||
/// 404 <c>not_found</c> (<c>trash_entry</c>); 409 <c>sequence_gone</c> (restore the sequence first), <c>sequence_busy</c>,
|
||||
/// <c>folder_in_use</c>; 422 <c>trash_hash_mismatch</c> (it stays in the trash); 503 <c>archive_offline</c>. Publishes
|
||||
/// <c>sequenceChanged</c> (<c>renders</c>).
|
||||
/// </summary>
|
||||
private static async Task<IResult> RestoreVideoAsync(HttpContext context, Caller caller, string name, ChronosDatabase db, ServerArchive archive,
|
||||
IVideoLibrary library, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
|
||||
{
|
||||
if (!library.IsAvailable) return ApiErrors.NotFound(context, "trash_entry");
|
||||
Render render;
|
||||
try
|
||||
{
|
||||
render = await library.RestoreAsync(archive.Id, name, lifetime.ApplicationStopping);
|
||||
}
|
||||
catch (DirectoryNotFoundException)
|
||||
{
|
||||
return ApiErrors.NotFound(context, "trash_entry");
|
||||
}
|
||||
catch (VideoLibraryException ex)
|
||||
{
|
||||
return VideoEndpoints.Refused(context, ex);
|
||||
}
|
||||
catch (ArchiveOfflineException)
|
||||
{
|
||||
return Offline(context);
|
||||
}
|
||||
catch (LeaseUnavailableException)
|
||||
{
|
||||
return ApiErrors.Conflict(context, "sequence_busy");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return ApiErrors.Conflict(context, "folder_in_use");
|
||||
}
|
||||
await audit.WriteAsync(caller, context, "trash_restored", "render", render.Id.ToString(), $"{name} · {Path.GetFileName(render.OutputPath.TrimEnd('/', '\\'))}");
|
||||
if (await db.Sequences.GetAsync(render.SequenceId, CancellationToken.None) is { } sequence)
|
||||
events.Publish(new SequenceChangedEvent(sequence.Id, "renders", sequence.FramesVersion, sequence.SettingsVersion));
|
||||
return Results.Json(new TrashRestoreDto(name, TrashKind.Videos.ToString().ToLowerInvariant(), render.SequenceId, 1, [], NewSequence: false),
|
||||
ProtocolJson.Default.TrashRestoreDto);
|
||||
}
|
||||
|
||||
/// <summary>The code of why a photo stayed in the trash (<see cref="TrashRestoreDto.KeptReasons"/>).</summary>
|
||||
private static string ReasonCode(KeptReason reason) => reason switch
|
||||
{
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
using System.Globalization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Videos;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Events;
|
||||
using Chronos.Server.Jobs;
|
||||
using Chronos.Server.Security;
|
||||
using Chronos.Server.Storage;
|
||||
|
||||
namespace Chronos.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/v1/videos</c> (owner review 1, R9; capability <see cref="ServerCapabilities.Videos"/>): every render of the
|
||||
/// server in one list, read by anyone who may read; deleting renders into the archive's trash (Delete), always a dry run
|
||||
/// first whose fingerprint the delete itself must give back, and restored through <c>/archive/trash/{name}/restore</c>;
|
||||
/// and copying them, hash-verified, into the server's videos folder as one <c>video-copy</c> job (Edit). The files
|
||||
/// themselves are <c>GET /api/v1/renders/{id}/file</c>. Deletes and copies are audited (<c>videos_deleted</c>,
|
||||
/// <c>videos_copied</c>). The panel manages and never edits (owner review 2, R6): nothing here changes a project or starts a render.
|
||||
/// </summary>
|
||||
public static class VideoEndpoints
|
||||
{
|
||||
/// <summary>The most renders one delete or copy names.</summary>
|
||||
public const int MaxIds = VideoQuery.MaxLimit;
|
||||
|
||||
/// <summary>Renders an audit entry names by file, the rest counted.</summary>
|
||||
private const int AuditNames = 5;
|
||||
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
var videos = api.MapGroup("/videos").Requires(Permissions.Read);
|
||||
videos.MapGet("", ListAsync);
|
||||
videos.MapGet("/{id:guid}", GetAsync);
|
||||
videos.MapPost("/delete", DeleteAsync).Requires(Permissions.Delete);
|
||||
videos.MapPost("/copy", CopyAsync).Requires(Permissions.Edit);
|
||||
}
|
||||
|
||||
/// <summary>The videos library behind these endpoints: the host's, or that of an archive engine of its own (a test host that replaces the archive module).</summary>
|
||||
internal static IVideoLibrary Library(IVideoLibrary? videos, ArchiveService? archives, ChronosDatabase db) =>
|
||||
videos ?? LibraryEndpoints.Engine(archives, db).Videos;
|
||||
|
||||
public static VideoDto Video(VideoItem item)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
var r = item.Render;
|
||||
return new VideoDto(r.Id, r.SequenceId, r.PresetName, r.Codec, r.Width, r.Height, r.Fps, r.DurationSeconds, r.Bytes, r.Created, r.ProducedBy,
|
||||
r.ProjectId, r.ProjectVersionId, r.Sha256, item.Kind, item.SequenceTitle, item.SequenceFirstCapture, item.ProjectName, item.ProjectVersionNumber,
|
||||
item.State, [.. item.Copies.Select(c => new VideoCopyDto(c.Path, c.CopiedAt))], item.FileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One page of videos: <c>q</c> (sequence title, preset or file name), <c>kind</c> (<c>video</c>, <c>still</c>,
|
||||
/// <c>sequence</c>), <c>codec</c>, <c>year</c>, <c>sequence</c>, <c>sort</c> (<see cref="VideoSorts"/>), <c>cursor</c>,
|
||||
/// <c>limit</c> (1–500). 400 <c>invalid_filter</c> (details: the filter).
|
||||
/// </summary>
|
||||
private static async Task<IResult> ListAsync(HttpContext context, string? q, string? kind, string? codec, int? year, Guid? sequence, string? sort,
|
||||
string? cursor, int? limit, ChronosDatabase db, [FromServices] ArchiveService? archives, [FromServices] IVideoLibrary? videos)
|
||||
{
|
||||
kind = Blank(kind)?.ToLowerInvariant();
|
||||
sort = Blank(sort)?.ToLowerInvariant();
|
||||
if (kind is not null and not (RenderKind.Video or RenderKind.Still or RenderKind.Sequence)) return ApiErrors.BadRequest(context, "invalid_filter", "kind");
|
||||
if (sort is not null && !VideoSorts.All.Contains(sort)) return ApiErrors.BadRequest(context, "invalid_filter", "sort");
|
||||
if (year is < 1 or > 9999) return ApiErrors.BadRequest(context, "invalid_filter", "year");
|
||||
var query = VideoQuery.From(new VideoQueryDto(Blank(q), kind, Blank(codec), year, sequence, sort, Blank(cursor), limit));
|
||||
VideoPage page;
|
||||
try
|
||||
{
|
||||
page = await Library(videos, archives, db).ListAsync(query, context.RequestAborted);
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or FormatException)
|
||||
{
|
||||
// A cursor of another listing, or one this server never gave.
|
||||
return ApiErrors.BadRequest(context, "invalid_cursor");
|
||||
}
|
||||
return Results.Json(new VideoPageDto([.. page.Items.Select(Video)], page.Next, page.Total), ProtocolJson.Default.VideoPageDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetAsync(HttpContext context, Guid id, ChronosDatabase db, [FromServices] ArchiveService? archives,
|
||||
[FromServices] IVideoLibrary? videos) =>
|
||||
await Library(videos, archives, db).GetAsync(id, context.RequestAborted) is { } item
|
||||
? Results.Json(Video(item), ProtocolJson.Default.VideoDto)
|
||||
: ApiErrors.NotFound(context, "render");
|
||||
|
||||
/// <summary>
|
||||
/// With <c>dryRun</c> the plan of moving <c>ids</c> into the archive's trash: the renders that go (one whose file is
|
||||
/// missing loses only its entry), their bytes, those left where they are (<c>busy</c>, <c>not_found</c>) and the plan's
|
||||
/// fingerprint; nothing moves. Otherwise the request carries that fingerprint and the renders move as planned, each
|
||||
/// into a trash entry (<see cref="VideoDeletePlanDto.TrashEntries"/>); copies in the videos folder are never touched.
|
||||
/// 400 <c>bad_request</c> (<c>ids</c>, <c>fingerprint</c>); 409 <c>plan_changed</c> (nothing moved), <c>video_busy</c>,
|
||||
/// <c>sequence_busy</c>, <c>folder_in_use</c>; 503 <c>archive_offline</c>. Publishes <c>sequenceChanged</c>
|
||||
/// (<c>renders</c>) for every sequence that lost a render.
|
||||
/// </summary>
|
||||
private static async Task<IResult> DeleteAsync(HttpContext context, Caller caller, VideoDeleteRequest request, ChronosDatabase db,
|
||||
[FromServices] ArchiveService? archives, [FromServices] IVideoLibrary? videos, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
|
||||
{
|
||||
if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids");
|
||||
var library = Library(videos, archives, db);
|
||||
if (!library.IsAvailable) return Unavailable(context);
|
||||
try
|
||||
{
|
||||
if (request.DryRun)
|
||||
{
|
||||
var plan = await library.PlanDeleteAsync(ids, context.RequestAborted);
|
||||
return Results.Json(new VideoDeletePlanDto([.. plan.Items.Select(Item)], plan.Bytes, [.. plan.Blocked.Select(Blocked)], plan.Fingerprint, DryRun: true),
|
||||
ProtocolJson.Default.VideoDeletePlanDto);
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(request.Fingerprint)) return ApiErrors.BadRequest(context, "bad_request", "fingerprint");
|
||||
// Files move into the trash: the delete runs to the end even if the client disconnects meanwhile.
|
||||
var result = await library.DeleteAsync(ids, request.Fingerprint, caller.User.Username, lifetime.ApplicationStopping);
|
||||
var moved = result.Deleted.Where(i => !i.Missing).Sum(i => i.Render.Bytes);
|
||||
if (result.Deleted.Count > 0)
|
||||
{
|
||||
await audit.WriteAsync(caller, context, "videos_deleted", "videos", result.Deleted.Count == 1 ? result.Deleted[0].Render.Id.ToString() : null,
|
||||
Summary(result.Deleted.Count, moved, result.Deleted.Select(i => i.FileName)));
|
||||
}
|
||||
foreach (var sequenceId in result.Deleted.Select(i => i.Render.SequenceId).Distinct())
|
||||
{
|
||||
if (await db.Sequences.GetAsync(sequenceId, CancellationToken.None) is { } sequence)
|
||||
events.Publish(new SequenceChangedEvent(sequence.Id, "renders", sequence.FramesVersion, sequence.SettingsVersion));
|
||||
}
|
||||
return Results.Json(new VideoDeletePlanDto([.. result.Deleted.Select(Item)], moved, [.. result.Blocked.Select(Blocked)], request.Fingerprint,
|
||||
DryRun: false, result.TrashEntries), ProtocolJson.Default.VideoDeletePlanDto);
|
||||
}
|
||||
catch (VideoLibraryException ex)
|
||||
{
|
||||
return Refused(context, ex);
|
||||
}
|
||||
catch (ArchiveOfflineException)
|
||||
{
|
||||
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
|
||||
}
|
||||
catch (LeaseUnavailableException)
|
||||
{
|
||||
return ApiErrors.Conflict(context, "sequence_busy");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// A file is open elsewhere: nothing of it moved.
|
||||
return ApiErrors.Conflict(context, "folder_in_use");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues one <c>video-copy</c> job copying <c>ids</c> into the server's videos folder (<see cref="ServerOptions.VideosPath"/>),
|
||||
/// each copy hash-verified before it takes its name (a free one, " (2)" on a collision); the renders are never touched.
|
||||
/// 202 with the job. 400 <c>bad_request</c> (<c>ids</c>); 404 <c>not_found</c> (<c>render</c>, details); 409
|
||||
/// <c>videos_folder_unset</c>, <c>job_unavailable</c>; 422 <c>videos_folder_invalid</c> (inside the archive or the data
|
||||
/// folder); 507 <c>videos_no_space</c> (the folder's volume cannot take the renders' bytes).
|
||||
/// </summary>
|
||||
private static async Task<IResult> CopyAsync(HttpContext context, Caller caller, VideoCopyRequest request, ChronosDatabase db, ServerOptions options,
|
||||
[FromServices] ArchiveService? archives, [FromServices] IVideoLibrary? videos, JobEngineHost host, VolumeSpace volumes, AuditLog audit)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids");
|
||||
var folder = Blank(options.VideosPath);
|
||||
var library = Library(videos, archives, db);
|
||||
if (folder is null) return ApiErrors.Conflict(context, VideoErrors.FolderUnset);
|
||||
if (!ServerSettingsStore.IsVideosFolder(folder, options) || (library.FolderProblem(folder) is { } problem && problem != VideoErrors.FolderUnset))
|
||||
return Refused(context, VideoErrors.FolderInvalid);
|
||||
var renders = new List<Render>(ids.Count);
|
||||
foreach (var id in ids)
|
||||
{
|
||||
if (await db.Renders.GetAsync(id, ct) is not { } render) return ApiErrors.NotFound(context, "render");
|
||||
renders.Add(render);
|
||||
}
|
||||
if (!library.IsAvailable || !host.CanRun(JobKind.VideoCopy)) return Unavailable(context);
|
||||
if (volumes.Measure(folder) is { } volume && volume.FreeBytes < renders.Sum(r => r.Bytes)) return Refused(context, VideoErrors.NoSpace);
|
||||
ArchiveJobRequest job;
|
||||
try
|
||||
{
|
||||
job = library.CopyJob(new VideoCopyParameters(ids, folder, FromServer: false, caller.User.Username));
|
||||
}
|
||||
catch (VideoLibraryException ex)
|
||||
{
|
||||
return Refused(context, ex);
|
||||
}
|
||||
var queued = await host.Engine.EnqueueAsync(job, caller.Id, ct);
|
||||
await audit.WriteAsync(caller, context, "videos_copied", "job", queued.Id.ToString(),
|
||||
Summary(renders.Count, renders.Sum(r => r.Bytes), renders.Select(r => Path.GetFileName(r.OutputPath.TrimEnd('/', '\\')))));
|
||||
return Results.Json(new VideoCopyResultDto(queued.Id), ProtocolJson.Default.VideoCopyResultDto, statusCode: StatusCodes.Status202Accepted);
|
||||
}
|
||||
|
||||
/// <summary>The answer of a library refusal: its code with its status.</summary>
|
||||
internal static IResult Refused(HttpContext context, VideoLibraryException ex) => Refused(context, ex.Code);
|
||||
|
||||
private static IResult Refused(HttpContext context, string code) => ApiErrors.Result(context, code switch
|
||||
{
|
||||
VideoErrors.FolderInvalid or VideoErrors.HashMismatch => StatusCodes.Status422UnprocessableEntity,
|
||||
VideoErrors.NoSpace => StatusCodes.Status507InsufficientStorage,
|
||||
_ => StatusCodes.Status409Conflict,
|
||||
}, code);
|
||||
|
||||
/// <summary>This server's archive engine has no videos library (a build before it): nothing can be deleted or copied.</summary>
|
||||
private static IResult Unavailable(HttpContext context) => ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.VideoCopy));
|
||||
|
||||
/// <summary>The ids of a request, each once in order; null when there are none, too many, or an empty one.</summary>
|
||||
private static List<Guid>? Ids(IReadOnlyList<Guid>? ids)
|
||||
{
|
||||
if (ids is null || ids.Count is 0 or > MaxIds || ids.Contains(Guid.Empty)) return null;
|
||||
return [.. ids.Distinct()];
|
||||
}
|
||||
|
||||
private static VideoDeleteItemDto Item(VideoItem item) =>
|
||||
new(item.Render.Id, item.Render.SequenceId, item.SequenceTitle, item.FileName, item.Missing ? 0 : item.Render.Bytes, item.Missing);
|
||||
|
||||
private static VideoBlockedDto Blocked(VideoBlocked blocked) => new(blocked.RenderId, blocked.Reason);
|
||||
|
||||
/// <summary>An audit entry's details: how many, their bytes, and the first file names.</summary>
|
||||
private static string Summary(int count, long bytes, IEnumerable<string> names) =>
|
||||
string.Create(CultureInfo.InvariantCulture, $"{count} · {bytes} · {string.Join(", ", names.Take(AuditNames))}");
|
||||
|
||||
private static string? Blank(string? text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim();
|
||||
}
|
||||
@@ -40,6 +40,7 @@ public sealed class ServerOptions
|
||||
("CHRONOS_SERVER_NAME", nameof(ServerName), (o, v) => o.ServerName = v),
|
||||
("CHRONOS_ARCHIVE_PATH", nameof(ArchivePath), (o, v) => o.ArchivePath = v),
|
||||
("CHRONOS_SPACE_PATH", nameof(SpacePath), (o, v) => o.SpacePath = v),
|
||||
("CHRONOS_VIDEOS_PATH", nameof(VideosPath), (o, v) => o.VideosPath = v),
|
||||
("CHRONOS_ADMIN_USER", nameof(AdminUser), (o, v) => o.AdminUser = v),
|
||||
("CHRONOS_ADMIN_PASSWORD", nameof(AdminPassword), (o, v) => o.AdminPassword = v),
|
||||
("CHRONOS_DB", nameof(Database), (o, v) => o.ApplyDatabase(v)),
|
||||
@@ -106,6 +107,14 @@ public sealed class ServerOptions
|
||||
/// </summary>
|
||||
public string? SpacePath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The folder "Copy to videos folder" copies renders into, hash-verified, flat, " (2)" on a collision (owner review 1,
|
||||
/// R9; key <c>VideosPath</c>, variable <c>CHRONOS_VIDEOS_PATH</c>, which locks it). Docker: the <c>/videos</c> volume.
|
||||
/// Unset by default, which turns copying off (<c>videos_folder_unset</c>); an absolute folder outside the archive and
|
||||
/// the data folder (<see cref="ServerSettingsStore.IsVideosFolder"/>). Chronos never deletes what it copied there.
|
||||
/// </summary>
|
||||
public string? VideosPath { get; set; }
|
||||
|
||||
public string DataPath { get; set; } = OperatingSystem.IsWindows() ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Chronos Server") : "/data";
|
||||
public string? AdminUser { get; set; }
|
||||
public string? AdminPassword { get; set; }
|
||||
@@ -394,6 +403,8 @@ public sealed class ServerOptions
|
||||
{
|
||||
throw new InvalidOperationException($"CHRONOS_TRUSTED_PROXIES must list IP addresses (such as 172.30.0.10) or networks in CIDR form: {ex.Message}", ex);
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(VideosPath) && !Path.IsPathFullyQualified(VideosPath.Trim()))
|
||||
throw new InvalidOperationException("CHRONOS_VIDEOS_PATH must be an absolute folder, such as /videos.");
|
||||
if (ChunkSizeBytes is < 64 * 1024 or > 64 * 1024 * 1024)
|
||||
throw new InvalidOperationException("The chunk size must be between 64 KiB and 64 MiB.");
|
||||
if (MaxUploadBytes < 1 || TokenLifetimeDays < 1 || JobHistoryDays < 1 || UploadRetentionHours < 1)
|
||||
|
||||
@@ -14,7 +14,8 @@ namespace Chronos.Server.Configuration;
|
||||
/// The admin panel's view of the configuration (BRIEF §14.8 Settings). Saving writes <c>/data/server.json</c> (only the
|
||||
/// edited keys; secrets and environment values are never written) and applies what can change while running, the
|
||||
/// parallelism and the priority queue included (owner review 1), and the log settings through <see cref="ServerLogging"/>
|
||||
/// (owner review 2, R11), and the public ports clients use (owner review 3); the listening ports, TLS and chunk size wait for
|
||||
/// (owner review 2, R11), the public ports clients use (owner review 3) and the videos folder (owner review 1, R9; checked by
|
||||
/// <see cref="IsVideosFolder"/>); the listening ports, TLS and chunk size wait for
|
||||
/// a restart. In a container the listening ports are locked: the template maps them. Job history is what the housekeeping system
|
||||
/// schedule is reset to (owner review 2, R10): the schedule's own value applies. The audit retention kept here is what the
|
||||
/// audit clean-up schedule is reset to; the endpoint shows that schedule's age limit in its place and puts a new one there
|
||||
@@ -27,9 +28,11 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
[
|
||||
JobKind.Render, JobKind.Import, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse, JobKind.DeepAnalyse, JobKind.Thumbs,
|
||||
JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move, JobKind.Backup, JobKind.Cleanup,
|
||||
JobKind.EmptyTrash, JobKind.Convert,
|
||||
JobKind.EmptyTrash, JobKind.Convert, JobKind.VideoCopy,
|
||||
];
|
||||
|
||||
private static readonly StringComparison PathComparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||
|
||||
private readonly Lock _gate = new();
|
||||
private ServerSettingsDto? _saved;
|
||||
|
||||
@@ -52,8 +55,9 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
Logs = request.Logs ?? before.Logs,
|
||||
PublicHttpPort = Public(request.PublicHttpPort, before.PublicHttpPort),
|
||||
PublicHttpsPort = Public(request.PublicHttpsPort, before.PublicHttpsPort),
|
||||
VideosPath = Videos(request.VideosPath, before.VideosPath),
|
||||
};
|
||||
if (Validate(request, before) is { } invalid) return ("invalid_setting", invalid);
|
||||
if (Validate(request, before, options) is { } invalid) return ("invalid_setting", invalid);
|
||||
lock (_gate)
|
||||
{
|
||||
var current = _saved ?? Snapshot(options, restartRequired: false);
|
||||
@@ -100,6 +104,8 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
// Read by LAN discovery and the admin redirect at every use: they apply at once.
|
||||
options.PublicHttpPort = request.PublicHttpPort;
|
||||
options.PublicHttpsPort = request.PublicHttpsPort;
|
||||
// Read by every copy request: it applies at once.
|
||||
options.VideosPath = request.VideosPath;
|
||||
logging.Apply(options);
|
||||
var restart = request.HttpPort != options.HttpPort || request.HttpsPort != options.HttpsPort
|
||||
|| !string.Equals(request.TlsMode, options.TlsMode.ToString(), StringComparison.OrdinalIgnoreCase)
|
||||
@@ -123,7 +129,41 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
private static ServerSettingsDto Snapshot(ServerOptions o, bool restartRequired) => new(
|
||||
o.ServerName, o.HttpPort, o.HttpsPort, o.TlsMode.ToString().ToLowerInvariant(), o.TlsCert, o.TlsKey, o.Language, o.Parallelism, o.PriorityQueue,
|
||||
Priorities(PriorityQueue(o)), o.Discovery, o.MaxUploadBytes, o.ChunkSizeBytes, o.JobHistoryDays, o.TokenLifetimeDays, o.UploadRetentionHours,
|
||||
Logs(o), LockedSettings(o), LockedBy(o), restartRequired, ProxyWarning: false, o.PublicHttpPort, o.PublicHttpsPort, o.InContainer);
|
||||
Logs(o), LockedSettings(o), LockedBy(o), restartRequired, ProxyWarning: false, o.PublicHttpPort, o.PublicHttpsPort, o.InContainer,
|
||||
string.IsNullOrWhiteSpace(o.VideosPath) ? null : o.VideosPath.Trim());
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="folder"/> may be the videos folder (owner review 1, R9): an absolute folder that is neither the
|
||||
/// archive nor the data folder nor inside either, so a copy never lands among the files the server indexes or keeps.
|
||||
/// </summary>
|
||||
public static bool IsVideosFolder(string folder, ServerOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
if (string.IsNullOrWhiteSpace(folder) || folder.Contains('\0', StringComparison.Ordinal) || !Path.IsPathFullyQualified(folder.Trim())) return false;
|
||||
string full;
|
||||
try
|
||||
{
|
||||
full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder.Trim()));
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
foreach (var root in new[] { options.ArchivePath, options.DataPath })
|
||||
{
|
||||
var rootFull = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root));
|
||||
if (string.Equals(full, rootFull, PathComparison) || full.StartsWith(rootFull + Path.DirectorySeparatorChar, PathComparison)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The videos folder as a request sets it: null keeps <paramref name="current"/>, an empty text clears it.</summary>
|
||||
private static string? Videos(string? requested, string? current) => requested switch
|
||||
{
|
||||
null => current,
|
||||
_ when string.IsNullOrWhiteSpace(requested) => null,
|
||||
_ => requested.Trim(),
|
||||
};
|
||||
|
||||
/// <summary>The listening ports, which a container's template maps (owner review 3).</summary>
|
||||
private static readonly string[] ContainerPorts = [nameof(ServerOptions.HttpPort), nameof(ServerOptions.HttpsPort)];
|
||||
@@ -177,8 +217,10 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
/// The first setting of <paramref name="r"/> out of range, or null. Listening ports are checked only when they change,
|
||||
/// so a value the panel cannot change (a container's, the test server's 0) never blocks saving the others.
|
||||
/// </summary>
|
||||
private static string? Validate(ServerSettingsDto r, ServerSettingsDto current)
|
||||
private static string? Validate(ServerSettingsDto r, ServerSettingsDto current, ServerOptions options)
|
||||
{
|
||||
// Checked when it changes, so a folder an environment variable sets never blocks saving the others.
|
||||
if (r.VideosPath is { } videos && videos != current.VideosPath && !IsVideosFolder(videos, options)) return nameof(ServerOptions.VideosPath);
|
||||
if (string.IsNullOrWhiteSpace(r.ServerName) || r.ServerName.Trim().Length > 60) return nameof(ServerOptions.ServerName);
|
||||
var portsChanged = r.HttpPort != current.HttpPort || r.HttpsPort != current.HttpsPort;
|
||||
if (portsChanged && r.HttpPort is < 1 or > 65535) return nameof(ServerOptions.HttpPort);
|
||||
@@ -244,6 +286,8 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
Add(nameof(ServerOptions.LogRotation), Rotation(a.Logs.Rotation), Rotation(b.Logs.Rotation), v => JsonValue.Create(v.ToString()));
|
||||
Add(nameof(ServerOptions.AuditRetentionDays), a.Logs.AuditRetentionDays, b.Logs.AuditRetentionDays, v => JsonValue.Create(v));
|
||||
Add(nameof(ServerOptions.DiagnosticsLogMb), a.Logs.DiagnosticsLogMb, b.Logs.DiagnosticsLogMb, v => JsonValue.Create(v));
|
||||
// A cleared videos folder is stored as null, so server.json no longer sets one.
|
||||
Add(nameof(ServerOptions.VideosPath), a.VideosPath, b.VideosPath, v => v is null ? null : JsonValue.Create(v));
|
||||
return changes;
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,8 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
|
||||
CHRONOS_TLS_CERT CHRONOS_TLS_KEY CHRONOS_LANG
|
||||
CHRONOS_SPACE_PATH folder whose volume's free space the admin panel shows (default: the archive's); on
|
||||
Unraid the share's array view (/mnt/user0/<share>) mapped read-only to /space
|
||||
CHRONOS_VIDEOS_PATH folder "Copy to videos folder" copies renders into, hash-verified (default: none, copying
|
||||
off); in a container the /videos volume
|
||||
CHRONOS_PARALLELISM photos the running job processes at once (jobs run one at a time; default: half the
|
||||
cores); CHRONOS_WORKERS, its former name, still sets it
|
||||
CHRONOS_PRIORITY_QUEUE a job of a higher level pauses the running one, which resumes afterwards (true | false)
|
||||
|
||||
@@ -187,6 +187,7 @@ public static class ServerHost
|
||||
ProjectEndpoints.Map(api);
|
||||
LibraryEndpoints.Map(api);
|
||||
FileEndpoints.Map(api);
|
||||
VideoEndpoints.Map(api);
|
||||
UploadEndpoints.Map(api);
|
||||
JobEndpoints.Map(api);
|
||||
ScheduleEndpoints.Map(api);
|
||||
|
||||
@@ -11,6 +11,7 @@ public static class FileResponses
|
||||
[".jpg"] = "image/jpeg",
|
||||
[".jpeg"] = "image/jpeg",
|
||||
[".png"] = "image/png",
|
||||
[".apng"] = "image/apng",
|
||||
[".gif"] = "image/gif",
|
||||
[".tif"] = "image/tiff",
|
||||
[".tiff"] = "image/tiff",
|
||||
@@ -22,6 +23,9 @@ public static class FileResponses
|
||||
[".mp4"] = "video/mp4",
|
||||
[".mov"] = "video/quicktime",
|
||||
[".avi"] = "video/x-msvideo",
|
||||
// The admin panel's player (owner review 1, R9) plays what a browser's <video> takes.
|
||||
[".webm"] = "video/webm",
|
||||
[".m4v"] = "video/mp4",
|
||||
}.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public static string ContentTypeOf(string fileName) =>
|
||||
|
||||
@@ -66,11 +66,29 @@ public sealed class RenderStore(ChronosDatabase db, ServerArchive archive, TimeP
|
||||
ProducedBy = producedBy,
|
||||
ProjectId = projectId,
|
||||
ProjectVersionId = projectVersionId,
|
||||
// Verified against the bytes when the upload completed (owner review 1, R9: every single-file render hashed).
|
||||
Sha256 = UploadRules.IsSha256(output.Sha256) ? output.Sha256.ToLowerInvariant() : null,
|
||||
Kind = KindOf(output.Kind),
|
||||
};
|
||||
await db.Renders.InsertAsync(render, cancellationToken);
|
||||
return (Render?)render;
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>The longest kind a render is recorded with.</summary>
|
||||
private const int MaxKindLength = 32;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="Render.Kind"/> a client or a render node names, as recorded: null for a video or an image sequence (told
|
||||
/// apart by the codec) and for anything that is not a plain lower-case word; a newer Chronos's kind as it is.
|
||||
/// </summary>
|
||||
public static string? KindOf(string? kind)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(kind)) return null;
|
||||
var word = kind.Trim().ToLowerInvariant();
|
||||
if (word.Length > MaxKindLength || !word.All(c => c is (>= 'a' and <= 'z') or '-')) return null;
|
||||
return word is RenderKind.Video or RenderKind.Sequence ? null : word;
|
||||
}
|
||||
|
||||
private static string Unique(string folder, string fileName)
|
||||
{
|
||||
var candidate = Path.Combine(folder, fileName);
|
||||
|
||||
@@ -98,8 +98,9 @@ public sealed class RenderUploads(
|
||||
|
||||
if (await uploads.StageVerifiedAsync(upload, cancellationToken) is not { } staged) return Outcome<RenderDto>.Fail(422, "hash_mismatch");
|
||||
var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken);
|
||||
// The hash just verified and the kind (a still, owner review 1, R9) are recorded with the render.
|
||||
var result = new RenderResultRequest(output.FileName, output.Size, output.Sha256, output.PresetName, output.Codec, output.Width, output.Height, output.Fps,
|
||||
output.DurationSeconds);
|
||||
output.DurationSeconds, output.Kind);
|
||||
Render? render;
|
||||
try
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user