merge: rc.14 parcel layout

This commit is contained in:
Alby96 committed 2026-11-06 17:14:07 +01:00
commit e97df55840
24 files changed
+605 -21

No files matched your search

+1 -1
View File
@@ -20,7 +20,7 @@ public static class ArchiveFailures
// any more (FrameTrash.RestoreAsync). Other IOExceptions and InvalidDataExceptions (a sidecar of another sequence)
// carry technical text.
LeaseUnavailableException or NewerFormatException or StaleRenamePlanException or NestedRenameException or StaleDeletePlanException
or SequenceInLibraryException or TrashMismatchException or Core.Project.ProjectTooLargeException => ex.Message,
or SequenceInLibraryException or TrashMismatchException or Core.Project.ProjectTooLargeException or ArchiveStructureException => ex.Message,
UnauthorizedAccessException => Loc.L("Archive.Failed.Access"),
DatabaseException => Loc.L("Archive.Failed.Index"),
ArgumentException => Loc.L("Archive.Failed.Gone"),
@@ -1,5 +1,6 @@
using System.IO;
using Chronos.App.Archiving;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Data.Archiving;
@@ -35,8 +36,14 @@ public sealed class EngineArchiveSetup(AppServices services) : IArchiveSetup
var defaults = services.Settings.ArchiveDefaults();
var archive = await Task.Run(async () =>
{
Directory.CreateDirectory(root);
return await archives.AdoptAsync(root, defaults, cancellationToken).ConfigureAwait(false);
// A new archive is made with its whole layout (the folder itself included), or not at all; an existing one gets
// the folders it lacks. One that can be written but not completed is refused with the reason, before it becomes
// the archive of this PC; a read-only one opens as before, to be browsed.
var opened = await archives.AdoptAsync(root, defaults, cancellationToken).ConfigureAwait(false);
var paths = new ArchivePaths(root);
if (ArchiveStructure.Ensure(paths) is { IsComplete: false } structure && ArchiveVolume.Probe(paths) == ArchiveAvailability.Online)
throw new ArchiveStructureException(structure);
return opened;
}, cancellationToken);
services.Settings.LastArchivePath = root;
services.SaveSettings();
@@ -1180,9 +1180,11 @@ public sealed class SettingsViewModel : SectionViewModel
{
var opened = await Task.Run(async () => File.Exists(new ArchivePaths(root).ManifestPath) ? await archives.OpenAsync(root) : null);
if (opened is not null) await Shell.Services.QueueScanAsync(opened, full: false);
// A folder that is no archive yet becomes one in place, with the archive's whole layout (as Welcome's Create).
else await Shell.Services.ArchiveSetup.CreateAsync(root);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or NewerFormatException
or DatabaseException)
or DatabaseException or ArgumentException or InvalidOperationException)
{
Log.Warning("settings", $"The archive at {root} could not be opened", ex);
Shell.Notify(Loc.L("Errors.Archive.Open"), ArchiveActions.Cause(ex), isError: true);
@@ -19,6 +19,15 @@ public static class ArchiveLayout
/// <summary>Resumable plans of mass operations (rename).</summary>
public const string JournalFolder = "journal";
/// <summary>Deleted sequences, photos and renders inside the root <see cref="MetaFolder"/>, kept until Empty.</summary>
public const string TrashFolder = "trash";
/// <summary>The photo entries inside <see cref="TrashFolder"/>.</summary>
public const string TrashPhotosFolder = "photos";
/// <summary>The deleted renders inside <see cref="TrashFolder"/> (owner review 1, R9).</summary>
public const string TrashVideosFolder = "videos";
public const string OriginalsFolder = "originals";
public const string ProxiesFolder = "proxies";
public const string ExportsFolder = "exports";
@@ -86,6 +95,9 @@ public sealed class ArchivePaths
public string LocksDirectory => Path.Combine(MetaDirectory, ArchiveLayout.LocksFolder);
public string StagingDirectory => Path.Combine(MetaDirectory, ArchiveLayout.StagingFolder);
public string JournalDirectory => Path.Combine(MetaDirectory, ArchiveLayout.JournalFolder);
public string TrashDirectory => Path.Combine(MetaDirectory, ArchiveLayout.TrashFolder);
public string TrashPhotosDirectory => Path.Combine(TrashDirectory, ArchiveLayout.TrashPhotosFolder);
public string TrashVideosDirectory => Path.Combine(TrashDirectory, ArchiveLayout.TrashVideosFolder);
/// <summary>Paths of the sequence stored in <paramref name="relativeFolder"/> (forward slashes).</summary>
public SequencePaths Sequence(string relativeFolder) => new(this, relativeFolder);
@@ -0,0 +1,134 @@
using Chronos.Core.Localization;
namespace Chronos.Core.Archiving;
/// <summary>Why the folders of an archive's layout could not all be created (<see cref="ArchiveStructure.Ensure"/>).</summary>
public enum ArchiveStructureProblem
{
None,
/// <summary>The drive or share of the archive is not there (unplugged, disconnected, not ready).</summary>
Unavailable,
/// <summary>The account Chronos runs as may not create folders there.</summary>
Denied,
/// <summary>The drive or share is read-only (write-protected disk, read-only mount).</summary>
ReadOnly,
/// <summary>Any other failure, a file where a folder belongs included.</summary>
Failed,
}
/// <summary>What <see cref="ArchiveStructure.Ensure"/> found and did.</summary>
/// <param name="Root">The archive root.</param>
/// <param name="Created">The folders created, parents first.</param>
/// <param name="Problem">Why the layout is not complete; <see cref="ArchiveStructureProblem.None"/> when it is.</param>
/// <param name="Folder">The folder that could not be created; null when the layout is complete.</param>
/// <param name="Detail">The system's own text of the failure, for the log; null when the layout is complete.</param>
public sealed record ArchiveStructureReport(string Root, IReadOnlyList<string> Created, ArchiveStructureProblem Problem, string? Folder, string? Detail)
{
public bool IsComplete => Problem == ArchiveStructureProblem.None;
/// <summary>The problem as one localized sentence naming the folder; null when the layout is complete.</summary>
public string? Message => Problem switch
{
ArchiveStructureProblem.None => null,
ArchiveStructureProblem.Unavailable => Loc.L("Archive.Structure.Unavailable", Folder ?? Root),
ArchiveStructureProblem.Denied => Loc.L("Archive.Structure.Denied", Folder ?? Root),
ArchiveStructureProblem.ReadOnly => Loc.L("Archive.Structure.ReadOnly", Folder ?? Root),
_ => Loc.L("Archive.Structure.Failed", Folder ?? Root),
};
}
/// <summary>The folders of an archive's layout could not all be created; the message is one localized sentence.</summary>
public sealed class ArchiveStructureException(ArchiveStructureReport report) : IOException(report.Message)
{
public ArchiveStructureReport Report { get; } = report;
}
/// <summary>
/// The folders every archive holds (BRIEF §7) whatever made it: the root's <c>.chronos</c> with <c>locks</c>,
/// <c>journal</c>, <c>staging</c> and <c>trash</c>, whose <c>photos</c> and <c>videos</c> areas hold the deleted photos and
/// renders. <c>archive.json</c> is the archive service's (it needs a name and an id); the folders of a sequence
/// (<c>originals</c>, <c>proxies</c>, <c>exports</c>, its <c>.chronos</c>) are made when the sequence is, and the
/// trash's <c>.erasing</c> and <c>.erased</c> only when Empty needs them.
/// </summary>
public static class ArchiveStructure
{
private const int WriteProtected = unchecked((int)0x80070013); // ERROR_WRITE_PROTECT
private const int NotReady = unchecked((int)0x80070015); // ERROR_NOT_READY
private const int BadNetworkPath = unchecked((int)0x80070035); // ERROR_BAD_NETPATH
private const int NetworkNameDeleted = unchecked((int)0x80070040); // ERROR_NETNAME_DELETED
private const int BadNetworkName = unchecked((int)0x80070043); // ERROR_BAD_NET_NAME
private const int UnixReadOnlyFileSystem = 30; // EROFS, which .NET keeps as the IOException's HResult
private const int UnixNoDevice = 19; // ENODEV
/// <summary>The layout's folders of <paramref name="archive"/>, parents first, the root included.</summary>
public static IReadOnlyList<string> Folders(ArchivePaths archive)
{
ArgumentNullException.ThrowIfNull(archive);
return [archive.Root, archive.MetaDirectory, archive.LocksDirectory, archive.JournalDirectory, archive.StagingDirectory,
archive.TrashDirectory, archive.TrashPhotosDirectory, archive.TrashVideosDirectory];
}
/// <summary>The layout's folders that are not there, parents first; nothing is created.</summary>
public static IReadOnlyList<string> Missing(ArchivePaths archive) => [.. Folders(archive).Where(f => !Directory.Exists(f))];
/// <summary>
/// Creates the layout's folders that are missing, never touching what is there: an existing folder and every file
/// stay as they are, and a file where a folder belongs is reported, not replaced. Safe to run any number of times
/// and by several processes at once. Stops at the first folder that cannot be created and says why; never throws for
/// the file system.
/// </summary>
/// <param name="archive">The archive root.</param>
/// <param name="createRoot">Whether a missing root is created (a new archive); otherwise it is reported unavailable.</param>
/// <param name="createDirectory">Creates one folder (<see cref="Directory.CreateDirectory(string)"/>; tests replace it).</param>
public static ArchiveStructureReport Ensure(ArchivePaths archive, bool createRoot = false, Action<string>? createDirectory = null)
{
ArgumentNullException.ThrowIfNull(archive);
createDirectory ??= static path => Directory.CreateDirectory(path);
var created = new List<string>();
if (!Directory.Exists(archive.Root) && (!createRoot || !VolumeIsThere(archive.Root)))
return new(archive.Root, created, ArchiveStructureProblem.Unavailable, archive.Root, null);
foreach (var folder in Folders(archive))
{
if (Directory.Exists(folder)) continue;
try
{
createDirectory(folder);
created.Add(folder);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return new(archive.Root, created, Classify(ex), folder, ex.Message);
}
}
return new(archive.Root, created, ArchiveStructureProblem.None, null, null);
}
/// <summary>Why creating a folder failed, from the exception the file system threw.</summary>
public static ArchiveStructureProblem Classify(Exception ex) => ex switch
{
UnauthorizedAccessException => ArchiveStructureProblem.Denied,
DirectoryNotFoundException or DriveNotFoundException => ArchiveStructureProblem.Unavailable,
IOException { HResult: WriteProtected } => ArchiveStructureProblem.ReadOnly,
IOException { HResult: NotReady or BadNetworkPath or NetworkNameDeleted or BadNetworkName } => ArchiveStructureProblem.Unavailable,
IOException { HResult: UnixReadOnlyFileSystem } when !OperatingSystem.IsWindows() => ArchiveStructureProblem.ReadOnly,
IOException { HResult: UnixNoDevice } when !OperatingSystem.IsWindows() => ArchiveStructureProblem.Unavailable,
_ => ArchiveStructureProblem.Failed,
};
/// <summary>Whether the drive or share <paramref name="root"/> lives on is there.</summary>
private static bool VolumeIsThere(string root)
{
try
{
return Path.GetPathRoot(root) is { Length: > 0 } volume && Directory.Exists(volume);
}
catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException)
{
return false;
}
}
}
+21 -2
View File
@@ -141,7 +141,8 @@ public sealed class ArchiveService : IJobHandlerProvider
settings = WithUsableName(settings, paths);
settings.Validate();
if (File.Exists(paths.ManifestPath)) throw new InvalidOperationException($"{paths.Root} already is a Chronos archive.");
Directory.CreateDirectory(paths.MetaDirectory);
var structure = EnsureStructure(paths, createRoot: true);
if (!structure.IsComplete) throw new ArchiveStructureException(structure);
var manifest = new ArchiveManifest
{
Id = Guid.CreateVersion7(),
@@ -164,7 +165,10 @@ public sealed class ArchiveService : IJobHandlerProvider
{
var paths = new ArchivePaths(root);
var archive = await RegisterAsync(paths, ManifestStore.ReadArchive(paths.ManifestPath), cancellationToken).ConfigureAwait(false);
if (ArchiveVolume.Probe(paths) != ArchiveAvailability.Online) return archive;
var availability = ArchiveVolume.Probe(paths);
// Folders an older Chronos, another program or a copy left out are made again; a read-only archive only says which.
if (availability != ArchiveAvailability.Offline) EnsureStructure(paths);
if (availability != ArchiveAvailability.Online) return archive;
try
{
await Renamer.ResumePendingAsync(archive, cancellationToken).ConfigureAwait(false);
@@ -571,6 +575,21 @@ public sealed class ArchiveService : IJobHandlerProvider
await Imports.PlanEraseAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), cardId, sourceRoot, progress,
cancellationToken).ConfigureAwait(false);
/// <summary>
/// Creates the folders of the archive's layout that are missing (<see cref="ArchiveStructure.Ensure"/>), logging what it
/// made and, as a warning, why the layout stays incomplete. <see cref="CreateAsync(string, ArchiveSettings, CancellationToken)"/>
/// and <see cref="OpenAsync"/> run it; it never throws for the file system.
/// </summary>
public static ArchiveStructureReport EnsureStructure(ArchivePaths paths, bool createRoot = false)
{
ArgumentNullException.ThrowIfNull(paths);
var report = ArchiveStructure.Ensure(paths, createRoot);
if (report.Created.Count > 0)
Log.Info("archive", $"Archive folders created in {paths.Root}: {string.Join(", ", report.Created.Select(f => f == paths.Root ? "." : paths.ToRelative(f)))}");
if (!report.IsComplete) Log.Warning("archive", $"The archive folders of {paths.Root} are incomplete: {report.Message} {report.Detail}".TrimEnd());
return report;
}
/// <summary>
/// <paramref name="settings"/> with a name an archive can keep: a blank one becomes the folder's name (the root itself
/// for a drive root), one longer than <see cref="ArchiveSettings.MaxNameLength"/> is shortened.
+1 -1
View File
@@ -110,7 +110,7 @@ public sealed record PhotoRestoreResult(Sequence Sequence, int Restored, IReadOn
public sealed partial class FrameTrash
{
/// <summary>Folder of the photo entries inside the trash.</summary>
public const string FolderName = "photos";
public const string FolderName = ArchiveLayout.TrashPhotosFolder;
/// <summary>What <see cref="TrashEntry.Name"/> of a photo entry starts with (the folder name follows).</summary>
public const string EntryPrefix = "photos-";
+1 -1
View File
@@ -119,7 +119,7 @@ public sealed class TrashMismatchException() : IOException(Loc.L("Archive.Error.
public sealed partial class SequenceTrash
{
/// <summary>Folder of the trash inside the archive's <c>.chronos</c>.</summary>
public const string FolderName = "trash";
public const string FolderName = ArchiveLayout.TrashFolder;
private const string RecordExtension = ".json";
+1 -1
View File
@@ -192,7 +192,7 @@ public static class VideoTrashNames
public const string Prefix = "videos-";
/// <summary>The folder of the videos area inside an archive's trash, which holds the entries and their records.</summary>
public const string FolderName = "videos";
public const string FolderName = Chronos.Core.Archiving.ArchiveLayout.TrashVideosFolder;
/// <summary>The entry name of render <paramref name="renderId"/> deleted at <paramref name="deletedAt"/>.</summary>
public static string EntryName(Guid renderId, DateTimeOffset deletedAt) =>
+9 -1
View File
@@ -86,6 +86,7 @@ public sealed record UploadDayDto(DateOnly Day, long Frames, long Bytes);
/// <summary>
/// <c>GET /api/v1/server/dashboard</c> (admin): everything the dashboard page shows in one call (BRIEF §14.8).
/// <see cref="ProxyWarning"/>: TLS mode is proxy and this request did not come through a trusted proxy over HTTPS.
/// <see cref="ArchiveProblem"/>: a folder of the archive's layout is missing and could not be created; null when it is complete.
/// </summary>
public sealed record DashboardDto(
string ServerName,
@@ -103,4 +104,11 @@ public sealed record DashboardDto(
IReadOnlyList<UploadDayDto> Uploads,
IReadOnlyList<AuditEntryDto> Activity,
IReadOnlyList<JobDto> ActiveJobs,
bool ProxyWarning);
bool ProxyWarning,
ArchiveProblemDto? ArchiveProblem = null);
/// <summary>
/// Why a folder of the archive's layout (BRIEF §7) could not be created: <see cref="Code"/> is <c>unavailable</c> (drive or
/// share not there), <c>denied</c>, <c>readOnly</c> or <c>failed</c>; <see cref="Folder"/> is the folder.
/// </summary>
public sealed record ArchiveProblemDto(string Code, string Folder);
@@ -6,6 +6,21 @@ import { activityText } from "../audit.js";
const SCAN_BUTTON = `<button class="btn small" data-scan data-i18n="Admin.Archive.Scan" data-i18n-title="Admin.Archive.Scan.Tip"></button>`;
// Why a folder of the archive's layout could not be created (DashboardDto.ArchiveProblem), each with its tooltip.
const ARCHIVE_PROBLEM_TIPS = {
unavailable: "Admin.Dashboard.ArchiveIncomplete.Unavailable.Tip",
denied: "Admin.Dashboard.ArchiveIncomplete.Denied.Tip",
readOnly: "Admin.Dashboard.ArchiveIncomplete.ReadOnly.Tip",
failed: "Admin.Dashboard.ArchiveIncomplete.Failed.Tip",
};
/** The warning chip of an incomplete archive layout; empty when every folder is there. */
function archiveProblemChip(problem) {
if (!problem) return "";
const tip = t(ARCHIVE_PROBLEM_TIPS[problem.code] ?? ARCHIVE_PROBLEM_TIPS.failed, problem.folder);
return `<span class="chip warn" title="${attr(tip)}" data-i18n="Admin.Dashboard.ArchiveIncomplete"></span>`;
}
export async function render(root, { api, setMeta, actions, onEvent }) {
let timer = null;
const refresh = () => {
@@ -28,7 +43,7 @@ export async function render(root, { api, setMeta, actions, onEvent }) {
const tls = `Admin.Settings.Tls.${d.tlsMode.charAt(0).toUpperCase()}${d.tlsMode.slice(1)}`;
setMeta(t("Admin.Dashboard.Meta", formatDuration(d.uptimeSeconds), d.database, t(tls),
t(d.discovery ? "Admin.Dashboard.DiscoveryOn" : "Admin.Dashboard.DiscoveryOff")));
actions.innerHTML = d.proxyWarning ? PROXY_WARNING : "";
actions.innerHTML = (d.proxyWarning ? PROXY_WARNING : "") + archiveProblemChip(d.archiveProblem);
applyStrings(actions);
// The space volume's figures (the space path when the server has one), the write volume apart when it differs.
const a = d.archive;
+11 -1
View File
@@ -69,10 +69,20 @@ public static class AdminEndpoints
[.. uploads.Select(u => new UploadDayDto(u.Day, u.Count, u.Bytes))],
[.. activity.Items.Select(Dto.Audit)],
[.. running.Items.Concat(queued.Items.OrderByDescending(j => j.Priority).ThenBy(j => j.Created)).Take(10).Select(Dto.Job)],
AdminPanel.BypassesProxy(context, options)),
AdminPanel.BypassesProxy(context, options),
ArchiveProblem(archive.CheckStructure())),
ProtocolJson.Default.DashboardDto);
}
/// <summary>The dashboard's warning of an incomplete archive layout; null when every folder is there.</summary>
private static ArchiveProblemDto? ArchiveProblem(Core.Archiving.ArchiveStructureReport report) => report.IsComplete ? null : new(report.Problem switch
{
Core.Archiving.ArchiveStructureProblem.Unavailable => "unavailable",
Core.Archiving.ArchiveStructureProblem.Denied => "denied",
Core.Archiving.ArchiveStructureProblem.ReadOnly => "readOnly",
_ => "failed",
}, report.Folder ?? report.Root);
private static async Task<IResult> SaveSettingsAsync(HttpContext context, Caller caller, ServerSettingsDto request, ServerSettingsStore store, ServerOptions options,
AuditLog audit, JobEngineHost jobs, SchedulerHost schedules)
{
+7 -3
View File
@@ -72,12 +72,16 @@ public static class SystemEndpoints
}).AllowAnonymousCaller();
}
/// <summary>Liveness for the container health check: 503 while the database cannot be reached.</summary>
private static async Task<IResult> HealthAsync(HttpContext context, ServerOptions options, ChronosDatabase db)
/// <summary>
/// Liveness for the container health check: 503 while the database cannot be reached. An incomplete archive layout is
/// reported in the checks without failing the check: the server still serves what it can.
/// </summary>
private static async Task<IResult> HealthAsync(HttpContext context, ServerOptions options, ChronosDatabase db, Storage.ServerArchive archive)
{
var checks = new Dictionary<string, string>(StringComparer.Ordinal)
{
["archive"] = Directory.Exists(options.ArchivePath) ? "ok" : "missing",
// "incomplete": a folder of the archive's layout could not be created (the dashboard says which and why).
["archive"] = !Directory.Exists(options.ArchivePath) ? "missing" : archive.Structure is { IsComplete: false } ? "incomplete" : "ok",
["data"] = Directory.Exists(options.DataPath) ? "ok" : "missing",
};
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted);
+5
View File
@@ -87,6 +87,11 @@ public static class ServerHost
+ "they could put a link in place of a folder and redirect the files the server moves. Let only those accounts change it (others may read it).",
options.ArchivePath);
}
if (archive.Structure is { IsComplete: false } structure)
{
app.Logger.LogWarning("The archive's folders are incomplete: {Problem} Uploads, deletions and conversions that need the missing folder fail "
+ "until it can be created; the dashboard shows the problem until then. {Detail}", structure.Message, structure.Detail ?? string.Empty);
}
// A space path that cannot be measured is warned about at start, not first when someone opens the dashboard.
if (!string.IsNullOrWhiteSpace(options.SpacePath)) app.Services.GetRequiredService<VolumeSpace>().Report(archive.Root);
if (options.FormerWorkersVariable)
+25 -2
View File
@@ -1,3 +1,4 @@
using Chronos.Core.Archiving;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
@@ -46,14 +47,36 @@ public sealed class ServerArchive(Archive archive)
public string Root => _current.RootPath;
/// <summary>
/// What the last <see cref="CheckStructure"/> found of the archive's folders; null before the first. The dashboard and
/// the health check show an incomplete layout.
/// </summary>
public ArchiveStructureReport? Structure => _structure;
private volatile ArchiveStructureReport? _structure;
/// <summary>
/// Creates the folders of the archive's layout that are missing (BRIEF §7) and remembers what it found
/// (<see cref="Structure"/>): at start, and each time the dashboard is read, so a share that comes back heals.
/// </summary>
public ArchiveStructureReport CheckStructure()
{
var report = ArchiveStructure.Ensure(new ArchivePaths(Root));
_structure = report;
return report;
}
/// <summary>
/// Opens the archive at the configured root through the archive engine: an existing Chronos archive is registered
/// (and relinked if it moved), any other folder becomes a new archive with the default templates.
/// (and relinked if it moved), any other folder becomes a new archive with the default templates. Either way the
/// folders of the archive's layout are made (<see cref="CheckStructure"/>).
/// </summary>
public static async Task<ServerArchive> OpenAsync(ChronosDatabase db, ServerOptions options, CancellationToken cancellationToken)
{
var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(options.ArchivePath));
var archive = await new ArchiveService(db).AdoptAsync(root, options.ServerName, cancellationToken).ConfigureAwait(false);
return new ServerArchive(archive);
var served = new ServerArchive(archive);
served.CheckStructure();
return served;
}
}